1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/interfaces/libpq/fe-connect.c,v 1.393 2010/05/26 21:39:27 tgl Exp $
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
26 #include "libpq-int.h"
28 #include "pg_config_paths.h"
35 #define _WIN32_IE 0x0500
42 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #ifdef HAVE_NETINET_TCP_H
46 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
51 #ifdef ENABLE_THREAD_SAFETY
53 #include "pthread-win32.h"
63 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
64 #define LDAP_DEPRECATED 1
66 typedef struct timeval LDAP_TIMEVAL;
68 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
69 PQExpBuffer errorMessage);
73 #include "mb/pg_wchar.h"
81 #define PGPASSFILE ".pgpass"
83 #define PGPASSFILE "pgpass.conf"
87 * Pre-9.0 servers will return this SQLSTATE if asked to set
88 * application_name in a startup packet. We hard-wire the value rather
89 * than looking into errcodes.h since it reflects historical behavior
90 * rather than that of the current code.
92 #define ERRCODE_APPNAME_UNKNOWN "42704"
94 /* This is part of the protocol so just define it */
95 #define ERRCODE_INVALID_PASSWORD "28P01"
98 * fall back options if they are not specified by arguments or defined
99 * by environment variables
101 #define DefaultHost "localhost"
102 #define DefaultTty ""
103 #define DefaultOption ""
104 #define DefaultAuthtype ""
105 #define DefaultPassword ""
107 #define DefaultSSLMode "prefer"
109 #define DefaultSSLMode "disable"
113 * Definition of the conninfo parameters and their fallback resources.
115 * If Environment-Var and Compiled-in are specified as NULL, no
116 * fallback is available. If after all no value can be determined
117 * for an option, an error is returned.
119 * The value for the username is treated specially in conninfo_parse.
120 * If the Compiled-in resource is specified as a NULL value, the
121 * user is determined by pg_fe_getauthname().
123 * The Label and Disp-Char entries are provided for applications that
124 * want to use PQconndefaults() to create a generic database connection
125 * dialog. Disp-Char is defined as follows:
126 * "" Normal input field
127 * "*" Password field - hide value
128 * "D" Debug option - don't show by default
130 * PQconninfoOptions[] is a constant static array that we use to initialize
131 * a dynamically allocated working copy. All the "val" fields in
132 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
133 * fields point to malloc'd strings that should be freed when the working
134 * array is freed (see PQconninfoFree).
137 static const PQconninfoOption PQconninfoOptions[] = {
139 * "authtype" is no longer used, so mark it "don't show". We keep it in
140 * the array so as not to reject conninfo strings from old apps that might
141 * still try to set it.
143 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
144 "Database-Authtype", "D", 20},
146 {"service", "PGSERVICE", NULL, NULL,
147 "Database-Service", "", 20},
149 {"user", "PGUSER", NULL, NULL,
150 "Database-User", "", 20},
152 {"password", "PGPASSWORD", NULL, NULL,
153 "Database-Password", "*", 20},
155 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
156 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
158 {"dbname", "PGDATABASE", NULL, NULL,
159 "Database-Name", "", 20},
161 {"host", "PGHOST", NULL, NULL,
162 "Database-Host", "", 40},
164 {"hostaddr", "PGHOSTADDR", NULL, NULL,
165 "Database-Host-IP-Address", "", 45},
167 {"port", "PGPORT", DEF_PGPORT_STR, NULL,
168 "Database-Port", "", 6},
171 * "tty" is no longer used either, but keep it present for backwards
174 {"tty", "PGTTY", DefaultTty, NULL,
175 "Backend-Debug-TTY", "D", 40},
177 {"options", "PGOPTIONS", DefaultOption, NULL,
178 "Backend-Debug-Options", "D", 40},
180 {"application_name", "PGAPPNAME", NULL, NULL,
181 "Application-Name", "", 64},
183 {"fallback_application_name", NULL, NULL, NULL,
184 "Fallback-Application-Name", "", 64},
189 * "requiressl" is deprecated, its purpose having been taken over by
190 * "sslmode". It remains for backwards compatibility.
192 {"requiressl", "PGREQUIRESSL", "0", NULL,
193 "Require-SSL", "D", 1},
197 * ssl options are allowed even without client SSL support because the
198 * client can still handle SSL modes "disable" and "allow". Other
199 * parameters have no effect on non-SSL connections, so there is no reason
200 * to exclude them since none of them are mandatory.
202 {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
203 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
205 {"sslcert", "PGSSLCERT", NULL, NULL,
206 "SSL-Client-Cert", "", 64},
208 {"sslkey", "PGSSLKEY", NULL, NULL,
209 "SSL-Client-Key", "", 64},
211 {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
212 "SSL-Root-Certificate", "", 64},
214 {"sslcrl", "PGSSLCRL", NULL, NULL,
215 "SSL-Revocation-List", "", 64},
217 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
218 /* Kerberos and GSSAPI authentication support specifying the service name */
219 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
220 "Kerberos-service-name", "", 20},
223 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
226 * GSSAPI and SSPI both enabled, give a way to override which is used by
229 {"gsslib", "PGGSSLIB", NULL, NULL,
230 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
233 {"replication", NULL, NULL, NULL,
234 "Replication", "D", 5},
236 /* Terminating entry --- MUST BE LAST */
237 {NULL, NULL, NULL, NULL,
241 static const PQEnvironmentOption EnvironmentOptions[] =
243 /* common user-interface settings */
245 "PGDATESTYLE", "datestyle"
251 "PGCLIENTENCODING", "client_encoding"
253 /* internal performance-related settings */
263 static bool connectOptions1(PGconn *conn, const char *conninfo);
264 static bool connectOptions2(PGconn *conn);
265 static int connectDBStart(PGconn *conn);
266 static int connectDBComplete(PGconn *conn);
267 static PGconn *makeEmptyPGconn(void);
268 static void fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
269 static void freePGconn(PGconn *conn);
270 static void closePGconn(PGconn *conn);
271 static PQconninfoOption *conninfo_parse(const char *conninfo,
272 PQExpBuffer errorMessage, bool use_defaults);
273 static PQconninfoOption *conninfo_array_parse(const char **keywords,
274 const char **values, PQExpBuffer errorMessage,
275 bool use_defaults, int expand_dbname);
276 static char *conninfo_getval(PQconninfoOption *connOptions,
277 const char *keyword);
278 static void defaultNoticeReceiver(void *arg, const PGresult *res);
279 static void defaultNoticeProcessor(void *arg, const char *message);
280 static int parseServiceInfo(PQconninfoOption *options,
281 PQExpBuffer errorMessage);
282 static int parseServiceFile(const char *serviceFile,
284 PQconninfoOption *options,
285 PQExpBuffer errorMessage,
287 static char *pwdfMatchesString(char *buf, char *token);
288 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
290 static bool getPgPassFilename(char *pgpassfile);
291 static void dot_pg_pass_warning(PGconn *conn);
292 static void default_threadlock(int acquire);
295 /* global variable because fe-auth.c needs to access it */
296 pgthreadlock_t pg_g_threadlock = default_threadlock;
300 * Connecting to a Database
302 * There are now six different ways a user of this API can connect to the
303 * database. Two are not recommended for use in new code, because of their
304 * lack of extensibility with respect to the passing of options to the
305 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
308 * If it is desired to connect in a synchronous (blocking) manner, use the
309 * function PQconnectdb or PQconnectdbParams. The former accepts a string
310 * of option = value pairs which must be parsed; the latter takes two NULL
311 * terminated arrays instead.
313 * To connect in an asynchronous (non-blocking) manner, use the functions
314 * PQconnectStart or PQconnectStartParams (which differ in the same way as
315 * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
317 * Internally, the static functions connectDBStart, connectDBComplete
318 * are part of the connection procedure.
324 * establishes a connection to a postgres backend through the postmaster
325 * using connection information in two arrays.
327 * The keywords array is defined as
329 * const char *params[] = {"option1", "option2", NULL}
331 * The values array is defined as
333 * const char *values[] = {"value1", "value2", NULL}
335 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
336 * if a memory allocation failed.
337 * If the status field of the connection returned is CONNECTION_BAD,
338 * then some fields may be null'ed out instead of having valid values.
340 * You should call PQfinish (if conn is not NULL) regardless of whether this
344 PQconnectdbParams(const char **keywords,
348 PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
350 if (conn && conn->status != CONNECTION_BAD)
351 (void) connectDBComplete(conn);
360 * establishes a connection to a postgres backend through the postmaster
361 * using connection information in a string.
363 * The conninfo string is a white-separated list of
367 * definitions. Value might be a single value containing no whitespaces or
368 * a single quoted string. If a single quote should appear anywhere in
369 * the value, it must be escaped with a backslash like \'
371 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
372 * if a memory allocation failed.
373 * If the status field of the connection returned is CONNECTION_BAD,
374 * then some fields may be null'ed out instead of having valid values.
376 * You should call PQfinish (if conn is not NULL) regardless of whether this
380 PQconnectdb(const char *conninfo)
382 PGconn *conn = PQconnectStart(conninfo);
384 if (conn && conn->status != CONNECTION_BAD)
385 (void) connectDBComplete(conn);
391 * PQconnectStartParams
393 * Begins the establishment of a connection to a postgres backend through the
394 * postmaster using connection information in a struct.
396 * See comment for PQconnectdbParams for the definition of the string format.
398 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
399 * you should not attempt to proceed with this connection. If the status
400 * field of the connection returned is CONNECTION_BAD, an error has
401 * occurred. In this case you should call PQfinish on the result, (perhaps
402 * inspecting the error message first). Other fields of the structure may not
403 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
404 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
407 * See PQconnectPoll for more info.
410 PQconnectStartParams(const char **keywords,
415 PQconninfoOption *connOptions;
418 * Allocate memory for the conn structure
420 conn = makeEmptyPGconn();
425 * Parse the conninfo arrays
427 connOptions = conninfo_array_parse(keywords, values,
429 true, expand_dbname);
430 if (connOptions == NULL)
432 conn->status = CONNECTION_BAD;
433 /* errorMessage is already set */
438 * Move option values into conn structure
440 fillPGconn(conn, connOptions);
443 * Free the option info - all is in conn now
445 PQconninfoFree(connOptions);
448 * Compute derived options
450 if (!connectOptions2(conn))
454 * Connect to the database
456 if (!connectDBStart(conn))
458 /* Just in case we failed to set it in connectDBStart */
459 conn->status = CONNECTION_BAD;
468 * Begins the establishment of a connection to a postgres backend through the
469 * postmaster using connection information in a string.
471 * See comment for PQconnectdb for the definition of the string format.
473 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
474 * you should not attempt to proceed with this connection. If the status
475 * field of the connection returned is CONNECTION_BAD, an error has
476 * occurred. In this case you should call PQfinish on the result, (perhaps
477 * inspecting the error message first). Other fields of the structure may not
478 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
479 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
482 * See PQconnectPoll for more info.
485 PQconnectStart(const char *conninfo)
490 * Allocate memory for the conn structure
492 conn = makeEmptyPGconn();
497 * Parse the conninfo string
499 if (!connectOptions1(conn, conninfo))
503 * Compute derived options
505 if (!connectOptions2(conn))
509 * Connect to the database
511 if (!connectDBStart(conn))
513 /* Just in case we failed to set it in connectDBStart */
514 conn->status = CONNECTION_BAD;
521 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
526 * Move option values into conn structure
528 * Don't put anything cute here --- intelligence should be in
529 * connectOptions2 ...
531 * XXX: probably worth checking strdup() return value here...
533 tmp = conninfo_getval(connOptions, "hostaddr");
534 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
535 tmp = conninfo_getval(connOptions, "host");
536 conn->pghost = tmp ? strdup(tmp) : NULL;
537 tmp = conninfo_getval(connOptions, "port");
538 conn->pgport = tmp ? strdup(tmp) : NULL;
539 tmp = conninfo_getval(connOptions, "tty");
540 conn->pgtty = tmp ? strdup(tmp) : NULL;
541 tmp = conninfo_getval(connOptions, "options");
542 conn->pgoptions = tmp ? strdup(tmp) : NULL;
543 tmp = conninfo_getval(connOptions, "application_name");
544 conn->appname = tmp ? strdup(tmp) : NULL;
545 tmp = conninfo_getval(connOptions, "fallback_application_name");
546 conn->fbappname = tmp ? strdup(tmp) : NULL;
547 tmp = conninfo_getval(connOptions, "dbname");
548 conn->dbName = tmp ? strdup(tmp) : NULL;
549 tmp = conninfo_getval(connOptions, "user");
550 conn->pguser = tmp ? strdup(tmp) : NULL;
551 tmp = conninfo_getval(connOptions, "password");
552 conn->pgpass = tmp ? strdup(tmp) : NULL;
553 tmp = conninfo_getval(connOptions, "connect_timeout");
554 conn->connect_timeout = tmp ? strdup(tmp) : NULL;
555 tmp = conninfo_getval(connOptions, "sslmode");
556 conn->sslmode = tmp ? strdup(tmp) : NULL;
557 tmp = conninfo_getval(connOptions, "sslkey");
558 conn->sslkey = tmp ? strdup(tmp) : NULL;
559 tmp = conninfo_getval(connOptions, "sslcert");
560 conn->sslcert = tmp ? strdup(tmp) : NULL;
561 tmp = conninfo_getval(connOptions, "sslrootcert");
562 conn->sslrootcert = tmp ? strdup(tmp) : NULL;
563 tmp = conninfo_getval(connOptions, "sslcrl");
564 conn->sslcrl = tmp ? strdup(tmp) : NULL;
566 tmp = conninfo_getval(connOptions, "requiressl");
567 if (tmp && tmp[0] == '1')
569 /* here warn that the requiressl option is deprecated? */
572 conn->sslmode = strdup("require");
575 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
576 tmp = conninfo_getval(connOptions, "krbsrvname");
577 conn->krbsrvname = tmp ? strdup(tmp) : NULL;
579 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
580 tmp = conninfo_getval(connOptions, "gsslib");
581 conn->gsslib = tmp ? strdup(tmp) : NULL;
583 tmp = conninfo_getval(connOptions, "replication");
584 conn->replication = tmp ? strdup(tmp) : NULL;
590 * Internal subroutine to set up connection parameters given an already-
591 * created PGconn and a conninfo string. Derived settings should be
592 * processed by calling connectOptions2 next. (We split them because
593 * PQsetdbLogin overrides defaults in between.)
595 * Returns true if OK, false if trouble (in which case errorMessage is set
596 * and so is conn->status).
599 connectOptions1(PGconn *conn, const char *conninfo)
601 PQconninfoOption *connOptions;
604 * Parse the conninfo string
606 connOptions = conninfo_parse(conninfo, &conn->errorMessage, true);
607 if (connOptions == NULL)
609 conn->status = CONNECTION_BAD;
610 /* errorMessage is already set */
615 * Move option values into conn structure
617 fillPGconn(conn, connOptions);
620 * Free the option info - all is in conn now
622 PQconninfoFree(connOptions);
630 * Compute derived connection options after absorbing all user-supplied info.
632 * Returns true if OK, false if trouble (in which case errorMessage is set
633 * and so is conn->status).
636 connectOptions2(PGconn *conn)
639 * If database name was not given, default it to equal user name
641 if ((conn->dbName == NULL || conn->dbName[0] == '\0')
642 && conn->pguser != NULL)
646 conn->dbName = strdup(conn->pguser);
650 * Supply default password if none given
652 if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
656 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
657 conn->dbName, conn->pguser);
658 if (conn->pgpass == NULL)
659 conn->pgpass = strdup(DefaultPassword);
661 conn->dot_pgpass_used = true;
665 * Allow unix socket specification in the host name
667 if (conn->pghost && is_absolute_path(conn->pghost))
669 if (conn->pgunixsocket)
670 free(conn->pgunixsocket);
671 conn->pgunixsocket = conn->pghost;
676 * validate sslmode option
680 if (strcmp(conn->sslmode, "disable") != 0
681 && strcmp(conn->sslmode, "allow") != 0
682 && strcmp(conn->sslmode, "prefer") != 0
683 && strcmp(conn->sslmode, "require") != 0
684 && strcmp(conn->sslmode, "verify-ca") != 0
685 && strcmp(conn->sslmode, "verify-full") != 0)
687 conn->status = CONNECTION_BAD;
688 printfPQExpBuffer(&conn->errorMessage,
689 libpq_gettext("invalid sslmode value: \"%s\"\n"),
695 switch (conn->sslmode[0])
697 case 'a': /* "allow" */
698 case 'p': /* "prefer" */
701 * warn user that an SSL connection will never be negotiated
702 * since SSL was not compiled in?
706 case 'r': /* "require" */
707 case 'v': /* "verify-ca" or "verify-full" */
708 conn->status = CONNECTION_BAD;
709 printfPQExpBuffer(&conn->errorMessage,
710 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
717 conn->sslmode = strdup(DefaultSSLMode);
720 * Only if we get this far is it appropriate to try to connect. (We need a
721 * state flag, rather than just the boolean result of this function, in
722 * case someone tries to PQreset() the PGconn.)
724 conn->options_valid = true;
732 * Parse an empty string like PQconnectdb() would do and return the
733 * resulting connection options array, ie, all the default values that are
734 * available from the environment etc. On error (eg out of memory),
737 * Using this function, an application may determine all possible options
738 * and their current default values.
740 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
741 * and should be freed when no longer needed via PQconninfoFree(). (In prior
742 * versions, the returned array was static, but that's not thread-safe.)
743 * Pre-7.0 applications that use this function will see a small memory leak
744 * until they are updated to call PQconninfoFree.
749 PQExpBufferData errorBuf;
750 PQconninfoOption *connOptions;
752 initPQExpBuffer(&errorBuf);
753 if (PQExpBufferBroken(&errorBuf))
754 return NULL; /* out of memory already :-( */
755 connOptions = conninfo_parse("", &errorBuf, true);
756 termPQExpBuffer(&errorBuf);
763 * establishes a connection to a postgres backend through the postmaster
764 * at the specified host and port.
766 * returns a PGconn* which is needed for all subsequent libpq calls
768 * if the status field of the connection returned is CONNECTION_BAD,
769 * then only the errorMessage is likely to be useful.
773 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
774 const char *pgtty, const char *dbName, const char *login,
780 * Allocate memory for the conn structure
782 conn = makeEmptyPGconn();
787 * If the dbName parameter contains '=', assume it's a conninfo string.
789 if (dbName && strchr(dbName, '='))
791 if (!connectOptions1(conn, dbName))
797 * Old-style path: first, parse an empty conninfo string in order to
798 * set up the same defaults that PQconnectdb() would use.
800 if (!connectOptions1(conn, ""))
803 /* Insert dbName parameter value into struct */
804 if (dbName && dbName[0] != '\0')
808 conn->dbName = strdup(dbName);
813 * Insert remaining parameters into struct, overriding defaults (as well
814 * as any conflicting data from dbName taken as a conninfo).
816 if (pghost && pghost[0] != '\0')
820 conn->pghost = strdup(pghost);
823 if (pgport && pgport[0] != '\0')
827 conn->pgport = strdup(pgport);
830 if (pgoptions && pgoptions[0] != '\0')
833 free(conn->pgoptions);
834 conn->pgoptions = strdup(pgoptions);
837 if (pgtty && pgtty[0] != '\0')
841 conn->pgtty = strdup(pgtty);
844 if (login && login[0] != '\0')
848 conn->pguser = strdup(login);
851 if (pwd && pwd[0] != '\0')
855 conn->pgpass = strdup(pwd);
859 * Compute derived options
861 if (!connectOptions2(conn))
865 * Connect to the database
867 if (connectDBStart(conn))
868 (void) connectDBComplete(conn);
876 * Sets the TCP_NODELAY socket option.
877 * Returns 1 if successful, 0 if not.
881 connectNoDelay(PGconn *conn)
886 if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
892 appendPQExpBuffer(&conn->errorMessage,
893 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
894 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
904 * connectFailureMessage -
905 * create a friendly error message on connection failure.
909 connectFailureMessage(PGconn *conn, int errorno)
913 #ifdef HAVE_UNIX_SOCKETS
914 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
916 char service[NI_MAXHOST];
918 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
920 service, sizeof(service),
922 appendPQExpBuffer(&conn->errorMessage,
923 libpq_gettext("could not connect to server: %s\n"
924 "\tIs the server running locally and accepting\n"
925 "\tconnections on Unix domain socket \"%s\"?\n"),
926 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
930 #endif /* HAVE_UNIX_SOCKETS */
932 appendPQExpBuffer(&conn->errorMessage,
933 libpq_gettext("could not connect to server: %s\n"
934 "\tIs the server running on host \"%s\" and accepting\n"
935 "\tTCP/IP connections on port %s?\n"),
936 SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
949 * Begin the process of making a connection to the backend.
951 * Returns 1 if successful, 0 if not.
955 connectDBStart(PGconn *conn)
959 struct addrinfo *addrs = NULL;
960 struct addrinfo hint;
967 if (!conn->options_valid)
968 goto connect_errReturn;
970 /* Ensure our buffers are empty */
971 conn->inStart = conn->inCursor = conn->inEnd = 0;
975 * Determine the parameters to pass to pg_getaddrinfo_all.
978 /* Initialize hint structure */
979 MemSet(&hint, 0, sizeof(hint));
980 hint.ai_socktype = SOCK_STREAM;
981 hint.ai_family = AF_UNSPEC;
983 /* Set up port number as a string */
984 if (conn->pgport != NULL && conn->pgport[0] != '\0')
986 portnum = atoi(conn->pgport);
987 if (portnum < 1 || portnum > 65535)
989 appendPQExpBuffer(&conn->errorMessage,
990 libpq_gettext("invalid port number: \"%s\"\n"),
992 goto connect_errReturn;
996 portnum = DEF_PGPORT;
997 snprintf(portstr, sizeof(portstr), "%d", portnum);
999 if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1001 /* Using pghostaddr avoids a hostname lookup */
1002 node = conn->pghostaddr;
1003 hint.ai_family = AF_UNSPEC;
1004 hint.ai_flags = AI_NUMERICHOST;
1006 else if (conn->pghost != NULL && conn->pghost[0] != '\0')
1008 /* Using pghost, so we have to look-up the hostname */
1009 node = conn->pghost;
1010 hint.ai_family = AF_UNSPEC;
1014 #ifdef HAVE_UNIX_SOCKETS
1015 /* pghostaddr and pghost are NULL, so use Unix domain socket */
1017 hint.ai_family = AF_UNIX;
1018 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
1020 /* Without Unix sockets, default to localhost instead */
1022 hint.ai_family = AF_UNSPEC;
1023 #endif /* HAVE_UNIX_SOCKETS */
1026 /* Use pg_getaddrinfo_all() to resolve the address */
1027 ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
1031 appendPQExpBuffer(&conn->errorMessage,
1032 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
1033 node, gai_strerror(ret));
1035 appendPQExpBuffer(&conn->errorMessage,
1036 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
1037 portstr, gai_strerror(ret));
1039 pg_freeaddrinfo_all(hint.ai_family, addrs);
1040 goto connect_errReturn;
1044 /* setup values based on SSL mode */
1045 if (conn->sslmode[0] == 'd') /* "disable" */
1046 conn->allow_ssl_try = false;
1047 else if (conn->sslmode[0] == 'a') /* "allow" */
1048 conn->wait_ssl_try = true;
1052 * Set up to try to connect, with protocol 3.0 as the first attempt.
1054 conn->addrlist = addrs;
1055 conn->addr_cur = addrs;
1056 conn->addrlist_family = hint.ai_family;
1057 conn->pversion = PG_PROTOCOL(3, 0);
1058 conn->send_appname = true;
1059 conn->status = CONNECTION_NEEDED;
1062 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1063 * so that it can easily be re-executed if needed again during the
1064 * asynchronous startup process. However, we must run it once here,
1065 * because callers expect a success return from this routine to mean that
1066 * we are in PGRES_POLLING_WRITING connection state.
1068 if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1072 if (conn->sock >= 0)
1074 pqsecure_close(conn);
1075 closesocket(conn->sock);
1078 conn->status = CONNECTION_BAD;
1086 * Block and complete a connection.
1088 * Returns 1 on success, 0 on failure.
1091 connectDBComplete(PGconn *conn)
1093 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1094 time_t finish_time = ((time_t) -1);
1096 if (conn == NULL || conn->status == CONNECTION_BAD)
1100 * Set up a time limit, if connect_timeout isn't zero.
1102 if (conn->connect_timeout != NULL)
1104 int timeout = atoi(conn->connect_timeout);
1109 * Rounding could cause connection to fail; need at least 2 secs
1113 /* calculate the finish time based on start + timeout */
1114 finish_time = time(NULL) + timeout;
1121 * Wait, if necessary. Note that the initial state (just after
1122 * PQconnectStart) is to wait for the socket to select for writing.
1126 case PGRES_POLLING_OK:
1129 * Reset stored error messages since we now have a working
1132 resetPQExpBuffer(&conn->errorMessage);
1133 return 1; /* success! */
1135 case PGRES_POLLING_READING:
1136 if (pqWaitTimed(1, 0, conn, finish_time))
1138 conn->status = CONNECTION_BAD;
1143 case PGRES_POLLING_WRITING:
1144 if (pqWaitTimed(0, 1, conn, finish_time))
1146 conn->status = CONNECTION_BAD;
1152 /* Just in case we failed to set it in PQconnectPoll */
1153 conn->status = CONNECTION_BAD;
1158 * Now try to advance the state machine.
1160 flag = PQconnectPoll(conn);
1167 * Poll an asynchronous connection.
1169 * Returns a PostgresPollingStatusType.
1170 * Before calling this function, use select(2) to determine when data
1173 * You must call PQfinish whether or not this fails.
1175 * This function and PQconnectStart are intended to allow connections to be
1176 * made without blocking the execution of your program on remote I/O. However,
1177 * there are a number of caveats:
1179 * o If you call PQtrace, ensure that the stream object into which you trace
1181 * o If you do not supply an IP address for the remote host (i.e. you
1182 * supply a host name instead) then PQconnectStart will block on
1183 * gethostbyname. You will be fine if using Unix sockets (i.e. by
1184 * supplying neither a host name nor a host address).
1185 * o If your backend wants to use Kerberos authentication then you must
1186 * supply both a host name and a host address, otherwise this function
1187 * may block on gethostname.
1191 PostgresPollingStatusType
1192 PQconnectPoll(PGconn *conn)
1199 return PGRES_POLLING_FAILED;
1201 /* Get the new data */
1202 switch (conn->status)
1205 * We really shouldn't have been polled in these two cases, but we
1208 case CONNECTION_BAD:
1209 return PGRES_POLLING_FAILED;
1211 return PGRES_POLLING_OK;
1213 /* These are reading states */
1214 case CONNECTION_AWAITING_RESPONSE:
1215 case CONNECTION_AUTH_OK:
1217 /* Load waiting data */
1218 int n = pqReadData(conn);
1223 return PGRES_POLLING_READING;
1228 /* These are writing states, so we just proceed. */
1229 case CONNECTION_STARTED:
1230 case CONNECTION_MADE:
1233 /* We allow pqSetenvPoll to decide whether to proceed. */
1234 case CONNECTION_SETENV:
1237 /* Special cases: proceed without waiting. */
1238 case CONNECTION_SSL_STARTUP:
1239 case CONNECTION_NEEDED:
1243 appendPQExpBuffer(&conn->errorMessage,
1245 "invalid connection state, "
1246 "probably indicative of memory corruption\n"
1252 keep_going: /* We will come back to here until there is
1253 * nothing left to do. */
1254 switch (conn->status)
1256 case CONNECTION_NEEDED:
1259 * Try to initiate a connection to one of the addresses
1260 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1261 * next one to try. We fail when we run out of addresses
1262 * (reporting the error returned for the *last* alternative,
1263 * which may not be what users expect :-().
1265 while (conn->addr_cur != NULL)
1267 struct addrinfo *addr_cur = conn->addr_cur;
1269 /* Remember current address for possible error msg */
1270 memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1271 addr_cur->ai_addrlen);
1272 conn->raddr.salen = addr_cur->ai_addrlen;
1275 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1279 * ignore socket() failure if we have more addresses
1282 if (addr_cur->ai_next != NULL)
1284 conn->addr_cur = addr_cur->ai_next;
1287 appendPQExpBuffer(&conn->errorMessage,
1288 libpq_gettext("could not create socket: %s\n"),
1289 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1294 * Select socket options: no delay of outgoing data for
1295 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1298 if (!IS_AF_UNIX(addr_cur->ai_family))
1300 if (!connectNoDelay(conn))
1302 closesocket(conn->sock);
1304 conn->addr_cur = addr_cur->ai_next;
1308 if (!pg_set_noblock(conn->sock))
1310 appendPQExpBuffer(&conn->errorMessage,
1311 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1312 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1313 closesocket(conn->sock);
1315 conn->addr_cur = addr_cur->ai_next;
1320 if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1322 appendPQExpBuffer(&conn->errorMessage,
1323 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1324 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1325 closesocket(conn->sock);
1327 conn->addr_cur = addr_cur->ai_next;
1330 #endif /* F_SETFD */
1333 * We have three methods of blocking SIGPIPE during
1334 * send() calls to this socket:
1336 * - setsockopt(sock, SO_NOSIGPIPE)
1337 * - send(sock, ..., MSG_NOSIGNAL)
1338 * - setting the signal mask to SIG_IGN during send()
1340 * The third method requires three syscalls per send,
1341 * so we prefer either of the first two, but they are
1342 * less portable. The state is tracked in the following
1343 * members of PGconn:
1345 * conn->sigpipe_so - we have set up SO_NOSIGPIPE
1346 * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
1348 * If we can use SO_NOSIGPIPE, then set sigpipe_so here
1349 * and we're done. Otherwise, set sigpipe_flag so that
1350 * we will try MSG_NOSIGNAL on sends. If we get an error
1351 * with MSG_NOSIGNAL, we'll clear that flag and revert to
1355 conn->sigpipe_so = false;
1357 conn->sigpipe_flag = true;
1359 conn->sigpipe_flag = false;
1360 #endif /* MSG_NOSIGNAL */
1364 if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
1365 (char *) &optval, sizeof(optval)) == 0)
1367 conn->sigpipe_so = true;
1368 conn->sigpipe_flag = false;
1370 #endif /* SO_NOSIGPIPE */
1373 * Start/make connection. This should not block, since we
1374 * are in nonblock mode. If it does, well, too bad.
1376 if (connect(conn->sock, addr_cur->ai_addr,
1377 addr_cur->ai_addrlen) < 0)
1379 if (SOCK_ERRNO == EINPROGRESS ||
1380 SOCK_ERRNO == EWOULDBLOCK ||
1381 SOCK_ERRNO == EINTR ||
1385 * This is fine - we're in non-blocking mode, and
1386 * the connection is in progress. Tell caller to
1387 * wait for write-ready on socket.
1389 conn->status = CONNECTION_STARTED;
1390 return PGRES_POLLING_WRITING;
1392 /* otherwise, trouble */
1397 * Hm, we're connected already --- seems the "nonblock
1398 * connection" wasn't. Advance the state machine and
1399 * go do the next stuff.
1401 conn->status = CONNECTION_STARTED;
1406 * This connection failed --- set up error report, then
1407 * close socket (do it this way in case close() affects
1408 * the value of errno...). We will ignore the connect()
1409 * failure and keep going if there are more addresses.
1411 connectFailureMessage(conn, SOCK_ERRNO);
1412 if (conn->sock >= 0)
1414 closesocket(conn->sock);
1419 * Try the next address, if any.
1421 conn->addr_cur = addr_cur->ai_next;
1422 } /* loop over addresses */
1425 * Ooops, no more addresses. An appropriate error message is
1426 * already set up, so just set the right status.
1431 case CONNECTION_STARTED:
1433 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1436 * Write ready, since we've made it here, so the connection
1437 * has been made ... or has failed.
1441 * Now check (using getsockopt) that there is not an error
1442 * state waiting for us on the socket.
1445 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1446 (char *) &optval, &optlen) == -1)
1448 appendPQExpBuffer(&conn->errorMessage,
1449 libpq_gettext("could not get socket error status: %s\n"),
1450 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1453 else if (optval != 0)
1456 * When using a nonblocking connect, we will typically see
1457 * connect failures at this point, so provide a friendly
1460 connectFailureMessage(conn, optval);
1463 * If more addresses remain, keep trying, just as in the
1464 * case where connect() returned failure immediately.
1466 if (conn->addr_cur->ai_next != NULL)
1468 if (conn->sock >= 0)
1470 closesocket(conn->sock);
1473 conn->addr_cur = conn->addr_cur->ai_next;
1474 conn->status = CONNECTION_NEEDED;
1480 /* Fill in the client address */
1481 conn->laddr.salen = sizeof(conn->laddr.addr);
1482 if (getsockname(conn->sock,
1483 (struct sockaddr *) & conn->laddr.addr,
1484 &conn->laddr.salen) < 0)
1486 appendPQExpBuffer(&conn->errorMessage,
1487 libpq_gettext("could not get client address from socket: %s\n"),
1488 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1493 * Make sure we can write before advancing to next step.
1495 conn->status = CONNECTION_MADE;
1496 return PGRES_POLLING_WRITING;
1499 case CONNECTION_MADE:
1507 * If SSL is enabled and we haven't already got it running,
1508 * request it instead of sending the startup message.
1510 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1512 /* Don't bother requesting SSL over a Unix socket */
1513 conn->allow_ssl_try = false;
1515 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1521 * Send the SSL request packet.
1523 * Theoretically, this could block, but it really
1524 * shouldn't since we only got here if the socket is
1527 pv = htonl(NEGOTIATE_SSL_CODE);
1528 if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1530 appendPQExpBuffer(&conn->errorMessage,
1531 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1532 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1535 /* Ok, wait for response */
1536 conn->status = CONNECTION_SSL_STARTUP;
1537 return PGRES_POLLING_READING;
1539 #endif /* USE_SSL */
1542 * Build the startup packet.
1544 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1545 startpacket = pqBuildStartupPacket3(conn, &packetlen,
1546 EnvironmentOptions);
1548 startpacket = pqBuildStartupPacket2(conn, &packetlen,
1549 EnvironmentOptions);
1553 * will not appendbuffer here, since it's likely to also
1556 printfPQExpBuffer(&conn->errorMessage,
1557 libpq_gettext("out of memory\n"));
1562 * Send the startup packet.
1564 * Theoretically, this could block, but it really shouldn't
1565 * since we only got here if the socket is write-ready.
1567 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
1569 appendPQExpBuffer(&conn->errorMessage,
1570 libpq_gettext("could not send startup packet: %s\n"),
1571 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1578 conn->status = CONNECTION_AWAITING_RESPONSE;
1579 return PGRES_POLLING_READING;
1583 * Handle SSL negotiation: wait for postmaster messages and
1584 * respond as necessary.
1586 case CONNECTION_SSL_STARTUP:
1589 PostgresPollingStatusType pollres;
1592 * On first time through, get the postmaster's response to our
1593 * SSL negotiation packet.
1595 if (conn->ssl == NULL)
1598 * We use pqReadData here since it has the logic to
1599 * distinguish no-data-yet from connection closure. Since
1600 * conn->ssl isn't set, a plain recv() will occur.
1605 rdresult = pqReadData(conn);
1608 /* errorMessage is already filled in */
1613 /* caller failed to wait for data */
1614 return PGRES_POLLING_READING;
1616 if (pqGetc(&SSLok, conn) < 0)
1618 /* should not happen really */
1619 return PGRES_POLLING_READING;
1621 /* mark byte consumed */
1622 conn->inStart = conn->inCursor;
1625 /* Set up global SSL state if required */
1626 if (pqsecure_initialize(conn) != 0)
1629 else if (SSLok == 'N')
1631 if (conn->sslmode[0] == 'r' || /* "require" */
1632 conn->sslmode[0] == 'v') /* "verify-ca" or
1635 /* Require SSL, but server does not want it */
1636 appendPQExpBuffer(&conn->errorMessage,
1637 libpq_gettext("server does not support SSL, but SSL was required\n"));
1640 /* Otherwise, proceed with normal startup */
1641 conn->allow_ssl_try = false;
1642 conn->status = CONNECTION_MADE;
1643 return PGRES_POLLING_WRITING;
1645 else if (SSLok == 'E')
1647 /* Received error - probably protocol mismatch */
1649 fprintf(conn->Pfdebug, "received error from server, attempting fallback to pre-7.0\n");
1650 if (conn->sslmode[0] == 'r' || /* "require" */
1651 conn->sslmode[0] == 'v') /* "verify-ca" or
1654 /* Require SSL, but server is too old */
1655 appendPQExpBuffer(&conn->errorMessage,
1656 libpq_gettext("server does not support SSL, but SSL was required\n"));
1659 /* Otherwise, try again without SSL */
1660 conn->allow_ssl_try = false;
1661 /* Assume it ain't gonna handle protocol 3, either */
1662 conn->pversion = PG_PROTOCOL(2, 0);
1663 /* Must drop the old connection */
1664 closesocket(conn->sock);
1666 conn->status = CONNECTION_NEEDED;
1671 appendPQExpBuffer(&conn->errorMessage,
1672 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1679 * Begin or continue the SSL negotiation process.
1681 pollres = pqsecure_open_client(conn);
1682 if (pollres == PGRES_POLLING_OK)
1684 /* SSL handshake done, ready to send startup packet */
1685 conn->status = CONNECTION_MADE;
1686 return PGRES_POLLING_WRITING;
1688 if (pollres == PGRES_POLLING_FAILED)
1691 * Failed ... if sslmode is "prefer" then do a non-SSL
1694 if (conn->sslmode[0] == 'p' /* "prefer" */
1695 && conn->allow_ssl_try /* redundant? */
1696 && !conn->wait_ssl_try) /* redundant? */
1698 /* only retry once */
1699 conn->allow_ssl_try = false;
1700 /* Must drop the old connection */
1701 closesocket(conn->sock);
1703 conn->status = CONNECTION_NEEDED;
1708 #else /* !USE_SSL */
1709 /* can't get here */
1711 #endif /* USE_SSL */
1715 * Handle authentication exchange: wait for postmaster messages
1716 * and respond as necessary.
1718 case CONNECTION_AWAITING_RESPONSE:
1726 * Scan the message from current point (note that if we find
1727 * the message is incomplete, we will return without advancing
1728 * inStart, and resume here next time).
1730 conn->inCursor = conn->inStart;
1732 /* Read type byte */
1733 if (pqGetc(&beresp, conn))
1735 /* We'll come back when there is more data */
1736 return PGRES_POLLING_READING;
1740 * Validate message type: we expect only an authentication
1741 * request or an error here. Anything else probably means
1742 * it's not Postgres on the other end at all.
1744 if (!(beresp == 'R' || beresp == 'E'))
1746 appendPQExpBuffer(&conn->errorMessage,
1748 "expected authentication request from "
1749 "server, but received %c\n"),
1754 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1756 /* Read message length word */
1757 if (pqGetInt(&msgLength, 4, conn))
1759 /* We'll come back when there is more data */
1760 return PGRES_POLLING_READING;
1765 /* Set phony message length to disable checks below */
1770 * Try to validate message length before using it.
1771 * Authentication requests can't be very large, although GSS
1772 * auth requests may not be that small. Errors can be a
1773 * little larger, but not huge. If we see a large apparent
1774 * length in an error, it means we're really talking to a
1775 * pre-3.0-protocol server; cope.
1777 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
1779 appendPQExpBuffer(&conn->errorMessage,
1781 "expected authentication request from "
1782 "server, but received %c\n"),
1787 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
1789 /* Handle error from a pre-3.0 server */
1790 conn->inCursor = conn->inStart + 1; /* reread data */
1791 if (pqGets_append(&conn->errorMessage, conn))
1793 /* We'll come back when there is more data */
1794 return PGRES_POLLING_READING;
1796 /* OK, we read the message; mark data consumed */
1797 conn->inStart = conn->inCursor;
1800 * The postmaster typically won't end its message with a
1801 * newline, so add one to conform to libpq conventions.
1803 appendPQExpBufferChar(&conn->errorMessage, '\n');
1806 * If we tried to open the connection in 3.0 protocol,
1807 * fall back to 2.0 protocol.
1809 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1811 conn->pversion = PG_PROTOCOL(2, 0);
1812 /* Must drop the old connection */
1813 pqsecure_close(conn);
1814 closesocket(conn->sock);
1816 conn->status = CONNECTION_NEEDED;
1824 * Can't process if message body isn't all here yet.
1826 * (In protocol 2.0 case, we are assuming messages carry at
1827 * least 4 bytes of data.)
1830 avail = conn->inEnd - conn->inCursor;
1831 if (avail < msgLength)
1834 * Before returning, try to enlarge the input buffer if
1835 * needed to hold the whole message; see notes in
1838 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1841 /* We'll come back when there is more data */
1842 return PGRES_POLLING_READING;
1845 /* Handle errors. */
1848 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1850 if (pqGetErrorNotice3(conn, true))
1852 /* We'll come back when there is more data */
1853 return PGRES_POLLING_READING;
1858 if (pqGets_append(&conn->errorMessage, conn))
1860 /* We'll come back when there is more data */
1861 return PGRES_POLLING_READING;
1864 /* OK, we read the message; mark data consumed */
1865 conn->inStart = conn->inCursor;
1870 * if sslmode is "allow" and we haven't tried an SSL
1871 * connection already, then retry with an SSL connection
1873 if (conn->sslmode[0] == 'a' /* "allow" */
1874 && conn->ssl == NULL
1875 && conn->allow_ssl_try
1876 && conn->wait_ssl_try)
1878 /* only retry once */
1879 conn->wait_ssl_try = false;
1880 /* Must drop the old connection */
1881 closesocket(conn->sock);
1883 conn->status = CONNECTION_NEEDED;
1888 * if sslmode is "prefer" and we're in an SSL connection,
1889 * then do a non-SSL retry
1891 if (conn->sslmode[0] == 'p' /* "prefer" */
1893 && conn->allow_ssl_try /* redundant? */
1894 && !conn->wait_ssl_try) /* redundant? */
1896 /* only retry once */
1897 conn->allow_ssl_try = false;
1898 /* Must drop the old connection */
1899 pqsecure_close(conn);
1900 closesocket(conn->sock);
1902 conn->status = CONNECTION_NEEDED;
1910 /* It is an authentication request. */
1911 /* Get the type of request. */
1912 if (pqGetInt((int *) &areq, 4, conn))
1914 /* We'll come back when there are more data */
1915 return PGRES_POLLING_READING;
1918 /* Get the password salt if there is one. */
1919 if (areq == AUTH_REQ_MD5)
1921 if (pqGetnchar(conn->md5Salt,
1922 sizeof(conn->md5Salt), conn))
1924 /* We'll come back when there are more data */
1925 return PGRES_POLLING_READING;
1928 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1931 * Continue GSSAPI/SSPI authentication
1933 if (areq == AUTH_REQ_GSS_CONT)
1935 int llen = msgLength - 4;
1938 * We can be called repeatedly for the same buffer. Avoid
1939 * re-allocating the buffer in this case - just re-use the
1942 if (llen != conn->ginbuf.length)
1944 if (conn->ginbuf.value)
1945 free(conn->ginbuf.value);
1947 conn->ginbuf.length = llen;
1948 conn->ginbuf.value = malloc(llen);
1949 if (!conn->ginbuf.value)
1951 printfPQExpBuffer(&conn->errorMessage,
1952 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1958 if (pqGetnchar(conn->ginbuf.value, llen, conn))
1960 /* We'll come back when there is more data. */
1961 return PGRES_POLLING_READING;
1967 * OK, we successfully read the message; mark data consumed
1969 conn->inStart = conn->inCursor;
1971 /* Respond to the request if necessary. */
1974 * Note that conn->pghost must be non-NULL if we are going to
1975 * avoid the Kerberos code doing a hostname look-up.
1978 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
1980 conn->errorMessage.len = strlen(conn->errorMessage.data);
1983 conn->errorMessage.len = strlen(conn->errorMessage.data);
1986 * Just make sure that any data sent by pg_fe_sendauth is
1987 * flushed out. Although this theoretically could block, it
1988 * really shouldn't since we don't send large auth responses.
1993 if (areq == AUTH_REQ_OK)
1995 /* We are done with authentication exchange */
1996 conn->status = CONNECTION_AUTH_OK;
1999 * Set asyncStatus so that PQsetResult will think that
2000 * what comes back next is the result of a query. See
2003 conn->asyncStatus = PGASYNC_BUSY;
2006 /* Look to see if we have more data yet. */
2010 case CONNECTION_AUTH_OK:
2013 * Now we expect to hear from the backend. A ReadyForQuery
2014 * message indicates that startup is successful, but we might
2015 * also get an Error message indicating failure. (Notice
2016 * messages indicating nonfatal warnings are also allowed by
2017 * the protocol, as are ParameterStatus and BackendKeyData
2018 * messages.) Easiest way to handle this is to let
2019 * PQgetResult() read the messages. We just have to fake it
2020 * out about the state of the connection, by setting
2021 * asyncStatus = PGASYNC_BUSY (done above).
2025 return PGRES_POLLING_READING;
2027 res = PQgetResult(conn);
2030 * NULL return indicating we have gone to IDLE state is
2035 if (res->resultStatus != PGRES_FATAL_ERROR)
2036 appendPQExpBuffer(&conn->errorMessage,
2037 libpq_gettext("unexpected message from server during startup\n"));
2038 else if (conn->send_appname &&
2039 (conn->appname || conn->fbappname))
2042 * If we tried to send application_name, check to see
2043 * if the error is about that --- pre-9.0 servers will
2044 * reject it at this stage of the process. If so,
2045 * close the connection and retry without sending
2046 * application_name. We could possibly get a false
2047 * SQLSTATE match here and retry uselessly, but there
2048 * seems no great harm in that; we'll just get the
2049 * same error again if it's unrelated.
2051 const char *sqlstate;
2053 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2055 strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2058 conn->send_appname = false;
2059 /* Must drop the old connection */
2060 pqsecure_close(conn);
2061 closesocket(conn->sock);
2063 conn->status = CONNECTION_NEEDED;
2069 * if the resultStatus is FATAL, then conn->errorMessage
2070 * already has a copy of the error; needn't copy it back.
2071 * But add a newline if it's not there already, since
2072 * postmaster error messages may not have one.
2074 if (conn->errorMessage.len <= 0 ||
2075 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2076 appendPQExpBufferChar(&conn->errorMessage, '\n');
2081 /* We can release the address list now. */
2082 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2083 conn->addrlist = NULL;
2084 conn->addr_cur = NULL;
2086 /* Fire up post-connection housekeeping if needed */
2087 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2089 conn->status = CONNECTION_SETENV;
2090 conn->setenv_state = SETENV_STATE_OPTION_SEND;
2091 conn->next_eo = EnvironmentOptions;
2092 return PGRES_POLLING_WRITING;
2095 /* Otherwise, we are open for business! */
2096 conn->status = CONNECTION_OK;
2097 return PGRES_POLLING_OK;
2100 case CONNECTION_SETENV:
2103 * Do post-connection housekeeping (only needed in protocol 2.0).
2105 * We pretend that the connection is OK for the duration of these
2108 conn->status = CONNECTION_OK;
2110 switch (pqSetenvPoll(conn))
2112 case PGRES_POLLING_OK: /* Success */
2115 case PGRES_POLLING_READING: /* Still going */
2116 conn->status = CONNECTION_SETENV;
2117 return PGRES_POLLING_READING;
2119 case PGRES_POLLING_WRITING: /* Still going */
2120 conn->status = CONNECTION_SETENV;
2121 return PGRES_POLLING_WRITING;
2127 /* We are open for business! */
2128 conn->status = CONNECTION_OK;
2129 return PGRES_POLLING_OK;
2132 appendPQExpBuffer(&conn->errorMessage,
2133 libpq_gettext("invalid connection state %d, "
2134 "probably indicative of memory corruption\n"),
2143 dot_pg_pass_warning(conn);
2146 * We used to close the socket at this point, but that makes it awkward
2147 * for those above us if they wish to remove this socket from their own
2148 * records (an fd_set for example). We'll just have this socket closed
2149 * when PQfinish is called (which is compulsory even after an error, since
2150 * the connection structure must be freed).
2152 conn->status = CONNECTION_BAD;
2153 return PGRES_POLLING_FAILED;
2159 * - create a PGconn data structure with (as yet) no interesting data
2162 makeEmptyPGconn(void)
2169 * Make sure socket support is up and running.
2173 if (WSAStartup(MAKEWORD(1, 1), &wsaData))
2178 conn = (PGconn *) malloc(sizeof(PGconn));
2187 /* Zero all pointers and booleans */
2188 MemSet(conn, 0, sizeof(PGconn));
2190 conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2191 conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2192 conn->status = CONNECTION_BAD;
2193 conn->asyncStatus = PGASYNC_IDLE;
2194 conn->xactStatus = PQTRANS_IDLE;
2195 conn->options_valid = false;
2196 conn->nonblocking = false;
2197 conn->setenv_state = SETENV_STATE_IDLE;
2198 conn->client_encoding = PG_SQL_ASCII;
2199 conn->std_strings = false; /* unless server says differently */
2200 conn->verbosity = PQERRORS_DEFAULT;
2202 conn->password_needed = false;
2203 conn->dot_pgpass_used = false;
2205 conn->allow_ssl_try = true;
2206 conn->wait_ssl_try = false;
2210 * We try to send at least 8K at a time, which is the usual size of pipe
2211 * buffers on Unix systems. That way, when we are sending a large amount
2212 * of data, we avoid incurring extra kernel context swaps for partial
2213 * bufferloads. The output buffer is initially made 16K in size, and we
2214 * try to dump it after accumulating 8K.
2216 * With the same goal of minimizing context swaps, the input buffer will
2217 * be enlarged anytime it has less than 8K free, so we initially allocate
2220 conn->inBufSize = 16 * 1024;
2221 conn->inBuffer = (char *) malloc(conn->inBufSize);
2222 conn->outBufSize = 16 * 1024;
2223 conn->outBuffer = (char *) malloc(conn->outBufSize);
2224 initPQExpBuffer(&conn->errorMessage);
2225 initPQExpBuffer(&conn->workBuffer);
2227 if (conn->inBuffer == NULL ||
2228 conn->outBuffer == NULL ||
2229 PQExpBufferBroken(&conn->errorMessage) ||
2230 PQExpBufferBroken(&conn->workBuffer))
2232 /* out of memory already :-( */
2242 * - free an idle (closed) PGconn data structure
2244 * NOTE: this should not overlap any functionality with closePGconn().
2245 * Clearing/resetting of transient state belongs there; what we do here is
2246 * release data that is to be held for the life of the PGconn structure.
2247 * If a value ought to be cleared/freed during PQreset(), do it there not here.
2250 freePGconn(PGconn *conn)
2254 /* let any event procs clean up their state data */
2255 for (i = 0; i < conn->nEvents; i++)
2257 PGEventConnDestroy evt;
2260 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2261 conn->events[i].passThrough);
2262 free(conn->events[i].name);
2269 if (conn->pghostaddr)
2270 free(conn->pghostaddr);
2273 if (conn->pgunixsocket)
2274 free(conn->pgunixsocket);
2277 if (conn->connect_timeout)
2278 free(conn->connect_timeout);
2279 if (conn->pgoptions)
2280 free(conn->pgoptions);
2282 free(conn->appname);
2283 if (conn->fbappname)
2284 free(conn->fbappname);
2287 if (conn->replication)
2288 free(conn->replication);
2294 free(conn->sslmode);
2296 free(conn->sslcert);
2299 if (conn->sslrootcert)
2300 free(conn->sslrootcert);
2303 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2304 if (conn->krbsrvname)
2305 free(conn->krbsrvname);
2307 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2311 /* Note that conn->Pfdebug is not ours to close or free */
2312 if (conn->last_query)
2313 free(conn->last_query);
2315 free(conn->inBuffer);
2316 if (conn->outBuffer)
2317 free(conn->outBuffer);
2318 termPQExpBuffer(&conn->errorMessage);
2319 termPQExpBuffer(&conn->workBuffer);
2330 * - properly close a connection to the backend
2332 * This should reset or release all transient state, but NOT the connection
2333 * parameters. On exit, the PGconn should be in condition to start a fresh
2334 * connection with the same parameters (see PQreset()).
2337 closePGconn(PGconn *conn)
2340 pgParameterStatus *pstatus;
2343 * Note that the protocol doesn't allow us to send Terminate messages
2344 * during the startup phase.
2346 if (conn->sock >= 0 && conn->status == CONNECTION_OK)
2349 * Try to send "close connection" message to backend. Ignore any
2352 pqPutMsgStart('X', false, conn);
2358 * Must reset the blocking status so a possible reconnect will work.
2360 * Don't call PQsetnonblocking() because it will fail if it's unable to
2361 * flush the connection.
2363 conn->nonblocking = FALSE;
2366 * Close the connection, reset all transient state, flush I/O buffers.
2368 if (conn->sock >= 0)
2370 pqsecure_close(conn);
2371 closesocket(conn->sock);
2374 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
2376 conn->asyncStatus = PGASYNC_IDLE;
2377 pqClearAsyncResult(conn); /* deallocate result and curTuple */
2378 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2379 conn->addrlist = NULL;
2380 conn->addr_cur = NULL;
2381 notify = conn->notifyHead;
2382 while (notify != NULL)
2384 PGnotify *prev = notify;
2386 notify = notify->next;
2389 conn->notifyHead = conn->notifyTail = NULL;
2390 pstatus = conn->pstatus;
2391 while (pstatus != NULL)
2393 pgParameterStatus *prev = pstatus;
2395 pstatus = pstatus->next;
2398 conn->pstatus = NULL;
2399 if (conn->lobjfuncs)
2400 free(conn->lobjfuncs);
2401 conn->lobjfuncs = NULL;
2402 conn->inStart = conn->inCursor = conn->inEnd = 0;
2409 gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2410 if (conn->gtarg_nam)
2411 gss_release_name(&min_s, &conn->gtarg_nam);
2412 if (conn->ginbuf.length)
2413 gss_release_buffer(&min_s, &conn->ginbuf);
2414 if (conn->goutbuf.length)
2415 gss_release_buffer(&min_s, &conn->goutbuf);
2419 if (conn->ginbuf.length)
2420 free(conn->ginbuf.value);
2421 conn->ginbuf.length = 0;
2422 conn->ginbuf.value = NULL;
2423 if (conn->sspitarget)
2424 free(conn->sspitarget);
2425 conn->sspitarget = NULL;
2428 FreeCredentialsHandle(conn->sspicred);
2429 free(conn->sspicred);
2430 conn->sspicred = NULL;
2434 DeleteSecurityContext(conn->sspictx);
2435 free(conn->sspictx);
2436 conn->sspictx = NULL;
2442 * PQfinish: properly close a connection to the backend. Also frees
2443 * the PGconn data structure so it shouldn't be re-used after this.
2446 PQfinish(PGconn *conn)
2456 * PQreset: resets the connection to the backend by closing the
2457 * existing connection and creating a new one.
2460 PQreset(PGconn *conn)
2466 if (connectDBStart(conn) && connectDBComplete(conn))
2469 * Notify event procs of successful reset. We treat an event proc
2470 * failure as disabling the connection ... good idea?
2474 for (i = 0; i < conn->nEvents; i++)
2476 PGEventConnReset evt;
2479 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2480 conn->events[i].passThrough))
2482 conn->status = CONNECTION_BAD;
2483 printfPQExpBuffer(&conn->errorMessage,
2484 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2485 conn->events[i].name);
2496 * resets the connection to the backend
2497 * closes the existing connection and makes a new one
2498 * Returns 1 on success, 0 on failure.
2501 PQresetStart(PGconn *conn)
2507 return connectDBStart(conn);
2516 * resets the connection to the backend
2517 * closes the existing connection and makes a new one
2519 PostgresPollingStatusType
2520 PQresetPoll(PGconn *conn)
2524 PostgresPollingStatusType status = PQconnectPoll(conn);
2526 if (status == PGRES_POLLING_OK)
2529 * Notify event procs of successful reset. We treat an event proc
2530 * failure as disabling the connection ... good idea?
2534 for (i = 0; i < conn->nEvents; i++)
2536 PGEventConnReset evt;
2539 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2540 conn->events[i].passThrough))
2542 conn->status = CONNECTION_BAD;
2543 printfPQExpBuffer(&conn->errorMessage,
2544 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2545 conn->events[i].name);
2546 return PGRES_POLLING_FAILED;
2554 return PGRES_POLLING_FAILED;
2558 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2560 * A copy is needed to be able to cancel a running query from a different
2561 * thread. If the same structure is used all structure members would have
2562 * to be individually locked (if the entire structure was locked, it would
2563 * be impossible to cancel a synchronous query because the structure would
2564 * have to stay locked for the duration of the query).
2567 PQgetCancel(PGconn *conn)
2577 cancel = malloc(sizeof(PGcancel));
2581 memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
2582 cancel->be_pid = conn->be_pid;
2583 cancel->be_key = conn->be_key;
2588 /* PQfreeCancel: free a cancel structure */
2590 PQfreeCancel(PGcancel *cancel)
2598 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2599 * current operation.
2601 * The return value is TRUE if the cancel request was successfully
2602 * dispatched, FALSE if not (in which case an error message is available).
2603 * Note: successful dispatch is no guarantee that there will be any effect at
2604 * the backend. The application must read the operation result as usual.
2606 * CAUTION: we want this routine to be safely callable from a signal handler
2607 * (for example, an application might want to call it in a SIGINT handler).
2608 * This means we cannot use any C library routine that might be non-reentrant.
2609 * malloc/free are often non-reentrant, and anything that might call them is
2610 * just as dangerous. We avoid sprintf here for that reason. Building up
2611 * error messages with strcpy/strcat is tedious but should be quite safe.
2612 * We also save/restore errno in case the signal handler support doesn't.
2614 * internal_cancel() is an internal helper function to make code-sharing
2615 * between the two versions of the cancel function possible.
2618 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
2619 char *errbuf, int errbufsize)
2621 int save_errno = SOCK_ERRNO;
2628 CancelRequestPacket cp;
2632 * We need to open a temporary connection to the postmaster. Do this with
2633 * only kernel calls.
2635 if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) < 0)
2637 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
2638 goto cancel_errReturn;
2641 if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
2644 if (SOCK_ERRNO == EINTR)
2645 /* Interrupted system call - we'll just try again */
2647 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
2648 goto cancel_errReturn;
2652 * We needn't set nonblocking I/O or NODELAY options here.
2655 /* Create and send the cancel request packet. */
2657 crp.packetlen = htonl((uint32) sizeof(crp));
2658 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2659 crp.cp.backendPID = htonl(be_pid);
2660 crp.cp.cancelAuthCode = htonl(be_key);
2663 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2665 if (SOCK_ERRNO == EINTR)
2666 /* Interrupted system call - we'll just try again */
2668 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
2669 goto cancel_errReturn;
2673 * Wait for the postmaster to close the connection, which indicates that
2674 * it's processed the request. Without this delay, we might issue another
2675 * command only to find that our cancel zaps that command instead of the
2676 * one we thought we were canceling. Note we don't actually expect this
2677 * read to obtain any data, we are just waiting for EOF to be signaled.
2680 if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
2682 if (SOCK_ERRNO == EINTR)
2683 /* Interrupted system call - we'll just try again */
2685 /* we ignore other error conditions */
2689 closesocket(tmpsock);
2690 SOCK_ERRNO_SET(save_errno);
2696 * Make sure we don't overflow the error buffer. Leave space for the \n at
2697 * the end, and for the terminating zero.
2699 maxlen = errbufsize - strlen(errbuf) - 2;
2702 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
2704 strcat(errbuf, "\n");
2707 closesocket(tmpsock);
2708 SOCK_ERRNO_SET(save_errno);
2713 * PQcancel: request query cancel
2715 * Returns TRUE if able to send the cancel request, FALSE if not.
2717 * On failure, an error message is stored in *errbuf, which must be of size
2718 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2722 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
2726 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
2730 return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
2731 errbuf, errbufsize);
2735 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2737 * Returns TRUE if able to send the cancel request, FALSE if not.
2739 * On failure, the error message is saved in conn->errorMessage; this means
2740 * that this can't be used when there might be other active operations on
2741 * the connection object.
2743 * NOTE: error messages will be cut off at the current size of the
2744 * error message buffer, since we dare not try to expand conn->errorMessage!
2747 PQrequestCancel(PGconn *conn)
2751 /* Check we have an open connection */
2757 strlcpy(conn->errorMessage.data,
2758 "PQrequestCancel() -- connection is not open\n",
2759 conn->errorMessage.maxlen);
2760 conn->errorMessage.len = strlen(conn->errorMessage.data);
2765 r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
2766 conn->errorMessage.data, conn->errorMessage.maxlen);
2769 conn->errorMessage.len = strlen(conn->errorMessage.data);
2776 * pqPacketSend() -- convenience routine to send a message to server.
2778 * pack_type: the single-byte message type code. (Pass zero for startup
2779 * packets, which have no message type code.)
2781 * buf, buf_len: contents of message. The given length includes only what
2782 * is in buf; the message type and message length fields are added here.
2784 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2785 * SIDE_EFFECTS: may block.
2787 * Note: all messages sent with this routine have a length word, whether
2788 * it's protocol 2.0 or 3.0.
2791 pqPacketSend(PGconn *conn, char pack_type,
2792 const void *buf, size_t buf_len)
2794 /* Start the message. */
2795 if (pqPutMsgStart(pack_type, true, conn))
2796 return STATUS_ERROR;
2798 /* Send the message body. */
2799 if (pqPutnchar(buf, buf_len, conn))
2800 return STATUS_ERROR;
2802 /* Finish the message. */
2803 if (pqPutMsgEnd(conn))
2804 return STATUS_ERROR;
2806 /* Flush to ensure backend gets it. */
2808 return STATUS_ERROR;
2815 #define LDAP_URL "ldap://"
2816 #define LDAP_DEF_PORT 389
2817 #define PGLDAP_TIMEOUT 2
2819 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2820 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2826 * Search the LDAP URL passed as first argument, treat the result as a
2827 * string of connection options that are parsed and added to the array of
2828 * options passed as second argument.
2830 * LDAP URLs must conform to RFC 1959 without escape sequences.
2831 * ldap://host:port/dn?attributes?scope?filter?extensions
2834 * 0 if the lookup was successful,
2835 * 1 if the connection to the LDAP server could be established but
2836 * the search was unsuccessful,
2837 * 2 if a connection could not be established, and
2838 * 3 if a fatal error occurred.
2840 * An error message is returned in the third argument for return codes 1 and 3.
2843 ldapServiceLookup(const char *purl, PQconninfoOption *options,
2844 PQExpBuffer errorMessage)
2846 int port = LDAP_DEF_PORT,
2867 char *attrs[2] = {NULL, NULL};
2871 struct berval **values;
2872 LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
2874 if ((url = strdup(purl)) == NULL)
2876 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
2881 * Parse URL components, check for correctness. Basically, url has '\0'
2882 * placed at component boundaries and variables are pointed at each
2886 if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
2888 printfPQExpBuffer(errorMessage,
2889 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
2895 hostname = url + strlen(LDAP_URL);
2896 if (*hostname == '/') /* no hostname? */
2897 hostname = "localhost"; /* the default */
2899 /* dn, "distinguished name" */
2900 p = strchr(url + strlen(LDAP_URL), '/');
2901 if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2903 printfPQExpBuffer(errorMessage, libpq_gettext(
2904 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
2908 *p = '\0'; /* terminate hostname */
2912 if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2914 printfPQExpBuffer(errorMessage, libpq_gettext(
2915 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2923 if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2925 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2933 if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
2935 printfPQExpBuffer(errorMessage,
2936 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
2942 if ((p = strchr(filter, '?')) != NULL)
2946 if ((p1 = strchr(hostname, ':')) != NULL)
2953 lport = strtol(portstr, &endptr, 10);
2954 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
2956 printfPQExpBuffer(errorMessage, libpq_gettext(
2957 "invalid LDAP URL \"%s\": invalid port number\n"), purl);
2964 /* Allow only one attribute */
2965 if (strchr(attrs[0], ',') != NULL)
2967 printfPQExpBuffer(errorMessage, libpq_gettext(
2968 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
2974 if (pg_strcasecmp(scopestr, "base") == 0)
2975 scope = LDAP_SCOPE_BASE;
2976 else if (pg_strcasecmp(scopestr, "one") == 0)
2977 scope = LDAP_SCOPE_ONELEVEL;
2978 else if (pg_strcasecmp(scopestr, "sub") == 0)
2979 scope = LDAP_SCOPE_SUBTREE;
2982 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
2987 /* initialize LDAP structure */
2988 if ((ld = ldap_init(hostname, port)) == NULL)
2990 printfPQExpBuffer(errorMessage,
2991 libpq_gettext("could not create LDAP structure\n"));
2997 * Initialize connection to the server. We do an explicit bind because we
2998 * want to return 2 if the bind fails.
3000 if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3002 /* error in ldap_simple_bind() */
3008 /* wait some time for the connection to succeed */
3010 if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3018 /* error in ldap_result() */
3027 if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3032 printfPQExpBuffer(errorMessage,
3033 libpq_gettext("lookup on LDAP server failed: %s\n"),
3034 ldap_err2string(rc));
3040 /* complain if there was not exactly one result */
3041 if ((rc = ldap_count_entries(ld, res)) != 1)
3043 printfPQExpBuffer(errorMessage,
3044 rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3045 : libpq_gettext("no entry found on LDAP lookup\n"));
3053 if ((entry = ldap_first_entry(ld, res)) == NULL)
3055 /* should never happen */
3056 printfPQExpBuffer(errorMessage,
3057 libpq_gettext("no entry found on LDAP lookup\n"));
3065 if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3067 printfPQExpBuffer(errorMessage,
3068 libpq_gettext("attribute has no values on LDAP lookup\n"));
3078 if (values[0] == NULL)
3080 printfPQExpBuffer(errorMessage,
3081 libpq_gettext("attribute has no values on LDAP lookup\n"));
3082 ldap_value_free_len(values);
3087 /* concatenate values to a single string */
3088 for (size = 0, i = 0; values[i] != NULL; ++i)
3089 size += values[i]->bv_len + 1;
3090 if ((result = malloc(size + 1)) == NULL)
3092 printfPQExpBuffer(errorMessage,
3093 libpq_gettext("out of memory\n"));
3094 ldap_value_free_len(values);
3098 for (p = result, i = 0; values[i] != NULL; ++i)
3100 strncpy(p, values[i]->bv_val, values[i]->bv_len);
3101 p += values[i]->bv_len;
3103 if (values[i + 1] == NULL)
3107 ldap_value_free_len(values);
3110 /* parse result string */
3111 oldstate = state = 0;
3112 for (p = result; *p != '\0'; ++p)
3116 case 0: /* between entries */
3117 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3123 case 1: /* in option name */
3124 if (ld_is_sp_tab(*p))
3129 else if (ld_is_nl_cr(*p))
3131 printfPQExpBuffer(errorMessage, libpq_gettext(
3132 "missing \"=\" after \"%s\" in connection info string\n"),
3142 case 2: /* after option name */
3147 else if (!ld_is_sp_tab(*p))
3149 printfPQExpBuffer(errorMessage, libpq_gettext(
3150 "missing \"=\" after \"%s\" in connection info string\n"),
3155 case 3: /* before option value */
3162 else if (ld_is_nl_cr(*p))
3164 optval = optname + strlen(optname); /* empty */
3167 else if (!ld_is_sp_tab(*p))
3173 case 4: /* in unquoted option value */
3174 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3180 case 5: /* in quoted option value */
3186 else if (*p == '\\')
3191 case 6: /* in quoted option value after escape */
3197 if (state == 0 && oldstate != 0)
3199 found_keyword = false;
3200 for (i = 0; options[i].keyword; i++)
3202 if (strcmp(options[i].keyword, optname) == 0)
3204 if (options[i].val == NULL)
3205 options[i].val = strdup(optval);
3206 found_keyword = true;
3212 printfPQExpBuffer(errorMessage,
3213 libpq_gettext("invalid connection option \"%s\"\n"),
3223 if (state == 5 || state == 6)
3225 printfPQExpBuffer(errorMessage, libpq_gettext(
3226 "unterminated quoted string in connection info string\n"));
3234 #define MAXBUFSIZE 256
3237 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3239 char *service = conninfo_getval(options, "service");
3240 char serviceFile[MAXPGPATH];
3242 bool group_found = false;
3244 struct stat stat_buf;
3247 * We have to special-case the environment variable PGSERVICE here, since
3248 * this is and should be called before inserting environment defaults for
3249 * other connection options.
3251 if (service == NULL)
3252 service = getenv("PGSERVICE");
3254 if (service == NULL)
3257 if ((env = getenv("PGSERVICEFILE")) != NULL)
3258 strlcpy(serviceFile, env, sizeof(serviceFile));
3261 char homedir[MAXPGPATH];
3263 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3265 printfPQExpBuffer(errorMessage, libpq_gettext("could not get home directory to locate service definition file"));
3268 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
3270 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3274 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3275 if (group_found || status != 0)
3281 * This could be used by any application so we can't use the binary
3282 * location to find our config files.
3284 snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3285 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3287 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3290 status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3297 printfPQExpBuffer(errorMessage,
3298 libpq_gettext("definition of service \"%s\" not found\n"), service);
3306 parseServiceFile(const char *serviceFile,
3307 const char *service,
3308 PQconninfoOption *options,
3309 PQExpBuffer errorMessage,
3315 char buf[MAXBUFSIZE],
3318 f = fopen(serviceFile, "r");
3321 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3326 while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3330 if (strlen(line) >= sizeof(buf) - 1)
3333 printfPQExpBuffer(errorMessage,
3334 libpq_gettext("line %d too long in service file \"%s\"\n"),
3340 /* ignore EOL at end of line */
3341 if (strlen(line) && line[strlen(line) - 1] == '\n')
3342 line[strlen(line) - 1] = 0;
3344 /* ignore leading blanks */
3345 while (*line && isspace((unsigned char) line[0]))
3348 /* ignore comments and empty lines */
3349 if (strlen(line) == 0 || line[0] == '#')
3352 /* Check for right groupname */
3357 /* group info already read */
3362 if (strncmp(line + 1, service, strlen(service)) == 0 &&
3363 line[strlen(service) + 1] == ']')
3364 *group_found = true;
3366 *group_found = false;
3373 * Finally, we are in the right group and can parse the line
3380 if (strncmp(line, "ldap", 4) == 0)
3382 int rc = ldapServiceLookup(line, options, errorMessage);
3384 /* if rc = 2, go on reading for fallback */
3401 val = strchr(line, '=');
3404 printfPQExpBuffer(errorMessage,
3405 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3414 * Set the parameter --- but don't override any previous
3417 found_keyword = false;
3418 for (i = 0; options[i].keyword; i++)
3420 if (strcmp(options[i].keyword, key) == 0)
3422 if (options[i].val == NULL)
3423 options[i].val = strdup(val);
3424 found_keyword = true;
3431 printfPQExpBuffer(errorMessage,
3432 libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3451 * Parse a string like PQconnectdb() would do and return the
3452 * resulting connection options array. NULL is returned on failure.
3453 * The result contains only options specified directly in the string,
3454 * not any possible default values.
3456 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3457 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3458 * both *errmsg and the result could be NULL.
3460 * NOTE: the returned array is dynamically allocated and should
3461 * be freed when no longer needed via PQconninfoFree().
3464 PQconninfoParse(const char *conninfo, char **errmsg)
3466 PQExpBufferData errorBuf;
3467 PQconninfoOption *connOptions;
3470 *errmsg = NULL; /* default */
3471 initPQExpBuffer(&errorBuf);
3472 if (PQExpBufferBroken(&errorBuf))
3473 return NULL; /* out of memory already :-( */
3474 connOptions = conninfo_parse(conninfo, &errorBuf, false);
3475 if (connOptions == NULL && errmsg)
3476 *errmsg = errorBuf.data;
3478 termPQExpBuffer(&errorBuf);
3483 * Conninfo parser routine
3485 * If successful, a malloc'd PQconninfoOption array is returned.
3486 * If not successful, NULL is returned and an error message is
3487 * left in errorMessage.
3488 * Defaults are supplied (from a service file, environment variables, etc)
3489 * for unspecified options, but only if use_defaults is TRUE.
3491 static PQconninfoOption *
3492 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
3501 PQconninfoOption *options;
3502 PQconninfoOption *option;
3504 /* Make a working copy of PQconninfoOptions */
3505 options = malloc(sizeof(PQconninfoOptions));
3506 if (options == NULL)
3508 printfPQExpBuffer(errorMessage,
3509 libpq_gettext("out of memory\n"));
3512 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3514 /* Need a modifiable copy of the input string */
3515 if ((buf = strdup(conninfo)) == NULL)
3517 printfPQExpBuffer(errorMessage,
3518 libpq_gettext("out of memory\n"));
3519 PQconninfoFree(options);
3526 /* Skip blanks before the parameter name */
3527 if (isspace((unsigned char) *cp))
3533 /* Get the parameter name */
3539 if (isspace((unsigned char) *cp))
3544 if (!isspace((unsigned char) *cp))
3553 /* Check that there is a following '=' */
3556 printfPQExpBuffer(errorMessage,
3557 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3559 PQconninfoFree(options);
3565 /* Skip blanks after the '=' */
3568 if (!isspace((unsigned char) *cp))
3573 /* Get the parameter value */
3581 if (isspace((unsigned char) *cp))
3605 printfPQExpBuffer(errorMessage,
3606 libpq_gettext("unterminated quoted string in connection info string\n"));
3607 PQconninfoFree(options);
3629 * Now we have the name and the value. Search for the param record.
3631 for (option = options; option->keyword != NULL; option++)
3633 if (strcmp(option->keyword, pname) == 0)
3636 if (option->keyword == NULL)
3638 printfPQExpBuffer(errorMessage,
3639 libpq_gettext("invalid connection option \"%s\"\n"),
3641 PQconninfoFree(options);
3651 option->val = strdup(pval);
3654 printfPQExpBuffer(errorMessage,
3655 libpq_gettext("out of memory\n"));
3656 PQconninfoFree(options);
3662 /* Done with the modifiable input string */
3666 * Stop here if caller doesn't want defaults filled in.
3672 * If there's a service spec, use it to obtain any not-explicitly-given
3675 if (parseServiceInfo(options, errorMessage))
3677 PQconninfoFree(options);
3682 * Get the fallback resources for parameters not specified in the conninfo
3683 * string nor the service.
3685 for (option = options; option->keyword != NULL; option++)
3687 if (option->val != NULL)
3688 continue; /* Value was in conninfo or service */
3691 * Try to get the environment variable fallback
3693 if (option->envvar != NULL)
3695 if ((tmp = getenv(option->envvar)) != NULL)
3697 option->val = strdup(tmp);
3700 printfPQExpBuffer(errorMessage,
3701 libpq_gettext("out of memory\n"));
3702 PQconninfoFree(options);
3710 * No environment variable specified or this one isn't set - try
3713 if (option->compiled != NULL)
3715 option->val = strdup(option->compiled);
3718 printfPQExpBuffer(errorMessage,
3719 libpq_gettext("out of memory\n"));
3720 PQconninfoFree(options);
3727 * Special handling for user
3729 if (strcmp(option->keyword, "user") == 0)
3731 option->val = pg_fe_getauthname(errorMessage);
3740 * Conninfo array parser routine
3742 * If successful, a malloc'd PQconninfoOption array is returned.
3743 * If not successful, NULL is returned and an error message is
3744 * left in errorMessage.
3745 * Defaults are supplied (from a service file, environment variables, etc)
3746 * for unspecified options, but only if use_defaults is TRUE.
3748 * If expand_dbname is non-zero, and the value passed for keyword "dbname"
3749 * contains an "=", assume it is a conninfo string and process it,
3750 * overriding any previously processed conflicting keywords. Subsequent
3751 * keywords will take precedence, however.
3753 static PQconninfoOption *
3754 conninfo_array_parse(const char **keywords, const char **values,
3755 PQExpBuffer errorMessage, bool use_defaults,
3759 PQconninfoOption *options;
3760 PQconninfoOption *str_options = NULL;
3761 PQconninfoOption *option;
3765 * If expand_dbname is non-zero, check keyword "dbname" to see if val is
3766 * actually a conninfo string
3768 while (expand_dbname && keywords[i])
3770 const char *pname = keywords[i];
3771 const char *pvalue = values[i];
3773 /* first find "dbname" if any */
3774 if (strcmp(pname, "dbname") == 0)
3776 /* next look for "=" in the value */
3777 if (pvalue && strchr(pvalue, '='))
3780 * Must be a conninfo string, so parse it, but do not use
3781 * defaults here -- those get picked up later. We only want to
3782 * override for those parameters actually passed.
3784 str_options = conninfo_parse(pvalue, errorMessage, false);
3785 if (str_options == NULL)
3793 /* Make a working copy of PQconninfoOptions */
3794 options = malloc(sizeof(PQconninfoOptions));
3795 if (options == NULL)
3797 printfPQExpBuffer(errorMessage,
3798 libpq_gettext("out of memory\n"));
3801 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
3804 /* Parse the keywords/values arrays */
3807 const char *pname = keywords[i];
3808 const char *pvalue = values[i];
3812 /* Search for the param record */
3813 for (option = options; option->keyword != NULL; option++)
3815 if (strcmp(option->keyword, pname) == 0)
3819 /* Check for invalid connection option */
3820 if (option->keyword == NULL)
3822 printfPQExpBuffer(errorMessage,
3823 libpq_gettext("invalid connection option \"%s\"\n"),
3825 PQconninfoFree(options);
3830 * If we are on the dbname parameter, and we have a parsed
3831 * conninfo string, copy those parameters across, overriding any
3832 * existing previous settings
3834 if (strcmp(pname, "dbname") == 0 && str_options)
3836 PQconninfoOption *str_option;
3838 for (str_option = str_options; str_option->keyword != NULL; str_option++)
3840 if (str_option->val != NULL)
3844 for (k = 0; options[k].keyword; k++)
3846 if (strcmp(options[k].keyword, str_option->keyword) == 0)
3849 free(options[k].val);
3850 options[k].val = strdup(str_option->val);
3860 * Store the value, overriding previous settings
3864 option->val = strdup(pvalue);
3867 printfPQExpBuffer(errorMessage,
3868 libpq_gettext("out of memory\n"));
3869 PQconninfoFree(options);
3876 PQconninfoFree(str_options);
3879 * Stop here if caller doesn't want defaults filled in.
3885 * If there's a service spec, use it to obtain any not-explicitly-given
3888 if (parseServiceInfo(options, errorMessage))
3890 PQconninfoFree(options);
3895 * Get the fallback resources for parameters not specified in the conninfo
3896 * string nor the service.
3898 for (option = options; option->keyword != NULL; option++)
3900 if (option->val != NULL)
3901 continue; /* Value was in conninfo or service */
3904 * Try to get the environment variable fallback
3906 if (option->envvar != NULL)
3908 if ((tmp = getenv(option->envvar)) != NULL)
3910 option->val = strdup(tmp);
3913 printfPQExpBuffer(errorMessage,
3914 libpq_gettext("out of memory\n"));
3915 PQconninfoFree(options);
3923 * No environment variable specified or this one isn't set - try
3926 if (option->compiled != NULL)
3928 option->val = strdup(option->compiled);
3931 printfPQExpBuffer(errorMessage,
3932 libpq_gettext("out of memory\n"));
3933 PQconninfoFree(options);
3940 * Special handling for user
3942 if (strcmp(option->keyword, "user") == 0)
3944 option->val = pg_fe_getauthname(errorMessage);
3953 conninfo_getval(PQconninfoOption *connOptions,
3954 const char *keyword)
3956 PQconninfoOption *option;
3958 for (option = connOptions; option->keyword != NULL; option++)
3960 if (strcmp(option->keyword, keyword) == 0)
3969 PQconninfoFree(PQconninfoOption *connOptions)
3971 PQconninfoOption *option;
3973 if (connOptions == NULL)
3976 for (option = connOptions; option->keyword != NULL; option++)
3978 if (option->val != NULL)
3985 /* =========== accessor functions for PGconn ========= */
3987 PQdb(const PGconn *conn)
3991 return conn->dbName;
3995 PQuser(const PGconn *conn)
3999 return conn->pguser;
4003 PQpass(const PGconn *conn)
4007 return conn->pgpass;
4011 PQhost(const PGconn *conn)
4015 return conn->pghost ? conn->pghost : conn->pgunixsocket;
4019 PQport(const PGconn *conn)
4023 return conn->pgport;
4027 PQtty(const PGconn *conn)
4035 PQoptions(const PGconn *conn)
4039 return conn->pgoptions;
4043 PQstatus(const PGconn *conn)
4046 return CONNECTION_BAD;
4047 return conn->status;
4050 PGTransactionStatusType
4051 PQtransactionStatus(const PGconn *conn)
4053 if (!conn || conn->status != CONNECTION_OK)
4054 return PQTRANS_UNKNOWN;
4055 if (conn->asyncStatus != PGASYNC_IDLE)
4056 return PQTRANS_ACTIVE;
4057 return conn->xactStatus;
4061 PQparameterStatus(const PGconn *conn, const char *paramName)
4063 const pgParameterStatus *pstatus;
4065 if (!conn || !paramName)
4067 for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
4069 if (strcmp(pstatus->name, paramName) == 0)
4070 return pstatus->value;
4076 PQprotocolVersion(const PGconn *conn)
4080 if (conn->status == CONNECTION_BAD)
4082 return PG_PROTOCOL_MAJOR(conn->pversion);
4086 PQserverVersion(const PGconn *conn)
4090 if (conn->status == CONNECTION_BAD)
4092 return conn->sversion;
4096 PQerrorMessage(const PGconn *conn)
4099 return libpq_gettext("connection pointer is NULL\n");
4101 return conn->errorMessage.data;
4105 PQsocket(const PGconn *conn)
4113 PQbackendPID(const PGconn *conn)
4115 if (!conn || conn->status != CONNECTION_OK)
4117 return conn->be_pid;
4121 PQconnectionNeedsPassword(const PGconn *conn)
4125 if (conn->password_needed &&
4126 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
4133 PQconnectionUsedPassword(const PGconn *conn)
4137 if (conn->password_needed)
4144 PQclientEncoding(const PGconn *conn)
4146 if (!conn || conn->status != CONNECTION_OK)
4148 return conn->client_encoding;
4152 PQsetClientEncoding(PGconn *conn, const char *encoding)
4155 static const char query[] = "set client_encoding to '%s'";
4159 if (!conn || conn->status != CONNECTION_OK)
4165 /* check query buffer overflow */
4166 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
4169 /* ok, now send a query */
4170 sprintf(qbuf, query, encoding);
4171 res = PQexec(conn, qbuf);
4175 if (res->resultStatus != PGRES_COMMAND_OK)
4180 * In protocol 2 we have to assume the setting will stick, and adjust
4181 * our state immediately. In protocol 3 and up we can rely on the
4182 * backend to report the parameter value, and we'll change state at
4185 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
4186 pqSaveParameterStatus(conn, "client_encoding", encoding);
4187 status = 0; /* everything is ok */
4194 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
4199 return PQERRORS_DEFAULT;
4200 old = conn->verbosity;
4201 conn->verbosity = verbosity;
4206 PQtrace(PGconn *conn, FILE *debug_port)
4211 conn->Pfdebug = debug_port;
4215 PQuntrace(PGconn *conn)
4221 fflush(conn->Pfdebug);
4222 conn->Pfdebug = NULL;
4227 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
4229 PQnoticeReceiver old;
4234 old = conn->noticeHooks.noticeRec;
4237 conn->noticeHooks.noticeRec = proc;
4238 conn->noticeHooks.noticeRecArg = arg;
4244 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
4246 PQnoticeProcessor old;
4251 old = conn->noticeHooks.noticeProc;
4254 conn->noticeHooks.noticeProc = proc;
4255 conn->noticeHooks.noticeProcArg = arg;
4261 * The default notice message receiver just gets the standard notice text
4262 * and sends it to the notice processor. This two-level setup exists
4263 * mostly for backwards compatibility; perhaps we should deprecate use of
4264 * PQsetNoticeProcessor?
4267 defaultNoticeReceiver(void *arg, const PGresult *res)
4269 (void) arg; /* not used */
4270 if (res->noticeHooks.noticeProc != NULL)
4271 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
4272 PQresultErrorMessage(res));
4276 * The default notice message processor just prints the
4277 * message on stderr. Applications can override this if they
4278 * want the messages to go elsewhere (a window, for example).
4279 * Note that simply discarding notices is probably a bad idea.
4282 defaultNoticeProcessor(void *arg, const char *message)
4284 (void) arg; /* not used */
4285 /* Note: we expect the supplied string to end with a newline already. */
4286 fprintf(stderr, "%s", message);
4290 * returns a pointer to the next token or NULL if the current
4291 * token doesn't match
4294 pwdfMatchesString(char *buf, char *token)
4298 bool bslash = false;
4300 if (buf == NULL || token == NULL)
4304 if (tbuf[0] == '*' && tbuf[1] == ':')
4308 if (*tbuf == '\\' && !bslash)
4313 if (*tbuf == ':' && *ttok == 0 && !bslash)
4329 /* Get a password from the password file. Return value is malloc'd. */
4331 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
4334 char pgpassfile[MAXPGPATH];
4335 struct stat stat_buf;
4337 #define LINELEN NAMEDATALEN*5
4340 if (dbname == NULL || strlen(dbname) == 0)
4343 if (username == NULL || strlen(username) == 0)
4346 /* 'localhost' matches pghost of '' or the default socket directory */
4347 if (hostname == NULL)
4348 hostname = DefaultHost;
4349 else if (is_absolute_path(hostname))
4352 * We should probably use canonicalize_path(), but then we have to
4353 * bring path.c into libpq, and it doesn't seem worth it.
4355 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
4356 hostname = DefaultHost;
4359 port = DEF_PGPORT_STR;
4361 if (!getPgPassFilename(pgpassfile))
4364 /* If password file cannot be opened, ignore it. */
4365 if (stat(pgpassfile, &stat_buf) != 0)
4369 if (!S_ISREG(stat_buf.st_mode))
4372 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
4377 /* If password file is insecure, alert the user and ignore it. */
4378 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
4381 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
4388 * On Win32, the directory is protected, so we don't have to check the
4393 fp = fopen(pgpassfile, "r");
4397 while (!feof(fp) && !ferror(fp))
4403 if (fgets(buf, sizeof(buf), fp) == NULL)
4410 /* Remove trailing newline */
4411 if (buf[len - 1] == '\n')
4414 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
4415 (t = pwdfMatchesString(t, port)) == NULL ||
4416 (t = pwdfMatchesString(t, dbname)) == NULL ||
4417 (t = pwdfMatchesString(t, username)) == NULL)
4431 static bool getPgPassFilename(char *pgpassfile)
4435 if ((passfile_env = getenv("PGPASSFILE")) != NULL)
4436 /* use the literal path from the environment, if set */
4437 strlcpy(pgpassfile, passfile_env, MAXPGPATH);
4440 char homedir[MAXPGPATH];
4442 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
4444 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
4450 * If the connection failed, we should mention if
4451 * we got the password from .pgpass in case that
4452 * password is wrong.
4455 dot_pg_pass_warning(PGconn *conn)
4457 /* If it was 'invalid authorization', add .pgpass mention */
4458 if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
4459 /* only works with >= 9.0 servers */
4460 strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
4461 ERRCODE_INVALID_PASSWORD) == 0)
4463 char pgpassfile[MAXPGPATH];
4465 if (!getPgPassFilename(pgpassfile))
4467 appendPQExpBuffer(&conn->errorMessage,
4468 libpq_gettext("password retrieved from file \"%s\"\n"),
4475 * Obtain user's home directory, return in given buffer
4477 * On Unix, this actually returns the user's home directory. On Windows
4478 * it returns the PostgreSQL-specific application data folder.
4480 * This is essentially the same as get_home_path(), but we don't use that
4481 * because we don't want to pull path.c into libpq (it pollutes application
4485 pqGetHomeDirectory(char *buf, int bufsize)
4488 char pwdbuf[BUFSIZ];
4489 struct passwd pwdstr;
4490 struct passwd *pwd = NULL;
4492 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
4494 strlcpy(buf, pwd->pw_dir, bufsize);
4497 char tmppath[MAX_PATH];
4499 ZeroMemory(tmppath, sizeof(tmppath));
4500 if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
4502 snprintf(buf, bufsize, "%s/postgresql", tmppath);
4508 * To keep the API consistent, the locking stubs are always provided, even
4509 * if they are not required.
4513 default_threadlock(int acquire)
4515 #ifdef ENABLE_THREAD_SAFETY
4517 static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
4519 static pthread_mutex_t singlethread_lock = NULL;
4520 static long mutex_initlock = 0;
4522 if (singlethread_lock == NULL)
4524 while (InterlockedExchange(&mutex_initlock, 1) == 1)
4525 /* loop, another thread own the lock */ ;
4526 if (singlethread_lock == NULL)
4528 if (pthread_mutex_init(&singlethread_lock, NULL))
4529 PGTHREAD_ERROR("failed to initialize mutex");
4531 InterlockedExchange(&mutex_initlock, 0);
4536 if (pthread_mutex_lock(&singlethread_lock))
4537 PGTHREAD_ERROR("failed to lock mutex");
4541 if (pthread_mutex_unlock(&singlethread_lock))
4542 PGTHREAD_ERROR("failed to unlock mutex");
4548 PQregisterThreadLock(pgthreadlock_t newhandler)
4550 pgthreadlock_t prev = pg_g_threadlock;
4553 pg_g_threadlock = newhandler;
4555 pg_g_threadlock = default_threadlock;