1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-connect.c,v 1.125 2000/03/24 01:39:55 tgl Exp $
13 *-------------------------------------------------------------------------
16 #include <sys/types.h>
23 #include "libpq-int.h"
29 #include <sys/socket.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
44 #include "miscadmin.h"
45 #include "mb/pg_wchar.h"
49 static int inet_aton(const char *cp, struct in_addr *inp) {
50 unsigned long a = inet_addr(cp);
60 static SSL_CTX *SSL_context = NULL;
63 #define NOTIFYLIST_INITIAL_SIZE 10
64 #define NOTIFYLIST_GROWBY 10
68 * Definition of the conninfo parameters and their fallback resources.
70 * If Environment-Var and Compiled-in are specified as NULL, no
71 * fallback is available. If after all no value can be determined
72 * for an option, an error is returned.
74 * The values for dbname and user are treated specially in conninfo_parse.
75 * If the Compiled-in resource is specified as a NULL value, the
76 * user is determined by fe_getauthname() and for dbname the user
79 * The Label and Disp-Char entries are provided for applications that
80 * want to use PQconndefaults() to create a generic database connection
81 * dialog. Disp-Char is defined as follows:
82 * "" Normal input field
83 * "*" Password field - hide value
84 * "D" Debug option - don't show by default
86 * PQconninfoOptions[] is a constant static array that we use to initialize
87 * a dynamically allocated working copy. All the "val" fields in
88 * PQconninfoOptions[] *must* be NULL. In a working copy, non-null "val"
89 * fields point to malloc'd strings that should be freed when the working
90 * array is freed (see PQconninfoFree).
93 static const PQconninfoOption PQconninfoOptions[] = {
94 /* "authtype" is no longer used, so mark it "don't show". We keep it
95 * in the array so as not to reject conninfo strings from old apps that
96 * might still try to set it.
98 {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
99 "Database-Authtype", "D", 20},
101 {"user", "PGUSER", NULL, NULL,
102 "Database-User", "", 20},
104 {"password", "PGPASSWORD", DefaultPassword, NULL,
105 "Database-Password", "*", 20},
107 {"dbname", "PGDATABASE", NULL, NULL,
108 "Database-Name", "", 20},
110 {"host", "PGHOST", NULL, NULL,
111 "Database-Host", "", 40},
113 {"hostaddr", "PGHOSTADDR", NULL, NULL,
114 "Database-Host-IPv4-Address", "", 15}, /* Room for abc.def.ghi.jkl */
116 {"port", "PGPORT", DEF_PGPORT, NULL,
117 "Database-Port", "", 6},
119 {"tty", "PGTTY", DefaultTty, NULL,
120 "Backend-Debug-TTY", "D", 40},
122 {"options", "PGOPTIONS", DefaultOption, NULL,
123 "Backend-Debug-Options", "D", 40},
125 /* Terminating entry --- MUST BE LAST */
126 {NULL, NULL, NULL, NULL,
130 static const struct EnvironmentOptions
134 } EnvironmentOptions[] =
137 /* common user-interface settings */
139 "PGDATESTYLE", "datestyle"
146 "PGCLIENTENCODING", "client_encoding"
149 /* internal performance-related settings */
159 static int connectDBStart(PGconn *conn);
160 static int connectDBComplete(PGconn *conn);
161 static bool PQsetenvStart(PGconn *conn);
162 static PostgresPollingStatusType PQsetenvPoll(PGconn *conn);
163 static PGconn *makeEmptyPGconn(void);
164 static void freePGconn(PGconn *conn);
165 static void closePGconn(PGconn *conn);
166 static PQconninfoOption *conninfo_parse(const char *conninfo,
167 PQExpBuffer errorMessage);
168 static char *conninfo_getval(PQconninfoOption *connOptions,
169 const char *keyword);
170 static void defaultNoticeProcessor(void *arg, const char *message);
174 * Connecting to a Database
176 * There are now four different ways a user of this API can connect to the
177 * database. Two are not recommended for use in new code, because of their
178 * lack of extensibility with respect to the passing of options to the
179 * backend. These are PQsetdb and PQsetdbLogin (the former now being a macro
182 * If it is desired to connect in a synchronous (blocking) manner, use the
183 * function PQconnectdb.
185 * To connect in an asychronous (non-blocking) manner, use the functions
186 * PQconnectStart, and PQconnectPoll.
188 * Internally, the static functions connectDBStart, connectDBComplete
189 * are part of the connection procedure.
197 * establishes a connection to a postgres backend through the postmaster
198 * using connection information in a string.
200 * The conninfo string is a white-separated list of
204 * definitions. Value might be a single value containing no whitespaces or
205 * a single quoted string. If a single quote should appear anywhere in
206 * the value, it must be escaped with a backslash like \'
208 * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
209 * if a memory allocation failed.
210 * If the status field of the connection returned is CONNECTION_BAD,
211 * then some fields may be null'ed out instead of having valid values.
213 * You should call PQfinish (if conn is not NULL) regardless of whether this
219 PQconnectdb(const char *conninfo)
221 PGconn *conn = PQconnectStart(conninfo);
223 if (conn && conn->status != CONNECTION_BAD)
224 (void) connectDBComplete(conn);
232 * Begins the establishment of a connection to a postgres backend through the
233 * postmaster using connection information in a string.
235 * See comment for PQconnectdb for the definition of the string format.
237 * Returns a PGconn*. If NULL is returned, a malloc error has occurred, and
238 * you should not attempt to proceed with this connection. If the status
239 * field of the connection returned is CONNECTION_BAD, an error has
240 * occurred. In this case you should call PQfinish on the result, (perhaps
241 * inspecting the error message first). Other fields of the structure may not
242 * be valid if that occurs. If the status field is not CONNECTION_BAD, then
243 * this stage has succeeded - call PQconnectPoll, using select(2) to see when
246 * See PQconnectPoll for more info.
251 PQconnectStart(const char *conninfo)
254 PQconninfoOption *connOptions;
258 * Allocate memory for the conn structure
262 conn = makeEmptyPGconn();
264 return (PGconn *) NULL;
267 * Parse the conninfo string
270 connOptions = conninfo_parse(conninfo, &conn->errorMessage);
271 if (connOptions == NULL)
273 conn->status = CONNECTION_BAD;
274 /* errorMessage is already set */
279 * Move option values into conn structure
281 tmp = conninfo_getval(connOptions, "hostaddr");
282 conn->pghostaddr = tmp ? strdup(tmp) : NULL;
283 tmp = conninfo_getval(connOptions, "host");
284 conn->pghost = tmp ? strdup(tmp) : NULL;
285 tmp = conninfo_getval(connOptions, "port");
286 conn->pgport = tmp ? strdup(tmp) : NULL;
287 tmp = conninfo_getval(connOptions, "tty");
288 conn->pgtty = tmp ? strdup(tmp) : NULL;
289 tmp = conninfo_getval(connOptions, "options");
290 conn->pgoptions = tmp ? strdup(tmp) : NULL;
291 tmp = conninfo_getval(connOptions, "dbname");
292 conn->dbName = tmp ? strdup(tmp) : NULL;
293 tmp = conninfo_getval(connOptions, "user");
294 conn->pguser = tmp ? strdup(tmp) : NULL;
295 tmp = conninfo_getval(connOptions, "password");
296 conn->pgpass = tmp ? strdup(tmp) : NULL;
299 * Free the option info - all is in conn now
302 PQconninfoFree(connOptions);
305 * Connect to the database
308 if (!connectDBStart(conn))
310 /* Just in case we failed to set it in connectDBStart */
311 conn->status = CONNECTION_BAD;
320 * Parse an empty string like PQconnectdb() would do and return the
321 * working connection options array.
323 * Using this function, an application may determine all possible options
324 * and their current default values.
326 * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
327 * and should be freed when no longer needed via PQconninfoFree(). (In prior
328 * versions, the returned array was static, but that's not thread-safe.)
329 * Pre-7.0 applications that use this function will see a small memory leak
330 * until they are updated to call PQconninfoFree.
336 PQExpBufferData errorBuf;
337 PQconninfoOption *connOptions;
339 initPQExpBuffer(&errorBuf);
340 connOptions = conninfo_parse("", &errorBuf);
341 termPQExpBuffer(&errorBuf);
348 * establishes a connection to a postgres backend through the postmaster
349 * at the specified host and port.
351 * returns a PGconn* which is needed for all subsequent libpq calls
352 * if the status field of the connection returned is CONNECTION_BAD,
353 * then some fields may be null'ed out instead of having valid values
355 * Uses these environment variables:
357 * PGHOST identifies host to which to connect if <pghost> argument
358 * is NULL or a null string.
360 * PGPORT identifies TCP port to which to connect if <pgport> argument
361 * is NULL or a null string.
363 * PGTTY identifies tty to which to send messages if <pgtty> argument
364 * is NULL or a null string.
366 * PGOPTIONS identifies connection options if <pgoptions> argument is
367 * NULL or a null string.
369 * PGUSER Postgres username to associate with the connection.
371 * PGPASSWORD The user's password.
373 * PGDATABASE name of database to which to connect if <pgdatabase>
374 * argument is NULL or a null string
376 * None of the above need be defined. There are defaults for all of them.
378 * To support "delimited identifiers" for database names, only convert
379 * the database name to lower case if it is not surrounded by double quotes.
380 * Otherwise, strip the double quotes but leave the reset of the string intact.
381 * - thomas 1997-11-08
386 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
387 const char *pgtty, const char *dbName, const char *login,
391 char *tmp; /* An error message from some service we call. */
392 bool error = FALSE; /* We encountered an error. */
394 conn = makeEmptyPGconn();
396 return (PGconn *) NULL;
398 if ((pghost == NULL) || pghost[0] == '\0')
400 if ((tmp = getenv("PGHOST")) != NULL)
401 conn->pghost = strdup(tmp);
404 conn->pghost = strdup(pghost);
406 if ((pgport == NULL) || pgport[0] == '\0')
408 if ((tmp = getenv("PGPORT")) == NULL)
410 conn->pgport = strdup(tmp);
413 conn->pgport = strdup(pgport);
415 if ((pgtty == NULL) || pgtty[0] == '\0')
417 if ((tmp = getenv("PGTTY")) == NULL)
419 conn->pgtty = strdup(tmp);
422 conn->pgtty = strdup(pgtty);
424 if ((pgoptions == NULL) || pgoptions[0] == '\0')
426 if ((tmp = getenv("PGOPTIONS")) == NULL)
428 conn->pgoptions = strdup(tmp);
431 conn->pgoptions = strdup(pgoptions);
434 conn->pguser = strdup(login);
435 else if ((tmp = getenv("PGUSER")) != NULL)
436 conn->pguser = strdup(tmp);
439 /* fe-auth.c has not been fixed to support PQExpBuffers, so: */
440 conn->pguser = fe_getauthname(conn->errorMessage.data);
441 conn->errorMessage.len = strlen(conn->errorMessage.data);
444 if (conn->pguser == NULL)
447 printfPQExpBuffer(&conn->errorMessage,
448 "FATAL: PQsetdbLogin(): Unable to determine a Postgres username!\n");
452 conn->pgpass = strdup(pwd);
453 else if ((tmp = getenv("PGPASSWORD")) != NULL)
454 conn->pgpass = strdup(tmp);
456 conn->pgpass = strdup(DefaultPassword);
458 if ((dbName == NULL) || dbName[0] == '\0')
460 if ((tmp = getenv("PGDATABASE")) != NULL)
461 conn->dbName = strdup(tmp);
462 else if (conn->pguser)
463 conn->dbName = strdup(conn->pguser);
466 conn->dbName = strdup(dbName);
470 conn->status = CONNECTION_BAD;
474 if (connectDBStart(conn))
475 (void) connectDBComplete(conn);
484 * get all additional infos out of dbName
488 update_db_info(PGconn *conn)
493 if (strchr(conn->dbName, '@') != NULL)
495 /* old style: dbname[@server][:port] */
496 tmp = strrchr(conn->dbName, ':');
497 if (tmp != NULL) /* port number given */
499 conn->pgport = strdup(tmp + 1);
503 tmp = strrchr(conn->dbName, '@');
504 if (tmp != NULL) /* host name given */
506 conn->pghost = strdup(tmp + 1);
510 conn->dbName = strdup(old);
518 * only allow protocols tcp and unix
520 if (strncmp(conn->dbName, "tcp:", 4) == 0)
522 else if (strncmp(conn->dbName, "unix:", 5) == 0)
527 if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
532 * <tcp|unix>:postgresql://server[:port][/dbname][?options]
534 offset += strlen("postgresql://");
536 tmp = strrchr(conn->dbName + offset, '?');
537 if (tmp != NULL) /* options given */
539 conn->pgoptions = strdup(tmp + 1);
543 tmp = strrchr(conn->dbName + offset, '/');
544 if (tmp != NULL) /* database name given */
546 conn->dbName = strdup(tmp + 1);
551 if ((tmp = getenv("PGDATABASE")) != NULL)
552 conn->dbName = strdup(tmp);
553 else if (conn->pguser)
554 conn->dbName = strdup(conn->pguser);
557 tmp = strrchr(old + offset, ':');
558 if (tmp != NULL) /* port number given */
560 conn->pgport = strdup(tmp + 1);
564 if (strncmp(old, "unix:", 5) == 0)
567 if (strcmp(old + offset, "localhost") != 0)
569 printfPQExpBuffer(&conn->errorMessage,
570 "connectDBStart() -- "
571 "non-TCP access only possible on "
577 conn->pghost = strdup(old + offset);
587 * connectMakeNonblocking -
588 * Make a connection non-blocking.
589 * Returns 1 if successful, 0 if not.
593 connectMakeNonblocking(PGconn *conn)
596 if (fcntl(conn->sock, F_SETFL, O_NONBLOCK) < 0)
599 if (ioctlsocket(conn->sock, FIONBIO, &on) != 0)
602 printfPQExpBuffer(&conn->errorMessage,
603 "connectMakeNonblocking -- fcntl() failed: errno=%d\n%s\n",
604 errno, strerror(errno));
613 * Sets the TCP_NODELAY socket option.
614 * Returns 1 if successful, 0 if not.
618 connectNoDelay(PGconn *conn)
623 pe = getprotobyname("TCP");
626 printfPQExpBuffer(&conn->errorMessage,
627 "connectNoDelay() -- "
628 "getprotobyname failed: errno=%d\n%s\n",
629 errno, strerror(errno));
632 if (setsockopt(conn->sock, pe->p_proto, TCP_NODELAY,
639 printfPQExpBuffer(&conn->errorMessage,
640 "connectNoDelay() -- setsockopt failed: errno=%d\n%s\n",
641 errno, strerror(errno));
643 printf("Winsock error: %i\n", WSAGetLastError());
654 * Start to make a connection to the backend so it is ready to receive
656 * Returns 1 if successful, 0 if not.
660 connectDBStart(PGconn *conn)
665 StartupPacket np; /* Used to negotiate SSL connection */
672 * parse dbName to get all additional info in it, if any
674 if (update_db_info(conn) != 0)
675 goto connect_errReturn;
677 /* Ensure our buffers are empty */
678 conn->inStart = conn->inCursor = conn->inEnd = 0;
682 * Set up the connection to postmaster/backend.
683 * Note that this supports IPv4 and UDP only.
686 MemSet((char *) &conn->raddr, 0, sizeof(conn->raddr));
688 if (conn->pghostaddr != NULL)
690 /* Using pghostaddr avoids a hostname lookup */
691 /* Note that this supports IPv4 only */
694 if(!inet_aton(conn->pghostaddr, &addr))
696 printfPQExpBuffer(&conn->errorMessage,
697 "connectDBStart() -- "
698 "invalid host address: %s\n", conn->pghostaddr);
699 goto connect_errReturn;
704 memmove((char *) &(conn->raddr.in.sin_addr),
705 (char *) &addr, sizeof(addr));
707 else if (conn->pghost != NULL)
709 /* Using pghost, so we have to look-up the hostname */
712 hp = gethostbyname(conn->pghost);
713 if ((hp == NULL) || (hp->h_addrtype != AF_INET))
715 printfPQExpBuffer(&conn->errorMessage,
716 "connectDBStart() -- unknown hostname: %s\n",
718 goto connect_errReturn;
722 memmove((char *) &(conn->raddr.in.sin_addr),
728 /* pghostaddr and pghost are NULL, so use UDP */
733 conn->raddr.sa.sa_family = family;
735 /* Set port number */
736 portno = atoi(conn->pgport);
737 if (family == AF_INET)
739 conn->raddr.in.sin_port = htons((unsigned short) (portno));
740 conn->raddr_len = sizeof(struct sockaddr_in);
742 #if !defined(WIN32) && !defined(__CYGWIN32__)
744 conn->raddr_len = UNIXSOCK_PATH(conn->raddr.un, portno);
749 if ((conn->sock = socket(family, SOCK_STREAM, 0)) < 0)
751 printfPQExpBuffer(&conn->errorMessage,
752 "connectDBStart() -- "
753 "socket() failed: errno=%d\n%s\n",
754 errno, strerror(errno));
755 goto connect_errReturn;
759 * Set the right options. Normally, we need nonblocking I/O, and we don't
760 * want delay of outgoing data for AF_INET sockets. If we are using SSL,
761 * then we need the blocking I/O (XXX Can this be fixed?).
764 if (family == AF_INET)
766 if (!connectNoDelay(conn))
767 goto connect_errReturn;
771 * Since I have no idea whether this is a valid thing to do under Windows
772 * before a connection is made, and since I have no way of testing it, I
773 * leave the code looking as below. When someone decides that they want
774 * non-blocking connections under Windows, they can define
775 * WIN32_NON_BLOCKING_CONNECTIONS before compilation. If it works, then
776 * this code can be cleaned up.
778 * Ewan Mellor <eem21@cam.ac.uk>.
780 #if (!defined(WIN32) || defined(WIN32_NON_BLOCKING_CONNECTIONS)) && !defined(USE_SSL)
781 if (connectMakeNonblocking(conn) == 0)
782 goto connect_errReturn;
786 /* This needs to be done before we set into nonblocking, since SSL
787 * negotiation does not like that mode */
789 /* Attempt to negotiate SSL usage */
790 if (conn->allow_ssl_try) {
791 memset((char *)&np, 0, sizeof(np));
792 np.protoVersion = htonl(NEGOTIATE_SSL_CODE);
793 if (pqPacketSend(conn, (char *) &np, sizeof(StartupPacket)) != STATUS_OK)
795 sprintf(conn->errorMessage,
796 "connectDB() -- couldn't send SSL negotiation packet: errno=%d\n%s\n",
797 errno, strerror(errno));
798 goto connect_errReturn;
800 /* Now receive the postmasters response */
801 if (recv(conn->sock, &SSLok, 1, 0) != 1) {
802 sprintf(conn->errorMessage, "PQconnectDB() -- couldn't read postmaster response: errno=%d\n%s\n",
803 errno, strerror(errno));
804 goto connect_errReturn;
809 SSL_load_error_strings();
811 SSL_context = SSL_CTX_new(SSLv23_method());
813 sprintf(conn->errorMessage,
814 "connectDB() -- couldn't create SSL context: %s\n",
815 ERR_reason_error_string(ERR_get_error()));
816 goto connect_errReturn;
819 if (!(conn->ssl = SSL_new(SSL_context)) ||
820 !SSL_set_fd(conn->ssl, conn->sock) ||
821 SSL_connect(conn->ssl) <= 0)
823 sprintf(conn->errorMessage,
824 "connectDB() -- couldn't establish SSL connection: %s\n",
825 ERR_reason_error_string(ERR_get_error()));
826 goto connect_errReturn;
828 /* SSL connection finished. Continue to send startup packet */
830 else if (SSLok == 'E') {
831 /* Received error - probably protocol mismatch */
833 fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-6.6.\n");
835 conn->allow_ssl_try = FALSE;
836 return connectDBStart(conn);
838 else if (SSLok != 'N') {
839 strcpy(conn->errorMessage,
840 "Received invalid negotiation response.\n");
841 goto connect_errReturn;
847 * Start / make connection. We are hopefully in non-blocking mode
848 * now, but it is possible that:
849 * 1. Older systems will still block on connect, despite the
850 * non-blocking flag. (Anyone know if this is true?)
851 * 2. We are running under Windows, and aren't even trying
852 * to be non-blocking (see above).
853 * 3. We are using SSL.
854 * Thus, we have make arrangements for all eventualities.
857 if (connect(conn->sock, &conn->raddr.sa, conn->raddr_len) < 0)
860 if (errno == EINPROGRESS || errno == 0)
862 if (WSAGetLastError() == WSAEINPROGRESS)
865 /* This is fine - we're in non-blocking mode, and the
866 * connection is in progress. */
867 conn->status = CONNECTION_STARTED;
871 /* Something's gone wrong */
872 printfPQExpBuffer(&conn->errorMessage,
873 "connectDBStart() -- connect() failed: %s\n"
874 "\tIs the postmaster running%s at '%s'\n"
875 "\tand accepting connections on %s '%s'?\n",
877 (family == AF_INET) ? " (with -i)" : "",
878 conn->pghost ? conn->pghost : "localhost",
879 (family == AF_INET) ?
880 "TCP/IP port" : "Unix socket",
882 goto connect_errReturn;
887 /* We're connected already */
888 conn->status = CONNECTION_MADE;
891 /* This makes the connection non-blocking, for all those cases which forced us
892 not to do it above. */
893 #if (defined(WIN32) && !defined(WIN32_NON_BLOCKING_CONNECTIONS)) || defined(USE_SSL)
894 if (connectMakeNonblocking(conn) == 0)
895 goto connect_errReturn;
904 closesocket(conn->sock);
910 conn->status = CONNECTION_BAD;
919 * Block and complete a connection.
921 * Returns 1 on success, 0 on failure.
925 connectDBComplete(PGconn *conn)
927 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
929 if (conn == NULL || conn->status == CONNECTION_BAD)
934 * Wait, if necessary. Note that the initial state (just after
935 * PQconnectStart) is to wait for the socket to select for writing.
939 case PGRES_POLLING_ACTIVE:
942 case PGRES_POLLING_OK:
943 return 1; /* success! */
945 case PGRES_POLLING_READING:
946 if (pqWait(1, 0, conn))
948 conn->status = CONNECTION_BAD;
953 case PGRES_POLLING_WRITING:
954 if (pqWait(0, 1, conn))
956 conn->status = CONNECTION_BAD;
962 /* Just in case we failed to set it in PQconnectPoll */
963 conn->status = CONNECTION_BAD;
967 * Now try to advance the state machine.
969 flag = PQconnectPoll(conn);
976 * Poll an asynchronous connection.
978 * Returns a PostgresPollingStatusType.
979 * Before calling this function, use select(2) to determine when data arrive.
981 * You must call PQfinish whether or not this fails.
983 * This function and PQconnectStart are intended to allow connections to be
984 * made without blocking the execution of your program on remote I/O. However,
985 * there are a number of caveats:
987 * o If you call PQtrace, ensure that the stream object into which you trace
989 * o If you do not supply an IP address for the remote host (i.e. you
990 * supply a host name instead) then this function will block on
991 * gethostbyname. You will be fine if using Unix sockets (i.e. by
992 * supplying neither a host name nor a host address).
993 * o If your backend wants to use Kerberos authentication then you must
994 * supply both a host name and a host address, otherwise this function
995 * may block on gethostname.
996 * o This function will block if compiled with USE_SSL.
1000 PostgresPollingStatusType
1001 PQconnectPoll(PGconn *conn)
1006 return PGRES_POLLING_FAILED;
1008 /* Get the new data */
1009 switch (conn->status)
1011 /* We really shouldn't have been polled in these two cases, but
1012 we can handle it. */
1013 case CONNECTION_BAD:
1014 return PGRES_POLLING_FAILED;
1016 return PGRES_POLLING_OK;
1018 /* These are reading states */
1019 case CONNECTION_AWAITING_RESPONSE:
1020 case CONNECTION_AUTH_OK:
1022 /* Load waiting data */
1023 int n = pqReadData(conn);
1028 return PGRES_POLLING_READING;
1033 /* These are writing states, so we just proceed. */
1034 case CONNECTION_STARTED:
1035 case CONNECTION_MADE:
1038 case CONNECTION_SETENV:
1039 /* We allow PQsetenvPoll to decide whether to proceed */
1043 printfPQExpBuffer(&conn->errorMessage,
1044 "PQconnectPoll() -- unknown connection state - "
1045 "probably indicative of memory corruption!\n");
1050 keep_going: /* We will come back to here until there is nothing left to
1052 switch(conn->status)
1054 case CONNECTION_STARTED:
1056 SOCKET_SIZE_TYPE laddrlen;
1062 SOCKET_SIZE_TYPE optlen = sizeof(optval);
1064 /* Write ready, since we've made it here, so the connection
1067 /* Now check (using getsockopt) that there is not an error
1068 state waiting for us on the socket. */
1070 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1071 &optval, &optlen) == -1)
1073 printfPQExpBuffer(&conn->errorMessage,
1074 "PQconnectPoll() -- getsockopt() failed: "
1076 errno, strerror(errno));
1079 else if (optval != 0)
1082 * When using a nonblocking connect, we will typically see
1083 * connect failures at this point, so provide a friendly
1086 printfPQExpBuffer(&conn->errorMessage,
1087 "PQconnectPoll() -- connect() failed: %s\n"
1088 "\tIs the postmaster running%s at '%s'\n"
1089 "\tand accepting connections on %s '%s'?\n",
1091 (conn->raddr.sa.sa_family == AF_INET) ? " (with -i)" : "",
1092 conn->pghost ? conn->pghost : "localhost",
1093 (conn->raddr.sa.sa_family == AF_INET) ?
1094 "TCP/IP port" : "Unix socket",
1099 /* Fill in the client address */
1100 laddrlen = sizeof(conn->laddr);
1101 if (getsockname(conn->sock, &conn->laddr.sa, &laddrlen) < 0)
1103 printfPQExpBuffer(&conn->errorMessage,
1104 "PQconnectPoll() -- getsockname() failed: "
1106 errno, strerror(errno));
1110 conn->status = CONNECTION_MADE;
1111 return PGRES_POLLING_WRITING;
1114 case CONNECTION_MADE:
1119 * Initialize the startup packet.
1122 MemSet((char *) &sp, 0, sizeof(StartupPacket));
1124 sp.protoVersion = (ProtocolVersion) htonl(PG_PROTOCOL_LIBPQ);
1126 strncpy(sp.user, conn->pguser, SM_USER);
1127 strncpy(sp.database, conn->dbName, SM_DATABASE);
1128 strncpy(sp.tty, conn->pgtty, SM_TTY);
1130 if (conn->pgoptions)
1131 strncpy(sp.options, conn->pgoptions, SM_OPTIONS);
1133 /* Send the startup packet.
1135 * Theoretically, this could block, but it really shouldn't
1136 * since we only got here if the socket is write-ready.
1139 if (pqPacketSend(conn, (char *) &sp,
1140 sizeof(StartupPacket)) != STATUS_OK)
1142 printfPQExpBuffer(&conn->errorMessage,
1143 "PQconnectPoll() -- "
1144 "couldn't send startup packet: "
1146 errno, strerror(errno));
1150 conn->status = CONNECTION_AWAITING_RESPONSE;
1151 return PGRES_POLLING_READING;
1155 * Handle the authentication exchange: wait for postmaster messages
1156 * and respond as necessary.
1158 case CONNECTION_AWAITING_RESPONSE:
1163 /* Scan the message from current point (note that if we find
1164 * the message is incomplete, we will return without advancing
1165 * inStart, and resume here next time).
1167 conn->inCursor = conn->inStart;
1169 if (pqGetc(&beresp, conn))
1171 /* We'll come back when there are more data */
1172 return PGRES_POLLING_READING;
1175 /* Handle errors. */
1178 if (pqGets(&conn->errorMessage, conn))
1180 /* We'll come back when there are more data */
1181 return PGRES_POLLING_READING;
1183 /* OK, we read the message; mark data consumed */
1184 conn->inStart = conn->inCursor;
1185 /* The postmaster typically won't end its message with a
1186 * newline, so add one to conform to libpq conventions.
1188 appendPQExpBufferChar(&conn->errorMessage, '\n');
1192 /* Otherwise it should be an authentication request. */
1195 printfPQExpBuffer(&conn->errorMessage,
1196 "PQconnectPoll() -- expected "
1197 "authentication request\n");
1201 /* Get the type of request. */
1202 if (pqGetInt((int *) &areq, 4, conn))
1204 /* We'll come back when there are more data */
1205 return PGRES_POLLING_READING;
1208 /* Get the password salt if there is one. */
1209 if (areq == AUTH_REQ_CRYPT)
1211 if (pqGetnchar(conn->salt, sizeof(conn->salt), conn))
1213 /* We'll come back when there are more data */
1214 return PGRES_POLLING_READING;
1218 /* OK, we successfully read the message; mark data consumed */
1219 conn->inStart = conn->inCursor;
1221 /* Respond to the request if necessary. */
1222 /* Note that conn->pghost must be non-NULL if we are going to
1223 * avoid the Kerberos code doing a hostname look-up. */
1224 /* XXX fe-auth.c has not been fixed to support PQExpBuffers, so: */
1225 if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1226 conn->errorMessage.data) != STATUS_OK)
1228 conn->errorMessage.len = strlen(conn->errorMessage.data);
1231 conn->errorMessage.len = strlen(conn->errorMessage.data);
1233 /* Just make sure that any data sent by fe_sendauth is flushed
1234 * out. Although this theoretically could block, it really
1235 * shouldn't since we don't send large auth responses.
1240 if (areq == AUTH_REQ_OK)
1242 /* We are done with authentication exchange */
1243 conn->status = CONNECTION_AUTH_OK;
1244 /* Set asyncStatus so that PQsetResult will think that what
1245 * comes back next is the result of a query. See below. */
1246 conn->asyncStatus = PGASYNC_BUSY;
1249 /* Look to see if we have more data yet. */
1253 case CONNECTION_AUTH_OK:
1256 * Now we expect to hear from the backend. A ReadyForQuery
1257 * message indicates that startup is successful, but we might
1258 * also get an Error message indicating failure. (Notice
1259 * messages indicating nonfatal warnings are also allowed by
1260 * the protocol, as is a BackendKeyData message.) Easiest way
1261 * to handle this is to let PQgetResult() read the messages. We
1262 * just have to fake it out about the state of the connection,
1263 * by setting asyncStatus = PGASYNC_BUSY (done above).
1268 return PGRES_POLLING_READING;
1270 res = PQgetResult(conn);
1271 /* NULL return indicating we have gone to
1272 IDLE state is expected */
1275 if (res->resultStatus != PGRES_FATAL_ERROR)
1276 printfPQExpBuffer(&conn->errorMessage,
1277 "PQconnectPoll() -- unexpected message "
1278 "during startup\n");
1279 /* if the resultStatus is FATAL, then conn->errorMessage
1280 * already has a copy of the error; needn't copy it back.
1281 * But add a newline if it's not there already, since
1282 * postmaster error messages may not have one.
1284 if (conn->errorMessage.len <= 0 ||
1285 conn->errorMessage.data[conn->errorMessage.len-1] != '\n')
1286 appendPQExpBufferChar(&conn->errorMessage, '\n');
1292 * Post-connection housekeeping. Prepare to send environment
1293 * variables to server.
1295 if (! PQsetenvStart(conn))
1298 conn->status = CONNECTION_SETENV;
1303 case CONNECTION_SETENV:
1304 /* We pretend that the connection is OK for the duration of
1306 conn->status = CONNECTION_OK;
1308 switch (PQsetenvPoll(conn))
1310 case PGRES_POLLING_OK: /* Success */
1311 conn->status = CONNECTION_OK;
1312 return PGRES_POLLING_OK;
1314 case PGRES_POLLING_READING: /* Still going */
1315 conn->status = CONNECTION_SETENV;
1316 return PGRES_POLLING_READING;
1318 case PGRES_POLLING_WRITING: /* Still going */
1319 conn->status = CONNECTION_SETENV;
1320 return PGRES_POLLING_WRITING;
1323 conn->status = CONNECTION_SETENV;
1329 printfPQExpBuffer(&conn->errorMessage,
1330 "PQconnectPoll() -- unknown connection state - "
1331 "probably indicative of memory corruption!\n");
1339 * We used to close the socket at this point, but that makes it awkward
1340 * for those above us if they wish to remove this socket from their
1341 * own records (an fd_set for example). We'll just have this socket
1342 * closed when PQfinish is called (which is compulsory even after an
1343 * error, since the connection structure must be freed).
1346 return PGRES_POLLING_FAILED;
1353 * Starts the process of passing the values of a standard set of environment
1354 * variables to the backend.
1359 PQsetenvStart(PGconn *conn)
1362 conn->status == CONNECTION_BAD ||
1363 conn->setenv_state != SETENV_STATE_IDLE)
1367 conn->setenv_state = SETENV_STATE_ENCODINGS_SEND;
1369 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1372 conn->next_eo = EnvironmentOptions;
1380 * Polls the process of passing the values of a standard set of environment
1381 * variables to the backend.
1385 static PostgresPollingStatusType
1386 PQsetenvPoll(PGconn *conn)
1390 static const char envname[] = "PGCLIENTENCODING";
1393 if (conn == NULL || conn->status == CONNECTION_BAD)
1394 return PGRES_POLLING_FAILED;
1396 /* Check whether there are any data for us */
1397 switch (conn->setenv_state)
1399 /* These are reading states */
1401 case SETENV_STATE_ENCODINGS_WAIT:
1403 case SETENV_STATE_OPTION_WAIT:
1405 /* Load waiting data */
1406 int n = pqReadData(conn);
1411 return PGRES_POLLING_READING;
1416 /* These are writing states, so we just proceed. */
1418 case SETENV_STATE_ENCODINGS_SEND:
1420 case SETENV_STATE_OPTION_SEND:
1423 /* Should we raise an error if called when not active? */
1424 case SETENV_STATE_IDLE:
1425 return PGRES_POLLING_OK;
1428 printfPQExpBuffer(&conn->errorMessage,
1429 "PQsetenvPoll() -- unknown state - "
1430 "probably indicative of memory corruption!\n");
1435 keep_going: /* We will come back to here until there is nothing left to
1437 switch(conn->setenv_state)
1441 case SETENV_STATE_ENCODINGS_SEND:
1445 /* query server encoding */
1446 env = getenv(envname);
1447 if (!env || *env == '\0')
1449 if (!PQsendQuery(conn,
1450 "select getdatabaseencoding()"))
1453 conn->setenv_state = SETENV_STATE_ENCODINGS_WAIT;
1454 return PGRES_POLLING_READING;
1458 case SETENV_STATE_ENCODINGS_WAIT:
1461 return PGRES_POLLING_READING;
1463 res = PQgetResult(conn);
1469 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1475 /* set client encoding in pg_conn struct */
1476 encoding = PQgetvalue(res, 0, 0);
1477 if (!encoding) /* this should not happen */
1478 conn->client_encoding = SQL_ASCII;
1480 conn->client_encoding = pg_char_to_encoding(encoding);
1482 /* We have to keep going in order to clear up the query */
1486 /* NULL result indicates that the query is finished */
1488 /* Move on to setting the environment options */
1489 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1494 case SETENV_STATE_OPTION_SEND:
1496 /* Send an Environment Option */
1497 char setQuery[100]; /* note length limits in sprintf's below */
1499 if (conn->next_eo->envName)
1503 if ((val = getenv(conn->next_eo->envName)))
1505 if (strcasecmp(val, "default") == 0)
1506 sprintf(setQuery, "SET %s = %.60s",
1507 conn->next_eo->pgName, val);
1509 sprintf(setQuery, "SET %s = '%.60s'",
1510 conn->next_eo->pgName, val);
1512 printf("Use environment variable %s to send %s\n",
1513 conn->next_eo->envName, setQuery);
1515 if (!PQsendQuery(conn, setQuery))
1518 conn->setenv_state = SETENV_STATE_OPTION_WAIT;
1527 /* No more options to send, so we are done. */
1528 conn->setenv_state = SETENV_STATE_IDLE;
1534 case SETENV_STATE_OPTION_WAIT:
1537 return PGRES_POLLING_READING;
1539 res = PQgetResult(conn);
1543 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1548 /* Don't need the result */
1550 /* We have to keep going in order to clear up the query */
1554 /* NULL result indicates that the query is finished */
1556 /* Send the next option */
1558 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1562 case SETENV_STATE_IDLE:
1563 return PGRES_POLLING_OK;
1566 printfPQExpBuffer(&conn->errorMessage,
1567 "PQsetenvPoll() -- unknown state - "
1568 "probably indicative of memory corruption!\n");
1575 conn->setenv_state = SETENV_STATE_IDLE;
1576 return PGRES_POLLING_FAILED;
1585 * Passes the values of a standard set of environment variables to the
1588 * Returns true on success, false on failure.
1590 * This function used to be exported for no particularly good reason.
1591 * Since it's no longer used by libpq itself, let's try #ifdef'ing it out
1592 * and see if anyone complains.
1596 PQsetenv(PGconn *conn)
1598 PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1600 if (! PQsetenvStart(conn))
1605 * Wait, if necessary. Note that the initial state (just after
1606 * PQsetenvStart) is to wait for the socket to select for writing.
1610 case PGRES_POLLING_ACTIVE:
1613 case PGRES_POLLING_OK:
1614 return true; /* success! */
1616 case PGRES_POLLING_READING:
1617 if (pqWait(1, 0, conn))
1619 conn->status = CONNECTION_BAD;
1624 case PGRES_POLLING_WRITING:
1625 if (pqWait(0, 1, conn))
1627 conn->status = CONNECTION_BAD;
1633 /* Just in case we failed to set it in PQsetenvPoll */
1634 conn->status = CONNECTION_BAD;
1638 * Now try to advance the state machine.
1640 flag = PQsetenvPoll(conn);
1644 #endif /* NOT_USED */
1649 * - create a PGconn data structure with (as yet) no interesting data
1652 makeEmptyPGconn(void)
1654 PGconn *conn = (PGconn *) malloc(sizeof(PGconn));
1659 /* Zero all pointers and booleans */
1660 MemSet((char *) conn, 0, sizeof(PGconn));
1662 conn->noticeHook = defaultNoticeProcessor;
1663 conn->status = CONNECTION_BAD;
1664 conn->asyncStatus = PGASYNC_IDLE;
1665 conn->setenv_state = SETENV_STATE_IDLE;
1666 conn->notifyList = DLNewList();
1669 conn->allow_ssl_try = TRUE;
1673 * The output buffer size is set to 8K, which is the usual size of pipe
1674 * buffers on Unix systems. That way, when we are sending a large
1675 * amount of data, we avoid incurring extra kernel context swaps for
1676 * partial bufferloads. Note that we currently don't ever enlarge
1677 * the output buffer.
1679 * With the same goal of minimizing context swaps, the input buffer will
1680 * be enlarged anytime it has less than 8K free, so we initially allocate
1683 conn->inBufSize = 16 * 1024;
1684 conn->inBuffer = (char *) malloc(conn->inBufSize);
1685 conn->outBufSize = 8 * 1024;
1686 conn->outBuffer = (char *) malloc(conn->outBufSize);
1687 conn->nonblocking = FALSE;
1688 initPQExpBuffer(&conn->errorMessage);
1689 initPQExpBuffer(&conn->workBuffer);
1690 if (conn->inBuffer == NULL ||
1691 conn->outBuffer == NULL ||
1692 conn->errorMessage.data == NULL ||
1693 conn->workBuffer.data == NULL)
1695 /* out of memory already :-( */
1704 * - free the PGconn data structure
1708 freePGconn(PGconn *conn)
1712 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1715 SSL_free(conn->ssl);
1717 if (conn->sock >= 0)
1719 closesocket(conn->sock);
1725 if (conn->pghostaddr)
1726 free(conn->pghostaddr);
1731 if (conn->pgoptions)
1732 free(conn->pgoptions);
1739 /* Note that conn->Pfdebug is not ours to close or free */
1740 if (conn->notifyList)
1741 DLFreeList(conn->notifyList);
1742 if (conn->lobjfuncs)
1743 free(conn->lobjfuncs);
1745 free(conn->inBuffer);
1746 if (conn->outBuffer)
1747 free(conn->outBuffer);
1748 termPQExpBuffer(&conn->errorMessage);
1749 termPQExpBuffer(&conn->workBuffer);
1755 - properly close a connection to the backend
1758 closePGconn(PGconn *conn)
1760 if (conn->sock >= 0)
1764 * Try to send "close connection" message to backend. Ignore any
1765 * error. Note: this routine used to go to substantial lengths to
1766 * avoid getting SIGPIPE'd if the connection were already closed.
1767 * Now we rely on pqFlush to avoid the signal.
1769 (void) pqPuts("X", conn);
1770 (void) pqFlush(conn);
1774 * must reset the blocking status so a possible reconnect will work
1775 * don't call PQsetnonblocking() because it will fail if it's unable
1776 * to flush the connection.
1778 conn->nonblocking = FALSE;
1781 * Close the connection, reset all transient state, flush I/O buffers.
1783 if (conn->sock >= 0)
1785 closesocket(conn->sock);
1790 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just
1792 conn->asyncStatus = PGASYNC_IDLE;
1793 pqClearAsyncResult(conn); /* deallocate result and curTuple */
1794 if (conn->lobjfuncs)
1795 free(conn->lobjfuncs);
1796 conn->lobjfuncs = NULL;
1797 conn->inStart = conn->inCursor = conn->inEnd = 0;
1799 conn->nonblocking = FALSE;
1805 properly close a connection to the backend
1806 also frees the PGconn data structure so it shouldn't be re-used
1810 PQfinish(PGconn *conn)
1820 resets the connection to the backend
1821 closes the existing connection and makes a new one
1824 PQreset(PGconn *conn)
1830 if (connectDBStart(conn))
1831 (void) connectDBComplete(conn);
1837 resets the connection to the backend
1838 closes the existing connection and makes a new one
1839 Returns 1 on success, 0 on failure.
1842 PQresetStart(PGconn *conn)
1848 return connectDBStart(conn);
1856 resets the connection to the backend
1857 closes the existing connection and makes a new one
1860 PostgresPollingStatusType
1861 PQresetPoll(PGconn *conn)
1865 return PQconnectPoll(conn);
1868 return PGRES_POLLING_FAILED;
1873 * PQrequestCancel: attempt to request cancellation of the current operation.
1875 * The return value is TRUE if the cancel request was successfully
1876 * dispatched, FALSE if not (in which case conn->errorMessage is set).
1877 * Note: successful dispatch is no guarantee that there will be any effect at
1878 * the backend. The application must read the operation result as usual.
1880 * XXX it was a bad idea to have the error message returned in
1881 * conn->errorMessage, since it could overwrite a message already there.
1882 * Would be better to return it in a char array passed by the caller.
1884 * CAUTION: we want this routine to be safely callable from a signal handler
1885 * (for example, an application might want to call it in a SIGINT handler).
1886 * This means we cannot use any C library routine that might be non-reentrant.
1887 * malloc/free are often non-reentrant, and anything that might call them is
1888 * just as dangerous. We avoid sprintf here for that reason. Building up
1889 * error messages with strcpy/strcat is tedious but should be quite safe.
1891 * NOTE: this routine must not generate any error message longer than
1892 * INITIAL_EXPBUFFER_SIZE (currently 256), since we dare not try to
1893 * expand conn->errorMessage!
1897 PQrequestCancel(PGconn *conn)
1903 CancelRequestPacket cp;
1906 /* Check we have an open connection */
1912 strcpy(conn->errorMessage.data,
1913 "PQrequestCancel() -- connection is not open\n");
1914 conn->errorMessage.len = strlen(conn->errorMessage.data);
1919 * We need to open a temporary connection to the postmaster. Use the
1920 * information saved by connectDB to do this with only kernel calls.
1922 if ((tmpsock = socket(conn->raddr.sa.sa_family, SOCK_STREAM, 0)) < 0)
1924 strcpy(conn->errorMessage.data,
1925 "PQrequestCancel() -- socket() failed: ");
1926 goto cancel_errReturn;
1928 if (connect(tmpsock, &conn->raddr.sa, conn->raddr_len) < 0)
1930 strcpy(conn->errorMessage.data,
1931 "PQrequestCancel() -- connect() failed: ");
1932 goto cancel_errReturn;
1936 * We needn't set nonblocking I/O or NODELAY options here.
1939 /* Create and send the cancel request packet. */
1941 crp.packetlen = htonl((uint32) sizeof(crp));
1942 crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
1943 crp.cp.backendPID = htonl(conn->be_pid);
1944 crp.cp.cancelAuthCode = htonl(conn->be_key);
1946 if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
1948 strcpy(conn->errorMessage.data,
1949 "PQrequestCancel() -- send() failed: ");
1950 goto cancel_errReturn;
1955 closesocket(tmpsock);
1963 strcat(conn->errorMessage.data, strerror(errno));
1964 strcat(conn->errorMessage.data, "\n");
1965 conn->errorMessage.len = strlen(conn->errorMessage.data);
1969 closesocket(tmpsock);
1979 * pqPacketSend() -- send a single-packet message.
1980 * this is like PacketSend(), defined in backend/libpq/pqpacket.c
1982 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
1983 * SIDE_EFFECTS: may block.
1986 pqPacketSend(PGconn *conn, const char *buf, size_t len)
1988 /* Send the total packet size. */
1990 if (pqPutInt(4 + len, 4, conn))
1991 return STATUS_ERROR;
1993 /* Send the packet itself. */
1995 if (pqPutnchar(buf, len, conn))
1996 return STATUS_ERROR;
1999 return STATUS_ERROR;
2006 * Conninfo parser routine
2008 * If successful, a malloc'd PQconninfoOption array is returned.
2009 * If not successful, NULL is returned and an error message is
2010 * left in errorMessage.
2013 static PQconninfoOption *
2014 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2022 PQconninfoOption *options;
2023 PQconninfoOption *option;
2024 char errortmp[INITIAL_EXPBUFFER_SIZE];
2026 /* Make a working copy of PQconninfoOptions */
2027 options = malloc(sizeof(PQconninfoOptions));
2028 if (options == NULL)
2030 printfPQExpBuffer(errorMessage,
2031 "FATAL: cannot allocate memory for copy of PQconninfoOptions\n");
2034 memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2036 /* Need a modifiable copy of the input string */
2037 if ((buf = strdup(conninfo)) == NULL)
2039 printfPQExpBuffer(errorMessage,
2040 "FATAL: cannot allocate memory for copy of conninfo string\n");
2041 PQconninfoFree(options);
2048 /* Skip blanks before the parameter name */
2055 /* Get the parameter name */
2075 /* Check that there is a following '=' */
2078 printfPQExpBuffer(errorMessage,
2079 "ERROR: Missing '=' after '%s' in conninfo\n",
2081 PQconninfoFree(options);
2087 /* Skip blanks after the '=' */
2095 /* Get the parameter value */
2127 printfPQExpBuffer(errorMessage,
2128 "ERROR: PQconnectdb() - unterminated quoted string in conninfo\n");
2129 PQconninfoFree(options);
2151 * Now we have the name and the value. Search
2152 * for the param record.
2155 for (option = options; option->keyword != NULL; option++)
2157 if (strcmp(option->keyword, pname) == 0)
2160 if (option->keyword == NULL)
2162 printfPQExpBuffer(errorMessage,
2163 "ERROR: Unknown conninfo option '%s'\n",
2165 PQconninfoFree(options);
2176 option->val = strdup(pval);
2179 /* Done with the modifiable input string */
2183 * Get the fallback resources for parameters not specified
2184 * in the conninfo string.
2187 for (option = options; option->keyword != NULL; option++)
2189 if (option->val != NULL)
2190 continue; /* Value was in conninfo */
2193 * Try to get the environment variable fallback
2196 if (option->envvar != NULL)
2198 if ((tmp = getenv(option->envvar)) != NULL)
2200 option->val = strdup(tmp);
2206 * No environment variable specified or this one isn't set -
2210 if (option->compiled != NULL)
2212 option->val = strdup(option->compiled);
2217 * Special handling for user
2220 if (strcmp(option->keyword, "user") == 0)
2222 option->val = fe_getauthname(errortmp);
2223 /* note any error message is thrown away */
2228 * Special handling for dbname
2231 if (strcmp(option->keyword, "dbname") == 0)
2233 tmp = conninfo_getval(options, "user");
2235 option->val = strdup(tmp);
2245 conninfo_getval(PQconninfoOption *connOptions,
2246 const char *keyword)
2248 PQconninfoOption *option;
2250 for (option = connOptions; option->keyword != NULL; option++)
2252 if (strcmp(option->keyword, keyword) == 0)
2261 PQconninfoFree(PQconninfoOption *connOptions)
2263 PQconninfoOption *option;
2265 if (connOptions == NULL)
2268 for (option = connOptions; option->keyword != NULL; option++)
2270 if (option->val != NULL)
2276 /* =========== accessor functions for PGconn ========= */
2278 PQdb(const PGconn *conn)
2281 return (char *) NULL;
2282 return conn->dbName;
2286 PQuser(const PGconn *conn)
2289 return (char *) NULL;
2290 return conn->pguser;
2294 PQpass(const PGconn *conn)
2297 return (char *) NULL;
2298 return conn->pgpass;
2302 PQhost(const PGconn *conn)
2305 return (char *) NULL;
2306 return conn->pghost;
2310 PQport(const PGconn *conn)
2313 return (char *) NULL;
2314 return conn->pgport;
2318 PQtty(const PGconn *conn)
2321 return (char *) NULL;
2326 PQoptions(const PGconn *conn)
2329 return (char *) NULL;
2330 return conn->pgoptions;
2334 PQstatus(const PGconn *conn)
2337 return CONNECTION_BAD;
2338 return conn->status;
2342 PQerrorMessage(const PGconn *conn)
2345 return "PQerrorMessage: conn pointer is NULL\n";
2347 return conn->errorMessage.data;
2351 PQsocket(const PGconn *conn)
2359 PQbackendPID(const PGconn *conn)
2361 if (!conn || conn->status != CONNECTION_OK)
2363 return conn->be_pid;
2367 PQclientEncoding(const PGconn *conn)
2369 if (!conn || conn->status != CONNECTION_OK)
2371 return conn->client_encoding;
2376 PQsetClientEncoding(PGconn *conn, const char *encoding)
2379 static char query[] = "set client_encoding to '%s'";
2383 if (!conn || conn->status != CONNECTION_OK)
2389 /* check query buffer overflow */
2390 if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2393 /* ok, now send a query */
2394 sprintf(qbuf, query, encoding);
2395 res = PQexec(conn, qbuf);
2397 if (res == (PGresult *)NULL)
2399 if (res->resultStatus != PGRES_COMMAND_OK)
2403 /* change libpq internal encoding */
2404 conn->client_encoding = pg_char_to_encoding(encoding);
2405 status = 0; /* everything is ok */
2412 PQsetClientEncoding(PGconn *conn, const char *encoding)
2419 PQtrace(PGconn *conn, FILE *debug_port)
2422 conn->status == CONNECTION_BAD)
2425 conn->Pfdebug = debug_port;
2429 PQuntrace(PGconn *conn)
2431 /* note: better allow untrace even when connection bad */
2436 fflush(conn->Pfdebug);
2437 conn->Pfdebug = NULL;
2442 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2444 PQnoticeProcessor old;
2449 old = conn->noticeHook;
2452 conn->noticeHook = proc;
2453 conn->noticeArg = arg;
2459 * The default notice/error message processor just prints the
2460 * message on stderr. Applications can override this if they
2461 * want the messages to go elsewhere (a window, for example).
2462 * Note that simply discarding notices is probably a bad idea.
2466 defaultNoticeProcessor(void *arg, const char *message)
2468 (void)arg; /*not used*/
2469 /* Note: we expect the supplied string to end with a newline already. */
2470 fprintf(stderr, "%s", message);