1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
16 #include "postgres_fe.h"
18 #include <sys/types.h>
26 #include "libpq-int.h"
28 #include "pg_config_paths.h"
35 #define _WIN32_IE 0x0500
42 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #ifdef HAVE_NETINET_TCP_H
46 #include <netinet/tcp.h>
48 #include <arpa/inet.h>
51 #ifdef ENABLE_THREAD_SAFETY
53 #include "pthread-win32.h"
63 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
64 #define LDAP_DEPRECATED 1
66 typedef struct timeval LDAP_TIMEVAL
;
68 static int ldapServiceLookup(const char *purl
, PQconninfoOption
*options
,
69 PQExpBuffer errorMessage
);
73 #include "mb/pg_wchar.h"
81 #define PGPASSFILE ".pgpass"
83 #define PGPASSFILE "pgpass.conf"
86 /* fall back options if they are not specified by arguments or defined
87 by environment variables */
88 #define DefaultHost "localhost"
90 #define DefaultOption ""
91 #define DefaultAuthtype ""
92 #define DefaultPassword ""
94 #define DefaultSSLMode "prefer"
96 #define DefaultSSLMode "disable"
100 * Definition of the conninfo parameters and their fallback resources.
102 * If Environment-Var and Compiled-in are specified as NULL, no
103 * fallback is available. If after all no value can be determined
104 * for an option, an error is returned.
106 * The value for the username is treated specially in conninfo_parse.
107 * If the Compiled-in resource is specified as a NULL value, the
108 * user is determined by pg_fe_getauthname().
110 * The Label and Disp-Char entries are provided for applications that
111 * want to use PQconndefaults() to create a generic database connection
112 * dialog. Disp-Char is defined as follows:
113 * "" Normal input field
114 * "*" Password field - hide value
115 * "D" Debug option - don't show by default
117 * PQconninfoOptions[] is a constant static array that we use to initialize
118 * a dynamically allocated working copy. All the "val" fields in
119 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
120 * fields point to malloc'd strings that should be freed when the working
121 * array is freed (see PQconninfoFree).
124 static const PQconninfoOption PQconninfoOptions
[] = {
126 * "authtype" is no longer used, so mark it "don't show". We keep it in
127 * the array so as not to reject conninfo strings from old apps that might
128 * still try to set it.
130 {"authtype", "PGAUTHTYPE", DefaultAuthtype
, NULL
,
131 "Database-Authtype", "D", 20},
133 {"service", "PGSERVICE", NULL
, NULL
,
134 "Database-Service", "", 20},
136 {"user", "PGUSER", NULL
, NULL
,
137 "Database-User", "", 20},
139 {"password", "PGPASSWORD", NULL
, NULL
,
140 "Database-Password", "*", 20},
142 {"connect_timeout", "PGCONNECT_TIMEOUT", NULL
, NULL
,
143 "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
145 {"dbname", "PGDATABASE", NULL
, NULL
,
146 "Database-Name", "", 20},
148 {"host", "PGHOST", NULL
, NULL
,
149 "Database-Host", "", 40},
151 {"hostaddr", "PGHOSTADDR", NULL
, NULL
,
152 "Database-Host-IP-Address", "", 45},
154 {"port", "PGPORT", DEF_PGPORT_STR
, NULL
,
155 "Database-Port", "", 6},
158 * "tty" is no longer used either, but keep it present for backwards
161 {"tty", "PGTTY", DefaultTty
, NULL
,
162 "Backend-Debug-TTY", "D", 40},
164 {"options", "PGOPTIONS", DefaultOption
, NULL
,
165 "Backend-Debug-Options", "D", 40},
170 * "requiressl" is deprecated, its purpose having been taken over by
171 * "sslmode". It remains for backwards compatibility.
173 {"requiressl", "PGREQUIRESSL", "0", NULL
,
174 "Require-SSL", "D", 1},
178 * "sslmode" option is allowed even without client SSL support because the
179 * client can still handle SSL modes "disable" and "allow".
181 {"sslmode", "PGSSLMODE", DefaultSSLMode
, NULL
,
182 "SSL-Mode", "", 8}, /* sizeof("disable") == 8 */
184 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
185 /* Kerberos and GSSAPI authentication support specifying the service name */
186 {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM
, NULL
,
187 "Kerberos-service-name", "", 20},
190 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
193 * GSSAPI and SSPI both enabled, give a way to override which is used by
196 {"gsslib", "PGGSSLIB", NULL
, NULL
,
197 "GSS-library", "", 7}, /* sizeof("gssapi") = 7 */
200 /* Terminating entry --- MUST BE LAST */
201 {NULL
, NULL
, NULL
, NULL
,
205 static const PQEnvironmentOption EnvironmentOptions
[] =
207 /* common user-interface settings */
209 "PGDATESTYLE", "datestyle"
215 "PGCLIENTENCODING", "client_encoding"
217 /* internal performance-related settings */
227 static bool connectOptions1(PGconn
*conn
, const char *conninfo
);
228 static bool connectOptions2(PGconn
*conn
);
229 static int connectDBStart(PGconn
*conn
);
230 static int connectDBComplete(PGconn
*conn
);
231 static PGconn
*makeEmptyPGconn(void);
232 static void freePGconn(PGconn
*conn
);
233 static void closePGconn(PGconn
*conn
);
234 static PQconninfoOption
*conninfo_parse(const char *conninfo
,
235 PQExpBuffer errorMessage
, bool use_defaults
);
236 static char *conninfo_getval(PQconninfoOption
*connOptions
,
237 const char *keyword
);
238 static void defaultNoticeReceiver(void *arg
, const PGresult
*res
);
239 static void defaultNoticeProcessor(void *arg
, const char *message
);
240 static int parseServiceInfo(PQconninfoOption
*options
,
241 PQExpBuffer errorMessage
);
242 static char *pwdfMatchesString(char *buf
, char *token
);
243 static char *PasswordFromFile(char *hostname
, char *port
, char *dbname
,
245 static void default_threadlock(int acquire
);
248 /* global variable because fe-auth.c needs to access it */
249 pgthreadlock_t pg_g_threadlock
= default_threadlock
;
253 * Connecting to a Database
255 * There are now four different ways a user of this API can connect to the
256 * database. Two are not recommended for use in new code, because of their
257 * lack of extensibility with respect to the passing of options to the
258 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
261 * If it is desired to connect in a synchronous (blocking) manner, use the
262 * function PQconnectdb.
264 * To connect in an asynchronous (non-blocking) manner, use the functions
265 * PQconnectStart, and PQconnectPoll.
267 * Internally, the static functions connectDBStart, connectDBComplete
268 * are part of the connection procedure.
274 * establishes a connection to a postgres backend through the postmaster
275 * using connection information in a string.
277 * The conninfo string is a white-separated list of
281 * definitions. Value might be a single value containing no whitespaces or
282 * a single quoted string. If a single quote should appear anywhere in
283 * the value, it must be escaped with a backslash like \'
285 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
286 * if a memory allocation failed.
287 * If the status field of the connection returned is CONNECTION_BAD,
288 * then some fields may be null'ed out instead of having valid values.
290 * You should call PQfinish (if conn is not NULL) regardless of whether this
294 PQconnectdb(const char *conninfo
)
296 PGconn
*conn
= PQconnectStart(conninfo
);
298 if (conn
&& conn
->status
!= CONNECTION_BAD
)
299 (void) connectDBComplete(conn
);
307 * Begins the establishment of a connection to a postgres backend through the
308 * postmaster using connection information in a string.
310 * See comment for PQconnectdb for the definition of the string format.
312 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
313 * you should not attempt to proceed with this connection. If the status
314 * field of the connection returned is CONNECTION_BAD, an error has
315 * occurred. In this case you should call PQfinish on the result, (perhaps
316 * inspecting the error message first). Other fields of the structure may not
317 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
318 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
321 * See PQconnectPoll for more info.
324 PQconnectStart(const char *conninfo
)
329 * Allocate memory for the conn structure
331 conn
= makeEmptyPGconn();
336 * Parse the conninfo string
338 if (!connectOptions1(conn
, conninfo
))
342 * Compute derived options
344 if (!connectOptions2(conn
))
348 * Connect to the database
350 if (!connectDBStart(conn
))
352 /* Just in case we failed to set it in connectDBStart */
353 conn
->status
= CONNECTION_BAD
;
362 * Internal subroutine to set up connection parameters given an already-
363 * created PGconn and a conninfo string. Derived settings should be
364 * processed by calling connectOptions2 next. (We split them because
365 * PQsetdbLogin overrides defaults in between.)
367 * Returns true if OK, false if trouble (in which case errorMessage is set
368 * and so is conn->status).
371 connectOptions1(PGconn
*conn
, const char *conninfo
)
373 PQconninfoOption
*connOptions
;
377 * Parse the conninfo string
379 connOptions
= conninfo_parse(conninfo
, &conn
->errorMessage
, true);
380 if (connOptions
== NULL
)
382 conn
->status
= CONNECTION_BAD
;
383 /* errorMessage is already set */
388 * Move option values into conn structure
390 * Don't put anything cute here --- intelligence should be in
391 * connectOptions2 ...
393 * XXX: probably worth checking strdup() return value here...
395 tmp
= conninfo_getval(connOptions
, "hostaddr");
396 conn
->pghostaddr
= tmp
? strdup(tmp
) : NULL
;
397 tmp
= conninfo_getval(connOptions
, "host");
398 conn
->pghost
= tmp
? strdup(tmp
) : NULL
;
399 tmp
= conninfo_getval(connOptions
, "port");
400 conn
->pgport
= tmp
? strdup(tmp
) : NULL
;
401 tmp
= conninfo_getval(connOptions
, "tty");
402 conn
->pgtty
= tmp
? strdup(tmp
) : NULL
;
403 tmp
= conninfo_getval(connOptions
, "options");
404 conn
->pgoptions
= tmp
? strdup(tmp
) : NULL
;
405 tmp
= conninfo_getval(connOptions
, "dbname");
406 conn
->dbName
= tmp
? strdup(tmp
) : NULL
;
407 tmp
= conninfo_getval(connOptions
, "user");
408 conn
->pguser
= tmp
? strdup(tmp
) : NULL
;
409 tmp
= conninfo_getval(connOptions
, "password");
410 conn
->pgpass
= tmp
? strdup(tmp
) : NULL
;
411 tmp
= conninfo_getval(connOptions
, "connect_timeout");
412 conn
->connect_timeout
= tmp
? strdup(tmp
) : NULL
;
413 tmp
= conninfo_getval(connOptions
, "sslmode");
414 conn
->sslmode
= tmp
? strdup(tmp
) : NULL
;
416 tmp
= conninfo_getval(connOptions
, "requiressl");
417 if (tmp
&& tmp
[0] == '1')
419 /* here warn that the requiressl option is deprecated? */
422 conn
->sslmode
= strdup("require");
425 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
426 tmp
= conninfo_getval(connOptions
, "krbsrvname");
427 conn
->krbsrvname
= tmp
? strdup(tmp
) : NULL
;
429 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
430 tmp
= conninfo_getval(connOptions
, "gsslib");
431 conn
->gsslib
= tmp
? strdup(tmp
) : NULL
;
435 * Free the option info - all is in conn now
437 PQconninfoFree(connOptions
);
445 * Compute derived connection options after absorbing all user-supplied info.
447 * Returns true if OK, false if trouble (in which case errorMessage is set
448 * and so is conn->status).
451 connectOptions2(PGconn
*conn
)
454 * If database name was not given, default it to equal user name
456 if ((conn
->dbName
== NULL
|| conn
->dbName
[0] == '\0')
457 && conn
->pguser
!= NULL
)
461 conn
->dbName
= strdup(conn
->pguser
);
465 * Supply default password if none given
467 if (conn
->pgpass
== NULL
|| conn
->pgpass
[0] == '\0')
471 conn
->pgpass
= PasswordFromFile(conn
->pghost
, conn
->pgport
,
472 conn
->dbName
, conn
->pguser
);
473 if (conn
->pgpass
== NULL
)
474 conn
->pgpass
= strdup(DefaultPassword
);
478 * Allow unix socket specification in the host name
480 if (conn
->pghost
&& is_absolute_path(conn
->pghost
))
482 if (conn
->pgunixsocket
)
483 free(conn
->pgunixsocket
);
484 conn
->pgunixsocket
= conn
->pghost
;
489 * validate sslmode option
493 if (strcmp(conn
->sslmode
, "disable") != 0
494 && strcmp(conn
->sslmode
, "allow") != 0
495 && strcmp(conn
->sslmode
, "prefer") != 0
496 && strcmp(conn
->sslmode
, "require") != 0)
498 conn
->status
= CONNECTION_BAD
;
499 printfPQExpBuffer(&conn
->errorMessage
,
500 libpq_gettext("invalid sslmode value: \"%s\"\n"),
506 switch (conn
->sslmode
[0])
508 case 'a': /* "allow" */
509 case 'p': /* "prefer" */
512 * warn user that an SSL connection will never be negotiated
513 * since SSL was not compiled in?
517 case 'r': /* "require" */
518 conn
->status
= CONNECTION_BAD
;
519 printfPQExpBuffer(&conn
->errorMessage
,
520 libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
527 conn
->sslmode
= strdup(DefaultSSLMode
);
530 * Only if we get this far is it appropriate to try to connect. (We need a
531 * state flag, rather than just the boolean result of this function, in
532 * case someone tries to PQreset() the PGconn.)
534 conn
->options_valid
= true;
542 * Parse an empty string like PQconnectdb() would do and return the
543 * resulting connection options array, ie, all the default values that are
544 * available from the environment etc. On error (eg out of memory),
547 * Using this function, an application may determine all possible options
548 * and their current default values.
550 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
551 * and should be freed when no longer needed via PQconninfoFree(). (In prior
552 * versions, the returned array was static, but that's not thread-safe.)
553 * Pre-7.0 applications that use this function will see a small memory leak
554 * until they are updated to call PQconninfoFree.
559 PQExpBufferData errorBuf
;
560 PQconninfoOption
*connOptions
;
562 initPQExpBuffer(&errorBuf
);
563 if (errorBuf
.data
== NULL
)
564 return NULL
; /* out of memory already :-( */
565 connOptions
= conninfo_parse("", &errorBuf
, true);
566 termPQExpBuffer(&errorBuf
);
573 * establishes a connection to a postgres backend through the postmaster
574 * at the specified host and port.
576 * returns a PGconn* which is needed for all subsequent libpq calls
578 * if the status field of the connection returned is CONNECTION_BAD,
579 * then only the errorMessage is likely to be useful.
583 PQsetdbLogin(const char *pghost
, const char *pgport
, const char *pgoptions
,
584 const char *pgtty
, const char *dbName
, const char *login
,
590 * Allocate memory for the conn structure
592 conn
= makeEmptyPGconn();
597 * If the dbName parameter contains '=', assume it's a conninfo string.
599 if (dbName
&& strchr(dbName
, '='))
601 if (!connectOptions1(conn
, dbName
))
607 * Old-style path: first, parse an empty conninfo string in order to
608 * set up the same defaults that PQconnectdb() would use.
610 if (!connectOptions1(conn
, ""))
613 /* Insert dbName parameter value into struct */
614 if (dbName
&& dbName
[0] != '\0')
618 conn
->dbName
= strdup(dbName
);
623 * Insert remaining parameters into struct, overriding defaults (as well
624 * as any conflicting data from dbName taken as a conninfo).
626 if (pghost
&& pghost
[0] != '\0')
630 conn
->pghost
= strdup(pghost
);
633 if (pgport
&& pgport
[0] != '\0')
637 conn
->pgport
= strdup(pgport
);
640 if (pgoptions
&& pgoptions
[0] != '\0')
643 free(conn
->pgoptions
);
644 conn
->pgoptions
= strdup(pgoptions
);
647 if (pgtty
&& pgtty
[0] != '\0')
651 conn
->pgtty
= strdup(pgtty
);
654 if (login
&& login
[0] != '\0')
658 conn
->pguser
= strdup(login
);
661 if (pwd
&& pwd
[0] != '\0')
665 conn
->pgpass
= strdup(pwd
);
669 * Compute derived options
671 if (!connectOptions2(conn
))
675 * Connect to the database
677 if (connectDBStart(conn
))
678 (void) connectDBComplete(conn
);
686 * Sets the TCP_NODELAY socket option.
687 * Returns 1 if successful, 0 if not.
691 connectNoDelay(PGconn
*conn
)
696 if (setsockopt(conn
->sock
, IPPROTO_TCP
, TCP_NODELAY
,
702 printfPQExpBuffer(&conn
->errorMessage
,
703 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
704 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
714 * connectFailureMessage -
715 * create a friendly error message on connection failure.
719 connectFailureMessage(PGconn
*conn
, int errorno
)
723 #ifdef HAVE_UNIX_SOCKETS
724 if (IS_AF_UNIX(conn
->raddr
.addr
.ss_family
))
726 char service
[NI_MAXHOST
];
728 pg_getnameinfo_all(&conn
->raddr
.addr
, conn
->raddr
.salen
,
730 service
, sizeof(service
),
732 printfPQExpBuffer(&conn
->errorMessage
,
733 libpq_gettext("could not connect to server: %s\n"
734 "\tIs the server running locally and accepting\n"
735 "\tconnections on Unix domain socket \"%s\"?\n"),
736 SOCK_STRERROR(errorno
, sebuf
, sizeof(sebuf
)),
740 #endif /* HAVE_UNIX_SOCKETS */
742 printfPQExpBuffer(&conn
->errorMessage
,
743 libpq_gettext("could not connect to server: %s\n"
744 "\tIs the server running on host \"%s\" and accepting\n"
745 "\tTCP/IP connections on port %s?\n"),
746 SOCK_STRERROR(errorno
, sebuf
, sizeof(sebuf
)),
759 * Begin the process of making a connection to the backend.
761 * Returns 1 if successful, 0 if not.
765 connectDBStart(PGconn
*conn
)
769 struct addrinfo
*addrs
= NULL
;
770 struct addrinfo hint
;
777 if (!conn
->options_valid
)
778 goto connect_errReturn
;
780 /* Ensure our buffers are empty */
781 conn
->inStart
= conn
->inCursor
= conn
->inEnd
= 0;
785 * Determine the parameters to pass to pg_getaddrinfo_all.
788 /* Initialize hint structure */
789 MemSet(&hint
, 0, sizeof(hint
));
790 hint
.ai_socktype
= SOCK_STREAM
;
791 hint
.ai_family
= AF_UNSPEC
;
793 /* Set up port number as a string */
794 if (conn
->pgport
!= NULL
&& conn
->pgport
[0] != '\0')
795 portnum
= atoi(conn
->pgport
);
797 portnum
= DEF_PGPORT
;
798 snprintf(portstr
, sizeof(portstr
), "%d", portnum
);
800 if (conn
->pghostaddr
!= NULL
&& conn
->pghostaddr
[0] != '\0')
802 /* Using pghostaddr avoids a hostname lookup */
803 node
= conn
->pghostaddr
;
804 hint
.ai_family
= AF_UNSPEC
;
805 hint
.ai_flags
= AI_NUMERICHOST
;
807 else if (conn
->pghost
!= NULL
&& conn
->pghost
[0] != '\0')
809 /* Using pghost, so we have to look-up the hostname */
811 hint
.ai_family
= AF_UNSPEC
;
815 #ifdef HAVE_UNIX_SOCKETS
816 /* pghostaddr and pghost are NULL, so use Unix domain socket */
818 hint
.ai_family
= AF_UNIX
;
819 UNIXSOCK_PATH(portstr
, portnum
, conn
->pgunixsocket
);
821 /* Without Unix sockets, default to localhost instead */
823 hint
.ai_family
= AF_UNSPEC
;
824 #endif /* HAVE_UNIX_SOCKETS */
827 /* Use pg_getaddrinfo_all() to resolve the address */
828 ret
= pg_getaddrinfo_all(node
, portstr
, &hint
, &addrs
);
832 printfPQExpBuffer(&conn
->errorMessage
,
833 libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
834 node
, gai_strerror(ret
));
836 printfPQExpBuffer(&conn
->errorMessage
,
837 libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
838 portstr
, gai_strerror(ret
));
840 pg_freeaddrinfo_all(hint
.ai_family
, addrs
);
841 goto connect_errReturn
;
845 /* setup values based on SSL mode */
846 if (conn
->sslmode
[0] == 'd') /* "disable" */
847 conn
->allow_ssl_try
= false;
848 else if (conn
->sslmode
[0] == 'a') /* "allow" */
849 conn
->wait_ssl_try
= true;
853 * Set up to try to connect, with protocol 3.0 as the first attempt.
855 conn
->addrlist
= addrs
;
856 conn
->addr_cur
= addrs
;
857 conn
->addrlist_family
= hint
.ai_family
;
858 conn
->pversion
= PG_PROTOCOL(3, 0);
859 conn
->status
= CONNECTION_NEEDED
;
862 * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
863 * so that it can easily be re-executed if needed again during the
864 * asynchronous startup process. However, we must run it once here,
865 * because callers expect a success return from this routine to mean that
866 * we are in PGRES_POLLING_WRITING connection state.
868 if (PQconnectPoll(conn
) == PGRES_POLLING_WRITING
)
874 pqsecure_close(conn
);
875 closesocket(conn
->sock
);
878 conn
->status
= CONNECTION_BAD
;
886 * Block and complete a connection.
888 * Returns 1 on success, 0 on failure.
891 connectDBComplete(PGconn
*conn
)
893 PostgresPollingStatusType flag
= PGRES_POLLING_WRITING
;
894 time_t finish_time
= ((time_t) -1);
896 if (conn
== NULL
|| conn
->status
== CONNECTION_BAD
)
900 * Set up a time limit, if connect_timeout isn't zero.
902 if (conn
->connect_timeout
!= NULL
)
904 int timeout
= atoi(conn
->connect_timeout
);
909 * Rounding could cause connection to fail; need at least 2 secs
913 /* calculate the finish time based on start + timeout */
914 finish_time
= time(NULL
) + timeout
;
921 * Wait, if necessary. Note that the initial state (just after
922 * PQconnectStart) is to wait for the socket to select for writing.
926 case PGRES_POLLING_OK
:
927 return 1; /* success! */
929 case PGRES_POLLING_READING
:
930 if (pqWaitTimed(1, 0, conn
, finish_time
))
932 conn
->status
= CONNECTION_BAD
;
937 case PGRES_POLLING_WRITING
:
938 if (pqWaitTimed(0, 1, conn
, finish_time
))
940 conn
->status
= CONNECTION_BAD
;
946 /* Just in case we failed to set it in PQconnectPoll */
947 conn
->status
= CONNECTION_BAD
;
952 * Now try to advance the state machine.
954 flag
= PQconnectPoll(conn
);
961 * Poll an asynchronous connection.
963 * Returns a PostgresPollingStatusType.
964 * Before calling this function, use select(2) to determine when data
967 * You must call PQfinish whether or not this fails.
969 * This function and PQconnectStart are intended to allow connections to be
970 * made without blocking the execution of your program on remote I/O. However,
971 * there are a number of caveats:
973 * o If you call PQtrace, ensure that the stream object into which you trace
975 * o If you do not supply an IP address for the remote host (i.e. you
976 * supply a host name instead) then PQconnectStart will block on
977 * gethostbyname. You will be fine if using Unix sockets (i.e. by
978 * supplying neither a host name nor a host address).
979 * o If your backend wants to use Kerberos authentication then you must
980 * supply both a host name and a host address, otherwise this function
981 * may block on gethostname.
985 PostgresPollingStatusType
986 PQconnectPoll(PGconn
*conn
)
992 return PGRES_POLLING_FAILED
;
994 /* Get the new data */
995 switch (conn
->status
)
998 * We really shouldn't have been polled in these two cases, but we
1001 case CONNECTION_BAD
:
1002 return PGRES_POLLING_FAILED
;
1004 return PGRES_POLLING_OK
;
1006 /* These are reading states */
1007 case CONNECTION_AWAITING_RESPONSE
:
1008 case CONNECTION_AUTH_OK
:
1010 /* Load waiting data */
1011 int n
= pqReadData(conn
);
1016 return PGRES_POLLING_READING
;
1021 /* These are writing states, so we just proceed. */
1022 case CONNECTION_STARTED
:
1023 case CONNECTION_MADE
:
1026 /* We allow pqSetenvPoll to decide whether to proceed. */
1027 case CONNECTION_SETENV
:
1030 /* Special cases: proceed without waiting. */
1031 case CONNECTION_SSL_STARTUP
:
1032 case CONNECTION_NEEDED
:
1036 printfPQExpBuffer(&conn
->errorMessage
,
1038 "invalid connection state, "
1039 "probably indicative of memory corruption\n"
1045 keep_going
: /* We will come back to here until there is
1046 * nothing left to do. */
1047 switch (conn
->status
)
1049 case CONNECTION_NEEDED
:
1052 * Try to initiate a connection to one of the addresses
1053 * returned by pg_getaddrinfo_all(). conn->addr_cur is the
1054 * next one to try. We fail when we run out of addresses
1055 * (reporting the error returned for the *last* alternative,
1056 * which may not be what users expect :-().
1058 while (conn
->addr_cur
!= NULL
)
1060 struct addrinfo
*addr_cur
= conn
->addr_cur
;
1062 /* Remember current address for possible error msg */
1063 memcpy(&conn
->raddr
.addr
, addr_cur
->ai_addr
,
1064 addr_cur
->ai_addrlen
);
1065 conn
->raddr
.salen
= addr_cur
->ai_addrlen
;
1068 conn
->sock
= socket(addr_cur
->ai_family
, SOCK_STREAM
, 0);
1072 * ignore socket() failure if we have more addresses
1075 if (addr_cur
->ai_next
!= NULL
)
1077 conn
->addr_cur
= addr_cur
->ai_next
;
1080 printfPQExpBuffer(&conn
->errorMessage
,
1081 libpq_gettext("could not create socket: %s\n"),
1082 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1087 * Select socket options: no delay of outgoing data for
1088 * TCP sockets, nonblock mode, close-on-exec. Fail if any
1091 if (!IS_AF_UNIX(addr_cur
->ai_family
))
1093 if (!connectNoDelay(conn
))
1095 closesocket(conn
->sock
);
1097 conn
->addr_cur
= addr_cur
->ai_next
;
1101 if (!pg_set_noblock(conn
->sock
))
1103 printfPQExpBuffer(&conn
->errorMessage
,
1104 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
1105 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1106 closesocket(conn
->sock
);
1108 conn
->addr_cur
= addr_cur
->ai_next
;
1113 if (fcntl(conn
->sock
, F_SETFD
, FD_CLOEXEC
) == -1)
1115 printfPQExpBuffer(&conn
->errorMessage
,
1116 libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1117 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1118 closesocket(conn
->sock
);
1120 conn
->addr_cur
= addr_cur
->ai_next
;
1123 #endif /* F_SETFD */
1126 * Start/make connection. This should not block, since we
1127 * are in nonblock mode. If it does, well, too bad.
1129 if (connect(conn
->sock
, addr_cur
->ai_addr
,
1130 addr_cur
->ai_addrlen
) < 0)
1132 if (SOCK_ERRNO
== EINPROGRESS
||
1133 SOCK_ERRNO
== EWOULDBLOCK
||
1134 SOCK_ERRNO
== EINTR
||
1138 * This is fine - we're in non-blocking mode, and
1139 * the connection is in progress. Tell caller to
1140 * wait for write-ready on socket.
1142 conn
->status
= CONNECTION_STARTED
;
1143 return PGRES_POLLING_WRITING
;
1145 /* otherwise, trouble */
1150 * Hm, we're connected already --- seems the "nonblock
1151 * connection" wasn't. Advance the state machine and
1152 * go do the next stuff.
1154 conn
->status
= CONNECTION_STARTED
;
1159 * This connection failed --- set up error report, then
1160 * close socket (do it this way in case close() affects
1161 * the value of errno...). We will ignore the connect()
1162 * failure and keep going if there are more addresses.
1164 connectFailureMessage(conn
, SOCK_ERRNO
);
1165 if (conn
->sock
>= 0)
1167 closesocket(conn
->sock
);
1172 * Try the next address, if any.
1174 conn
->addr_cur
= addr_cur
->ai_next
;
1175 } /* loop over addresses */
1178 * Ooops, no more addresses. An appropriate error message is
1179 * already set up, so just set the right status.
1184 case CONNECTION_STARTED
:
1187 ACCEPT_TYPE_ARG3 optlen
= sizeof(optval
);
1190 * Write ready, since we've made it here, so the connection
1191 * has been made ... or has failed.
1195 * Now check (using getsockopt) that there is not an error
1196 * state waiting for us on the socket.
1199 if (getsockopt(conn
->sock
, SOL_SOCKET
, SO_ERROR
,
1200 (char *) &optval
, &optlen
) == -1)
1202 printfPQExpBuffer(&conn
->errorMessage
,
1203 libpq_gettext("could not get socket error status: %s\n"),
1204 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1207 else if (optval
!= 0)
1210 * When using a nonblocking connect, we will typically see
1211 * connect failures at this point, so provide a friendly
1214 connectFailureMessage(conn
, optval
);
1217 * If more addresses remain, keep trying, just as in the
1218 * case where connect() returned failure immediately.
1220 if (conn
->addr_cur
->ai_next
!= NULL
)
1222 if (conn
->sock
>= 0)
1224 closesocket(conn
->sock
);
1227 conn
->addr_cur
= conn
->addr_cur
->ai_next
;
1228 conn
->status
= CONNECTION_NEEDED
;
1234 /* Fill in the client address */
1235 conn
->laddr
.salen
= sizeof(conn
->laddr
.addr
);
1236 if (getsockname(conn
->sock
,
1237 (struct sockaddr
*) & conn
->laddr
.addr
,
1238 &conn
->laddr
.salen
) < 0)
1240 printfPQExpBuffer(&conn
->errorMessage
,
1241 libpq_gettext("could not get client address from socket: %s\n"),
1242 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1247 * Make sure we can write before advancing to next step.
1249 conn
->status
= CONNECTION_MADE
;
1250 return PGRES_POLLING_WRITING
;
1253 case CONNECTION_MADE
:
1261 * If SSL is enabled and we haven't already got it running,
1262 * request it instead of sending the startup message.
1264 if (IS_AF_UNIX(conn
->raddr
.addr
.ss_family
))
1266 /* Don't bother requesting SSL over a Unix socket */
1267 conn
->allow_ssl_try
= false;
1269 if (conn
->allow_ssl_try
&& !conn
->wait_ssl_try
&&
1275 * Send the SSL request packet.
1277 * Theoretically, this could block, but it really
1278 * shouldn't since we only got here if the socket is
1281 pv
= htonl(NEGOTIATE_SSL_CODE
);
1282 if (pqPacketSend(conn
, 0, &pv
, sizeof(pv
)) != STATUS_OK
)
1284 printfPQExpBuffer(&conn
->errorMessage
,
1285 libpq_gettext("could not send SSL negotiation packet: %s\n"),
1286 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1289 /* Ok, wait for response */
1290 conn
->status
= CONNECTION_SSL_STARTUP
;
1291 return PGRES_POLLING_READING
;
1293 #endif /* USE_SSL */
1296 * Build the startup packet.
1298 if (PG_PROTOCOL_MAJOR(conn
->pversion
) >= 3)
1299 startpacket
= pqBuildStartupPacket3(conn
, &packetlen
,
1300 EnvironmentOptions
);
1302 startpacket
= pqBuildStartupPacket2(conn
, &packetlen
,
1303 EnvironmentOptions
);
1306 printfPQExpBuffer(&conn
->errorMessage
,
1307 libpq_gettext("out of memory\n"));
1312 * Send the startup packet.
1314 * Theoretically, this could block, but it really shouldn't
1315 * since we only got here if the socket is write-ready.
1317 if (pqPacketSend(conn
, 0, startpacket
, packetlen
) != STATUS_OK
)
1319 printfPQExpBuffer(&conn
->errorMessage
,
1320 libpq_gettext("could not send startup packet: %s\n"),
1321 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1328 conn
->status
= CONNECTION_AWAITING_RESPONSE
;
1329 return PGRES_POLLING_READING
;
1333 * Handle SSL negotiation: wait for postmaster messages and
1334 * respond as necessary.
1336 case CONNECTION_SSL_STARTUP
:
1339 PostgresPollingStatusType pollres
;
1342 * On first time through, get the postmaster's response to our
1343 * SSL negotiation packet.
1345 if (conn
->ssl
== NULL
)
1348 * We use pqReadData here since it has the logic to
1349 * distinguish no-data-yet from connection closure. Since
1350 * conn->ssl isn't set, a plain recv() will occur.
1355 rdresult
= pqReadData(conn
);
1358 /* errorMessage is already filled in */
1363 /* caller failed to wait for data */
1364 return PGRES_POLLING_READING
;
1366 if (pqGetc(&SSLok
, conn
) < 0)
1368 /* should not happen really */
1369 return PGRES_POLLING_READING
;
1371 /* mark byte consumed */
1372 conn
->inStart
= conn
->inCursor
;
1375 /* Do one-time setup; this creates conn->ssl */
1376 if (pqsecure_initialize(conn
) == -1)
1379 else if (SSLok
== 'N')
1381 if (conn
->sslmode
[0] == 'r') /* "require" */
1383 /* Require SSL, but server does not want it */
1384 printfPQExpBuffer(&conn
->errorMessage
,
1385 libpq_gettext("server does not support SSL, but SSL was required\n"));
1388 /* Otherwise, proceed with normal startup */
1389 conn
->allow_ssl_try
= false;
1390 conn
->status
= CONNECTION_MADE
;
1391 return PGRES_POLLING_WRITING
;
1393 else if (SSLok
== 'E')
1395 /* Received error - probably protocol mismatch */
1397 fprintf(conn
->Pfdebug
, "received error from server, attempting fallback to pre-7.0\n");
1398 if (conn
->sslmode
[0] == 'r') /* "require" */
1400 /* Require SSL, but server is too old */
1401 printfPQExpBuffer(&conn
->errorMessage
,
1402 libpq_gettext("server does not support SSL, but SSL was required\n"));
1405 /* Otherwise, try again without SSL */
1406 conn
->allow_ssl_try
= false;
1407 /* Assume it ain't gonna handle protocol 3, either */
1408 conn
->pversion
= PG_PROTOCOL(2, 0);
1409 /* Must drop the old connection */
1410 closesocket(conn
->sock
);
1412 conn
->status
= CONNECTION_NEEDED
;
1417 printfPQExpBuffer(&conn
->errorMessage
,
1418 libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1425 * Begin or continue the SSL negotiation process.
1427 pollres
= pqsecure_open_client(conn
);
1428 if (pollres
== PGRES_POLLING_OK
)
1430 /* SSL handshake done, ready to send startup packet */
1431 conn
->status
= CONNECTION_MADE
;
1432 return PGRES_POLLING_WRITING
;
1434 if (pollres
== PGRES_POLLING_FAILED
)
1437 * Failed ... if sslmode is "prefer" then do a non-SSL
1440 if (conn
->sslmode
[0] == 'p' /* "prefer" */
1441 && conn
->allow_ssl_try
/* redundant? */
1442 && !conn
->wait_ssl_try
) /* redundant? */
1444 /* only retry once */
1445 conn
->allow_ssl_try
= false;
1446 /* Must drop the old connection */
1447 closesocket(conn
->sock
);
1449 conn
->status
= CONNECTION_NEEDED
;
1454 #else /* !USE_SSL */
1455 /* can't get here */
1457 #endif /* USE_SSL */
1461 * Handle authentication exchange: wait for postmaster messages
1462 * and respond as necessary.
1464 case CONNECTION_AWAITING_RESPONSE
:
1472 * Scan the message from current point (note that if we find
1473 * the message is incomplete, we will return without advancing
1474 * inStart, and resume here next time).
1476 conn
->inCursor
= conn
->inStart
;
1478 /* Read type byte */
1479 if (pqGetc(&beresp
, conn
))
1481 /* We'll come back when there is more data */
1482 return PGRES_POLLING_READING
;
1486 * Validate message type: we expect only an authentication
1487 * request or an error here. Anything else probably means
1488 * it's not Postgres on the other end at all.
1490 if (!(beresp
== 'R' || beresp
== 'E'))
1492 printfPQExpBuffer(&conn
->errorMessage
,
1494 "expected authentication request from "
1495 "server, but received %c\n"),
1500 if (PG_PROTOCOL_MAJOR(conn
->pversion
) >= 3)
1502 /* Read message length word */
1503 if (pqGetInt(&msgLength
, 4, conn
))
1505 /* We'll come back when there is more data */
1506 return PGRES_POLLING_READING
;
1511 /* Set phony message length to disable checks below */
1516 * Try to validate message length before using it.
1517 * Authentication requests can't be very large, although GSS
1518 * auth requests may not be that small. Errors can be a
1519 * little larger, but not huge. If we see a large apparent
1520 * length in an error, it means we're really talking to a
1521 * pre-3.0-protocol server; cope.
1523 if (beresp
== 'R' && (msgLength
< 8 || msgLength
> 2000))
1525 printfPQExpBuffer(&conn
->errorMessage
,
1527 "expected authentication request from "
1528 "server, but received %c\n"),
1533 if (beresp
== 'E' && (msgLength
< 8 || msgLength
> 30000))
1535 /* Handle error from a pre-3.0 server */
1536 conn
->inCursor
= conn
->inStart
+ 1; /* reread data */
1537 if (pqGets(&conn
->errorMessage
, conn
))
1539 /* We'll come back when there is more data */
1540 return PGRES_POLLING_READING
;
1542 /* OK, we read the message; mark data consumed */
1543 conn
->inStart
= conn
->inCursor
;
1546 * The postmaster typically won't end its message with a
1547 * newline, so add one to conform to libpq conventions.
1549 appendPQExpBufferChar(&conn
->errorMessage
, '\n');
1552 * If we tried to open the connection in 3.0 protocol,
1553 * fall back to 2.0 protocol.
1555 if (PG_PROTOCOL_MAJOR(conn
->pversion
) >= 3)
1557 conn
->pversion
= PG_PROTOCOL(2, 0);
1558 /* Must drop the old connection */
1559 pqsecure_close(conn
);
1560 closesocket(conn
->sock
);
1562 conn
->status
= CONNECTION_NEEDED
;
1570 * Can't process if message body isn't all here yet.
1572 * (In protocol 2.0 case, we are assuming messages carry at
1573 * least 4 bytes of data.)
1576 avail
= conn
->inEnd
- conn
->inCursor
;
1577 if (avail
< msgLength
)
1580 * Before returning, try to enlarge the input buffer if
1581 * needed to hold the whole message; see notes in
1584 if (pqCheckInBufferSpace(conn
->inCursor
+ (size_t) msgLength
,
1587 /* We'll come back when there is more data */
1588 return PGRES_POLLING_READING
;
1591 /* Handle errors. */
1594 if (PG_PROTOCOL_MAJOR(conn
->pversion
) >= 3)
1596 if (pqGetErrorNotice3(conn
, true))
1598 /* We'll come back when there is more data */
1599 return PGRES_POLLING_READING
;
1604 if (pqGets(&conn
->errorMessage
, conn
))
1606 /* We'll come back when there is more data */
1607 return PGRES_POLLING_READING
;
1610 /* OK, we read the message; mark data consumed */
1611 conn
->inStart
= conn
->inCursor
;
1616 * if sslmode is "allow" and we haven't tried an SSL
1617 * connection already, then retry with an SSL connection
1619 if (conn
->sslmode
[0] == 'a' /* "allow" */
1620 && conn
->ssl
== NULL
1621 && conn
->allow_ssl_try
1622 && conn
->wait_ssl_try
)
1624 /* only retry once */
1625 conn
->wait_ssl_try
= false;
1626 /* Must drop the old connection */
1627 closesocket(conn
->sock
);
1629 conn
->status
= CONNECTION_NEEDED
;
1634 * if sslmode is "prefer" and we're in an SSL connection,
1635 * then do a non-SSL retry
1637 if (conn
->sslmode
[0] == 'p' /* "prefer" */
1639 && conn
->allow_ssl_try
/* redundant? */
1640 && !conn
->wait_ssl_try
) /* redundant? */
1642 /* only retry once */
1643 conn
->allow_ssl_try
= false;
1644 /* Must drop the old connection */
1645 pqsecure_close(conn
);
1646 closesocket(conn
->sock
);
1648 conn
->status
= CONNECTION_NEEDED
;
1656 /* It is an authentication request. */
1657 /* Get the type of request. */
1658 if (pqGetInt((int *) &areq
, 4, conn
))
1660 /* We'll come back when there are more data */
1661 return PGRES_POLLING_READING
;
1664 /* Get the password salt if there is one. */
1665 if (areq
== AUTH_REQ_MD5
)
1667 if (pqGetnchar(conn
->md5Salt
,
1668 sizeof(conn
->md5Salt
), conn
))
1670 /* We'll come back when there are more data */
1671 return PGRES_POLLING_READING
;
1674 if (areq
== AUTH_REQ_CRYPT
)
1676 if (pqGetnchar(conn
->cryptSalt
,
1677 sizeof(conn
->cryptSalt
), conn
))
1679 /* We'll come back when there are more data */
1680 return PGRES_POLLING_READING
;
1683 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1686 * Continue GSSAPI/SSPI authentication
1688 if (areq
== AUTH_REQ_GSS_CONT
)
1690 int llen
= msgLength
- 4;
1693 * We can be called repeatedly for the same buffer. Avoid
1694 * re-allocating the buffer in this case - just re-use the
1697 if (llen
!= conn
->ginbuf
.length
)
1699 if (conn
->ginbuf
.value
)
1700 free(conn
->ginbuf
.value
);
1702 conn
->ginbuf
.length
= llen
;
1703 conn
->ginbuf
.value
= malloc(llen
);
1704 if (!conn
->ginbuf
.value
)
1706 printfPQExpBuffer(&conn
->errorMessage
,
1707 libpq_gettext("out of memory allocating GSSAPI buffer (%i)"),
1713 if (pqGetnchar(conn
->ginbuf
.value
, llen
, conn
))
1715 /* We'll come back when there is more data. */
1716 return PGRES_POLLING_READING
;
1722 * OK, we successfully read the message; mark data consumed
1724 conn
->inStart
= conn
->inCursor
;
1726 /* Respond to the request if necessary. */
1729 * Note that conn->pghost must be non-NULL if we are going to
1730 * avoid the Kerberos code doing a hostname look-up.
1733 if (pg_fe_sendauth(areq
, conn
) != STATUS_OK
)
1735 conn
->errorMessage
.len
= strlen(conn
->errorMessage
.data
);
1738 conn
->errorMessage
.len
= strlen(conn
->errorMessage
.data
);
1741 * Just make sure that any data sent by pg_fe_sendauth is
1742 * flushed out. Although this theoretically could block, it
1743 * really shouldn't since we don't send large auth responses.
1748 if (areq
== AUTH_REQ_OK
)
1750 /* We are done with authentication exchange */
1751 conn
->status
= CONNECTION_AUTH_OK
;
1754 * Set asyncStatus so that PQsetResult will think that
1755 * what comes back next is the result of a query. See
1758 conn
->asyncStatus
= PGASYNC_BUSY
;
1761 /* Look to see if we have more data yet. */
1765 case CONNECTION_AUTH_OK
:
1768 * Now we expect to hear from the backend. A ReadyForQuery
1769 * message indicates that startup is successful, but we might
1770 * also get an Error message indicating failure. (Notice
1771 * messages indicating nonfatal warnings are also allowed by
1772 * the protocol, as are ParameterStatus and BackendKeyData
1773 * messages.) Easiest way to handle this is to let
1774 * PQgetResult() read the messages. We just have to fake it
1775 * out about the state of the connection, by setting
1776 * asyncStatus = PGASYNC_BUSY (done above).
1780 return PGRES_POLLING_READING
;
1782 res
= PQgetResult(conn
);
1785 * NULL return indicating we have gone to IDLE state is
1790 if (res
->resultStatus
!= PGRES_FATAL_ERROR
)
1791 printfPQExpBuffer(&conn
->errorMessage
,
1792 libpq_gettext("unexpected message from server during startup\n"));
1795 * if the resultStatus is FATAL, then conn->errorMessage
1796 * already has a copy of the error; needn't copy it back.
1797 * But add a newline if it's not there already, since
1798 * postmaster error messages may not have one.
1800 if (conn
->errorMessage
.len
<= 0 ||
1801 conn
->errorMessage
.data
[conn
->errorMessage
.len
- 1] != '\n')
1802 appendPQExpBufferChar(&conn
->errorMessage
, '\n');
1807 /* We can release the address list now. */
1808 pg_freeaddrinfo_all(conn
->addrlist_family
, conn
->addrlist
);
1809 conn
->addrlist
= NULL
;
1810 conn
->addr_cur
= NULL
;
1812 /* Fire up post-connection housekeeping if needed */
1813 if (PG_PROTOCOL_MAJOR(conn
->pversion
) < 3)
1815 conn
->status
= CONNECTION_SETENV
;
1816 conn
->setenv_state
= SETENV_STATE_OPTION_SEND
;
1817 conn
->next_eo
= EnvironmentOptions
;
1818 return PGRES_POLLING_WRITING
;
1821 /* Otherwise, we are open for business! */
1822 conn
->status
= CONNECTION_OK
;
1823 return PGRES_POLLING_OK
;
1826 case CONNECTION_SETENV
:
1829 * Do post-connection housekeeping (only needed in protocol 2.0).
1831 * We pretend that the connection is OK for the duration of these
1834 conn
->status
= CONNECTION_OK
;
1836 switch (pqSetenvPoll(conn
))
1838 case PGRES_POLLING_OK
: /* Success */
1841 case PGRES_POLLING_READING
: /* Still going */
1842 conn
->status
= CONNECTION_SETENV
;
1843 return PGRES_POLLING_READING
;
1845 case PGRES_POLLING_WRITING
: /* Still going */
1846 conn
->status
= CONNECTION_SETENV
;
1847 return PGRES_POLLING_WRITING
;
1853 /* We are open for business! */
1854 conn
->status
= CONNECTION_OK
;
1855 return PGRES_POLLING_OK
;
1858 printfPQExpBuffer(&conn
->errorMessage
,
1860 "invalid connection state %c, "
1861 "probably indicative of memory corruption\n"
1872 * We used to close the socket at this point, but that makes it awkward
1873 * for those above us if they wish to remove this socket from their own
1874 * records (an fd_set for example). We'll just have this socket closed
1875 * when PQfinish is called (which is compulsory even after an error, since
1876 * the connection structure must be freed).
1878 conn
->status
= CONNECTION_BAD
;
1879 return PGRES_POLLING_FAILED
;
1885 * - create a PGconn data structure with (as yet) no interesting data
1888 makeEmptyPGconn(void)
1895 * Make sure socket support is up and running.
1899 if (WSAStartup(MAKEWORD(1, 1), &wsaData
))
1904 conn
= (PGconn
*) malloc(sizeof(PGconn
));
1913 /* Zero all pointers and booleans */
1914 MemSet(conn
, 0, sizeof(PGconn
));
1916 conn
->noticeHooks
.noticeRec
= defaultNoticeReceiver
;
1917 conn
->noticeHooks
.noticeProc
= defaultNoticeProcessor
;
1918 conn
->status
= CONNECTION_BAD
;
1919 conn
->asyncStatus
= PGASYNC_IDLE
;
1920 conn
->xactStatus
= PQTRANS_IDLE
;
1921 conn
->options_valid
= false;
1922 conn
->nonblocking
= false;
1923 conn
->setenv_state
= SETENV_STATE_IDLE
;
1924 conn
->client_encoding
= PG_SQL_ASCII
;
1925 conn
->std_strings
= false; /* unless server says differently */
1926 conn
->verbosity
= PQERRORS_DEFAULT
;
1928 conn
->password_needed
= false;
1930 conn
->allow_ssl_try
= true;
1931 conn
->wait_ssl_try
= false;
1935 * We try to send at least 8K at a time, which is the usual size of pipe
1936 * buffers on Unix systems. That way, when we are sending a large amount
1937 * of data, we avoid incurring extra kernel context swaps for partial
1938 * bufferloads. The output buffer is initially made 16K in size, and we
1939 * try to dump it after accumulating 8K.
1941 * With the same goal of minimizing context swaps, the input buffer will
1942 * be enlarged anytime it has less than 8K free, so we initially allocate
1945 conn
->inBufSize
= 16 * 1024;
1946 conn
->inBuffer
= (char *) malloc(conn
->inBufSize
);
1947 conn
->outBufSize
= 16 * 1024;
1948 conn
->outBuffer
= (char *) malloc(conn
->outBufSize
);
1949 initPQExpBuffer(&conn
->errorMessage
);
1950 initPQExpBuffer(&conn
->workBuffer
);
1952 if (conn
->inBuffer
== NULL
||
1953 conn
->outBuffer
== NULL
||
1954 conn
->errorMessage
.data
== NULL
||
1955 conn
->workBuffer
.data
== NULL
)
1957 /* out of memory already :-( */
1967 * - free an idle (closed) PGconn data structure
1969 * NOTE: this should not overlap any functionality with closePGconn().
1970 * Clearing/resetting of transient state belongs there; what we do here is
1971 * release data that is to be held for the life of the PGconn structure.
1972 * If a value ought to be cleared/freed during PQreset(), do it there not here.
1975 freePGconn(PGconn
*conn
)
1979 /* let any event procs clean up their state data */
1980 for (i
= 0; i
< conn
->nEvents
; i
++)
1982 PGEventConnDestroy evt
;
1985 (void) conn
->events
[i
].proc(PGEVT_CONNDESTROY
, &evt
,
1986 conn
->events
[i
].passThrough
);
1987 free(conn
->events
[i
].name
);
1994 if (conn
->pghostaddr
)
1995 free(conn
->pghostaddr
);
1998 if (conn
->pgunixsocket
)
1999 free(conn
->pgunixsocket
);
2002 if (conn
->connect_timeout
)
2003 free(conn
->connect_timeout
);
2004 if (conn
->pgoptions
)
2005 free(conn
->pgoptions
);
2013 free(conn
->sslmode
);
2014 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2015 if (conn
->krbsrvname
)
2016 free(conn
->krbsrvname
);
2018 /* Note that conn->Pfdebug is not ours to close or free */
2019 if (conn
->last_query
)
2020 free(conn
->last_query
);
2022 free(conn
->inBuffer
);
2023 if (conn
->outBuffer
)
2024 free(conn
->outBuffer
);
2025 termPQExpBuffer(&conn
->errorMessage
);
2026 termPQExpBuffer(&conn
->workBuffer
);
2037 * - properly close a connection to the backend
2039 * This should reset or release all transient state, but NOT the connection
2040 * parameters. On exit, the PGconn should be in condition to start a fresh
2041 * connection with the same parameters (see PQreset()).
2044 closePGconn(PGconn
*conn
)
2047 pgParameterStatus
*pstatus
;
2050 * Note that the protocol doesn't allow us to send Terminate messages
2051 * during the startup phase.
2053 if (conn
->sock
>= 0 && conn
->status
== CONNECTION_OK
)
2056 * Try to send "close connection" message to backend. Ignore any
2059 pqPutMsgStart('X', false, conn
);
2065 * Must reset the blocking status so a possible reconnect will work.
2067 * Don't call PQsetnonblocking() because it will fail if it's unable to
2068 * flush the connection.
2070 conn
->nonblocking
= FALSE
;
2073 * Close the connection, reset all transient state, flush I/O buffers.
2075 if (conn
->sock
>= 0)
2077 pqsecure_close(conn
);
2078 closesocket(conn
->sock
);
2081 conn
->status
= CONNECTION_BAD
; /* Well, not really _bad_ - just
2083 conn
->asyncStatus
= PGASYNC_IDLE
;
2084 pqClearAsyncResult(conn
); /* deallocate result and curTuple */
2085 pg_freeaddrinfo_all(conn
->addrlist_family
, conn
->addrlist
);
2086 conn
->addrlist
= NULL
;
2087 conn
->addr_cur
= NULL
;
2088 notify
= conn
->notifyHead
;
2089 while (notify
!= NULL
)
2091 PGnotify
*prev
= notify
;
2093 notify
= notify
->next
;
2096 conn
->notifyHead
= conn
->notifyTail
= NULL
;
2097 pstatus
= conn
->pstatus
;
2098 while (pstatus
!= NULL
)
2100 pgParameterStatus
*prev
= pstatus
;
2102 pstatus
= pstatus
->next
;
2105 conn
->pstatus
= NULL
;
2106 if (conn
->lobjfuncs
)
2107 free(conn
->lobjfuncs
);
2108 conn
->lobjfuncs
= NULL
;
2109 conn
->inStart
= conn
->inCursor
= conn
->inEnd
= 0;
2116 gss_delete_sec_context(&min_s
, &conn
->gctx
, GSS_C_NO_BUFFER
);
2117 if (conn
->gtarg_nam
)
2118 gss_release_name(&min_s
, &conn
->gtarg_nam
);
2119 if (conn
->ginbuf
.length
)
2120 gss_release_buffer(&min_s
, &conn
->ginbuf
);
2121 if (conn
->goutbuf
.length
)
2122 gss_release_buffer(&min_s
, &conn
->goutbuf
);
2126 if (conn
->ginbuf
.length
)
2127 free(conn
->ginbuf
.value
);
2128 conn
->ginbuf
.length
= 0;
2129 conn
->ginbuf
.value
= NULL
;
2130 if (conn
->sspitarget
)
2131 free(conn
->sspitarget
);
2132 conn
->sspitarget
= NULL
;
2135 FreeCredentialsHandle(conn
->sspicred
);
2136 free(conn
->sspicred
);
2137 conn
->sspicred
= NULL
;
2141 DeleteSecurityContext(conn
->sspictx
);
2142 free(conn
->sspictx
);
2143 conn
->sspictx
= NULL
;
2149 * PQfinish: properly close a connection to the backend. Also frees
2150 * the PGconn data structure so it shouldn't be re-used after this.
2153 PQfinish(PGconn
*conn
)
2163 * PQreset: resets the connection to the backend by closing the
2164 * existing connection and creating a new one.
2167 PQreset(PGconn
*conn
)
2173 if (connectDBStart(conn
) && connectDBComplete(conn
))
2176 * Notify event procs of successful reset. We treat an event
2177 * proc failure as disabling the connection ... good idea?
2181 for (i
= 0; i
< conn
->nEvents
; i
++)
2183 PGEventConnReset evt
;
2186 if (!conn
->events
[i
].proc(PGEVT_CONNRESET
, &evt
,
2187 conn
->events
[i
].passThrough
))
2189 conn
->status
= CONNECTION_BAD
;
2190 printfPQExpBuffer(&conn
->errorMessage
,
2191 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2192 conn
->events
[i
].name
);
2203 * resets the connection to the backend
2204 * closes the existing connection and makes a new one
2205 * Returns 1 on success, 0 on failure.
2208 PQresetStart(PGconn
*conn
)
2214 return connectDBStart(conn
);
2223 * resets the connection to the backend
2224 * closes the existing connection and makes a new one
2226 PostgresPollingStatusType
2227 PQresetPoll(PGconn
*conn
)
2231 PostgresPollingStatusType status
= PQconnectPoll(conn
);
2233 if (status
== PGRES_POLLING_OK
)
2236 * Notify event procs of successful reset. We treat an event
2237 * proc failure as disabling the connection ... good idea?
2241 for (i
= 0; i
< conn
->nEvents
; i
++)
2243 PGEventConnReset evt
;
2246 if (!conn
->events
[i
].proc(PGEVT_CONNRESET
, &evt
,
2247 conn
->events
[i
].passThrough
))
2249 conn
->status
= CONNECTION_BAD
;
2250 printfPQExpBuffer(&conn
->errorMessage
,
2251 libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
2252 conn
->events
[i
].name
);
2253 return PGRES_POLLING_FAILED
;
2261 return PGRES_POLLING_FAILED
;
2265 * PQcancelGet: get a PGcancel structure corresponding to a connection.
2267 * A copy is needed to be able to cancel a running query from a different
2268 * thread. If the same structure is used all structure members would have
2269 * to be individually locked (if the entire structure was locked, it would
2270 * be impossible to cancel a synchronous query because the structure would
2271 * have to stay locked for the duration of the query).
2274 PQgetCancel(PGconn
*conn
)
2284 cancel
= malloc(sizeof(PGcancel
));
2288 memcpy(&cancel
->raddr
, &conn
->raddr
, sizeof(SockAddr
));
2289 cancel
->be_pid
= conn
->be_pid
;
2290 cancel
->be_key
= conn
->be_key
;
2295 /* PQfreeCancel: free a cancel structure */
2297 PQfreeCancel(PGcancel
*cancel
)
2305 * PQcancel and PQrequestCancel: attempt to request cancellation of the
2306 * current operation.
2308 * The return value is TRUE if the cancel request was successfully
2309 * dispatched, FALSE if not (in which case an error message is available).
2310 * Note: successful dispatch is no guarantee that there will be any effect at
2311 * the backend. The application must read the operation result as usual.
2313 * CAUTION: we want this routine to be safely callable from a signal handler
2314 * (for example, an application might want to call it in a SIGINT handler).
2315 * This means we cannot use any C library routine that might be non-reentrant.
2316 * malloc/free are often non-reentrant, and anything that might call them is
2317 * just as dangerous. We avoid sprintf here for that reason. Building up
2318 * error messages with strcpy/strcat is tedious but should be quite safe.
2319 * We also save/restore errno in case the signal handler support doesn't.
2321 * internal_cancel() is an internal helper function to make code-sharing
2322 * between the two versions of the cancel function possible.
2325 internal_cancel(SockAddr
*raddr
, int be_pid
, int be_key
,
2326 char *errbuf
, int errbufsize
)
2328 int save_errno
= SOCK_ERRNO
;
2335 CancelRequestPacket cp
;
2339 * We need to open a temporary connection to the postmaster. Do this with
2340 * only kernel calls.
2342 if ((tmpsock
= socket(raddr
->addr
.ss_family
, SOCK_STREAM
, 0)) < 0)
2344 strlcpy(errbuf
, "PQcancel() -- socket() failed: ", errbufsize
);
2345 goto cancel_errReturn
;
2348 if (connect(tmpsock
, (struct sockaddr
*) & raddr
->addr
,
2351 if (SOCK_ERRNO
== EINTR
)
2352 /* Interrupted system call - we'll just try again */
2354 strlcpy(errbuf
, "PQcancel() -- connect() failed: ", errbufsize
);
2355 goto cancel_errReturn
;
2359 * We needn't set nonblocking I/O or NODELAY options here.
2362 /* Create and send the cancel request packet. */
2364 crp
.packetlen
= htonl((uint32
) sizeof(crp
));
2365 crp
.cp
.cancelRequestCode
= (MsgType
) htonl(CANCEL_REQUEST_CODE
);
2366 crp
.cp
.backendPID
= htonl(be_pid
);
2367 crp
.cp
.cancelAuthCode
= htonl(be_key
);
2370 if (send(tmpsock
, (char *) &crp
, sizeof(crp
), 0) != (int) sizeof(crp
))
2372 if (SOCK_ERRNO
== EINTR
)
2373 /* Interrupted system call - we'll just try again */
2375 strlcpy(errbuf
, "PQcancel() -- send() failed: ", errbufsize
);
2376 goto cancel_errReturn
;
2380 * Wait for the postmaster to close the connection, which indicates that
2381 * it's processed the request. Without this delay, we might issue another
2382 * command only to find that our cancel zaps that command instead of the
2383 * one we thought we were canceling. Note we don't actually expect this
2384 * read to obtain any data, we are just waiting for EOF to be signaled.
2387 if (recv(tmpsock
, (char *) &crp
, 1, 0) < 0)
2389 if (SOCK_ERRNO
== EINTR
)
2390 /* Interrupted system call - we'll just try again */
2392 /* we ignore other error conditions */
2396 closesocket(tmpsock
);
2397 SOCK_ERRNO_SET(save_errno
);
2403 * Make sure we don't overflow the error buffer. Leave space for the \n at
2404 * the end, and for the terminating zero.
2406 maxlen
= errbufsize
- strlen(errbuf
) - 2;
2409 strncat(errbuf
, SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)),
2411 strcat(errbuf
, "\n");
2414 closesocket(tmpsock
);
2415 SOCK_ERRNO_SET(save_errno
);
2420 * PQcancel: request query cancel
2422 * Returns TRUE if able to send the cancel request, FALSE if not.
2424 * On failure, an error message is stored in *errbuf, which must be of size
2425 * errbufsize (recommended size is 256 bytes). *errbuf is not changed on
2429 PQcancel(PGcancel
*cancel
, char *errbuf
, int errbufsize
)
2433 strlcpy(errbuf
, "PQcancel() -- no cancel object supplied", errbufsize
);
2437 return internal_cancel(&cancel
->raddr
, cancel
->be_pid
, cancel
->be_key
,
2438 errbuf
, errbufsize
);
2442 * PQrequestCancel: old, not thread-safe function for requesting query cancel
2444 * Returns TRUE if able to send the cancel request, FALSE if not.
2446 * On failure, the error message is saved in conn->errorMessage; this means
2447 * that this can't be used when there might be other active operations on
2448 * the connection object.
2450 * NOTE: error messages will be cut off at the current size of the
2451 * error message buffer, since we dare not try to expand conn->errorMessage!
2454 PQrequestCancel(PGconn
*conn
)
2458 /* Check we have an open connection */
2464 strlcpy(conn
->errorMessage
.data
,
2465 "PQrequestCancel() -- connection is not open\n",
2466 conn
->errorMessage
.maxlen
);
2467 conn
->errorMessage
.len
= strlen(conn
->errorMessage
.data
);
2472 r
= internal_cancel(&conn
->raddr
, conn
->be_pid
, conn
->be_key
,
2473 conn
->errorMessage
.data
, conn
->errorMessage
.maxlen
);
2476 conn
->errorMessage
.len
= strlen(conn
->errorMessage
.data
);
2483 * pqPacketSend() -- convenience routine to send a message to server.
2485 * pack_type: the single-byte message type code. (Pass zero for startup
2486 * packets, which have no message type code.)
2488 * buf, buf_len: contents of message. The given length includes only what
2489 * is in buf; the message type and message length fields are added here.
2491 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2492 * SIDE_EFFECTS: may block.
2494 * Note: all messages sent with this routine have a length word, whether
2495 * it's protocol 2.0 or 3.0.
2498 pqPacketSend(PGconn
*conn
, char pack_type
,
2499 const void *buf
, size_t buf_len
)
2501 /* Start the message. */
2502 if (pqPutMsgStart(pack_type
, true, conn
))
2503 return STATUS_ERROR
;
2505 /* Send the message body. */
2506 if (pqPutnchar(buf
, buf_len
, conn
))
2507 return STATUS_ERROR
;
2509 /* Finish the message. */
2510 if (pqPutMsgEnd(conn
))
2511 return STATUS_ERROR
;
2513 /* Flush to ensure backend gets it. */
2515 return STATUS_ERROR
;
2522 #define LDAP_URL "ldap://"
2523 #define LDAP_DEF_PORT 389
2524 #define PGLDAP_TIMEOUT 2
2526 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
2527 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
2533 * Search the LDAP URL passed as first argument, treat the result as a
2534 * string of connection options that are parsed and added to the array of
2535 * options passed as second argument.
2537 * LDAP URLs must conform to RFC 1959 without escape sequences.
2538 * ldap://host:port/dn?attributes?scope?filter?extensions
2541 * 0 if the lookup was successful,
2542 * 1 if the connection to the LDAP server could be established but
2543 * the search was unsuccessful,
2544 * 2 if a connection could not be established, and
2545 * 3 if a fatal error occurred.
2547 * An error message is returned in the third argument for return codes 1 and 3.
2550 ldapServiceLookup(const char *purl
, PQconninfoOption
*options
,
2551 PQExpBuffer errorMessage
)
2553 int port
= LDAP_DEF_PORT
,
2574 char *attrs
[2] = {NULL
, NULL
};
2578 struct berval
**values
;
2579 LDAP_TIMEVAL time
= {PGLDAP_TIMEOUT
, 0};
2581 if ((url
= strdup(purl
)) == NULL
)
2583 printfPQExpBuffer(errorMessage
, libpq_gettext("out of memory\n"));
2588 * Parse URL components, check for correctness. Basically, url has '\0'
2589 * placed at component boundaries and variables are pointed at each
2593 if (pg_strncasecmp(url
, LDAP_URL
, strlen(LDAP_URL
)) != 0)
2595 printfPQExpBuffer(errorMessage
,
2596 libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl
);
2602 hostname
= url
+ strlen(LDAP_URL
);
2603 if (*hostname
== '/') /* no hostname? */
2604 hostname
= "localhost"; /* the default */
2606 /* dn, "distinguished name" */
2607 p
= strchr(url
+ strlen(LDAP_URL
), '/');
2608 if (p
== NULL
|| *(p
+ 1) == '\0' || *(p
+ 1) == '?')
2610 printfPQExpBuffer(errorMessage
, libpq_gettext(
2611 "invalid LDAP URL \"%s\": missing distinguished name\n"), purl
);
2615 *p
= '\0'; /* terminate hostname */
2619 if ((p
= strchr(dn
, '?')) == NULL
|| *(p
+ 1) == '\0' || *(p
+ 1) == '?')
2621 printfPQExpBuffer(errorMessage
, libpq_gettext(
2622 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl
);
2630 if ((p
= strchr(attrs
[0], '?')) == NULL
|| *(p
+ 1) == '\0' || *(p
+ 1) == '?')
2632 printfPQExpBuffer(errorMessage
, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl
);
2640 if ((p
= strchr(scopestr
, '?')) == NULL
|| *(p
+ 1) == '\0' || *(p
+ 1) == '?')
2642 printfPQExpBuffer(errorMessage
,
2643 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl
);
2649 if ((p
= strchr(filter
, '?')) != NULL
)
2653 if ((p1
= strchr(hostname
, ':')) != NULL
)
2660 lport
= strtol(portstr
, &endptr
, 10);
2661 if (*portstr
== '\0' || *endptr
!= '\0' || errno
|| lport
< 0 || lport
> 65535)
2663 printfPQExpBuffer(errorMessage
, libpq_gettext(
2664 "invalid LDAP URL \"%s\": invalid port number\n"), purl
);
2671 /* Allow only one attribute */
2672 if (strchr(attrs
[0], ',') != NULL
)
2674 printfPQExpBuffer(errorMessage
, libpq_gettext(
2675 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl
);
2681 if (pg_strcasecmp(scopestr
, "base") == 0)
2682 scope
= LDAP_SCOPE_BASE
;
2683 else if (pg_strcasecmp(scopestr
, "one") == 0)
2684 scope
= LDAP_SCOPE_ONELEVEL
;
2685 else if (pg_strcasecmp(scopestr
, "sub") == 0)
2686 scope
= LDAP_SCOPE_SUBTREE
;
2689 printfPQExpBuffer(errorMessage
, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl
);
2694 /* initialize LDAP structure */
2695 if ((ld
= ldap_init(hostname
, port
)) == NULL
)
2697 printfPQExpBuffer(errorMessage
,
2698 libpq_gettext("could not create LDAP structure\n"));
2704 * Initialize connection to the server. We do an explicit bind because we
2705 * want to return 2 if the bind fails.
2707 if ((msgid
= ldap_simple_bind(ld
, NULL
, NULL
)) == -1)
2709 /* error in ldap_simple_bind() */
2715 /* wait some time for the connection to succeed */
2717 if ((rc
= ldap_result(ld
, msgid
, LDAP_MSG_ALL
, &time
, &res
)) == -1 ||
2725 /* error in ldap_result() */
2734 if ((rc
= ldap_search_st(ld
, dn
, scope
, filter
, attrs
, 0, &time
, &res
))
2739 printfPQExpBuffer(errorMessage
,
2740 libpq_gettext("lookup on LDAP server failed: %s\n"),
2741 ldap_err2string(rc
));
2747 /* complain if there was not exactly one result */
2748 if ((rc
= ldap_count_entries(ld
, res
)) != 1)
2750 printfPQExpBuffer(errorMessage
,
2751 rc
? libpq_gettext("more than one entry found on LDAP lookup\n")
2752 : libpq_gettext("no entry found on LDAP lookup\n"));
2760 if ((entry
= ldap_first_entry(ld
, res
)) == NULL
)
2762 /* should never happen */
2763 printfPQExpBuffer(errorMessage
,
2764 libpq_gettext("no entry found on LDAP lookup\n"));
2772 if ((values
= ldap_get_values_len(ld
, entry
, attrs
[0])) == NULL
)
2774 printfPQExpBuffer(errorMessage
,
2775 libpq_gettext("attribute has no values on LDAP lookup\n"));
2785 if (values
[0] == NULL
)
2787 printfPQExpBuffer(errorMessage
,
2788 libpq_gettext("attribute has no values on LDAP lookup\n"));
2789 ldap_value_free_len(values
);
2794 /* concatenate values to a single string */
2795 for (size
= 0, i
= 0; values
[i
] != NULL
; ++i
)
2796 size
+= values
[i
]->bv_len
+ 1;
2797 if ((result
= malloc(size
+ 1)) == NULL
)
2799 printfPQExpBuffer(errorMessage
,
2800 libpq_gettext("out of memory\n"));
2801 ldap_value_free_len(values
);
2805 for (p
= result
, i
= 0; values
[i
] != NULL
; ++i
)
2807 strncpy(p
, values
[i
]->bv_val
, values
[i
]->bv_len
);
2808 p
+= values
[i
]->bv_len
;
2810 if (values
[i
+ 1] == NULL
)
2814 ldap_value_free_len(values
);
2817 /* parse result string */
2818 oldstate
= state
= 0;
2819 for (p
= result
; *p
!= '\0'; ++p
)
2823 case 0: /* between entries */
2824 if (!ld_is_sp_tab(*p
) && !ld_is_nl_cr(*p
))
2830 case 1: /* in option name */
2831 if (ld_is_sp_tab(*p
))
2836 else if (ld_is_nl_cr(*p
))
2838 printfPQExpBuffer(errorMessage
, libpq_gettext(
2839 "missing \"=\" after \"%s\" in connection info string\n"),
2849 case 2: /* after option name */
2854 else if (!ld_is_sp_tab(*p
))
2856 printfPQExpBuffer(errorMessage
, libpq_gettext(
2857 "missing \"=\" after \"%s\" in connection info string\n"),
2862 case 3: /* before option value */
2869 else if (ld_is_nl_cr(*p
))
2871 optval
= optname
+ strlen(optname
); /* empty */
2874 else if (!ld_is_sp_tab(*p
))
2880 case 4: /* in unquoted option value */
2881 if (ld_is_sp_tab(*p
) || ld_is_nl_cr(*p
))
2887 case 5: /* in quoted option value */
2893 else if (*p
== '\\')
2898 case 6: /* in quoted option value after escape */
2904 if (state
== 0 && oldstate
!= 0)
2906 found_keyword
= false;
2907 for (i
= 0; options
[i
].keyword
; i
++)
2909 if (strcmp(options
[i
].keyword
, optname
) == 0)
2911 if (options
[i
].val
== NULL
)
2912 options
[i
].val
= strdup(optval
);
2913 found_keyword
= true;
2919 printfPQExpBuffer(errorMessage
,
2920 libpq_gettext("invalid connection option \"%s\"\n"),
2930 if (state
== 5 || state
== 6)
2932 printfPQExpBuffer(errorMessage
, libpq_gettext(
2933 "unterminated quoted string in connection info string\n"));
2941 #define MAXBUFSIZE 256
2944 parseServiceInfo(PQconninfoOption
*options
, PQExpBuffer errorMessage
)
2946 char *service
= conninfo_getval(options
, "service");
2947 char serviceFile
[MAXPGPATH
];
2948 bool group_found
= false;
2953 * We have to special-case the environment variable PGSERVICE here, since
2954 * this is and should be called before inserting environment defaults for
2955 * other connection options.
2957 if (service
== NULL
)
2958 service
= getenv("PGSERVICE");
2961 * This could be used by any application so we can't use the binary
2962 * location to find our config files.
2964 snprintf(serviceFile
, MAXPGPATH
, "%s/pg_service.conf",
2965 getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR
);
2967 if (service
!= NULL
)
2970 char buf
[MAXBUFSIZE
],
2973 f
= fopen(serviceFile
, "r");
2976 printfPQExpBuffer(errorMessage
, libpq_gettext("ERROR: service file \"%s\" not found\n"),
2981 while ((line
= fgets(buf
, sizeof(buf
), f
)) != NULL
)
2985 if (strlen(line
) >= sizeof(buf
) - 1)
2988 printfPQExpBuffer(errorMessage
,
2989 libpq_gettext("ERROR: line %d too long in service file \"%s\"\n"),
2995 /* ignore EOL at end of line */
2996 if (strlen(line
) && line
[strlen(line
) - 1] == '\n')
2997 line
[strlen(line
) - 1] = 0;
2999 /* ignore leading blanks */
3000 while (*line
&& isspace((unsigned char) line
[0]))
3003 /* ignore comments and empty lines */
3004 if (strlen(line
) == 0 || line
[0] == '#')
3007 /* Check for right groupname */
3012 /* group info already read */
3017 if (strncmp(line
+ 1, service
, strlen(service
)) == 0 &&
3018 line
[strlen(service
) + 1] == ']')
3021 group_found
= false;
3028 * Finally, we are in the right group and can parse the
3036 if (strncmp(line
, "ldap", 4) == 0)
3038 int rc
= ldapServiceLookup(line
, options
, errorMessage
);
3040 /* if rc = 2, go on reading for fallback */
3057 val
= strchr(line
, '=');
3060 printfPQExpBuffer(errorMessage
,
3061 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3070 * Set the parameter --- but don't override any previous
3073 found_keyword
= false;
3074 for (i
= 0; options
[i
].keyword
; i
++)
3076 if (strcmp(options
[i
].keyword
, key
) == 0)
3078 if (options
[i
].val
== NULL
)
3079 options
[i
].val
= strdup(val
);
3080 found_keyword
= true;
3087 printfPQExpBuffer(errorMessage
,
3088 libpq_gettext("ERROR: syntax error in service file \"%s\", line %d\n"),
3108 * Parse a string like PQconnectdb() would do and return the
3109 * resulting connection options array. NULL is returned on failure.
3110 * The result contains only options specified directly in the string,
3111 * not any possible default values.
3113 * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3114 * string on failure (use PQfreemem to free it). In out-of-memory conditions
3115 * both *errmsg and the result could be NULL.
3117 * NOTE: the returned array is dynamically allocated and should
3118 * be freed when no longer needed via PQconninfoFree().
3121 PQconninfoParse(const char *conninfo
, char **errmsg
)
3123 PQExpBufferData errorBuf
;
3124 PQconninfoOption
*connOptions
;
3127 *errmsg
= NULL
; /* default */
3128 initPQExpBuffer(&errorBuf
);
3129 if (errorBuf
.data
== NULL
)
3130 return NULL
; /* out of memory already :-( */
3131 connOptions
= conninfo_parse(conninfo
, &errorBuf
, false);
3132 if (connOptions
== NULL
&& errmsg
)
3133 *errmsg
= errorBuf
.data
;
3135 termPQExpBuffer(&errorBuf
);
3140 * Conninfo parser routine
3142 * If successful, a malloc'd PQconninfoOption array is returned.
3143 * If not successful, NULL is returned and an error message is
3144 * left in errorMessage.
3145 * Defaults are supplied (from a service file, environment variables, etc)
3146 * for unspecified options, but only if use_defaults is TRUE.
3148 static PQconninfoOption
*
3149 conninfo_parse(const char *conninfo
, PQExpBuffer errorMessage
,
3158 PQconninfoOption
*options
;
3159 PQconninfoOption
*option
;
3161 /* Make a working copy of PQconninfoOptions */
3162 options
= malloc(sizeof(PQconninfoOptions
));
3163 if (options
== NULL
)
3165 printfPQExpBuffer(errorMessage
,
3166 libpq_gettext("out of memory\n"));
3169 memcpy(options
, PQconninfoOptions
, sizeof(PQconninfoOptions
));
3171 /* Need a modifiable copy of the input string */
3172 if ((buf
= strdup(conninfo
)) == NULL
)
3174 printfPQExpBuffer(errorMessage
,
3175 libpq_gettext("out of memory\n"));
3176 PQconninfoFree(options
);
3183 /* Skip blanks before the parameter name */
3184 if (isspace((unsigned char) *cp
))
3190 /* Get the parameter name */
3196 if (isspace((unsigned char) *cp
))
3201 if (!isspace((unsigned char) *cp
))
3210 /* Check that there is a following '=' */
3213 printfPQExpBuffer(errorMessage
,
3214 libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
3216 PQconninfoFree(options
);
3222 /* Skip blanks after the '=' */
3225 if (!isspace((unsigned char) *cp
))
3230 /* Get the parameter value */
3238 if (isspace((unsigned char) *cp
))
3262 printfPQExpBuffer(errorMessage
,
3263 libpq_gettext("unterminated quoted string in connection info string\n"));
3264 PQconninfoFree(options
);
3286 * Now we have the name and the value. Search for the param record.
3288 for (option
= options
; option
->keyword
!= NULL
; option
++)
3290 if (strcmp(option
->keyword
, pname
) == 0)
3293 if (option
->keyword
== NULL
)
3295 printfPQExpBuffer(errorMessage
,
3296 libpq_gettext("invalid connection option \"%s\"\n"),
3298 PQconninfoFree(options
);
3308 option
->val
= strdup(pval
);
3311 printfPQExpBuffer(errorMessage
,
3312 libpq_gettext("out of memory\n"));
3313 PQconninfoFree(options
);
3319 /* Done with the modifiable input string */
3323 * Stop here if caller doesn't want defaults filled in.
3329 * If there's a service spec, use it to obtain any not-explicitly-given
3332 if (parseServiceInfo(options
, errorMessage
))
3334 PQconninfoFree(options
);
3339 * Get the fallback resources for parameters not specified in the conninfo
3340 * string nor the service.
3342 for (option
= options
; option
->keyword
!= NULL
; option
++)
3344 if (option
->val
!= NULL
)
3345 continue; /* Value was in conninfo or service */
3348 * Try to get the environment variable fallback
3350 if (option
->envvar
!= NULL
)
3352 if ((tmp
= getenv(option
->envvar
)) != NULL
)
3354 option
->val
= strdup(tmp
);
3357 printfPQExpBuffer(errorMessage
,
3358 libpq_gettext("out of memory\n"));
3359 PQconninfoFree(options
);
3367 * No environment variable specified or this one isn't set - try
3370 if (option
->compiled
!= NULL
)
3372 option
->val
= strdup(option
->compiled
);
3375 printfPQExpBuffer(errorMessage
,
3376 libpq_gettext("out of memory\n"));
3377 PQconninfoFree(options
);
3384 * Special handling for user
3386 if (strcmp(option
->keyword
, "user") == 0)
3388 option
->val
= pg_fe_getauthname(errorMessage
);
3398 conninfo_getval(PQconninfoOption
*connOptions
,
3399 const char *keyword
)
3401 PQconninfoOption
*option
;
3403 for (option
= connOptions
; option
->keyword
!= NULL
; option
++)
3405 if (strcmp(option
->keyword
, keyword
) == 0)
3414 PQconninfoFree(PQconninfoOption
*connOptions
)
3416 PQconninfoOption
*option
;
3418 if (connOptions
== NULL
)
3421 for (option
= connOptions
; option
->keyword
!= NULL
; option
++)
3423 if (option
->val
!= NULL
)
3430 /* =========== accessor functions for PGconn ========= */
3432 PQdb(const PGconn
*conn
)
3436 return conn
->dbName
;
3440 PQuser(const PGconn
*conn
)
3444 return conn
->pguser
;
3448 PQpass(const PGconn
*conn
)
3452 return conn
->pgpass
;
3456 PQhost(const PGconn
*conn
)
3460 return conn
->pghost
? conn
->pghost
: conn
->pgunixsocket
;
3464 PQport(const PGconn
*conn
)
3468 return conn
->pgport
;
3472 PQtty(const PGconn
*conn
)
3480 PQoptions(const PGconn
*conn
)
3484 return conn
->pgoptions
;
3488 PQstatus(const PGconn
*conn
)
3491 return CONNECTION_BAD
;
3492 return conn
->status
;
3495 PGTransactionStatusType
3496 PQtransactionStatus(const PGconn
*conn
)
3498 if (!conn
|| conn
->status
!= CONNECTION_OK
)
3499 return PQTRANS_UNKNOWN
;
3500 if (conn
->asyncStatus
!= PGASYNC_IDLE
)
3501 return PQTRANS_ACTIVE
;
3502 return conn
->xactStatus
;
3506 PQparameterStatus(const PGconn
*conn
, const char *paramName
)
3508 const pgParameterStatus
*pstatus
;
3510 if (!conn
|| !paramName
)
3512 for (pstatus
= conn
->pstatus
; pstatus
!= NULL
; pstatus
= pstatus
->next
)
3514 if (strcmp(pstatus
->name
, paramName
) == 0)
3515 return pstatus
->value
;
3521 PQprotocolVersion(const PGconn
*conn
)
3525 if (conn
->status
== CONNECTION_BAD
)
3527 return PG_PROTOCOL_MAJOR(conn
->pversion
);
3531 PQserverVersion(const PGconn
*conn
)
3535 if (conn
->status
== CONNECTION_BAD
)
3537 return conn
->sversion
;
3541 PQerrorMessage(const PGconn
*conn
)
3544 return libpq_gettext("connection pointer is NULL\n");
3546 return conn
->errorMessage
.data
;
3550 PQsocket(const PGconn
*conn
)
3558 PQbackendPID(const PGconn
*conn
)
3560 if (!conn
|| conn
->status
!= CONNECTION_OK
)
3562 return conn
->be_pid
;
3566 PQconnectionNeedsPassword(const PGconn
*conn
)
3570 if (conn
->password_needed
&&
3571 (conn
->pgpass
== NULL
|| conn
->pgpass
[0] == '\0'))
3578 PQconnectionUsedPassword(const PGconn
*conn
)
3582 if (conn
->password_needed
)
3589 PQclientEncoding(const PGconn
*conn
)
3591 if (!conn
|| conn
->status
!= CONNECTION_OK
)
3593 return conn
->client_encoding
;
3597 PQsetClientEncoding(PGconn
*conn
, const char *encoding
)
3600 static const char query
[] = "set client_encoding to '%s'";
3604 if (!conn
|| conn
->status
!= CONNECTION_OK
)
3610 /* check query buffer overflow */
3611 if (sizeof(qbuf
) < (sizeof(query
) + strlen(encoding
)))
3614 /* ok, now send a query */
3615 sprintf(qbuf
, query
, encoding
);
3616 res
= PQexec(conn
, qbuf
);
3620 if (res
->resultStatus
!= PGRES_COMMAND_OK
)
3625 * In protocol 2 we have to assume the setting will stick, and adjust
3626 * our state immediately. In protocol 3 and up we can rely on the
3627 * backend to report the parameter value, and we'll change state at
3630 if (PG_PROTOCOL_MAJOR(conn
->pversion
) < 3)
3631 pqSaveParameterStatus(conn
, "client_encoding", encoding
);
3632 status
= 0; /* everything is ok */
3639 PQsetErrorVerbosity(PGconn
*conn
, PGVerbosity verbosity
)
3644 return PQERRORS_DEFAULT
;
3645 old
= conn
->verbosity
;
3646 conn
->verbosity
= verbosity
;
3651 PQtrace(PGconn
*conn
, FILE *debug_port
)
3656 conn
->Pfdebug
= debug_port
;
3660 PQuntrace(PGconn
*conn
)
3666 fflush(conn
->Pfdebug
);
3667 conn
->Pfdebug
= NULL
;
3672 PQsetNoticeReceiver(PGconn
*conn
, PQnoticeReceiver proc
, void *arg
)
3674 PQnoticeReceiver old
;
3679 old
= conn
->noticeHooks
.noticeRec
;
3682 conn
->noticeHooks
.noticeRec
= proc
;
3683 conn
->noticeHooks
.noticeRecArg
= arg
;
3689 PQsetNoticeProcessor(PGconn
*conn
, PQnoticeProcessor proc
, void *arg
)
3691 PQnoticeProcessor old
;
3696 old
= conn
->noticeHooks
.noticeProc
;
3699 conn
->noticeHooks
.noticeProc
= proc
;
3700 conn
->noticeHooks
.noticeProcArg
= arg
;
3706 * The default notice message receiver just gets the standard notice text
3707 * and sends it to the notice processor. This two-level setup exists
3708 * mostly for backwards compatibility; perhaps we should deprecate use of
3709 * PQsetNoticeProcessor?
3712 defaultNoticeReceiver(void *arg
, const PGresult
*res
)
3714 (void) arg
; /* not used */
3715 if (res
->noticeHooks
.noticeProc
!= NULL
)
3716 (*res
->noticeHooks
.noticeProc
) (res
->noticeHooks
.noticeProcArg
,
3717 PQresultErrorMessage(res
));
3721 * The default notice message processor just prints the
3722 * message on stderr. Applications can override this if they
3723 * want the messages to go elsewhere (a window, for example).
3724 * Note that simply discarding notices is probably a bad idea.
3727 defaultNoticeProcessor(void *arg
, const char *message
)
3729 (void) arg
; /* not used */
3730 /* Note: we expect the supplied string to end with a newline already. */
3731 fprintf(stderr
, "%s", message
);
3735 * returns a pointer to the next token or NULL if the current
3736 * token doesn't match
3739 pwdfMatchesString(char *buf
, char *token
)
3743 bool bslash
= false;
3745 if (buf
== NULL
|| token
== NULL
)
3753 if (*tbuf
== '\\' && !bslash
)
3758 if (*tbuf
== ':' && *ttok
== 0 && !bslash
)
3774 /* Get a password from the password file. Return value is malloc'd. */
3776 PasswordFromFile(char *hostname
, char *port
, char *dbname
, char *username
)
3779 char pgpassfile
[MAXPGPATH
];
3780 struct stat stat_buf
;
3783 #define LINELEN NAMEDATALEN*5
3786 if (dbname
== NULL
|| strlen(dbname
) == 0)
3789 if (username
== NULL
|| strlen(username
) == 0)
3792 /* 'localhost' matches pghost of '' or the default socket directory */
3793 if (hostname
== NULL
)
3794 hostname
= DefaultHost
;
3795 else if (is_absolute_path(hostname
))
3798 * We should probably use canonicalize_path(), but then we have to
3799 * bring path.c into libpq, and it doesn't seem worth it.
3801 if (strcmp(hostname
, DEFAULT_PGSOCKET_DIR
) == 0)
3802 hostname
= DefaultHost
;
3805 port
= DEF_PGPORT_STR
;
3807 if ((passfile_env
= getenv("PGPASSFILE")) != NULL
)
3808 /* use the literal path from the environment, if set */
3809 strlcpy(pgpassfile
, passfile_env
, sizeof(pgpassfile
));
3812 char homedir
[MAXPGPATH
];
3814 if (!pqGetHomeDirectory(homedir
, sizeof(homedir
)))
3816 snprintf(pgpassfile
, MAXPGPATH
, "%s/%s", homedir
, PGPASSFILE
);
3819 /* If password file cannot be opened, ignore it. */
3820 if (stat(pgpassfile
, &stat_buf
) != 0)
3824 if (!S_ISREG(stat_buf
.st_mode
))
3827 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
3832 /* If password file is insecure, alert the user and ignore it. */
3833 if (stat_buf
.st_mode
& (S_IRWXG
| S_IRWXO
))
3836 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
3843 * On Win32, the directory is protected, so we don't have to check the
3848 fp
= fopen(pgpassfile
, "r");
3858 fgets(buf
, sizeof(buf
), fp
);
3864 /* Remove trailing newline */
3865 if (buf
[len
- 1] == '\n')
3868 if ((t
= pwdfMatchesString(t
, hostname
)) == NULL
||
3869 (t
= pwdfMatchesString(t
, port
)) == NULL
||
3870 (t
= pwdfMatchesString(t
, dbname
)) == NULL
||
3871 (t
= pwdfMatchesString(t
, username
)) == NULL
)
3885 * Obtain user's home directory, return in given buffer
3887 * On Unix, this actually returns the user's home directory. On Windows
3888 * it returns the PostgreSQL-specific application data folder.
3890 * This is essentially the same as get_home_path(), but we don't use that
3891 * because we don't want to pull path.c into libpq (it pollutes application
3895 pqGetHomeDirectory(char *buf
, int bufsize
)
3898 char pwdbuf
[BUFSIZ
];
3899 struct passwd pwdstr
;
3900 struct passwd
*pwd
= NULL
;
3902 if (pqGetpwuid(geteuid(), &pwdstr
, pwdbuf
, sizeof(pwdbuf
), &pwd
) != 0)
3904 strlcpy(buf
, pwd
->pw_dir
, bufsize
);
3907 char tmppath
[MAX_PATH
];
3909 ZeroMemory(tmppath
, sizeof(tmppath
));
3910 if (SHGetFolderPath(NULL
, CSIDL_APPDATA
, NULL
, 0, tmppath
) != S_OK
)
3912 snprintf(buf
, bufsize
, "%s/postgresql", tmppath
);
3918 * To keep the API consistent, the locking stubs are always provided, even
3919 * if they are not required.
3923 default_threadlock(int acquire
)
3925 #ifdef ENABLE_THREAD_SAFETY
3927 static pthread_mutex_t singlethread_lock
= PTHREAD_MUTEX_INITIALIZER
;
3929 static pthread_mutex_t singlethread_lock
= NULL
;
3930 static long mutex_initlock
= 0;
3932 if (singlethread_lock
== NULL
)
3934 while (InterlockedExchange(&mutex_initlock
, 1) == 1)
3935 /* loop, another thread own the lock */ ;
3936 if (singlethread_lock
== NULL
)
3938 if (pthread_mutex_init(&singlethread_lock
, NULL
))
3939 PGTHREAD_ERROR("failed to initialize mutex");
3941 InterlockedExchange(&mutex_initlock
, 0);
3946 if (pthread_mutex_lock(&singlethread_lock
))
3947 PGTHREAD_ERROR("failed to lock mutex");
3951 if (pthread_mutex_unlock(&singlethread_lock
))
3952 PGTHREAD_ERROR("failed to unlock mutex");
3958 PQregisterThreadLock(pgthreadlock_t newhandler
)
3960 pgthreadlock_t prev
= pg_g_threadlock
;
3963 pg_g_threadlock
= newhandler
;
3965 pg_g_threadlock
= default_threadlock
;