]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-connect.c
Fold PQsetenv working state into PGconn, rather than trying to maintain
[postgresql] / src / interfaces / libpq / fe-connect.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-connect.c
4  *        functions related to setting up a connection to the backend
5  *
6  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-connect.c,v 1.125 2000/03/24 01:39:55 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include <sys/types.h>
17 #include <fcntl.h>
18 #include <errno.h>
19 #include <ctype.h>
20
21 #include "postgres.h"
22 #include "libpq-fe.h"
23 #include "libpq-int.h"
24 #include "fe-auth.h"
25
26 #ifdef WIN32
27 #include "win32.h"
28 #else
29 #include <sys/socket.h>
30 #include <unistd.h>
31 #include <netdb.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
34 #endif
35
36 #ifndef HAVE_STRDUP
37 #include "strdup.h"
38 #endif
39 #ifdef HAVE_CRYPT_H
40 #include <crypt.h>
41 #endif
42
43 #ifdef MULTIBYTE
44 #include "miscadmin.h"
45 #include "mb/pg_wchar.h"
46 #endif
47
48 #ifdef WIN32
49 static int inet_aton(const char *cp, struct in_addr *inp) {
50         unsigned long a = inet_addr(cp);
51         if (a == -1)
52                 return 0;
53         inp->s_addr = a;        
54         return 1;
55 }
56 #endif
57
58
59 #ifdef USE_SSL
60 static SSL_CTX *SSL_context = NULL;
61 #endif
62
63 #define NOTIFYLIST_INITIAL_SIZE 10
64 #define NOTIFYLIST_GROWBY 10
65
66
67 /* ----------
68  * Definition of the conninfo parameters and their fallback resources.
69  *
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.
73  *
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
77  * name is copied.
78  *
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
85  *
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).
91  * ----------
92  */
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.
97          */
98         {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
99         "Database-Authtype", "D", 20},
100
101         {"user", "PGUSER", NULL, NULL,
102         "Database-User", "", 20},
103
104         {"password", "PGPASSWORD", DefaultPassword, NULL,
105         "Database-Password", "*", 20},
106
107         {"dbname", "PGDATABASE", NULL, NULL,
108         "Database-Name", "", 20},
109
110         {"host", "PGHOST", NULL, NULL,
111         "Database-Host", "", 40},
112
113         {"hostaddr", "PGHOSTADDR", NULL, NULL,
114          "Database-Host-IPv4-Address", "", 15}, /* Room for abc.def.ghi.jkl */
115
116         {"port", "PGPORT", DEF_PGPORT, NULL,
117         "Database-Port", "", 6},
118
119         {"tty", "PGTTY", DefaultTty, NULL,
120         "Backend-Debug-TTY", "D", 40},
121
122         {"options", "PGOPTIONS", DefaultOption, NULL,
123         "Backend-Debug-Options", "D", 40},
124
125         /* Terminating entry --- MUST BE LAST */
126         {NULL, NULL, NULL, NULL,
127         NULL, NULL, 0}
128 };
129
130 static const struct EnvironmentOptions
131 {
132         const char *envName,
133                            *pgName;
134 }                       EnvironmentOptions[] =
135
136 {
137         /* common user-interface settings */
138         {
139                 "PGDATESTYLE", "datestyle"
140         },
141         {
142                 "PGTZ", "timezone"
143         },
144 #ifdef MULTIBYTE
145         {
146                 "PGCLIENTENCODING", "client_encoding"
147         },
148 #endif
149         /* internal performance-related settings */
150         {
151                 "PGGEQO", "geqo"
152         },
153         {
154                 NULL, NULL
155         }
156 };
157
158
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);
171
172
173 /* ----------------
174  *      Connecting to a Database
175  *
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
180  * to the latter).
181  *
182  * If it is desired to connect in a synchronous (blocking) manner, use the
183  * function PQconnectdb.
184  *
185  * To connect in an asychronous (non-blocking) manner, use the functions
186  * PQconnectStart, and PQconnectPoll.
187  *
188  * Internally, the static functions connectDBStart, connectDBComplete
189  * are part of the connection procedure.
190  * 
191  * ----------------
192  */
193
194 /* ----------------
195  *              PQconnectdb
196  *
197  * establishes a connection to a postgres backend through the postmaster
198  * using connection information in a string.
199  *
200  * The conninfo string is a white-separated list of
201  *
202  *         option = value
203  *
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 \'
207  *
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.
212  *
213  * You should call PQfinish (if conn is not NULL) regardless of whether this
214  * call succeeded.
215  *
216  * ----------------
217  */
218 PGconn *
219 PQconnectdb(const char *conninfo)
220 {
221         PGconn *conn = PQconnectStart(conninfo);
222
223         if (conn && conn->status != CONNECTION_BAD)
224                 (void) connectDBComplete(conn);
225
226         return conn;
227 }
228
229 /* ----------------
230  *              PQconnectStart
231  *
232  * Begins the establishment of a connection to a postgres backend through the
233  * postmaster using connection information in a string.
234  *
235  * See comment for PQconnectdb for the definition of the string format.
236  *
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
244  * this is necessary.
245  *
246  * See PQconnectPoll for more info.
247  *
248  * ----------------
249  */
250 PGconn *
251 PQconnectStart(const char *conninfo)
252 {
253         PGconn     *conn;
254         PQconninfoOption *connOptions;
255         char       *tmp;
256
257         /* ----------
258          * Allocate memory for the conn structure
259          * ----------
260          */
261         
262         conn = makeEmptyPGconn();
263         if (conn == NULL)
264                 return (PGconn *) NULL;
265
266         /* ----------
267          * Parse the conninfo string
268          * ----------
269          */
270         connOptions = conninfo_parse(conninfo, &conn->errorMessage);
271         if (connOptions == NULL)
272         {
273                 conn->status = CONNECTION_BAD;
274                 /* errorMessage is already set */
275                 return conn;
276         }
277
278         /*
279          * Move option values into conn structure
280          */
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;
297
298         /* ----------
299          * Free the option info - all is in conn now
300          * ----------
301          */
302         PQconninfoFree(connOptions);
303
304         /* ----------
305          * Connect to the database
306          * ----------
307          */
308         if (!connectDBStart(conn))
309         {
310                 /* Just in case we failed to set it in connectDBStart */
311                 conn->status = CONNECTION_BAD;
312         }
313
314         return conn;
315 }
316
317 /* ----------------
318  *              PQconndefaults
319  *
320  * Parse an empty string like PQconnectdb() would do and return the
321  * working connection options array.
322  *
323  * Using this function, an application may determine all possible options
324  * and their current default values.
325  *
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.
331  * ----------------
332  */
333 PQconninfoOption *
334 PQconndefaults(void)
335 {
336         PQExpBufferData  errorBuf;
337         PQconninfoOption *connOptions;
338
339         initPQExpBuffer(&errorBuf);
340         connOptions = conninfo_parse("", &errorBuf);
341         termPQExpBuffer(&errorBuf);
342         return connOptions;
343 }
344
345 /* ----------------
346  *              PQsetdbLogin
347  *
348  * establishes a connection to a postgres backend through the postmaster
349  * at the specified host and port.
350  *
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
354  *
355  *      Uses these environment variables:
356  *
357  *        PGHOST           identifies host to which to connect if <pghost> argument
358  *                                 is NULL or a null string.
359  *
360  *        PGPORT           identifies TCP port to which to connect if <pgport> argument
361  *                                 is NULL or a null string.
362  *
363  *        PGTTY            identifies tty to which to send messages if <pgtty> argument
364  *                                 is NULL or a null string.
365  *
366  *        PGOPTIONS    identifies connection options if <pgoptions> argument is
367  *                                 NULL or a null string.
368  *
369  *        PGUSER           Postgres username to associate with the connection.
370  *
371  *        PGPASSWORD   The user's password.
372  *
373  *        PGDATABASE   name of database to which to connect if <pgdatabase>
374  *                                 argument is NULL or a null string
375  *
376  *        None of the above need be defined.  There are defaults for all of them.
377  *
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
382  *
383  * ----------------
384  */
385 PGconn *
386 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
387                          const char *pgtty, const char *dbName, const char *login,
388                          const char *pwd)
389 {
390         PGconn     *conn;
391         char       *tmp;        /* An error message from some service we call. */
392         bool            error = FALSE;  /* We encountered an error. */
393
394         conn = makeEmptyPGconn();
395         if (conn == NULL)
396                 return (PGconn *) NULL;
397
398         if ((pghost == NULL) || pghost[0] == '\0')
399         {
400                 if ((tmp = getenv("PGHOST")) != NULL)
401                         conn->pghost = strdup(tmp);
402         }
403         else
404                 conn->pghost = strdup(pghost);
405
406         if ((pgport == NULL) || pgport[0] == '\0')
407         {
408                 if ((tmp = getenv("PGPORT")) == NULL)
409                         tmp = DEF_PGPORT;
410                 conn->pgport = strdup(tmp);
411         }
412         else
413                 conn->pgport = strdup(pgport);
414
415         if ((pgtty == NULL) || pgtty[0] == '\0')
416         {
417                 if ((tmp = getenv("PGTTY")) == NULL)
418                         tmp = DefaultTty;
419                 conn->pgtty = strdup(tmp);
420         }
421         else
422                 conn->pgtty = strdup(pgtty);
423
424         if ((pgoptions == NULL) || pgoptions[0] == '\0')
425         {
426                 if ((tmp = getenv("PGOPTIONS")) == NULL)
427                         tmp = DefaultOption;
428                 conn->pgoptions = strdup(tmp);
429         }
430         else
431                 conn->pgoptions = strdup(pgoptions);
432
433         if (login)
434                 conn->pguser = strdup(login);
435         else if ((tmp = getenv("PGUSER")) != NULL)
436                 conn->pguser = strdup(tmp);
437         else
438         {
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);
442         }
443
444         if (conn->pguser == NULL)
445         {
446                 error = TRUE;
447                 printfPQExpBuffer(&conn->errorMessage,
448                                                   "FATAL: PQsetdbLogin(): Unable to determine a Postgres username!\n");
449         }
450
451         if (pwd)
452                 conn->pgpass = strdup(pwd);
453         else if ((tmp = getenv("PGPASSWORD")) != NULL)
454                 conn->pgpass = strdup(tmp);
455         else
456                 conn->pgpass = strdup(DefaultPassword);
457
458         if ((dbName == NULL) || dbName[0] == '\0')
459         {
460                 if ((tmp = getenv("PGDATABASE")) != NULL)
461                         conn->dbName = strdup(tmp);
462                 else if (conn->pguser)
463                         conn->dbName = strdup(conn->pguser);
464         }
465         else
466                 conn->dbName = strdup(dbName);
467
468         if (error)
469         {
470                 conn->status = CONNECTION_BAD;
471         }
472         else
473         {
474                 if (connectDBStart(conn))
475                         (void) connectDBComplete(conn);
476         }
477                 
478         return conn;
479 }
480
481
482 /*
483  * update_db_info -
484  * get all additional infos out of dbName
485  *
486  */
487 static int
488 update_db_info(PGconn *conn)
489 {
490         char       *tmp,
491                            *old = conn->dbName;
492
493         if (strchr(conn->dbName, '@') != NULL)
494         {
495                 /* old style: dbname[@server][:port] */
496                 tmp = strrchr(conn->dbName, ':');
497                 if (tmp != NULL)                /* port number given */
498                 {
499                         conn->pgport = strdup(tmp + 1);
500                         *tmp = '\0';
501                 }
502
503                 tmp = strrchr(conn->dbName, '@');
504                 if (tmp != NULL)                /* host name given */
505                 {
506                         conn->pghost = strdup(tmp + 1);
507                         *tmp = '\0';
508                 }
509
510                 conn->dbName = strdup(old);
511                 free(old);
512         }
513         else
514         {
515                 int                     offset;
516
517                 /*
518                  * only allow protocols tcp and unix
519                  */
520                 if (strncmp(conn->dbName, "tcp:", 4) == 0)
521                         offset = 4;
522                 else if (strncmp(conn->dbName, "unix:", 5) == 0)
523                         offset = 5;
524                 else
525                         return 0;
526
527                 if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
528                 {
529
530                         /*
531                          * new style:
532                          * <tcp|unix>:postgresql://server[:port][/dbname][?options]
533                          */
534                         offset += strlen("postgresql://");
535
536                         tmp = strrchr(conn->dbName + offset, '?');
537                         if (tmp != NULL)        /* options given */
538                         {
539                                 conn->pgoptions = strdup(tmp + 1);
540                                 *tmp = '\0';
541                         }
542
543                         tmp = strrchr(conn->dbName + offset, '/');
544                         if (tmp != NULL)        /* database name given */
545                         {
546                                 conn->dbName = strdup(tmp + 1);
547                                 *tmp = '\0';
548                         }
549                         else
550                         {
551                                 if ((tmp = getenv("PGDATABASE")) != NULL)
552                                         conn->dbName = strdup(tmp);
553                                 else if (conn->pguser)
554                                         conn->dbName = strdup(conn->pguser);
555                         }
556
557                         tmp = strrchr(old + offset, ':');
558                         if (tmp != NULL)        /* port number given */
559                         {
560                                 conn->pgport = strdup(tmp + 1);
561                                 *tmp = '\0';
562                         }
563
564                         if (strncmp(old, "unix:", 5) == 0)
565                         {
566                                 conn->pghost = NULL;
567                                 if (strcmp(old + offset, "localhost") != 0)
568                                 {
569                                         printfPQExpBuffer(&conn->errorMessage,
570                                                                           "connectDBStart() -- "
571                                                                           "non-TCP access only possible on "
572                                                                           "localhost\n");
573                                         return 1;
574                                 }
575                         }
576                         else
577                                 conn->pghost = strdup(old + offset);
578
579                         free(old);
580                 }
581         }
582
583         return 0;
584 }
585
586 /* ----------
587  * connectMakeNonblocking -
588  * Make a connection non-blocking.
589  * Returns 1 if successful, 0 if not.
590  * ----------
591  */
592 static int
593 connectMakeNonblocking(PGconn *conn)
594 {
595 #ifndef WIN32
596         if (fcntl(conn->sock, F_SETFL, O_NONBLOCK) < 0)
597 #else
598         int on = 1;
599         if (ioctlsocket(conn->sock, FIONBIO, &on) != 0)
600 #endif
601         {
602                 printfPQExpBuffer(&conn->errorMessage,
603                                                   "connectMakeNonblocking -- fcntl() failed: errno=%d\n%s\n",
604                                                   errno, strerror(errno));
605                 return 0;
606         }
607
608         return 1;
609 }
610
611 /* ----------
612  * connectNoDelay -
613  * Sets the TCP_NODELAY socket option.
614  * Returns 1 if successful, 0 if not.
615  * ----------
616  */
617 static int
618 connectNoDelay(PGconn *conn)
619 {
620         struct protoent *pe;
621         int                     on = 1;
622
623         pe = getprotobyname("TCP");
624         if (pe == NULL)
625         {
626                 printfPQExpBuffer(&conn->errorMessage,
627                                                   "connectNoDelay() -- "
628                                                   "getprotobyname failed: errno=%d\n%s\n",
629                                                   errno, strerror(errno));
630                 return 0;
631         }
632         if (setsockopt(conn->sock, pe->p_proto, TCP_NODELAY,
633 #ifdef WIN32
634                                    (char *)
635 #endif
636                                    &on,
637                                    sizeof(on)) < 0)
638         {
639                 printfPQExpBuffer(&conn->errorMessage,
640                                                   "connectNoDelay() -- setsockopt failed: errno=%d\n%s\n",
641                                                   errno, strerror(errno));
642 #ifdef WIN32
643                 printf("Winsock error: %i\n", WSAGetLastError());
644 #endif
645                 return 0;
646         }
647
648         return 1;
649 }
650
651
652 /* ----------
653  * connectDBStart -
654  * Start to make a connection to the backend so it is ready to receive
655  * queries.
656  * Returns 1 if successful, 0 if not.
657  * ----------
658  */
659 static int
660 connectDBStart(PGconn *conn)
661 {
662         int                     portno,
663                                 family;
664 #ifdef USE_SSL
665         StartupPacket           np; /* Used to negotiate SSL connection */
666         char                    SSLok;
667 #endif
668
669         if (!conn)
670                 return 0;
671         /*
672          * parse dbName to get all additional info in it, if any
673          */
674         if (update_db_info(conn) != 0)
675                 goto connect_errReturn;
676
677         /* Ensure our buffers are empty */
678         conn->inStart = conn->inCursor = conn->inEnd = 0;
679         conn->outCount = 0;
680
681         /*
682          * Set up the connection to postmaster/backend.
683          * Note that this supports IPv4 and UDP only.
684          */
685
686         MemSet((char *) &conn->raddr, 0, sizeof(conn->raddr));
687
688         if (conn->pghostaddr != NULL)
689         {
690                 /* Using pghostaddr avoids a hostname lookup */
691                 /* Note that this supports IPv4 only */
692                 struct in_addr addr;
693
694                 if(!inet_aton(conn->pghostaddr, &addr))
695                 {
696                         printfPQExpBuffer(&conn->errorMessage,
697                                                           "connectDBStart() -- "
698                                                           "invalid host address: %s\n", conn->pghostaddr);
699                         goto connect_errReturn;
700                 }
701
702                 family = AF_INET;
703
704                 memmove((char *) &(conn->raddr.in.sin_addr),
705                                 (char *) &addr, sizeof(addr));
706         }
707         else if (conn->pghost != NULL)
708         {
709                 /* Using pghost, so we have to look-up the hostname */
710                 struct hostent *hp;
711
712                 hp = gethostbyname(conn->pghost);
713                 if ((hp == NULL) || (hp->h_addrtype != AF_INET))
714                 {
715                         printfPQExpBuffer(&conn->errorMessage,
716                                                           "connectDBStart() --  unknown hostname: %s\n",
717                                                           conn->pghost);
718                         goto connect_errReturn;
719                 }
720                 family = AF_INET;
721
722                 memmove((char *) &(conn->raddr.in.sin_addr),
723                                 (char *) hp->h_addr,
724                                 hp->h_length);
725         }
726         else
727         {
728                 /* pghostaddr and pghost are NULL, so use UDP */
729                 family = AF_UNIX;
730         }
731
732         /* Set family */
733         conn->raddr.sa.sa_family = family;
734
735         /* Set port number */
736         portno = atoi(conn->pgport);
737         if (family == AF_INET)
738         {
739                 conn->raddr.in.sin_port = htons((unsigned short) (portno));
740                 conn->raddr_len = sizeof(struct sockaddr_in);
741         }
742 #if !defined(WIN32) && !defined(__CYGWIN32__)
743                 else
744                         conn->raddr_len = UNIXSOCK_PATH(conn->raddr.un, portno);
745 #endif
746
747
748         /* Open a socket */
749         if ((conn->sock = socket(family, SOCK_STREAM, 0)) < 0)
750         {
751                 printfPQExpBuffer(&conn->errorMessage,
752                                                   "connectDBStart() -- "
753                                                   "socket() failed: errno=%d\n%s\n",
754                                                   errno, strerror(errno));
755                 goto connect_errReturn;
756         }
757
758         /* ----------
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?).
762          * ---------- */
763
764         if (family == AF_INET)
765         {
766                 if (!connectNoDelay(conn))
767                         goto connect_errReturn;
768         }
769
770         /* ----------
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.
777          *
778          *   Ewan Mellor <eem21@cam.ac.uk>.
779          * ---------- */
780 #if (!defined(WIN32) || defined(WIN32_NON_BLOCKING_CONNECTIONS)) && !defined(USE_SSL)
781         if (connectMakeNonblocking(conn) == 0)
782                 goto connect_errReturn;
783 #endif  
784
785 #ifdef USE_SSL
786         /* This needs to be done before we set into nonblocking, since SSL
787          * negotiation does not like that mode */
788
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)
794             {
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;
799             }
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;
805           }
806           if (SSLok == 'S') {
807             if (!SSL_context) 
808               {
809                 SSL_load_error_strings();
810                 SSL_library_init();
811                 SSL_context = SSL_CTX_new(SSLv23_method());
812                 if (!SSL_context) {
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;
817                 }
818               }
819             if (!(conn->ssl = SSL_new(SSL_context)) ||
820                 !SSL_set_fd(conn->ssl, conn->sock) ||
821                 SSL_connect(conn->ssl) <= 0) 
822               {
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;
827               }
828             /* SSL connection finished. Continue to send startup packet */
829           }
830           else if (SSLok == 'E') {
831             /* Received error - probably protocol mismatch */
832             if (conn->Pfdebug)
833               fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-6.6.\n");
834             close(conn->sock);
835             conn->allow_ssl_try = FALSE;
836             return connectDBStart(conn);
837           }
838           else if (SSLok != 'N') {
839             strcpy(conn->errorMessage,
840                    "Received invalid negotiation response.\n");
841             goto connect_errReturn;
842           }
843         }
844 #endif
845
846         /* ----------
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.
855          * ----------
856          */
857         if (connect(conn->sock, &conn->raddr.sa, conn->raddr_len) < 0)
858         {
859 #ifndef WIN32
860                 if (errno == EINPROGRESS || errno == 0)
861 #else
862                 if (WSAGetLastError() == WSAEINPROGRESS)
863 #endif
864                 {
865                         /* This is fine - we're in non-blocking mode, and the
866                          * connection is in progress. */
867                         conn->status = CONNECTION_STARTED;
868                 }
869                 else
870                 {
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",
876                                                           strerror(errno),
877                                                           (family == AF_INET) ? " (with -i)" : "",
878                                                           conn->pghost ? conn->pghost : "localhost",
879                                                           (family == AF_INET) ?
880                                                           "TCP/IP port" : "Unix socket",
881                                                           conn->pgport);
882                         goto connect_errReturn;
883                 }
884         }
885         else
886         {
887                 /* We're connected already */
888                 conn->status = CONNECTION_MADE;
889         }
890
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;
896 #endif  
897
898         return 1;
899
900 connect_errReturn:
901         if (conn->sock >= 0)
902         {
903 #ifdef WIN32
904                 closesocket(conn->sock);
905 #else
906                 close(conn->sock);
907 #endif
908                 conn->sock = -1;
909         }
910         conn->status = CONNECTION_BAD;
911
912         return 0;
913 }
914
915
916 /* ----------------
917  *              connectDBComplete
918  *
919  * Block and complete a connection.
920  *
921  * Returns 1 on success, 0 on failure.
922  * ----------------
923  */
924 static int
925 connectDBComplete(PGconn *conn)
926 {
927         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
928
929         if (conn == NULL || conn->status == CONNECTION_BAD)
930                 return 0;
931
932         for (;;) {
933                 /*
934                  * Wait, if necessary.  Note that the initial state (just after
935                  * PQconnectStart) is to wait for the socket to select for writing.
936                  */
937                 switch (flag)
938                 {
939                         case PGRES_POLLING_ACTIVE:
940                                 break;
941
942                         case PGRES_POLLING_OK:
943                                 return 1;               /* success! */
944                                 
945                         case PGRES_POLLING_READING:
946                                 if (pqWait(1, 0, conn))
947                                 {
948                                         conn->status = CONNECTION_BAD;
949                                         return 0;
950                                 }
951                                 break;
952
953                         case PGRES_POLLING_WRITING:
954                                 if (pqWait(0, 1, conn))
955                                 {
956                                         conn->status = CONNECTION_BAD;
957                                         return 0;
958                                 }
959                                 break;
960
961                         default:
962                                 /* Just in case we failed to set it in PQconnectPoll */
963                                 conn->status = CONNECTION_BAD;
964                                 return 0;
965                 }
966                 /*
967                  * Now try to advance the state machine.
968                  */
969                 flag = PQconnectPoll(conn);
970         }
971 }
972
973 /* ----------------
974  *              PQconnectPoll
975  *
976  * Poll an asynchronous connection.
977  *
978  * Returns a PostgresPollingStatusType.
979  * Before calling this function, use select(2) to determine when data arrive.
980  * 
981  * You must call PQfinish whether or not this fails.
982  *
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:
986  *
987  *   o  If you call PQtrace, ensure that the stream object into which you trace
988  *      will not block.
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.
997  *
998  * ----------------
999  */
1000 PostgresPollingStatusType
1001 PQconnectPoll(PGconn *conn)
1002 {
1003         PGresult   *res;
1004
1005         if (conn == NULL)
1006                 return PGRES_POLLING_FAILED;
1007
1008         /* Get the new data */
1009         switch (conn->status)
1010         {
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;
1015                 case CONNECTION_OK:
1016                         return PGRES_POLLING_OK;
1017
1018                 /* These are reading states */
1019                 case CONNECTION_AWAITING_RESPONSE:
1020                 case CONNECTION_AUTH_OK:
1021                 {
1022                         /* Load waiting data */
1023                         int n = pqReadData(conn);
1024                                 
1025                         if (n < 0)
1026                                 goto error_return;
1027                         if (n == 0)
1028                                 return PGRES_POLLING_READING;
1029
1030                         break;
1031                 }
1032
1033                 /* These are writing states, so we just proceed. */
1034                 case CONNECTION_STARTED:
1035                 case CONNECTION_MADE:
1036                    break;
1037
1038                 case CONNECTION_SETENV:
1039                         /* We allow PQsetenvPoll to decide whether to proceed */
1040                         break;
1041
1042                 default:
1043                         printfPQExpBuffer(&conn->errorMessage,
1044                                                           "PQconnectPoll() -- unknown connection state - "
1045                                                           "probably indicative of memory corruption!\n");
1046                         goto error_return;
1047         }
1048
1049
1050  keep_going: /* We will come back to here until there is nothing left to
1051                                 parse. */
1052         switch(conn->status)
1053         {
1054                 case CONNECTION_STARTED:
1055                 {
1056                         SOCKET_SIZE_TYPE laddrlen;
1057 #ifndef WIN32
1058                         int optval;
1059 #else
1060                         char optval;
1061 #endif
1062                         SOCKET_SIZE_TYPE optlen = sizeof(optval);
1063
1064                         /* Write ready, since we've made it here, so the connection
1065                          * has been made. */
1066
1067                         /* Now check (using getsockopt) that there is not an error
1068                            state waiting for us on the socket. */
1069
1070                         if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1071                                                    &optval, &optlen) == -1)
1072                         {
1073                                 printfPQExpBuffer(&conn->errorMessage,
1074                                                                   "PQconnectPoll() -- getsockopt() failed: "
1075                                                                   "errno=%d\n%s\n",
1076                                                                   errno, strerror(errno));
1077                                 goto error_return;
1078                         }
1079                         else if (optval != 0)
1080                         {
1081                                 /*
1082                                  * When using a nonblocking connect, we will typically see
1083                                  * connect failures at this point, so provide a friendly
1084                                  * error message.
1085                                  */
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",
1090                                                                   strerror(optval),
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",
1095                                                                   conn->pgport);
1096                                 goto error_return;
1097                         }
1098
1099                         /* Fill in the client address */
1100                         laddrlen = sizeof(conn->laddr);
1101                         if (getsockname(conn->sock, &conn->laddr.sa, &laddrlen) < 0)
1102                         {
1103                                 printfPQExpBuffer(&conn->errorMessage,
1104                                                                   "PQconnectPoll() -- getsockname() failed: "
1105                                                                   "errno=%d\n%s\n",
1106                                                                   errno, strerror(errno));
1107                                 goto error_return;
1108                         }
1109
1110                         conn->status = CONNECTION_MADE;
1111                         return PGRES_POLLING_WRITING;
1112                 }
1113
1114                 case CONNECTION_MADE:
1115                 {
1116                         StartupPacket sp;
1117                         
1118                         /*
1119                          * Initialize the startup packet.
1120                          */
1121
1122                         MemSet((char *) &sp, 0, sizeof(StartupPacket));
1123         
1124                         sp.protoVersion = (ProtocolVersion) htonl(PG_PROTOCOL_LIBPQ);
1125                         
1126                         strncpy(sp.user, conn->pguser, SM_USER);
1127                         strncpy(sp.database, conn->dbName, SM_DATABASE);
1128                         strncpy(sp.tty, conn->pgtty, SM_TTY);
1129
1130                         if (conn->pgoptions)
1131                                 strncpy(sp.options, conn->pgoptions, SM_OPTIONS);
1132
1133                         /* Send the startup packet.
1134                          *
1135                          * Theoretically, this could block, but it really shouldn't
1136                          * since we only got here if the socket is write-ready.
1137                          */
1138
1139                         if (pqPacketSend(conn, (char *) &sp,
1140                                                          sizeof(StartupPacket)) != STATUS_OK)
1141                         {
1142                                 printfPQExpBuffer(&conn->errorMessage,
1143                                                                   "PQconnectPoll() --  "
1144                                                                   "couldn't send startup packet: "
1145                                                                   "errno=%d\n%s\n",
1146                                                                   errno, strerror(errno));
1147                                 goto error_return;
1148                         }
1149
1150                         conn->status = CONNECTION_AWAITING_RESPONSE;
1151                         return PGRES_POLLING_READING;
1152                 }
1153
1154                 /*
1155                  * Handle the authentication exchange: wait for postmaster messages
1156                  * and respond as necessary.
1157                  */
1158                 case CONNECTION_AWAITING_RESPONSE:
1159                 {
1160                         char            beresp;
1161                         AuthRequest areq;
1162
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).
1166                          */
1167                         conn->inCursor = conn->inStart;
1168
1169                         if (pqGetc(&beresp, conn))
1170                         {
1171                                 /* We'll come back when there are more data */
1172                                 return PGRES_POLLING_READING;
1173                         }
1174
1175                         /* Handle errors. */
1176                         if (beresp == 'E')
1177                         {
1178                                 if (pqGets(&conn->errorMessage, conn))
1179                                 {
1180                                         /* We'll come back when there are more data */
1181                                         return PGRES_POLLING_READING;
1182                                 }
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.
1187                                  */
1188                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
1189                                 goto error_return;
1190                         }
1191
1192                         /* Otherwise it should be an authentication request. */
1193                         if (beresp != 'R')
1194                         {
1195                                 printfPQExpBuffer(&conn->errorMessage,
1196                                                                   "PQconnectPoll() -- expected "
1197                                                                   "authentication request\n");
1198                                 goto error_return;
1199                         }
1200
1201                         /* Get the type of request. */
1202                         if (pqGetInt((int *) &areq, 4, conn))
1203                         {
1204                                 /* We'll come back when there are more data */
1205                                 return PGRES_POLLING_READING;
1206                         }
1207
1208                         /* Get the password salt if there is one. */
1209                         if (areq == AUTH_REQ_CRYPT)
1210                         {
1211                                 if (pqGetnchar(conn->salt, sizeof(conn->salt), conn))
1212                                 {
1213                                         /* We'll come back when there are more data */
1214                                         return PGRES_POLLING_READING;
1215                                 }
1216                         }
1217
1218                         /* OK, we successfully read the message; mark data consumed */
1219                         conn->inStart = conn->inCursor;
1220
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)
1227                         {
1228                                 conn->errorMessage.len = strlen(conn->errorMessage.data);
1229                                 goto error_return;
1230                         }
1231                         conn->errorMessage.len = strlen(conn->errorMessage.data);
1232
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.
1236                          */
1237                         if (pqFlush(conn))
1238                                 goto error_return;
1239
1240                         if (areq == AUTH_REQ_OK)
1241                         {
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;
1247                         }
1248
1249                         /* Look to see if we have more data yet. */
1250                         goto keep_going;
1251                 }
1252
1253                 case CONNECTION_AUTH_OK:
1254                 {
1255                         /* ----------
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).
1264                          *----------
1265                          */
1266
1267                         if (PQisBusy(conn))
1268                                 return PGRES_POLLING_READING;
1269                         
1270                         res = PQgetResult(conn);
1271                         /* NULL return indicating we have gone to
1272                            IDLE state is expected */
1273                         if (res)
1274                         {
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.
1283                                  */
1284                                 if (conn->errorMessage.len <= 0 ||
1285                                         conn->errorMessage.data[conn->errorMessage.len-1] != '\n')
1286                                         appendPQExpBufferChar(&conn->errorMessage, '\n');
1287                                 PQclear(res);
1288                                 goto error_return;
1289                         }
1290
1291                         /*
1292                          * Post-connection housekeeping. Prepare to send environment
1293                          * variables to server.
1294                          */
1295                         if (! PQsetenvStart(conn))
1296                                 goto error_return;
1297
1298                         conn->status = CONNECTION_SETENV;
1299
1300                         goto keep_going;
1301                 }
1302
1303                 case CONNECTION_SETENV:
1304                         /* We pretend that the connection is OK for the duration of
1305                            these queries. */
1306                         conn->status = CONNECTION_OK;
1307
1308                         switch (PQsetenvPoll(conn))
1309                         {
1310                                 case PGRES_POLLING_OK: /* Success */
1311                                         conn->status = CONNECTION_OK;
1312                                         return PGRES_POLLING_OK;
1313
1314                                 case PGRES_POLLING_READING: /* Still going */
1315                                         conn->status = CONNECTION_SETENV;
1316                                         return PGRES_POLLING_READING;
1317
1318                                 case PGRES_POLLING_WRITING: /* Still going */
1319                                         conn->status = CONNECTION_SETENV;
1320                                         return PGRES_POLLING_WRITING;
1321
1322                                 default:
1323                                         conn->status = CONNECTION_SETENV;
1324                                         goto error_return;
1325                         }
1326                         /* Unreachable */
1327
1328                 default:
1329                         printfPQExpBuffer(&conn->errorMessage,
1330                                                           "PQconnectPoll() -- unknown connection state - "
1331                                                           "probably indicative of memory corruption!\n");
1332                         goto error_return;
1333         }
1334
1335         /* Unreachable */
1336
1337 error_return:
1338         /* ----------
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).
1344          * ----------
1345          */
1346         return PGRES_POLLING_FAILED;
1347 }
1348
1349
1350 /* ----------------
1351  *              PQsetenvStart
1352  *
1353  * Starts the process of passing the values of a standard set of environment
1354  * variables to the backend.
1355  *
1356  * ----------------
1357  */
1358 static bool
1359 PQsetenvStart(PGconn *conn)
1360 {
1361         if (conn == NULL ||
1362                 conn->status == CONNECTION_BAD ||
1363                 conn->setenv_state != SETENV_STATE_IDLE)
1364                 return false;
1365
1366 #ifdef MULTIBYTE
1367         conn->setenv_state = SETENV_STATE_ENCODINGS_SEND;
1368 #else
1369         conn->setenv_state = SETENV_STATE_OPTION_SEND;
1370 #endif
1371         
1372         conn->next_eo = EnvironmentOptions;
1373
1374         return true;
1375 }
1376
1377 /* ----------------
1378  *              PQsetenvPoll
1379  *
1380  * Polls the process of passing the values of a standard set of environment
1381  * variables to the backend.
1382  *
1383  * ----------------
1384  */
1385 static PostgresPollingStatusType
1386 PQsetenvPoll(PGconn *conn)
1387 {
1388         PGresult   *res;
1389 #ifdef MULTIBYTE
1390         static const char envname[] = "PGCLIENTENCODING";
1391 #endif
1392
1393         if (conn == NULL || conn->status == CONNECTION_BAD)
1394                 return PGRES_POLLING_FAILED;
1395
1396         /* Check whether there are any data for us */
1397         switch (conn->setenv_state)
1398         {
1399                 /* These are reading states */
1400 #ifdef MULTIBYTE
1401                 case SETENV_STATE_ENCODINGS_WAIT:
1402 #endif
1403                 case SETENV_STATE_OPTION_WAIT:
1404                 {
1405                         /* Load waiting data */
1406                         int n = pqReadData(conn);
1407                                 
1408                         if (n < 0)
1409                                 goto error_return;
1410                         if (n == 0)
1411                                 return PGRES_POLLING_READING;
1412
1413                         break;
1414                 }
1415
1416                 /* These are writing states, so we just proceed. */
1417 #ifdef MULTIBYTE
1418                 case SETENV_STATE_ENCODINGS_SEND:
1419 #endif
1420                 case SETENV_STATE_OPTION_SEND:
1421                         break;
1422
1423                 /* Should we raise an error if called when not active? */
1424                 case SETENV_STATE_IDLE:
1425                         return PGRES_POLLING_OK;
1426
1427                 default:
1428                         printfPQExpBuffer(&conn->errorMessage,
1429                                                           "PQsetenvPoll() -- unknown state - "
1430                                                           "probably indicative of memory corruption!\n");
1431                         goto error_return;
1432         }
1433
1434
1435  keep_going: /* We will come back to here until there is nothing left to
1436                                 parse. */
1437         switch(conn->setenv_state)
1438         {
1439
1440 #ifdef MULTIBYTE
1441                 case SETENV_STATE_ENCODINGS_SEND:
1442                 {
1443                         const char *env;
1444                         
1445                         /* query server encoding */
1446                         env = getenv(envname);
1447                         if (!env || *env == '\0')
1448                         {
1449                                 if (!PQsendQuery(conn,
1450                                                                  "select getdatabaseencoding()"))
1451                                         goto error_return;
1452
1453                                 conn->setenv_state = SETENV_STATE_ENCODINGS_WAIT;
1454                                 return PGRES_POLLING_READING;
1455                         }
1456                 }
1457
1458                 case SETENV_STATE_ENCODINGS_WAIT:
1459                 {
1460                         if (PQisBusy(conn))
1461                                 return PGRES_POLLING_READING;
1462                         
1463                         res = PQgetResult(conn);
1464
1465                         if (res)
1466                         {
1467                                 char *encoding;
1468
1469                                 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1470                                 {
1471                                         PQclear(res);
1472                                         goto error_return;
1473                                 }
1474
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;
1479                                 else
1480                                         conn->client_encoding = pg_char_to_encoding(encoding);
1481                                 PQclear(res);
1482                                 /* We have to keep going in order to clear up the query */
1483                                 goto keep_going;
1484                         }
1485
1486                         /* NULL result indicates that the query is finished */
1487
1488                         /* Move on to setting the environment options */
1489                         conn->setenv_state = SETENV_STATE_OPTION_SEND;
1490                         goto keep_going;
1491                 }
1492 #endif
1493
1494                 case SETENV_STATE_OPTION_SEND:
1495                 {
1496                         /* Send an Environment Option */
1497                         char            setQuery[100];  /* note length limits in sprintf's below */
1498
1499                         if (conn->next_eo->envName)
1500                         {
1501                                 const char *val;
1502
1503                                 if ((val = getenv(conn->next_eo->envName)))
1504                                 {
1505                                         if (strcasecmp(val, "default") == 0)
1506                                                 sprintf(setQuery, "SET %s = %.60s",
1507                                                                 conn->next_eo->pgName, val);
1508                                         else
1509                                                 sprintf(setQuery, "SET %s = '%.60s'",
1510                                                                 conn->next_eo->pgName, val);
1511 #ifdef CONNECTDEBUG
1512                                         printf("Use environment variable %s to send %s\n",
1513                                                    conn->next_eo->envName, setQuery);
1514 #endif
1515                                         if (!PQsendQuery(conn, setQuery))
1516                                                 goto error_return;
1517
1518                                         conn->setenv_state = SETENV_STATE_OPTION_WAIT;
1519                                 }
1520                                 else
1521                                 {
1522                                         conn->next_eo++;
1523                                 }
1524                         }
1525                         else
1526                         {
1527                                 /* No more options to send, so we are done. */
1528                                 conn->setenv_state = SETENV_STATE_IDLE;
1529                         }
1530
1531                         goto keep_going;
1532                 }
1533
1534                 case SETENV_STATE_OPTION_WAIT:
1535                 {
1536                         if (PQisBusy(conn))
1537                                 return PGRES_POLLING_READING;
1538                         
1539                         res = PQgetResult(conn);
1540
1541                         if (res)
1542                         {
1543                                 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1544                                 {
1545                                         PQclear(res);
1546                                         goto error_return;
1547                                 }
1548                                 /* Don't need the result */
1549                                 PQclear(res);
1550                                 /* We have to keep going in order to clear up the query */
1551                                 goto keep_going;
1552                         }
1553
1554                         /* NULL result indicates that the query is finished */
1555
1556                         /* Send the next option */
1557                         conn->next_eo++;
1558                         conn->setenv_state = SETENV_STATE_OPTION_SEND;
1559                         goto keep_going;
1560                 }
1561
1562                 case SETENV_STATE_IDLE:
1563                         return PGRES_POLLING_OK;
1564
1565                 default:
1566                         printfPQExpBuffer(&conn->errorMessage,
1567                                                           "PQsetenvPoll() -- unknown state - "
1568                                                           "probably indicative of memory corruption!\n");
1569                         goto error_return;
1570         }
1571
1572         /* Unreachable */
1573
1574  error_return:
1575         conn->setenv_state = SETENV_STATE_IDLE;
1576         return PGRES_POLLING_FAILED;
1577 }
1578
1579
1580 #ifdef NOT_USED
1581
1582 /* ----------------
1583  *              PQsetenv
1584  *
1585  * Passes the values of a standard set of environment variables to the
1586  * backend.
1587  *
1588  * Returns true on success, false on failure.
1589  *
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.
1593  * ----------------
1594  */
1595 static bool
1596 PQsetenv(PGconn *conn)
1597 {
1598         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1599
1600         if (! PQsetenvStart(conn))
1601                 return false;
1602
1603         for (;;) {
1604                 /*
1605                  * Wait, if necessary.  Note that the initial state (just after
1606                  * PQsetenvStart) is to wait for the socket to select for writing.
1607                  */
1608                 switch (flag)
1609                 {
1610                         case PGRES_POLLING_ACTIVE:
1611                                 break;
1612
1613                         case PGRES_POLLING_OK:
1614                                 return true;    /* success! */
1615                                 
1616                         case PGRES_POLLING_READING:
1617                                 if (pqWait(1, 0, conn))
1618                                 {
1619                                         conn->status = CONNECTION_BAD;
1620                                         return false;
1621                                 }
1622                                 break;
1623
1624                         case PGRES_POLLING_WRITING:
1625                                 if (pqWait(0, 1, conn))
1626                                 {
1627                                         conn->status = CONNECTION_BAD;
1628                                         return false;
1629                                 }
1630                                 break;
1631
1632                         default:
1633                                 /* Just in case we failed to set it in PQsetenvPoll */
1634                                 conn->status = CONNECTION_BAD;
1635                                 return false;
1636                 }
1637                 /*
1638                  * Now try to advance the state machine.
1639                  */
1640                 flag = PQsetenvPoll(conn);
1641         }
1642 }
1643
1644 #endif /* NOT_USED */
1645
1646
1647 /*
1648  * makeEmptyPGconn
1649  *       - create a PGconn data structure with (as yet) no interesting data
1650  */
1651 static PGconn *
1652 makeEmptyPGconn(void)
1653 {
1654         PGconn     *conn = (PGconn *) malloc(sizeof(PGconn));
1655
1656         if (conn == NULL)
1657                 return conn;
1658
1659         /* Zero all pointers and booleans */
1660         MemSet((char *) conn, 0, sizeof(PGconn));
1661
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();
1667         conn->sock = -1;
1668 #ifdef USE_SSL
1669         conn->allow_ssl_try = TRUE;
1670 #endif
1671
1672         /*
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.
1678          *
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
1681          * twice that.
1682          */
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)
1694         {
1695                 /* out of memory already :-( */
1696                 freePGconn(conn);
1697                 conn = NULL;
1698         }
1699         return conn;
1700 }
1701
1702 /*
1703  * freePGconn
1704  *       - free the PGconn data structure
1705  *
1706  */
1707 static void
1708 freePGconn(PGconn *conn)
1709 {
1710         if (!conn)
1711                 return;
1712         pqClearAsyncResult(conn);       /* deallocate result and curTuple */
1713 #ifdef USE_SSL
1714         if (conn->ssl)
1715           SSL_free(conn->ssl);
1716 #endif
1717         if (conn->sock >= 0)
1718 #ifdef WIN32
1719                 closesocket(conn->sock);
1720 #else
1721                 close(conn->sock);
1722 #endif
1723         if (conn->pghost)
1724                 free(conn->pghost);
1725         if (conn->pghostaddr)
1726                 free(conn->pghostaddr);
1727         if (conn->pgport)
1728                 free(conn->pgport);
1729         if (conn->pgtty)
1730                 free(conn->pgtty);
1731         if (conn->pgoptions)
1732                 free(conn->pgoptions);
1733         if (conn->dbName)
1734                 free(conn->dbName);
1735         if (conn->pguser)
1736                 free(conn->pguser);
1737         if (conn->pgpass)
1738                 free(conn->pgpass);
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);
1744         if (conn->inBuffer)
1745                 free(conn->inBuffer);
1746         if (conn->outBuffer)
1747                 free(conn->outBuffer);
1748         termPQExpBuffer(&conn->errorMessage);
1749         termPQExpBuffer(&conn->workBuffer);
1750         free(conn);
1751 }
1752
1753 /*
1754    closePGconn
1755          - properly close a connection to the backend
1756 */
1757 static void
1758 closePGconn(PGconn *conn)
1759 {
1760         if (conn->sock >= 0)
1761         {
1762
1763                 /*
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.
1768                  */
1769                 (void) pqPuts("X", conn);
1770                 (void) pqFlush(conn);
1771         }
1772
1773         /* 
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.
1777          */
1778         conn->nonblocking = FALSE;
1779
1780         /*
1781          * Close the connection, reset all transient state, flush I/O buffers.
1782          */
1783         if (conn->sock >= 0)
1784 #ifdef WIN32
1785                 closesocket(conn->sock);
1786 #else
1787                 close(conn->sock);
1788 #endif
1789         conn->sock = -1;
1790         conn->status = CONNECTION_BAD;          /* Well, not really _bad_ - just
1791                                                                                  * absent */
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;
1798         conn->outCount = 0;
1799         conn->nonblocking = FALSE;
1800
1801 }
1802
1803 /*
1804    PQfinish:
1805           properly close a connection to the backend
1806           also frees the PGconn data structure so it shouldn't be re-used
1807           after this
1808 */
1809 void
1810 PQfinish(PGconn *conn)
1811 {
1812         if (conn)
1813         {
1814                 closePGconn(conn);
1815                 freePGconn(conn);
1816         }
1817 }
1818
1819 /* PQreset :
1820    resets the connection to the backend
1821    closes the existing connection and makes a new one
1822 */
1823 void
1824 PQreset(PGconn *conn)
1825 {
1826         if (conn)
1827         {
1828                 closePGconn(conn);
1829
1830                 if (connectDBStart(conn))
1831                         (void) connectDBComplete(conn);
1832         }
1833 }
1834
1835
1836 /* PQresetStart :
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.
1840 */
1841 int
1842 PQresetStart(PGconn *conn)
1843 {
1844         if (conn)
1845         {
1846                 closePGconn(conn);
1847
1848                 return connectDBStart(conn);
1849         }
1850
1851         return 0;
1852 }
1853
1854
1855 /* PQresetPoll :
1856    resets the connection to the backend
1857    closes the existing connection and makes a new one
1858 */
1859
1860 PostgresPollingStatusType
1861 PQresetPoll(PGconn *conn)
1862 {
1863         if (conn)
1864         {
1865                 return PQconnectPoll(conn);
1866         }
1867
1868         return PGRES_POLLING_FAILED;
1869 }
1870
1871
1872 /*
1873  * PQrequestCancel: attempt to request cancellation of the current operation.
1874  *
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.
1879  *
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.
1883  *
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.
1890  *
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!
1894  */
1895
1896 int
1897 PQrequestCancel(PGconn *conn)
1898 {
1899         int                     tmpsock = -1;
1900         struct
1901         {
1902                 uint32          packetlen;
1903                 CancelRequestPacket cp;
1904         }                       crp;
1905
1906         /* Check we have an open connection */
1907         if (!conn)
1908                 return FALSE;
1909
1910         if (conn->sock < 0)
1911         {
1912                 strcpy(conn->errorMessage.data,
1913                            "PQrequestCancel() -- connection is not open\n");
1914                 conn->errorMessage.len = strlen(conn->errorMessage.data);
1915                 return FALSE;
1916         }
1917
1918         /*
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.
1921          */
1922         if ((tmpsock = socket(conn->raddr.sa.sa_family, SOCK_STREAM, 0)) < 0)
1923         {
1924                 strcpy(conn->errorMessage.data,
1925                            "PQrequestCancel() -- socket() failed: ");
1926                 goto cancel_errReturn;
1927         }
1928         if (connect(tmpsock, &conn->raddr.sa, conn->raddr_len) < 0)
1929         {
1930                 strcpy(conn->errorMessage.data,
1931                            "PQrequestCancel() -- connect() failed: ");
1932                 goto cancel_errReturn;
1933         }
1934
1935         /*
1936          * We needn't set nonblocking I/O or NODELAY options here.
1937          */
1938
1939         /* Create and send the cancel request packet. */
1940
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);
1945
1946         if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
1947         {
1948                 strcpy(conn->errorMessage.data,
1949                            "PQrequestCancel() -- send() failed: ");
1950                 goto cancel_errReturn;
1951         }
1952
1953         /* Sent it, done */
1954 #ifdef WIN32
1955         closesocket(tmpsock);
1956 #else
1957         close(tmpsock);
1958 #endif
1959
1960         return TRUE;
1961
1962 cancel_errReturn:
1963         strcat(conn->errorMessage.data, strerror(errno));
1964         strcat(conn->errorMessage.data, "\n");
1965         conn->errorMessage.len = strlen(conn->errorMessage.data);
1966         if (tmpsock >= 0)
1967         {
1968 #ifdef WIN32
1969                 closesocket(tmpsock);
1970 #else
1971                 close(tmpsock);
1972 #endif
1973         }
1974         return FALSE;
1975 }
1976
1977
1978 /*
1979  * pqPacketSend() -- send a single-packet message.
1980  * this is like PacketSend(), defined in backend/libpq/pqpacket.c
1981  *
1982  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
1983  * SIDE_EFFECTS: may block.
1984 */
1985 int
1986 pqPacketSend(PGconn *conn, const char *buf, size_t len)
1987 {
1988         /* Send the total packet size. */
1989
1990         if (pqPutInt(4 + len, 4, conn))
1991                 return STATUS_ERROR;
1992
1993         /* Send the packet itself. */
1994
1995         if (pqPutnchar(buf, len, conn))
1996                 return STATUS_ERROR;
1997
1998         if (pqFlush(conn))
1999                 return STATUS_ERROR;
2000
2001         return STATUS_OK;
2002 }
2003
2004
2005 /* ----------------
2006  * Conninfo parser routine
2007  *
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.
2011  * ----------------
2012  */
2013 static PQconninfoOption *
2014 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2015 {
2016         char       *pname;
2017         char       *pval;
2018         char       *buf;
2019         char       *tmp;
2020         char       *cp;
2021         char       *cp2;
2022         PQconninfoOption *options;
2023         PQconninfoOption *option;
2024         char            errortmp[INITIAL_EXPBUFFER_SIZE];
2025
2026         /* Make a working copy of PQconninfoOptions */
2027         options = malloc(sizeof(PQconninfoOptions));
2028         if (options == NULL)
2029         {
2030                 printfPQExpBuffer(errorMessage,
2031                   "FATAL: cannot allocate memory for copy of PQconninfoOptions\n");
2032                 return NULL;
2033         }
2034         memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2035
2036         /* Need a modifiable copy of the input string */
2037         if ((buf = strdup(conninfo)) == NULL)
2038         {
2039                 printfPQExpBuffer(errorMessage,
2040                   "FATAL: cannot allocate memory for copy of conninfo string\n");
2041                 PQconninfoFree(options);
2042                 return NULL;
2043         }
2044         cp = buf;
2045
2046         while (*cp)
2047         {
2048                 /* Skip blanks before the parameter name */
2049                 if (isspace(*cp))
2050                 {
2051                         cp++;
2052                         continue;
2053                 }
2054
2055                 /* Get the parameter name */
2056                 pname = cp;
2057                 while (*cp)
2058                 {
2059                         if (*cp == '=')
2060                                 break;
2061                         if (isspace(*cp))
2062                         {
2063                                 *cp++ = '\0';
2064                                 while (*cp)
2065                                 {
2066                                         if (!isspace(*cp))
2067                                                 break;
2068                                         cp++;
2069                                 }
2070                                 break;
2071                         }
2072                         cp++;
2073                 }
2074
2075                 /* Check that there is a following '=' */
2076                 if (*cp != '=')
2077                 {
2078                         printfPQExpBuffer(errorMessage,
2079                                                           "ERROR: Missing '=' after '%s' in conninfo\n",
2080                                                           pname);
2081                         PQconninfoFree(options);
2082                         free(buf);
2083                         return NULL;
2084                 }
2085                 *cp++ = '\0';
2086
2087                 /* Skip blanks after the '=' */
2088                 while (*cp)
2089                 {
2090                         if (!isspace(*cp))
2091                                 break;
2092                         cp++;
2093                 }
2094
2095                 /* Get the parameter value */
2096                 pval = cp;
2097
2098                 if (*cp != '\'')
2099                 {
2100                         cp2 = pval;
2101                         while (*cp)
2102                         {
2103                                 if (isspace(*cp))
2104                                 {
2105                                         *cp++ = '\0';
2106                                         break;
2107                                 }
2108                                 if (*cp == '\\')
2109                                 {
2110                                         cp++;
2111                                         if (*cp != '\0')
2112                                                 *cp2++ = *cp++;
2113                                 }
2114                                 else
2115                                         *cp2++ = *cp++;
2116                         }
2117                         *cp2 = '\0';
2118                 }
2119                 else
2120                 {
2121                         cp2 = pval;
2122                         cp++;
2123                         for (;;)
2124                         {
2125                                 if (*cp == '\0')
2126                                 {
2127                                         printfPQExpBuffer(errorMessage,
2128                                                         "ERROR: PQconnectdb() - unterminated quoted string in conninfo\n");
2129                                         PQconninfoFree(options);
2130                                         free(buf);
2131                                         return NULL;
2132                                 }
2133                                 if (*cp == '\\')
2134                                 {
2135                                         cp++;
2136                                         if (*cp != '\0')
2137                                                 *cp2++ = *cp++;
2138                                         continue;
2139                                 }
2140                                 if (*cp == '\'')
2141                                 {
2142                                         *cp2 = '\0';
2143                                         cp++;
2144                                         break;
2145                                 }
2146                                 *cp2++ = *cp++;
2147                         }
2148                 }
2149
2150                 /* ----------
2151                  * Now we have the name and the value. Search
2152                  * for the param record.
2153                  * ----------
2154                  */
2155                 for (option = options; option->keyword != NULL; option++)
2156                 {
2157                         if (strcmp(option->keyword, pname) == 0)
2158                                 break;
2159                 }
2160                 if (option->keyword == NULL)
2161                 {
2162                         printfPQExpBuffer(errorMessage,
2163                                                           "ERROR: Unknown conninfo option '%s'\n",
2164                                                           pname);
2165                         PQconninfoFree(options);
2166                         free(buf);
2167                         return NULL;
2168                 }
2169
2170                 /* ----------
2171                  * Store the value
2172                  * ----------
2173                  */
2174                 if (option->val)
2175                         free(option->val);
2176                 option->val = strdup(pval);
2177         }
2178
2179         /* Done with the modifiable input string */
2180         free(buf);
2181
2182         /* ----------
2183          * Get the fallback resources for parameters not specified
2184          * in the conninfo string.
2185          * ----------
2186          */
2187         for (option = options; option->keyword != NULL; option++)
2188         {
2189                 if (option->val != NULL)
2190                         continue;                       /* Value was in conninfo */
2191
2192                 /* ----------
2193                  * Try to get the environment variable fallback
2194                  * ----------
2195                  */
2196                 if (option->envvar != NULL)
2197                 {
2198                         if ((tmp = getenv(option->envvar)) != NULL)
2199                         {
2200                                 option->val = strdup(tmp);
2201                                 continue;
2202                         }
2203                 }
2204
2205                 /* ----------
2206                  * No environment variable specified or this one isn't set -
2207                  * try compiled in
2208                  * ----------
2209                  */
2210                 if (option->compiled != NULL)
2211                 {
2212                         option->val = strdup(option->compiled);
2213                         continue;
2214                 }
2215
2216                 /* ----------
2217                  * Special handling for user
2218                  * ----------
2219                  */
2220                 if (strcmp(option->keyword, "user") == 0)
2221                 {
2222                         option->val = fe_getauthname(errortmp);
2223                         /* note any error message is thrown away */
2224                         continue;
2225                 }
2226
2227                 /* ----------
2228                  * Special handling for dbname
2229                  * ----------
2230                  */
2231                 if (strcmp(option->keyword, "dbname") == 0)
2232                 {
2233                         tmp = conninfo_getval(options, "user");
2234                         if (tmp)
2235                                 option->val = strdup(tmp);
2236                         continue;
2237                 }
2238         }
2239
2240         return options;
2241 }
2242
2243
2244 static char *
2245 conninfo_getval(PQconninfoOption *connOptions,
2246                                 const char *keyword)
2247 {
2248         PQconninfoOption *option;
2249
2250         for (option = connOptions; option->keyword != NULL; option++)
2251         {
2252                 if (strcmp(option->keyword, keyword) == 0)
2253                         return option->val;
2254         }
2255
2256         return NULL;
2257 }
2258
2259
2260 void
2261 PQconninfoFree(PQconninfoOption *connOptions)
2262 {
2263         PQconninfoOption *option;
2264
2265         if (connOptions == NULL)
2266                 return;
2267
2268         for (option = connOptions; option->keyword != NULL; option++)
2269         {
2270                 if (option->val != NULL)
2271                         free(option->val);
2272         }
2273         free(connOptions);
2274 }
2275
2276 /* =========== accessor functions for PGconn ========= */
2277 char *
2278 PQdb(const PGconn *conn)
2279 {
2280         if (!conn)
2281                 return (char *) NULL;
2282         return conn->dbName;
2283 }
2284
2285 char *
2286 PQuser(const PGconn *conn)
2287 {
2288         if (!conn)
2289                 return (char *) NULL;
2290         return conn->pguser;
2291 }
2292
2293 char *
2294 PQpass(const PGconn *conn)
2295 {
2296         if (!conn)
2297                 return (char *) NULL;
2298         return conn->pgpass;
2299 }
2300
2301 char *
2302 PQhost(const PGconn *conn)
2303 {
2304         if (!conn)
2305                 return (char *) NULL;
2306         return conn->pghost;
2307 }
2308
2309 char *
2310 PQport(const PGconn *conn)
2311 {
2312         if (!conn)
2313                 return (char *) NULL;
2314         return conn->pgport;
2315 }
2316
2317 char *
2318 PQtty(const PGconn *conn)
2319 {
2320         if (!conn)
2321                 return (char *) NULL;
2322         return conn->pgtty;
2323 }
2324
2325 char *
2326 PQoptions(const PGconn *conn)
2327 {
2328         if (!conn)
2329                 return (char *) NULL;
2330         return conn->pgoptions;
2331 }
2332
2333 ConnStatusType
2334 PQstatus(const PGconn *conn)
2335 {
2336         if (!conn)
2337                 return CONNECTION_BAD;
2338         return conn->status;
2339 }
2340
2341 char *
2342 PQerrorMessage(const PGconn *conn)
2343 {
2344         if (!conn)
2345                 return "PQerrorMessage: conn pointer is NULL\n";
2346
2347         return conn->errorMessage.data;
2348 }
2349
2350 int
2351 PQsocket(const PGconn *conn)
2352 {
2353         if (!conn)
2354                 return -1;
2355         return conn->sock;
2356 }
2357
2358 int
2359 PQbackendPID(const PGconn *conn)
2360 {
2361         if (!conn || conn->status != CONNECTION_OK)
2362                 return 0;
2363         return conn->be_pid;
2364 }
2365
2366 int
2367 PQclientEncoding(const PGconn *conn)
2368 {
2369         if (!conn || conn->status != CONNECTION_OK)
2370                 return -1;
2371         return conn->client_encoding;
2372 }
2373
2374 #ifdef MULTIBYTE
2375 int
2376 PQsetClientEncoding(PGconn *conn, const char *encoding)
2377 {
2378         char qbuf[128];
2379         static char query[] = "set client_encoding to '%s'";
2380         PGresult *res;
2381         int status;
2382
2383         if (!conn || conn->status != CONNECTION_OK)
2384                 return -1;
2385
2386         if (!encoding)
2387                 return -1;
2388
2389         /* check query buffer overflow */
2390         if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2391                 return -1;
2392
2393         /* ok, now send a query */
2394         sprintf(qbuf, query, encoding);
2395         res = PQexec(conn, qbuf);
2396
2397         if (res == (PGresult *)NULL)
2398                 return -1;
2399         if (res->resultStatus != PGRES_COMMAND_OK)
2400                 status = -1;
2401         else
2402         {
2403                 /* change libpq internal encoding */
2404                 conn->client_encoding = pg_char_to_encoding(encoding);
2405                 status = 0;     /* everything is ok */
2406         }
2407         PQclear(res);
2408         return(status);
2409 }
2410 #else
2411 int
2412 PQsetClientEncoding(PGconn *conn, const char *encoding)
2413 {
2414         return -1;
2415 }
2416 #endif
2417
2418 void
2419 PQtrace(PGconn *conn, FILE *debug_port)
2420 {
2421         if (conn == NULL ||
2422                 conn->status == CONNECTION_BAD)
2423                 return;
2424         PQuntrace(conn);
2425         conn->Pfdebug = debug_port;
2426 }
2427
2428 void
2429 PQuntrace(PGconn *conn)
2430 {
2431         /* note: better allow untrace even when connection bad */
2432         if (conn == NULL)
2433                 return;
2434         if (conn->Pfdebug)
2435         {
2436                 fflush(conn->Pfdebug);
2437                 conn->Pfdebug = NULL;
2438         }
2439 }
2440
2441 PQnoticeProcessor
2442 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2443 {
2444         PQnoticeProcessor old;
2445
2446         if (conn == NULL)
2447                 return NULL;
2448
2449         old = conn->noticeHook;
2450         if (proc)
2451         {
2452                 conn->noticeHook = proc;
2453                 conn->noticeArg = arg;
2454         }
2455         return old;
2456 }
2457
2458 /*
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.
2463  */
2464
2465 static void
2466 defaultNoticeProcessor(void *arg, const char *message)
2467 {
2468     (void)arg; /*not used*/
2469         /* Note: we expect the supplied string to end with a newline already. */
2470         fprintf(stderr, "%s", message);
2471 }