]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-connect.c
Simplify the socket handling code by supplying a replacement getaddrinfo()
[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-2002, PostgreSQL Global Development Group
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.229 2003/03/29 11:31:51 petere Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres_fe.h"
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <errno.h>
22 #include <ctype.h>
23 #include <time.h>
24
25 #ifndef HAVE_STRDUP
26 #include "strdup.h"
27 #endif
28 #ifdef HAVE_CRYPT_H
29 #include <crypt.h>
30 #endif
31
32 #include "libpq-fe.h"
33 #include "libpq-int.h"
34 #include "fe-auth.h"
35
36 #ifdef WIN32
37 #include "win32.h"
38 #else
39 #include <sys/socket.h>
40 #include <unistd.h>
41 #include <netdb.h>
42 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_TCP_H
44 #include <netinet/tcp.h>
45 #endif
46 #include <arpa/inet.h>
47 #endif
48
49 #include "libpq/ip.h"
50 #include "mb/pg_wchar.h"
51
52
53 #ifdef WIN32
54 static int
55 inet_aton(const char *cp, struct in_addr * inp)
56 {
57         unsigned long a = inet_addr(cp);
58
59         if (a == -1)
60                 return 0;
61         inp->s_addr = a;
62         return 1;
63 }
64 #endif
65
66
67 #define NOTIFYLIST_INITIAL_SIZE 10
68 #define NOTIFYLIST_GROWBY 10
69
70 #define PGPASSFILE ".pgpass"
71
72 /* ----------
73  * Definition of the conninfo parameters and their fallback resources.
74  *
75  * If Environment-Var and Compiled-in are specified as NULL, no
76  * fallback is available. If after all no value can be determined
77  * for an option, an error is returned.
78  *
79  * The values for dbname and user are treated specially in conninfo_parse.
80  * If the Compiled-in resource is specified as a NULL value, the
81  * user is determined by fe_getauthname() and for dbname the user
82  * name is copied.
83  *
84  * The Label and Disp-Char entries are provided for applications that
85  * want to use PQconndefaults() to create a generic database connection
86  * dialog. Disp-Char is defined as follows:
87  *              ""              Normal input field
88  *              "*"             Password field - hide value
89  *              "D"             Debug option - don't show by default
90  *
91  * PQconninfoOptions[] is a constant static array that we use to initialize
92  * a dynamically allocated working copy.  All the "val" fields in
93  * PQconninfoOptions[] *must* be NULL.  In a working copy, non-null "val"
94  * fields point to malloc'd strings that should be freed when the working
95  * array is freed (see PQconninfoFree).
96  * ----------
97  */
98 static const PQconninfoOption PQconninfoOptions[] = {
99         /*
100          * "authtype" is no longer used, so mark it "don't show".  We keep it
101          * in the array so as not to reject conninfo strings from old apps
102          * that might still try to set it.
103          */
104         {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
105         "Database-Authtype", "D", 20},
106
107         {"service", "PGSERVICE", NULL, NULL,
108         "Database-Service", "", 20},
109
110         {"user", "PGUSER", NULL, NULL,
111         "Database-User", "", 20},
112
113         {"password", "PGPASSWORD", DefaultPassword, NULL,
114         "Database-Password", "*", 20},
115
116         {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
117         "Connect-timeout", "", 10}, /* strlen(INT32_MAX) == 10 */
118
119         {"dbname", "PGDATABASE", NULL, NULL,
120         "Database-Name", "", 20},
121
122         {"host", "PGHOST", NULL, NULL,
123         "Database-Host", "", 40},
124
125         {"hostaddr", "PGHOSTADDR", NULL, NULL,
126         "Database-Host-IP-Address", "", 45},
127
128         {"port", "PGPORT", DEF_PGPORT_STR, NULL,
129         "Database-Port", "", 6},
130
131         {"tty", "PGTTY", DefaultTty, NULL,
132         "Backend-Debug-TTY", "D", 40},
133
134         {"options", "PGOPTIONS", DefaultOption, NULL,
135         "Backend-Debug-Options", "D", 40},
136
137 #ifdef USE_SSL
138         {"requiressl", "PGREQUIRESSL", "0", NULL,
139         "Require-SSL", "", 1},
140 #endif
141
142         /* Terminating entry --- MUST BE LAST */
143         {NULL, NULL, NULL, NULL,
144         NULL, NULL, 0}
145 };
146
147 static const struct EnvironmentOptions
148 {
149         const char *envName,
150                            *pgName;
151 }       EnvironmentOptions[] =
152
153 {
154         /* common user-interface settings */
155         {
156                 "PGDATESTYLE", "datestyle"
157         },
158         {
159                 "PGTZ", "timezone"
160         },
161         {
162                 "PGCLIENTENCODING", "client_encoding"
163         },
164         /* internal performance-related settings */
165         {
166                 "PGGEQO", "geqo"
167         },
168         {
169                 NULL, NULL
170         }
171 };
172
173
174 static int      connectDBStart(PGconn *conn);
175 static int      connectDBComplete(PGconn *conn);
176 static bool PQsetenvStart(PGconn *conn);
177 static PostgresPollingStatusType PQsetenvPoll(PGconn *conn);
178 static PGconn *makeEmptyPGconn(void);
179 static void freePGconn(PGconn *conn);
180 static void closePGconn(PGconn *conn);
181 static PQconninfoOption *conninfo_parse(const char *conninfo,
182                            PQExpBuffer errorMessage);
183 static char *conninfo_getval(PQconninfoOption *connOptions,
184                                 const char *keyword);
185 static void defaultNoticeProcessor(void *arg, const char *message);
186 static int parseServiceInfo(PQconninfoOption *options,
187                                  PQExpBuffer errorMessage);
188 char       *pwdfMatchesString(char *buf, char *token);
189 char *PasswordFromFile(char *hostname, char *port, char *dbname,
190                                  char *username);
191
192 /*
193  *              Connecting to a Database
194  *
195  * There are now four different ways a user of this API can connect to the
196  * database.  Two are not recommended for use in new code, because of their
197  * lack of extensibility with respect to the passing of options to the
198  * backend.  These are PQsetdb and PQsetdbLogin (the former now being a macro
199  * to the latter).
200  *
201  * If it is desired to connect in a synchronous (blocking) manner, use the
202  * function PQconnectdb.
203  *
204  * To connect in an asynchronous (non-blocking) manner, use the functions
205  * PQconnectStart, and PQconnectPoll.
206  *
207  * Internally, the static functions connectDBStart, connectDBComplete
208  * are part of the connection procedure.
209  */
210
211 /*
212  *              PQconnectdb
213  *
214  * establishes a connection to a postgres backend through the postmaster
215  * using connection information in a string.
216  *
217  * The conninfo string is a white-separated list of
218  *
219  *         option = value
220  *
221  * definitions. Value might be a single value containing no whitespaces or
222  * a single quoted string. If a single quote should appear anywhere in
223  * the value, it must be escaped with a backslash like \'
224  *
225  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
226  * if a memory allocation failed.
227  * If the status field of the connection returned is CONNECTION_BAD,
228  * then some fields may be null'ed out instead of having valid values.
229  *
230  * You should call PQfinish (if conn is not NULL) regardless of whether this
231  * call succeeded.
232  */
233 PGconn *
234 PQconnectdb(const char *conninfo)
235 {
236         PGconn     *conn = PQconnectStart(conninfo);
237
238         if (conn && conn->status != CONNECTION_BAD)
239                 (void) connectDBComplete(conn);
240
241         return conn;
242 }
243
244 /*
245  *              PQconnectStart
246  *
247  * Begins the establishment of a connection to a postgres backend through the
248  * postmaster using connection information in a string.
249  *
250  * See comment for PQconnectdb for the definition of the string format.
251  *
252  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
253  * you should not attempt to proceed with this connection.      If the status
254  * field of the connection returned is CONNECTION_BAD, an error has
255  * occurred. In this case you should call PQfinish on the result, (perhaps
256  * inspecting the error message first).  Other fields of the structure may not
257  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
258  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
259  * this is necessary.
260  *
261  * See PQconnectPoll for more info.
262  */
263 PGconn *
264 PQconnectStart(const char *conninfo)
265 {
266         PGconn     *conn;
267         PQconninfoOption *connOptions;
268         char       *tmp;
269
270         /*
271          * Allocate memory for the conn structure
272          */
273
274         conn = makeEmptyPGconn();
275         if (conn == NULL)
276                 return (PGconn *) NULL;
277
278         /*
279          * Parse the conninfo string
280          */
281         connOptions = conninfo_parse(conninfo, &conn->errorMessage);
282         if (connOptions == NULL)
283         {
284                 conn->status = CONNECTION_BAD;
285                 /* errorMessage is already set */
286                 return conn;
287         }
288
289         /*
290          * Move option values into conn structure
291          */
292         tmp = conninfo_getval(connOptions, "hostaddr");
293         conn->pghostaddr = tmp ? strdup(tmp) : NULL;
294         tmp = conninfo_getval(connOptions, "host");
295         conn->pghost = tmp ? strdup(tmp) : NULL;
296         tmp = conninfo_getval(connOptions, "port");
297         conn->pgport = tmp ? strdup(tmp) : NULL;
298         tmp = conninfo_getval(connOptions, "tty");
299         conn->pgtty = tmp ? strdup(tmp) : NULL;
300         tmp = conninfo_getval(connOptions, "options");
301         conn->pgoptions = tmp ? strdup(tmp) : NULL;
302         tmp = conninfo_getval(connOptions, "dbname");
303         conn->dbName = tmp ? strdup(tmp) : NULL;
304         tmp = conninfo_getval(connOptions, "user");
305         conn->pguser = tmp ? strdup(tmp) : NULL;
306         tmp = conninfo_getval(connOptions, "password");
307         conn->pgpass = tmp ? strdup(tmp) : NULL;
308         if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
309         {
310                 if (conn->pgpass)
311                         free(conn->pgpass);
312                 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
313                                                                                 conn->dbName, conn->pguser);
314                 if (conn->pgpass == NULL)
315                         conn->pgpass = strdup(DefaultPassword);
316         }
317         tmp = conninfo_getval(connOptions, "connect_timeout");
318         conn->connect_timeout = tmp ? strdup(tmp) : NULL;
319 #ifdef USE_SSL
320         tmp = conninfo_getval(connOptions, "requiressl");
321         if (tmp && tmp[0] == '1')
322                 conn->require_ssl = true;
323 #endif
324
325         /*
326          * Free the option info - all is in conn now
327          */
328         PQconninfoFree(connOptions);
329
330         /*
331          * Allow unix socket specification in the host name
332          */
333         if (conn->pghost && conn->pghost[0] == '/')
334         {
335                 if (conn->pgunixsocket)
336                         free(conn->pgunixsocket);
337                 conn->pgunixsocket = conn->pghost;
338                 conn->pghost = NULL;
339         }
340
341         /*
342          * Connect to the database
343          */
344         if (!connectDBStart(conn))
345         {
346                 /* Just in case we failed to set it in connectDBStart */
347                 conn->status = CONNECTION_BAD;
348         }
349
350         return conn;
351 }
352
353 /*
354  *              PQconndefaults
355  *
356  * Parse an empty string like PQconnectdb() would do and return the
357  * working connection options array.
358  *
359  * Using this function, an application may determine all possible options
360  * and their current default values.
361  *
362  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
363  * and should be freed when no longer needed via PQconninfoFree().      (In prior
364  * versions, the returned array was static, but that's not thread-safe.)
365  * Pre-7.0 applications that use this function will see a small memory leak
366  * until they are updated to call PQconninfoFree.
367  */
368 PQconninfoOption *
369 PQconndefaults(void)
370 {
371         PQExpBufferData errorBuf;
372         PQconninfoOption *connOptions;
373
374         initPQExpBuffer(&errorBuf);
375         connOptions = conninfo_parse("", &errorBuf);
376         termPQExpBuffer(&errorBuf);
377         return connOptions;
378 }
379
380 /* ----------------
381  *              PQsetdbLogin
382  *
383  * establishes a connection to a postgres backend through the postmaster
384  * at the specified host and port.
385  *
386  * returns a PGconn* which is needed for all subsequent libpq calls
387  * if the status field of the connection returned is CONNECTION_BAD,
388  * then some fields may be null'ed out instead of having valid values
389  *
390  *      Uses these environment variables:
391  *
392  *        PGHOST           identifies host to which to connect if <pghost> argument
393  *                                 is NULL or a null string.
394  *
395  *        PGPORT           identifies TCP port to which to connect if <pgport> argument
396  *                                 is NULL or a null string.
397  *
398  *        PGTTY            identifies tty to which to send messages if <pgtty> argument
399  *                                 is NULL or a null string.
400  *
401  *        PGOPTIONS    identifies connection options if <pgoptions> argument is
402  *                                 NULL or a null string.
403  *
404  *        PGUSER           Postgres username to associate with the connection.
405  *
406  *        PGPASSWORD   The user's password.
407  *
408  *        PGDATABASE   name of database to which to connect if <pgdatabase>
409  *                                 argument is NULL or a null string
410  *
411  *        None of the above need be defined.  There are defaults for all of them.
412  *
413  * To support "delimited identifiers" for database names, only convert
414  * the database name to lower case if it is not surrounded by double quotes.
415  * Otherwise, strip the double quotes but leave the reset of the string intact.
416  * - thomas 1997-11-08
417  * ----------------
418  */
419 PGconn *
420 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
421                          const char *pgtty, const char *dbName, const char *login,
422                          const char *pwd)
423 {
424         PGconn     *conn;
425         char       *tmp;                        /* An error message from some service we
426                                                                  * call. */
427         bool            error = FALSE;  /* We encountered an error. */
428
429         conn = makeEmptyPGconn();
430         if (conn == NULL)
431                 return (PGconn *) NULL;
432
433         if (pghost)
434                 conn->pghost = strdup(pghost);
435         else if ((tmp = getenv("PGHOST")) != NULL)
436                 conn->pghost = strdup(tmp);
437
438         if (pgport == NULL || pgport[0] == '\0')
439         {
440                 tmp = getenv("PGPORT");
441                 if (tmp == NULL || tmp[0] == '\0')
442                         tmp = DEF_PGPORT_STR;
443                 conn->pgport = strdup(tmp);
444         }
445         else
446                 conn->pgport = strdup(pgport);
447
448         /*
449          * We don't allow unix socket path as a function parameter. This
450          * allows unix socket specification in the host name.
451          */
452         if (conn->pghost && conn->pghost[0] == '/')
453         {
454                 if (conn->pgunixsocket)
455                         free(conn->pgunixsocket);
456                 conn->pgunixsocket = conn->pghost;
457                 conn->pghost = NULL;
458         }
459
460         if (pgtty == NULL)
461         {
462                 if ((tmp = getenv("PGTTY")) == NULL)
463                         tmp = DefaultTty;
464                 conn->pgtty = strdup(tmp);
465         }
466         else
467                 conn->pgtty = strdup(pgtty);
468
469         if (pgoptions == NULL)
470         {
471                 if ((tmp = getenv("PGOPTIONS")) == NULL)
472                         tmp = DefaultOption;
473                 conn->pgoptions = strdup(tmp);
474         }
475         else
476                 conn->pgoptions = strdup(pgoptions);
477
478         if (login)
479                 conn->pguser = strdup(login);
480         else if ((tmp = getenv("PGUSER")) != NULL)
481                 conn->pguser = strdup(tmp);
482         else
483         {
484                 /* fe-auth.c has not been fixed to support PQExpBuffers, so: */
485                 conn->pguser = fe_getauthname(conn->errorMessage.data);
486                 conn->errorMessage.len = strlen(conn->errorMessage.data);
487         }
488
489         if (conn->pguser == NULL)
490         {
491                 error = TRUE;
492                 printfPQExpBuffer(&conn->errorMessage,
493                                                   libpq_gettext("could not determine the PostgreSQL user name to use\n"));
494         }
495
496         if (dbName == NULL)
497         {
498                 if ((tmp = getenv("PGDATABASE")) != NULL)
499                         conn->dbName = strdup(tmp);
500                 else if (conn->pguser)
501                         conn->dbName = strdup(conn->pguser);
502         }
503         else
504                 conn->dbName = strdup(dbName);
505
506         if (pwd)
507                 conn->pgpass = strdup(pwd);
508         else if ((tmp = getenv("PGPASSWORD")) != NULL)
509                 conn->pgpass = strdup(tmp);
510         else if ((tmp = PasswordFromFile(conn->pghost, conn->pgport,
511                                                                          conn->dbName, conn->pguser)) != NULL)
512                 conn->pgpass = tmp;
513         else
514                 conn->pgpass = strdup(DefaultPassword);
515
516         if ((tmp = getenv("PGCONNECT_TIMEOUT")) != NULL)
517                 conn->connect_timeout = strdup(tmp);
518
519 #ifdef USE_SSL
520         if ((tmp = getenv("PGREQUIRESSL")) != NULL)
521                 conn->require_ssl = (tmp[0] == '1') ? true : false;
522 #endif
523
524         if (error)
525                 conn->status = CONNECTION_BAD;
526         else
527         {
528                 if (connectDBStart(conn))
529                         (void) connectDBComplete(conn);
530         }
531
532         return conn;
533 }
534
535
536 #ifdef NOT_USED                                 /* because it's broken */
537 /*
538  * update_db_info -
539  * get all additional info out of dbName
540  *
541  */
542 static int
543 update_db_info(PGconn *conn)
544 {
545         char       *tmp,
546                            *tmp2,
547                            *old = conn->dbName;
548
549         if (strchr(conn->dbName, '@') != NULL)
550         {
551                 /* old style: dbname[@server][:port] */
552                 tmp = strrchr(conn->dbName, ':');
553                 if (tmp != NULL)                /* port number given */
554                 {
555                         if (conn->pgport)
556                                 free(conn->pgport);
557                         conn->pgport = strdup(tmp + 1);
558                         *tmp = '\0';
559                 }
560
561                 tmp = strrchr(conn->dbName, '@');
562                 if (tmp != NULL)                /* host name given */
563                 {
564                         if (conn->pghost)
565                                 free(conn->pghost);
566                         conn->pghost = strdup(tmp + 1);
567                         *tmp = '\0';
568                 }
569
570                 conn->dbName = strdup(old);
571                 free(old);
572         }
573         else
574         {
575                 int                     offset;
576
577                 /*
578                  * only allow protocols tcp and unix
579                  */
580                 if (strncmp(conn->dbName, "tcp:", 4) == 0)
581                         offset = 4;
582                 else if (strncmp(conn->dbName, "unix:", 5) == 0)
583                         offset = 5;
584                 else
585                         return 0;
586
587                 if (strncmp(conn->dbName + offset, "postgresql://", strlen("postgresql://")) == 0)
588                 {
589
590                         /*-------
591                          * new style:
592                          *      <tcp|unix>:postgresql://server[:port|:/unixsocket/path:]
593                          *      [/db name][?options]
594                          *-------
595                          */
596                         offset += strlen("postgresql://");
597
598                         tmp = strrchr(conn->dbName + offset, '?');
599                         if (tmp != NULL)        /* options given */
600                         {
601                                 if (conn->pgoptions)
602                                         free(conn->pgoptions);
603                                 conn->pgoptions = strdup(tmp + 1);
604                                 *tmp = '\0';
605                         }
606
607                         tmp = strrchr(conn->dbName + offset, '/');
608                         if (tmp != NULL)        /* database name given */
609                         {
610                                 if (conn->dbName)
611                                         free(conn->dbName);
612                                 conn->dbName = strdup(tmp + 1);
613                                 *tmp = '\0';
614                         }
615                         else
616                         {
617                                 /*
618                                  * Why do we default only this value from the environment
619                                  * again?
620                                  */
621                                 if ((tmp = getenv("PGDATABASE")) != NULL)
622                                 {
623                                         if (conn->dbName)
624                                                 free(conn->dbName);
625                                         conn->dbName = strdup(tmp);
626                                 }
627                                 else if (conn->pguser)
628                                 {
629                                         if (conn->dbName)
630                                                 free(conn->dbName);
631                                         conn->dbName = strdup(conn->pguser);
632                                 }
633                         }
634
635                         tmp = strrchr(old + offset, ':');
636                         if (tmp != NULL)        /* port number or Unix socket path given */
637                         {
638                                 *tmp = '\0';
639                                 if ((tmp2 = strchr(tmp + 1, ':')) != NULL)
640                                 {
641                                         if (strncmp(old, "unix:", 5) != 0)
642                                         {
643                                                 printfPQExpBuffer(&conn->errorMessage,
644                                                                                   "connectDBStart() -- "
645                                                                 "socket name can only be specified with "
646                                                                                   "non-TCP\n");
647                                                 return 1;
648                                         }
649                                         *tmp2 = '\0';
650                                         if (conn->pgunixsocket)
651                                                 free(conn->pgunixsocket);
652                                         conn->pgunixsocket = strdup(tmp + 1);
653                                 }
654                                 else
655                                 {
656                                         if (conn->pgport)
657                                                 free(conn->pgport);
658                                         conn->pgport = strdup(tmp + 1);
659                                         if (conn->pgunixsocket)
660                                                 free(conn->pgunixsocket);
661                                         conn->pgunixsocket = NULL;
662                                 }
663                         }
664
665                         if (strncmp(old, "unix:", 5) == 0)
666                         {
667                                 if (conn->pghost)
668                                         free(conn->pghost);
669                                 conn->pghost = NULL;
670                                 if (strcmp(old + offset, "localhost") != 0)
671                                 {
672                                         printfPQExpBuffer(&conn->errorMessage,
673                                                                           "connectDBStart() -- "
674                                                                           "non-TCP access only possible on "
675                                                                           "localhost\n");
676                                         return 1;
677                                 }
678                         }
679                         else
680                         {
681                                 if (conn->pghost)
682                                         free(conn->pghost);
683                                 conn->pghost = strdup(old + offset);
684                         }
685                         free(old);
686                 }
687         }
688
689         return 0;
690 }
691 #endif   /* NOT_USED */
692
693
694 /* ----------
695  * connectMakeNonblocking -
696  * Make a connection non-blocking.
697  * Returns 1 if successful, 0 if not.
698  * ----------
699  */
700 static int
701 connectMakeNonblocking(PGconn *conn)
702 {
703 #if defined(WIN32) || defined(__BEOS__)
704         int                     on = 1;
705 #endif
706
707 #if defined(WIN32)
708         if (ioctlsocket(conn->sock, FIONBIO, &on) != 0)
709 #elif defined(__BEOS__)
710                 if (ioctl(conn->sock, FIONBIO, &on) != 0)
711 #else
712         if (fcntl(conn->sock, F_SETFL, O_NONBLOCK) < 0)
713 #endif
714         {
715                 printfPQExpBuffer(&conn->errorMessage,
716                 libpq_gettext("could not set socket to non-blocking mode: %s\n"),
717                                                   SOCK_STRERROR(SOCK_ERRNO));
718                 return 0;
719         }
720
721         return 1;
722 }
723
724 /* ----------
725  * connectNoDelay -
726  * Sets the TCP_NODELAY socket option.
727  * Returns 1 if successful, 0 if not.
728  * ----------
729  */
730 static int
731 connectNoDelay(PGconn *conn)
732 {
733         int                     on = 1;
734
735         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
736                                    (char *) &on,
737                                    sizeof(on)) < 0)
738         {
739                 printfPQExpBuffer(&conn->errorMessage,
740                 libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
741                                                   SOCK_STRERROR(SOCK_ERRNO));
742                 return 0;
743         }
744
745         return 1;
746 }
747
748
749 /* ----------
750  * connectFailureMessage -
751  * create a friendly error message on connection failure.
752  * ----------
753  */
754 static void
755 connectFailureMessage(PGconn *conn, int errorno)
756 {
757         if (conn->raddr.sa.sa_family == AF_UNIX)
758                 printfPQExpBuffer(&conn->errorMessage,
759                                                   libpq_gettext(
760                                                                           "could not connect to server: %s\n"
761                                                 "\tIs the server running locally and accepting\n"
762                                                   "\tconnections on Unix domain socket \"%s\"?\n"
763                                                                                 ),
764                                                   SOCK_STRERROR(errorno),
765                                                   conn->raddr.un.sun_path);
766         else
767                 printfPQExpBuffer(&conn->errorMessage,
768                                                   libpq_gettext(
769                                                                           "could not connect to server: %s\n"
770                                          "\tIs the server running on host %s and accepting\n"
771                                                                          "\tTCP/IP connections on port %s?\n"
772                                                                                 ),
773                                                   SOCK_STRERROR(errorno),
774                                                   conn->pghost
775                                                   ? conn->pghost
776                                                   : (conn->pghostaddr
777                                                          ? conn->pghostaddr
778                                                          : "???"),
779                                                   conn->pgport);
780 }
781
782
783 /* ----------
784  * connectDBStart -
785  * Start to make a connection to the backend so it is ready to receive
786  * queries.
787  * Returns 1 if successful, 0 if not.
788  * ----------
789  */
790 static int
791 connectDBStart(PGconn *conn)
792 {
793         int                     portnum;
794         char            portstr[64];
795 #ifdef USE_SSL
796         StartupPacket np;                       /* Used to negotiate SSL connection */
797         char            SSLok;
798 #endif
799         struct addrinfo *addrs = NULL;
800         struct addrinfo *addr_cur = NULL;
801         struct addrinfo hint;
802         const char *node = NULL;
803         const char *unix_node = "unix";
804         int                     ret;
805
806         /* Initialize hint structure */
807         MemSet(&hint, 0, sizeof(hint));
808         hint.ai_socktype = SOCK_STREAM;
809
810         if (!conn)
811                 return 0;
812
813 #ifdef NOT_USED
814         /*
815          * parse dbName to get all additional info in it, if any
816          */
817         if (update_db_info(conn) != 0)
818                 goto connect_errReturn;
819 #endif
820
821         /* Ensure our buffers are empty */
822         conn->inStart = conn->inCursor = conn->inEnd = 0;
823         conn->outCount = 0;
824
825         /*
826          * Set up the connection to postmaster/backend.
827          */
828
829         MemSet((char *) &conn->raddr, 0, sizeof(conn->raddr));
830
831         /* Set port number */
832         if (conn->pgport != NULL && conn->pgport[0] != '\0')
833                 portnum = atoi(conn->pgport);
834         else
835                 portnum = DEF_PGPORT;
836         snprintf(portstr, sizeof(portstr), "%d", portnum);
837
838         if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
839         {
840                 /* Using pghostaddr avoids a hostname lookup */
841                 node = conn->pghostaddr;
842                 hint.ai_family = AF_UNSPEC;
843                 hint.ai_flags = AI_NUMERICHOST;
844         }
845         else if (conn->pghost != NULL && conn->pghost[0] != '\0')
846         {
847                 /* Using pghost, so we have to look-up the hostname */
848                 node = conn->pghost;
849                 hint.ai_family = AF_UNSPEC;
850         }
851         else
852         {
853                 /* pghostaddr and pghost are NULL, so use Unix domain socket */
854 #ifdef HAVE_UNIX_SOCKETS
855                 node = unix_node;
856                 hint.ai_family = AF_UNIX;
857                 UNIXSOCK_PATH(conn->raddr.un, portnum, conn->pgunixsocket);
858                 conn->raddr_len = UNIXSOCK_LEN(conn->raddr.un);
859                 StrNCpy(portstr, conn->raddr.un.sun_path, sizeof(portstr));
860 #ifdef USE_SSL
861                 /* Don't bother requesting SSL over a Unix socket */
862                 conn->allow_ssl_try = false;
863                 conn->require_ssl = false;
864 #endif
865 #endif   /* HAVE_UNIX_SOCKETS */
866         }
867
868         /* Use getaddrinfo2() to resolve the address */
869         ret = getaddrinfo2(node, portstr, &hint, &addrs);
870         if (ret || addrs == NULL)
871         {
872                 printfPQExpBuffer(&conn->errorMessage,
873                                                   libpq_gettext("getaddrinfo() failed: %s\n"),
874                                                   gai_strerror(ret));
875                 goto connect_errReturn;
876         }
877
878         /*
879          * We loop over the possible addresses returned by getaddrinfo2(),
880          * and fail only when they all fail (reporting the error returned
881          * for the *last* alternative, which may not be what users expect
882          * :-().
883          *
884          * In either case, we never actually fall out of the loop; the
885          * only exits are via "break" or "goto connect_errReturn".  Thus,
886          * there is no exit test in the for().
887          */
888         for (addr_cur = addrs; ; addr_cur = addr_cur->ai_next)
889         {
890                 /* Open a socket */
891                 conn->sock = socket(addr_cur->ai_family, SOCK_STREAM,
892                                                         addr_cur->ai_protocol);
893                 if (conn->sock < 0)
894                 {
895                         /* ignore socket() failure if we have more addrs to try */
896                         if (addr_cur->ai_next != NULL)
897                                 continue;
898                         printfPQExpBuffer(&conn->errorMessage,
899                                                           libpq_gettext("could not create socket: %s\n"),
900                                                           SOCK_STRERROR(SOCK_ERRNO));
901                         goto connect_errReturn;
902                 }
903
904                 /*
905                  * Set the right options. Normally, we need nonblocking I/O, and we
906                  * don't want delay of outgoing data for AF_INET sockets.  If we are
907                  * using SSL, then we need the blocking I/O (XXX Can this be fixed?).
908                  */
909
910                 if (isAF_INETx(addr_cur->ai_family))
911                 {
912                         if (!connectNoDelay(conn))
913                                 goto connect_errReturn;
914                 }
915
916 #if !defined(USE_SSL)
917                 if (connectMakeNonblocking(conn) == 0)
918                         goto connect_errReturn;
919 #endif
920
921                 /* ----------
922                  * Start / make connection.  We are hopefully in non-blocking mode
923                  * now, but it is possible that:
924                  *       1. Older systems will still block on connect, despite the
925                  *              non-blocking flag. (Anyone know if this is true?)
926                  *       2. We are using SSL.
927                  * Thus, we have to make arrangements for all eventualities.
928                  * ----------
929                  */
930 retry1:
931                 if (connect(conn->sock, addr_cur->ai_addr, addr_cur->ai_addrlen) < 0)
932                 {
933                         if (SOCK_ERRNO == EINTR)
934                                 /* Interrupted system call - we'll just try again */
935                                 goto retry1;
936
937                         if (SOCK_ERRNO == EINPROGRESS || SOCK_ERRNO == EWOULDBLOCK || SOCK_ERRNO == 0)
938                         {
939                                 /*
940                                  * This is fine - we're in non-blocking mode, and the
941                                  * connection is in progress.
942                                  */
943                                 conn->status = CONNECTION_STARTED;
944                                 break;
945                         }
946                         /* otherwise, trouble */
947                 }
948                 else
949                 {
950                         /* We're connected already */
951                         conn->status = CONNECTION_MADE;
952                         break;
953                 }
954                 /*
955                  * This connection failed.  We need to close the socket,
956                  * and either loop to try the next address or report an error.
957                  */
958                 /* ignore connect() failure if we have more addrs to try */
959                 if (addr_cur->ai_next != NULL)
960                 {
961                         close(conn->sock);
962                         conn->sock = -1;
963                         continue;
964                 }
965                 /* copy failed address for error report */
966                 memcpy(&conn->raddr, addr_cur->ai_addr, addr_cur->ai_addrlen);
967                 conn->raddr_len = addr_cur->ai_addrlen;
968                 connectFailureMessage(conn, SOCK_ERRNO);
969                 goto connect_errReturn;
970         } /* loop over addrs */
971
972         /* Remember the successfully opened address alternative */
973         memcpy(&conn->raddr, addr_cur->ai_addr, addr_cur->ai_addrlen);
974         conn->raddr_len = addr_cur->ai_addrlen;
975         /* and release the address list */
976         freeaddrinfo2(hint.ai_family, addrs);
977         addrs = NULL;
978
979 #ifdef USE_SSL
980         /* Attempt to negotiate SSL usage */
981         if (conn->allow_ssl_try)
982         {
983                 memset((char *) &np, 0, sizeof(np));
984                 np.protoVersion = htonl(NEGOTIATE_SSL_CODE);
985                 if (pqPacketSend(conn, (char *) &np, sizeof(StartupPacket)) != STATUS_OK)
986                 {
987                         printfPQExpBuffer(&conn->errorMessage,
988                         libpq_gettext("could not send SSL negotiation packet: %s\n"),
989                                                           SOCK_STRERROR(SOCK_ERRNO));
990                         goto connect_errReturn;
991                 }
992 retry2:
993                 /* Now receive the postmasters response */
994                 if (recv(conn->sock, &SSLok, 1, 0) != 1)
995                 {
996                         if (SOCK_ERRNO == EINTR)
997                                 /* Interrupted system call - we'll just try again */
998                                 goto retry2;
999
1000                         printfPQExpBuffer(&conn->errorMessage,
1001                                                           libpq_gettext("could not receive server response to SSL negotiation packet: %s\n"),
1002                                                           SOCK_STRERROR(SOCK_ERRNO));
1003                         goto connect_errReturn;
1004                 }
1005                 if (SSLok == 'S')
1006                 {
1007                         if (pqsecure_initialize(conn) == -1 ||
1008                                 pqsecure_open_client(conn) == -1)
1009                                 goto connect_errReturn;
1010                         /* SSL connection finished. Continue to send startup packet */
1011                 }
1012                 else if (SSLok == 'E')
1013                 {
1014                         /* Received error - probably protocol mismatch */
1015                         if (conn->Pfdebug)
1016                                 fprintf(conn->Pfdebug, "Postmaster reports error, attempting fallback to pre-7.0.\n");
1017                         pqsecure_close(conn);
1018 #ifdef WIN32
1019                         closesocket(conn->sock);
1020 #else
1021                         close(conn->sock);
1022 #endif
1023                         conn->sock = -1;
1024                         conn->allow_ssl_try = FALSE;
1025                         return connectDBStart(conn);
1026                 }
1027                 else if (SSLok != 'N')
1028                 {
1029                         printfPQExpBuffer(&conn->errorMessage,
1030                                                           libpq_gettext("received invalid response to SSL negotiation: %c\n"),
1031                                                           SSLok);
1032                         goto connect_errReturn;
1033                 }
1034         }
1035         if (conn->require_ssl && !conn->ssl)
1036         {
1037                 /* Require SSL, but server does not support/want it */
1038                 printfPQExpBuffer(&conn->errorMessage,
1039                                                   libpq_gettext("server does not support SSL, but SSL was required\n"));
1040                 goto connect_errReturn;
1041         }
1042 #endif
1043
1044         /*
1045          * This makes the connection non-blocking, for all those cases which
1046          * forced us not to do it above.
1047          */
1048 #if defined(USE_SSL)
1049         if (connectMakeNonblocking(conn) == 0)
1050                 goto connect_errReturn;
1051 #endif
1052
1053         return 1;
1054
1055 connect_errReturn:
1056         if (conn->sock >= 0)
1057         {
1058                 pqsecure_close(conn);
1059 #ifdef WIN32
1060                 closesocket(conn->sock);
1061 #else
1062                 close(conn->sock);
1063 #endif
1064                 conn->sock = -1;
1065         }
1066         conn->status = CONNECTION_BAD;
1067         if (addrs != NULL)
1068                 freeaddrinfo2(hint.ai_family, addrs);
1069         return 0;
1070 }
1071
1072
1073 /*
1074  *              connectDBComplete
1075  *
1076  * Block and complete a connection.
1077  *
1078  * Returns 1 on success, 0 on failure.
1079  */
1080 static int
1081 connectDBComplete(PGconn *conn)
1082 {
1083         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1084         time_t          finish_time = ((time_t) -1);
1085
1086         if (conn == NULL || conn->status == CONNECTION_BAD)
1087                 return 0;
1088
1089         /*
1090          * Set up a time limit, if connect_timeout isn't zero.
1091          */
1092         if (conn->connect_timeout != NULL)
1093         {
1094                 int                     timeout = atoi(conn->connect_timeout);
1095
1096                 if (timeout > 0)
1097                 {
1098                         /*
1099                          * Rounding could cause connection to fail; need at least 2
1100                          * secs
1101                          */
1102                         if (timeout < 2)
1103                                 timeout = 2;
1104                         /* calculate the finish time based on start + timeout */
1105                         finish_time = time(NULL) + timeout;
1106                 }
1107         }
1108
1109         for (;;)
1110         {
1111                 /*
1112                  * Wait, if necessary.  Note that the initial state (just after
1113                  * PQconnectStart) is to wait for the socket to select for
1114                  * writing.
1115                  */
1116                 switch (flag)
1117                 {
1118                         case PGRES_POLLING_OK:
1119                                 return 1;               /* success! */
1120
1121                         case PGRES_POLLING_READING:
1122                                 if (pqWaitTimed(1, 0, conn, finish_time))
1123                                 {
1124                                         conn->status = CONNECTION_BAD;
1125                                         return 0;
1126                                 }
1127                                 break;
1128
1129                         case PGRES_POLLING_WRITING:
1130                                 if (pqWaitTimed(0, 1, conn, finish_time))
1131                                 {
1132                                         conn->status = CONNECTION_BAD;
1133                                         return 0;
1134                                 }
1135                                 break;
1136
1137                         default:
1138                                 /* Just in case we failed to set it in PQconnectPoll */
1139                                 conn->status = CONNECTION_BAD;
1140                                 return 0;
1141                 }
1142
1143                 /*
1144                  * Now try to advance the state machine.
1145                  */
1146                 flag = PQconnectPoll(conn);
1147         }
1148 }
1149
1150 /* ----------------
1151  *              PQconnectPoll
1152  *
1153  * Poll an asynchronous connection.
1154  *
1155  * Returns a PostgresPollingStatusType.
1156  * Before calling this function, use select(2) to determine when data
1157  * has arrived..
1158  *
1159  * You must call PQfinish whether or not this fails.
1160  *
1161  * This function and PQconnectStart are intended to allow connections to be
1162  * made without blocking the execution of your program on remote I/O. However,
1163  * there are a number of caveats:
1164  *
1165  *       o      If you call PQtrace, ensure that the stream object into which you trace
1166  *              will not block.
1167  *       o      If you do not supply an IP address for the remote host (i.e. you
1168  *              supply a host name instead) then this function will block on
1169  *              gethostbyname.  You will be fine if using Unix sockets (i.e. by
1170  *              supplying neither a host name nor a host address).
1171  *       o      If your backend wants to use Kerberos authentication then you must
1172  *              supply both a host name and a host address, otherwise this function
1173  *              may block on gethostname.
1174  *       o      This function will block if compiled with USE_SSL.
1175  *
1176  * ----------------
1177  */
1178 PostgresPollingStatusType
1179 PQconnectPoll(PGconn *conn)
1180 {
1181         PGresult   *res;
1182
1183         if (conn == NULL)
1184                 return PGRES_POLLING_FAILED;
1185
1186         /* Get the new data */
1187         switch (conn->status)
1188         {
1189                         /*
1190                          * We really shouldn't have been polled in these two cases,
1191                          * but we can handle it.
1192                          */
1193                 case CONNECTION_BAD:
1194                         return PGRES_POLLING_FAILED;
1195                 case CONNECTION_OK:
1196                         return PGRES_POLLING_OK;
1197
1198                         /* These are reading states */
1199                 case CONNECTION_AWAITING_RESPONSE:
1200                 case CONNECTION_AUTH_OK:
1201                         {
1202                                 /* Load waiting data */
1203                                 int                     n = pqReadData(conn);
1204
1205                                 if (n < 0)
1206                                         goto error_return;
1207                                 if (n == 0)
1208                                         return PGRES_POLLING_READING;
1209
1210                                 break;
1211                         }
1212
1213                         /* These are writing states, so we just proceed. */
1214                 case CONNECTION_STARTED:
1215                 case CONNECTION_MADE:
1216                         break;
1217
1218                 case CONNECTION_SETENV:
1219                         /* We allow PQsetenvPoll to decide whether to proceed */
1220                         break;
1221
1222                 default:
1223                         printfPQExpBuffer(&conn->errorMessage,
1224                                                           libpq_gettext(
1225                                                                                         "invalid connection state, "
1226                                                          "probably indicative of memory corruption\n"
1227                                                                                         ));
1228                         goto error_return;
1229         }
1230
1231
1232 keep_going:                                             /* We will come back to here until there
1233                                                                  * is nothing left to parse. */
1234         switch (conn->status)
1235         {
1236                 case CONNECTION_STARTED:
1237                         {
1238                                 ACCEPT_TYPE_ARG3 laddrlen;
1239                                 int                     optval;
1240                                 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1241
1242                                 /*
1243                                  * Write ready, since we've made it here, so the
1244                                  * connection has been made.
1245                                  */
1246
1247                                 /*
1248                                  * Now check (using getsockopt) that there is not an error
1249                                  * state waiting for us on the socket.
1250                                  */
1251
1252                                 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1253                                                            (char *) &optval, &optlen) == -1)
1254                                 {
1255                                         printfPQExpBuffer(&conn->errorMessage,
1256                                                                           libpq_gettext("could not get socket error status: %s\n"),
1257                                                                           SOCK_STRERROR(SOCK_ERRNO));
1258                                         goto error_return;
1259                                 }
1260                                 else if (optval != 0)
1261                                 {
1262                                         /*
1263                                          * When using a nonblocking connect, we will typically
1264                                          * see connect failures at this point, so provide a
1265                                          * friendly error message.
1266                                          */
1267                                         connectFailureMessage(conn, optval);
1268                                         goto error_return;
1269                                 }
1270
1271                                 /* Fill in the client address */
1272                                 laddrlen = sizeof(conn->laddr);
1273                                 if (getsockname(conn->sock, &conn->laddr.sa, &laddrlen) < 0)
1274                                 {
1275                                         printfPQExpBuffer(&conn->errorMessage,
1276                                                                           libpq_gettext("could not get client address from socket: %s\n"),
1277                                                                           SOCK_STRERROR(SOCK_ERRNO));
1278                                         goto error_return;
1279                                 }
1280
1281                                 conn->status = CONNECTION_MADE;
1282                                 return PGRES_POLLING_WRITING;
1283                         }
1284
1285                 case CONNECTION_MADE:
1286                         {
1287                                 StartupPacket sp;
1288
1289                                 /*
1290                                  * Initialize the startup packet.
1291                                  */
1292
1293                                 MemSet((char *) &sp, 0, sizeof(StartupPacket));
1294
1295                                 sp.protoVersion = (ProtocolVersion) htonl(PG_PROTOCOL_LIBPQ);
1296
1297                                 strncpy(sp.user, conn->pguser, SM_USER);
1298                                 strncpy(sp.database, conn->dbName, SM_DATABASE);
1299                                 strncpy(sp.tty, conn->pgtty, SM_TTY);
1300
1301                                 if (conn->pgoptions)
1302                                         strncpy(sp.options, conn->pgoptions, SM_OPTIONS);
1303
1304                                 /*
1305                                  * Send the startup packet.
1306                                  *
1307                                  * Theoretically, this could block, but it really shouldn't
1308                                  * since we only got here if the socket is write-ready.
1309                                  */
1310
1311                                 if (pqPacketSend(conn, (char *) &sp,
1312                                                                  sizeof(StartupPacket)) != STATUS_OK)
1313                                 {
1314                                         printfPQExpBuffer(&conn->errorMessage,
1315                                         libpq_gettext("could not send startup packet: %s\n"),
1316                                                                           SOCK_STRERROR(SOCK_ERRNO));
1317                                         goto error_return;
1318                                 }
1319
1320                                 conn->status = CONNECTION_AWAITING_RESPONSE;
1321                                 return PGRES_POLLING_READING;
1322                         }
1323
1324                         /*
1325                          * Handle the authentication exchange: wait for postmaster
1326                          * messages and respond as necessary.
1327                          */
1328                 case CONNECTION_AWAITING_RESPONSE:
1329                         {
1330                                 char            beresp;
1331                                 AuthRequest areq;
1332
1333                                 /*
1334                                  * Scan the message from current point (note that if we
1335                                  * find the message is incomplete, we will return without
1336                                  * advancing inStart, and resume here next time).
1337                                  */
1338                                 conn->inCursor = conn->inStart;
1339
1340                                 if (pqGetc(&beresp, conn))
1341                                 {
1342                                         /* We'll come back when there is more data */
1343                                         return PGRES_POLLING_READING;
1344                                 }
1345
1346                                 /* Handle errors. */
1347                                 if (beresp == 'E')
1348                                 {
1349                                         if (pqGets(&conn->errorMessage, conn))
1350                                         {
1351                                                 /* We'll come back when there is more data */
1352                                                 return PGRES_POLLING_READING;
1353                                         }
1354                                         /* OK, we read the message; mark data consumed */
1355                                         conn->inStart = conn->inCursor;
1356
1357                                         /*
1358                                          * The postmaster typically won't end its message with
1359                                          * a newline, so add one to conform to libpq
1360                                          * conventions.
1361                                          */
1362                                         appendPQExpBufferChar(&conn->errorMessage, '\n');
1363                                         goto error_return;
1364                                 }
1365
1366                                 /* Otherwise it should be an authentication request. */
1367                                 if (beresp != 'R')
1368                                 {
1369                                         printfPQExpBuffer(&conn->errorMessage,
1370                                                                           libpq_gettext(
1371                                                                   "expected authentication request from "
1372                                                                                           "server, but received %c\n"
1373                                                                                                         ),
1374                                                                           beresp);
1375                                         goto error_return;
1376                                 }
1377
1378                                 /* Get the type of request. */
1379                                 if (pqGetInt((int *) &areq, 4, conn))
1380                                 {
1381                                         /* We'll come back when there are more data */
1382                                         return PGRES_POLLING_READING;
1383                                 }
1384
1385                                 /* Get the password salt if there is one. */
1386                                 if (areq == AUTH_REQ_MD5)
1387                                 {
1388                                         if (pqGetnchar(conn->md5Salt,
1389                                                                    sizeof(conn->md5Salt), conn))
1390                                         {
1391                                                 /* We'll come back when there are more data */
1392                                                 return PGRES_POLLING_READING;
1393                                         }
1394                                 }
1395                                 if (areq == AUTH_REQ_CRYPT)
1396                                 {
1397                                         if (pqGetnchar(conn->cryptSalt,
1398                                                                    sizeof(conn->cryptSalt), conn))
1399                                         {
1400                                                 /* We'll come back when there are more data */
1401                                                 return PGRES_POLLING_READING;
1402                                         }
1403                                 }
1404
1405                                 /*
1406                                  * OK, we successfully read the message; mark data
1407                                  * consumed
1408                                  */
1409                                 conn->inStart = conn->inCursor;
1410
1411                                 /* Respond to the request if necessary. */
1412
1413                                 /*
1414                                  * Note that conn->pghost must be non-NULL if we are going
1415                                  * to avoid the Kerberos code doing a hostname look-up.
1416                                  */
1417
1418                                 /*
1419                                  * XXX fe-auth.c has not been fixed to support
1420                                  * PQExpBuffers, so:
1421                                  */
1422                                 if (fe_sendauth(areq, conn, conn->pghost, conn->pgpass,
1423                                                                 conn->errorMessage.data) != STATUS_OK)
1424                                 {
1425                                         conn->errorMessage.len = strlen(conn->errorMessage.data);
1426                                         goto error_return;
1427                                 }
1428                                 conn->errorMessage.len = strlen(conn->errorMessage.data);
1429
1430                                 /*
1431                                  * Just make sure that any data sent by fe_sendauth is
1432                                  * flushed out.  Although this theoretically could block,
1433                                  * it really shouldn't since we don't send large auth
1434                                  * responses.
1435                                  */
1436                                 if (pqFlush(conn))
1437                                         goto error_return;
1438
1439                                 if (areq == AUTH_REQ_OK)
1440                                 {
1441                                         /* We are done with authentication exchange */
1442                                         conn->status = CONNECTION_AUTH_OK;
1443
1444                                         /*
1445                                          * Set asyncStatus so that PQsetResult will think that
1446                                          * what comes back next is the result of a query.  See
1447                                          * below.
1448                                          */
1449                                         conn->asyncStatus = PGASYNC_BUSY;
1450                                 }
1451
1452                                 /* Look to see if we have more data yet. */
1453                                 goto keep_going;
1454                         }
1455
1456                 case CONNECTION_AUTH_OK:
1457                         {
1458                                 /*
1459                                  * Now we expect to hear from the backend. A ReadyForQuery
1460                                  * message indicates that startup is successful, but we
1461                                  * might also get an Error message indicating failure.
1462                                  * (Notice messages indicating nonfatal warnings are also
1463                                  * allowed by the protocol, as is a BackendKeyData
1464                                  * message.) Easiest way to handle this is to let
1465                                  * PQgetResult() read the messages. We just have to fake
1466                                  * it out about the state of the connection, by setting
1467                                  * asyncStatus = PGASYNC_BUSY (done above).
1468                                  */
1469
1470                                 if (PQisBusy(conn))
1471                                         return PGRES_POLLING_READING;
1472
1473                                 res = PQgetResult(conn);
1474
1475                                 /*
1476                                  * NULL return indicating we have gone to IDLE state is
1477                                  * expected
1478                                  */
1479                                 if (res)
1480                                 {
1481                                         if (res->resultStatus != PGRES_FATAL_ERROR)
1482                                                 printfPQExpBuffer(&conn->errorMessage,
1483                                                                                   libpq_gettext("unexpected message from server during startup\n"));
1484
1485                                         /*
1486                                          * if the resultStatus is FATAL, then
1487                                          * conn->errorMessage already has a copy of the error;
1488                                          * needn't copy it back. But add a newline if it's not
1489                                          * there already, since postmaster error messages may
1490                                          * not have one.
1491                                          */
1492                                         if (conn->errorMessage.len <= 0 ||
1493                                                 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
1494                                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
1495                                         PQclear(res);
1496                                         goto error_return;
1497                                 }
1498
1499                                 /*
1500                                  * Post-connection housekeeping. Prepare to send
1501                                  * environment variables to server.
1502                                  */
1503                                 if (!PQsetenvStart(conn))
1504                                         goto error_return;
1505
1506                                 conn->status = CONNECTION_SETENV;
1507
1508                                 goto keep_going;
1509                         }
1510
1511                 case CONNECTION_SETENV:
1512
1513                         /*
1514                          * We pretend that the connection is OK for the duration of
1515                          * these queries.
1516                          */
1517                         conn->status = CONNECTION_OK;
1518
1519                         switch (PQsetenvPoll(conn))
1520                         {
1521                                 case PGRES_POLLING_OK:  /* Success */
1522                                         conn->status = CONNECTION_OK;
1523                                         return PGRES_POLLING_OK;
1524
1525                                 case PGRES_POLLING_READING:             /* Still going */
1526                                         conn->status = CONNECTION_SETENV;
1527                                         return PGRES_POLLING_READING;
1528
1529                                 case PGRES_POLLING_WRITING:             /* Still going */
1530                                         conn->status = CONNECTION_SETENV;
1531                                         return PGRES_POLLING_WRITING;
1532
1533                                 default:
1534                                         conn->status = CONNECTION_SETENV;
1535                                         goto error_return;
1536                         }
1537                         /* Unreachable */
1538
1539                 default:
1540                         printfPQExpBuffer(&conn->errorMessage,
1541                                                           libpq_gettext(
1542                                                                                   "invalid connection state %c, "
1543                                                          "probably indicative of memory corruption\n"
1544                                                                                         ),
1545                                                           conn->status);
1546                         goto error_return;
1547         }
1548
1549         /* Unreachable */
1550
1551 error_return:
1552
1553         /*
1554          * We used to close the socket at this point, but that makes it
1555          * awkward for those above us if they wish to remove this socket from
1556          * their own records (an fd_set for example).  We'll just have this
1557          * socket closed when PQfinish is called (which is compulsory even
1558          * after an error, since the connection structure must be freed).
1559          */
1560         return PGRES_POLLING_FAILED;
1561 }
1562
1563
1564 /*
1565  *              PQsetenvStart
1566  *
1567  * Starts the process of passing the values of a standard set of environment
1568  * variables to the backend.
1569  */
1570 static bool
1571 PQsetenvStart(PGconn *conn)
1572 {
1573         if (conn == NULL ||
1574                 conn->status == CONNECTION_BAD ||
1575                 conn->setenv_state != SETENV_STATE_IDLE)
1576                 return false;
1577
1578         conn->setenv_state = SETENV_STATE_ENCODINGS_SEND;
1579         conn->next_eo = EnvironmentOptions;
1580
1581         return true;
1582 }
1583
1584 /*
1585  *              PQsetenvPoll
1586  *
1587  * Polls the process of passing the values of a standard set of environment
1588  * variables to the backend.
1589  */
1590 static PostgresPollingStatusType
1591 PQsetenvPoll(PGconn *conn)
1592 {
1593         PGresult   *res;
1594
1595         if (conn == NULL || conn->status == CONNECTION_BAD)
1596                 return PGRES_POLLING_FAILED;
1597
1598         /* Check whether there are any data for us */
1599         switch (conn->setenv_state)
1600         {
1601                         /* These are reading states */
1602                 case SETENV_STATE_ENCODINGS_WAIT:
1603                 case SETENV_STATE_OPTION_WAIT:
1604                         {
1605                                 /* Load waiting data */
1606                                 int                     n = pqReadData(conn);
1607
1608                                 if (n < 0)
1609                                         goto error_return;
1610                                 if (n == 0)
1611                                         return PGRES_POLLING_READING;
1612
1613                                 break;
1614                         }
1615
1616                         /* These are writing states, so we just proceed. */
1617                 case SETENV_STATE_ENCODINGS_SEND:
1618                 case SETENV_STATE_OPTION_SEND:
1619                         break;
1620
1621                         /* Should we raise an error if called when not active? */
1622                 case SETENV_STATE_IDLE:
1623                         return PGRES_POLLING_OK;
1624
1625                 default:
1626                         printfPQExpBuffer(&conn->errorMessage,
1627                                                           libpq_gettext(
1628                                                                                         "invalid setenv state %c, "
1629                                                          "probably indicative of memory corruption\n"
1630                                                                                         ),
1631                                                           conn->setenv_state);
1632                         goto error_return;
1633         }
1634
1635         /* We will loop here until there is nothing left to do in this call. */
1636         for (;;)
1637         {
1638                 switch (conn->setenv_state)
1639                 {
1640                         case SETENV_STATE_ENCODINGS_SEND:
1641                                 {
1642                                         const char *env = getenv("PGCLIENTENCODING");
1643
1644                                         if (!env || *env == '\0')
1645                                         {
1646                                                 /*
1647                                                  * PGCLIENTENCODING is not specified, so query
1648                                                  * server for it.  We must use begin/commit in
1649                                                  * case autocommit is off by default.
1650                                                  */
1651                                                 if (!PQsendQuery(conn, "begin; select pg_client_encoding(); commit"))
1652                                                         goto error_return;
1653
1654                                                 conn->setenv_state = SETENV_STATE_ENCODINGS_WAIT;
1655                                                 return PGRES_POLLING_READING;
1656                                         }
1657                                         else
1658                                         {
1659                                                 /* otherwise set client encoding in pg_conn struct */
1660                                                 int                     encoding = pg_char_to_encoding(env);
1661
1662                                                 if (encoding < 0)
1663                                                 {
1664                                                         printfPQExpBuffer(&conn->errorMessage,
1665                                                                                           libpq_gettext("invalid encoding name in PGCLIENTENCODING: %s\n"),
1666                                                                                           env);
1667                                                         goto error_return;
1668                                                 }
1669                                                 conn->client_encoding = encoding;
1670
1671                                                 /* Move on to setting the environment options */
1672                                                 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1673                                         }
1674                                         break;
1675                                 }
1676
1677                         case SETENV_STATE_ENCODINGS_WAIT:
1678                                 {
1679                                         if (PQisBusy(conn))
1680                                                 return PGRES_POLLING_READING;
1681
1682                                         res = PQgetResult(conn);
1683
1684                                         if (res)
1685                                         {
1686                                                 if (PQresultStatus(res) == PGRES_TUPLES_OK)
1687                                                 {
1688                                                         /* set client encoding in pg_conn struct */
1689                                                         char       *encoding;
1690
1691                                                         encoding = PQgetvalue(res, 0, 0);
1692                                                         if (!encoding)          /* this should not happen */
1693                                                                 conn->client_encoding = PG_SQL_ASCII;
1694                                                         else
1695                                                                 conn->client_encoding = pg_char_to_encoding(encoding);
1696                                                 }
1697                                                 else if (PQresultStatus(res) != PGRES_COMMAND_OK)
1698                                                 {
1699                                                         PQclear(res);
1700                                                         goto error_return;
1701                                                 }
1702                                                 PQclear(res);
1703                                                 /* Keep reading until PQgetResult returns NULL */
1704                                         }
1705                                         else
1706                                         {
1707                                                 /*
1708                                                  * NULL result indicates that the query is
1709                                                  * finished
1710                                                  */
1711                                                 /* Move on to setting the environment options */
1712                                                 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1713                                         }
1714                                         break;
1715                                 }
1716
1717                         case SETENV_STATE_OPTION_SEND:
1718                                 {
1719                                         /* Send an Environment Option */
1720                                         char            setQuery[100];  /* note length limits in
1721                                                                                                  * sprintf's below */
1722
1723                                         if (conn->next_eo->envName)
1724                                         {
1725                                                 const char *val;
1726
1727                                                 if ((val = getenv(conn->next_eo->envName)))
1728                                                 {
1729                                                         if (strcasecmp(val, "default") == 0)
1730                                                                 sprintf(setQuery, "SET %s = %.60s",
1731                                                                                 conn->next_eo->pgName, val);
1732                                                         else
1733                                                                 sprintf(setQuery, "SET %s = '%.60s'",
1734                                                                                 conn->next_eo->pgName, val);
1735 #ifdef CONNECTDEBUG
1736                                                         printf("Use environment variable %s to send %s\n",
1737                                                                    conn->next_eo->envName, setQuery);
1738 #endif
1739                                                         if (!PQsendQuery(conn, setQuery))
1740                                                                 goto error_return;
1741
1742                                                         conn->setenv_state = SETENV_STATE_OPTION_WAIT;
1743                                                 }
1744                                                 else
1745                                                         conn->next_eo++;
1746                                         }
1747                                         else
1748                                         {
1749                                                 /* No more options to send, so we are done. */
1750                                                 conn->setenv_state = SETENV_STATE_IDLE;
1751                                         }
1752                                         break;
1753                                 }
1754
1755                         case SETENV_STATE_OPTION_WAIT:
1756                                 {
1757                                         if (PQisBusy(conn))
1758                                                 return PGRES_POLLING_READING;
1759
1760                                         res = PQgetResult(conn);
1761
1762                                         if (res)
1763                                         {
1764                                                 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1765                                                 {
1766                                                         PQclear(res);
1767                                                         goto error_return;
1768                                                 }
1769                                                 PQclear(res);
1770                                                 /* Keep reading until PQgetResult returns NULL */
1771                                         }
1772                                         else
1773                                         {
1774                                                 /*
1775                                                  * NULL result indicates that the query is
1776                                                  * finished
1777                                                  */
1778                                                 /* Send the next option */
1779                                                 conn->next_eo++;
1780                                                 conn->setenv_state = SETENV_STATE_OPTION_SEND;
1781                                         }
1782                                         break;
1783                                 }
1784
1785                         case SETENV_STATE_IDLE:
1786                                 return PGRES_POLLING_OK;
1787
1788                         default:
1789                                 printfPQExpBuffer(&conn->errorMessage,
1790                                                                   libpq_gettext("invalid state %c, "
1791                                                    "probably indicative of memory corruption\n"),
1792                                                                   conn->setenv_state);
1793                                 goto error_return;
1794                 }
1795         }
1796
1797         /* Unreachable */
1798
1799 error_return:
1800         conn->setenv_state = SETENV_STATE_IDLE;
1801         return PGRES_POLLING_FAILED;
1802 }
1803
1804
1805 #ifdef NOT_USED
1806
1807 /*
1808  *              PQsetenv
1809  *
1810  * Passes the values of a standard set of environment variables to the
1811  * backend.
1812  *
1813  * Returns true on success, false on failure.
1814  *
1815  * This function used to be exported for no particularly good reason.
1816  * Since it's no longer used by libpq itself, let's try #ifdef'ing it out
1817  * and see if anyone complains.
1818  */
1819 static bool
1820 PQsetenv(PGconn *conn)
1821 {
1822         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1823
1824         if (!PQsetenvStart(conn))
1825                 return false;
1826
1827         for (;;)
1828         {
1829                 /*
1830                  * Wait, if necessary.  Note that the initial state (just after
1831                  * PQsetenvStart) is to wait for the socket to select for writing.
1832                  */
1833                 switch (flag)
1834                 {
1835                         case PGRES_POLLING_OK:
1836                                 return true;    /* success! */
1837
1838                         case PGRES_POLLING_READING:
1839                                 if (pqWait(1, 0, conn))
1840                                 {
1841                                         conn->status = CONNECTION_BAD;
1842                                         return false;
1843                                 }
1844                                 break;
1845
1846                         case PGRES_POLLING_WRITING:
1847                                 if (pqWait(0, 1, conn))
1848                                 {
1849                                         conn->status = CONNECTION_BAD;
1850                                         return false;
1851                                 }
1852                                 break;
1853
1854                         default:
1855                                 /* Just in case we failed to set it in PQsetenvPoll */
1856                                 conn->status = CONNECTION_BAD;
1857                                 return false;
1858                 }
1859
1860                 /*
1861                  * Now try to advance the state machine.
1862                  */
1863                 flag = PQsetenvPoll(conn);
1864         }
1865 }
1866 #endif   /* NOT_USED */
1867
1868
1869 /*
1870  * makeEmptyPGconn
1871  *       - create a PGconn data structure with (as yet) no interesting data
1872  */
1873 static PGconn *
1874 makeEmptyPGconn(void)
1875 {
1876         PGconn     *conn = (PGconn *) malloc(sizeof(PGconn));
1877
1878         if (conn == NULL)
1879                 return conn;
1880
1881         /* Zero all pointers and booleans */
1882         MemSet((char *) conn, 0, sizeof(PGconn));
1883
1884         conn->noticeHook = defaultNoticeProcessor;
1885         conn->status = CONNECTION_BAD;
1886         conn->asyncStatus = PGASYNC_IDLE;
1887         conn->setenv_state = SETENV_STATE_IDLE;
1888         conn->notifyList = DLNewList();
1889         conn->sock = -1;
1890 #ifdef USE_SSL
1891         conn->allow_ssl_try = TRUE;
1892 #endif
1893
1894         /*
1895          * The output buffer size is set to 8K, which is the usual size of
1896          * pipe buffers on Unix systems.  That way, when we are sending a
1897          * large amount of data, we avoid incurring extra kernel context swaps
1898          * for partial bufferloads.  Note that we currently don't ever enlarge
1899          * the output buffer.
1900          *
1901          * With the same goal of minimizing context swaps, the input buffer will
1902          * be enlarged anytime it has less than 8K free, so we initially
1903          * allocate twice that.
1904          */
1905         conn->inBufSize = 16 * 1024;
1906         conn->inBuffer = (char *) malloc(conn->inBufSize);
1907         conn->outBufSize = 8 * 1024;
1908         conn->outBuffer = (char *) malloc(conn->outBufSize);
1909         conn->nonblocking = FALSE;
1910         initPQExpBuffer(&conn->errorMessage);
1911         initPQExpBuffer(&conn->workBuffer);
1912         if (conn->inBuffer == NULL ||
1913                 conn->outBuffer == NULL ||
1914                 conn->errorMessage.data == NULL ||
1915                 conn->workBuffer.data == NULL)
1916         {
1917                 /* out of memory already :-( */
1918                 freePGconn(conn);
1919                 conn = NULL;
1920         }
1921         return conn;
1922 }
1923
1924 /*
1925  * freePGconn
1926  *       - free the PGconn data structure
1927  *
1928  */
1929 static void
1930 freePGconn(PGconn *conn)
1931 {
1932         if (!conn)
1933                 return;
1934         pqClearAsyncResult(conn);       /* deallocate result and curTuple */
1935         if (conn->sock >= 0)
1936         {
1937                 pqsecure_close(conn);
1938 #ifdef WIN32
1939                 closesocket(conn->sock);
1940 #else
1941                 close(conn->sock);
1942 #endif
1943         }
1944         if (conn->pghost)
1945                 free(conn->pghost);
1946         if (conn->pghostaddr)
1947                 free(conn->pghostaddr);
1948         if (conn->pgport)
1949                 free(conn->pgport);
1950         if (conn->pgunixsocket)
1951                 free(conn->pgunixsocket);
1952         if (conn->pgtty)
1953                 free(conn->pgtty);
1954         if (conn->pgoptions)
1955                 free(conn->pgoptions);
1956         if (conn->dbName)
1957                 free(conn->dbName);
1958         if (conn->pguser)
1959                 free(conn->pguser);
1960         if (conn->pgpass)
1961                 free(conn->pgpass);
1962         if (conn->connect_timeout)
1963                 free(conn->connect_timeout);
1964         /* Note that conn->Pfdebug is not ours to close or free */
1965         if (conn->notifyList)
1966                 DLFreeList(conn->notifyList);
1967         if (conn->lobjfuncs)
1968                 free(conn->lobjfuncs);
1969         if (conn->inBuffer)
1970                 free(conn->inBuffer);
1971         if (conn->outBuffer)
1972                 free(conn->outBuffer);
1973         termPQExpBuffer(&conn->errorMessage);
1974         termPQExpBuffer(&conn->workBuffer);
1975         free(conn);
1976 }
1977
1978 /*
1979    closePGconn
1980          - properly close a connection to the backend
1981 */
1982 static void
1983 closePGconn(PGconn *conn)
1984 {
1985         /*
1986          * Note that the protocol doesn't allow us to send Terminate messages
1987          * during the startup phase.
1988          */
1989         if (conn->sock >= 0 && conn->status == CONNECTION_OK)
1990         {
1991                 /*
1992                  * Try to send "close connection" message to backend. Ignore any
1993                  * error. Note: this routine used to go to substantial lengths to
1994                  * avoid getting SIGPIPE'd if the connection were already closed.
1995                  * Now we rely on pqFlush to avoid the signal.
1996                  */
1997                 pqPutc('X', conn);
1998                 pqFlush(conn);
1999         }
2000
2001         /*
2002          * must reset the blocking status so a possible reconnect will work
2003          * don't call PQsetnonblocking() because it will fail if it's unable
2004          * to flush the connection.
2005          */
2006         conn->nonblocking = FALSE;
2007
2008         /*
2009          * Close the connection, reset all transient state, flush I/O buffers.
2010          */
2011         if (conn->sock >= 0)
2012         {
2013                 pqsecure_close(conn);
2014 #ifdef WIN32
2015                 closesocket(conn->sock);
2016 #else
2017                 close(conn->sock);
2018 #endif
2019         }
2020         conn->sock = -1;
2021         conn->status = CONNECTION_BAD;          /* Well, not really _bad_ - just
2022                                                                                  * absent */
2023         conn->asyncStatus = PGASYNC_IDLE;
2024         pqClearAsyncResult(conn);       /* deallocate result and curTuple */
2025         if (conn->lobjfuncs)
2026                 free(conn->lobjfuncs);
2027         conn->lobjfuncs = NULL;
2028         conn->inStart = conn->inCursor = conn->inEnd = 0;
2029         conn->outCount = 0;
2030         conn->nonblocking = FALSE;
2031
2032 }
2033
2034 /*
2035    PQfinish:
2036           properly close a connection to the backend
2037           also frees the PGconn data structure so it shouldn't be re-used
2038           after this
2039 */
2040 void
2041 PQfinish(PGconn *conn)
2042 {
2043         if (conn)
2044         {
2045                 closePGconn(conn);
2046                 freePGconn(conn);
2047         }
2048 }
2049
2050 /* PQreset :
2051    resets the connection to the backend
2052    closes the existing connection and makes a new one
2053 */
2054 void
2055 PQreset(PGconn *conn)
2056 {
2057         if (conn)
2058         {
2059                 closePGconn(conn);
2060
2061                 if (connectDBStart(conn))
2062                         (void) connectDBComplete(conn);
2063         }
2064 }
2065
2066
2067 /* PQresetStart :
2068    resets the connection to the backend
2069    closes the existing connection and makes a new one
2070    Returns 1 on success, 0 on failure.
2071 */
2072 int
2073 PQresetStart(PGconn *conn)
2074 {
2075         if (conn)
2076         {
2077                 closePGconn(conn);
2078
2079                 return connectDBStart(conn);
2080         }
2081
2082         return 0;
2083 }
2084
2085
2086 /* PQresetPoll :
2087    resets the connection to the backend
2088    closes the existing connection and makes a new one
2089 */
2090
2091 PostgresPollingStatusType
2092 PQresetPoll(PGconn *conn)
2093 {
2094         if (conn)
2095                 return PQconnectPoll(conn);
2096
2097         return PGRES_POLLING_FAILED;
2098 }
2099
2100
2101 /*
2102  * PQrequestCancel: attempt to request cancellation of the current operation.
2103  *
2104  * The return value is TRUE if the cancel request was successfully
2105  * dispatched, FALSE if not (in which case conn->errorMessage is set).
2106  * Note: successful dispatch is no guarantee that there will be any effect at
2107  * the backend.  The application must read the operation result as usual.
2108  *
2109  * XXX it was a bad idea to have the error message returned in
2110  * conn->errorMessage, since it could overwrite a message already there.
2111  * Would be better to return it in a char array passed by the caller.
2112  *
2113  * CAUTION: we want this routine to be safely callable from a signal handler
2114  * (for example, an application might want to call it in a SIGINT handler).
2115  * This means we cannot use any C library routine that might be non-reentrant.
2116  * malloc/free are often non-reentrant, and anything that might call them is
2117  * just as dangerous.  We avoid sprintf here for that reason.  Building up
2118  * error messages with strcpy/strcat is tedious but should be quite safe.
2119  * We also save/restore errno in case the signal handler support doesn't.
2120  *
2121  * NOTE: this routine must not generate any error message longer than
2122  * INITIAL_EXPBUFFER_SIZE (currently 256), since we dare not try to
2123  * expand conn->errorMessage!
2124  */
2125
2126 int
2127 PQrequestCancel(PGconn *conn)
2128 {
2129         int                     save_errno = SOCK_ERRNO;
2130         int                     tmpsock = -1;
2131         struct
2132         {
2133                 uint32          packetlen;
2134                 CancelRequestPacket cp;
2135         }                       crp;
2136
2137         /* Check we have an open connection */
2138         if (!conn)
2139                 return FALSE;
2140
2141         if (conn->sock < 0)
2142         {
2143                 strcpy(conn->errorMessage.data,
2144                            "PQrequestCancel() -- connection is not open\n");
2145                 conn->errorMessage.len = strlen(conn->errorMessage.data);
2146 #ifdef WIN32
2147                 WSASetLastError(save_errno);
2148 #else
2149                 errno = save_errno;
2150 #endif
2151                 return FALSE;
2152         }
2153
2154         /*
2155          * We need to open a temporary connection to the postmaster. Use the
2156          * information saved by connectDB to do this with only kernel calls.
2157          */
2158         if ((tmpsock = socket(conn->raddr.sa.sa_family, SOCK_STREAM, 0)) < 0)
2159         {
2160                 strcpy(conn->errorMessage.data,
2161                            "PQrequestCancel() -- socket() failed: ");
2162                 goto cancel_errReturn;
2163         }
2164 retry3:
2165         if (connect(tmpsock, &conn->raddr.sa, conn->raddr_len) < 0)
2166         {
2167                 if (SOCK_ERRNO == EINTR)
2168                         /* Interrupted system call - we'll just try again */
2169                         goto retry3;
2170                 strcpy(conn->errorMessage.data,
2171                            "PQrequestCancel() -- connect() failed: ");
2172                 goto cancel_errReturn;
2173         }
2174
2175         /*
2176          * We needn't set nonblocking I/O or NODELAY options here.
2177          */
2178
2179         /* Create and send the cancel request packet. */
2180
2181         crp.packetlen = htonl((uint32) sizeof(crp));
2182         crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
2183         crp.cp.backendPID = htonl(conn->be_pid);
2184         crp.cp.cancelAuthCode = htonl(conn->be_key);
2185
2186 retry4:
2187         if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
2188         {
2189                 if (SOCK_ERRNO == EINTR)
2190                         /* Interrupted system call - we'll just try again */
2191                         goto retry4;
2192                 strcpy(conn->errorMessage.data,
2193                            "PQrequestCancel() -- send() failed: ");
2194                 goto cancel_errReturn;
2195         }
2196
2197         /* Sent it, done */
2198 #ifdef WIN32
2199         closesocket(tmpsock);
2200         WSASetLastError(save_errno);
2201 #else
2202         close(tmpsock);
2203         errno = save_errno;
2204 #endif
2205
2206         return TRUE;
2207
2208 cancel_errReturn:
2209         strcat(conn->errorMessage.data, SOCK_STRERROR(SOCK_ERRNO));
2210         strcat(conn->errorMessage.data, "\n");
2211         conn->errorMessage.len = strlen(conn->errorMessage.data);
2212         if (tmpsock >= 0)
2213         {
2214 #ifdef WIN32
2215                 closesocket(tmpsock);
2216                 WSASetLastError(save_errno);
2217 #else
2218                 close(tmpsock);
2219                 errno = save_errno;
2220 #endif
2221         }
2222         return FALSE;
2223 }
2224
2225
2226 /*
2227  * pqPacketSend() -- send a single-packet message.
2228  * this is like PacketSend(), defined in backend/libpq/pqpacket.c
2229  *
2230  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
2231  * SIDE_EFFECTS: may block.
2232 */
2233 int
2234 pqPacketSend(PGconn *conn, const char *buf, size_t len)
2235 {
2236         /* Send the total packet size. */
2237
2238         if (pqPutInt(4 + len, 4, conn))
2239                 return STATUS_ERROR;
2240
2241         /* Send the packet itself. */
2242
2243         if (pqPutnchar(buf, len, conn))
2244                 return STATUS_ERROR;
2245
2246         if (pqFlush(conn))
2247                 return STATUS_ERROR;
2248
2249         return STATUS_OK;
2250 }
2251
2252
2253
2254 #ifndef SYSCONFDIR
2255 #error "You must compile this file with SYSCONFDIR defined."
2256 #endif
2257
2258 #define MAXBUFSIZE 256
2259
2260 static int
2261 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
2262 {
2263         char       *service = conninfo_getval(options, "service");
2264         char       *serviceFile = SYSCONFDIR "/pg_service.conf";
2265         int                     group_found = 0;
2266         int                     linenr = 0,
2267                                 i;
2268
2269         if (service != NULL)
2270         {
2271                 FILE       *f;
2272                 char            buf[MAXBUFSIZE],
2273                                    *line;
2274
2275                 f = fopen(serviceFile, "r");
2276                 if (f == NULL)
2277                 {
2278                         printfPQExpBuffer(errorMessage, "ERROR: Service file '%s' not found\n",
2279                                                           serviceFile);
2280                         return 1;
2281                 }
2282
2283                 while ((line = fgets(buf, MAXBUFSIZE - 1, f)) != NULL)
2284                 {
2285                         linenr++;
2286
2287                         if (strlen(line) >= MAXBUFSIZE - 2)
2288                         {
2289                                 fclose(f);
2290                                 printfPQExpBuffer(errorMessage,
2291                                                 "ERROR: line %d too long in service file '%s'\n",
2292                                                                   linenr,
2293                                                                   serviceFile);
2294                                 return 2;
2295                         }
2296
2297                         /* ignore EOL at end of line */
2298                         if (strlen(line) && line[strlen(line) - 1] == '\n')
2299                                 line[strlen(line) - 1] = 0;
2300
2301                         /* ignore leading blanks */
2302                         while (*line && isspace((unsigned char) line[0]))
2303                                 line++;
2304
2305                         /* ignore comments and empty lines */
2306                         if (strlen(line) == 0 || line[0] == '#')
2307                                 continue;
2308
2309                         /* Check for right groupname */
2310                         if (line[0] == '[')
2311                         {
2312                                 if (group_found)
2313                                 {
2314                                         /* group info already read */
2315                                         fclose(f);
2316                                         return 0;
2317                                 }
2318
2319                                 if (strncmp(line + 1, service, strlen(service)) == 0 &&
2320                                         line[strlen(service) + 1] == ']')
2321                                         group_found = 1;
2322                                 else
2323                                         group_found = 0;
2324                         }
2325                         else
2326                         {
2327                                 if (group_found)
2328                                 {
2329                                         /*
2330                                          * Finally, we are in the right group and can parse
2331                                          * the line
2332                                          */
2333                                         char       *key,
2334                                                            *val;
2335                                         int                     found_keyword;
2336
2337                                         key = strtok(line, "=");
2338                                         if (key == NULL)
2339                                         {
2340                                                 printfPQExpBuffer(errorMessage,
2341                                                                                   "ERROR: syntax error in service file '%s', line %d\n",
2342                                                                                   serviceFile,
2343                                                                                   linenr);
2344                                                 fclose(f);
2345                                                 return 3;
2346                                         }
2347
2348                                         /*
2349                                          *      If not already set, set the database name to the
2350                                          *      name of the service
2351                                          */
2352                                         for (i = 0; options[i].keyword; i++)
2353                                                 if (strcmp(options[i].keyword, "dbname") == 0)
2354                                                         if (options[i].val == NULL)
2355                                                                 options[i].val = strdup(service);
2356
2357                                         val = line + strlen(line) + 1;
2358
2359                                         found_keyword = 0;
2360                                         for (i = 0; options[i].keyword; i++)
2361                                         {
2362                                                 if (strcmp(options[i].keyword, key) == 0)
2363                                                 {
2364                                                         if (options[i].val != NULL)
2365                                                                 free(options[i].val);
2366                                                         options[i].val = strdup(val);
2367                                                         found_keyword = 1;
2368                                                 }
2369                                         }
2370
2371                                         if (!found_keyword)
2372                                         {
2373                                                 printfPQExpBuffer(errorMessage,
2374                                                                                   "ERROR: syntax error in service file '%s', line %d\n",
2375                                                                                   serviceFile,
2376                                                                                   linenr);
2377                                                 fclose(f);
2378                                                 return 3;
2379                                         }
2380                                 }
2381                         }
2382                 }
2383
2384                 fclose(f);
2385         }
2386
2387         return 0;
2388 }
2389
2390
2391 /*
2392  * Conninfo parser routine
2393  *
2394  * If successful, a malloc'd PQconninfoOption array is returned.
2395  * If not successful, NULL is returned and an error message is
2396  * left in errorMessage.
2397  */
2398 static PQconninfoOption *
2399 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage)
2400 {
2401         char       *pname;
2402         char       *pval;
2403         char       *buf;
2404         char       *tmp;
2405         char       *cp;
2406         char       *cp2;
2407         PQconninfoOption *options;
2408         PQconninfoOption *option;
2409         char            errortmp[INITIAL_EXPBUFFER_SIZE];
2410
2411         /* Make a working copy of PQconninfoOptions */
2412         options = malloc(sizeof(PQconninfoOptions));
2413         if (options == NULL)
2414         {
2415                 printfPQExpBuffer(errorMessage,
2416                                                   libpq_gettext("out of memory\n"));
2417                 return NULL;
2418         }
2419         memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
2420
2421         /* Need a modifiable copy of the input string */
2422         if ((buf = strdup(conninfo)) == NULL)
2423         {
2424                 printfPQExpBuffer(errorMessage,
2425                                                   libpq_gettext("out of memory\n"));
2426                 PQconninfoFree(options);
2427                 return NULL;
2428         }
2429         cp = buf;
2430
2431         while (*cp)
2432         {
2433                 /* Skip blanks before the parameter name */
2434                 if (isspace((unsigned char) *cp))
2435                 {
2436                         cp++;
2437                         continue;
2438                 }
2439
2440                 /* Get the parameter name */
2441                 pname = cp;
2442                 while (*cp)
2443                 {
2444                         if (*cp == '=')
2445                                 break;
2446                         if (isspace((unsigned char) *cp))
2447                         {
2448                                 *cp++ = '\0';
2449                                 while (*cp)
2450                                 {
2451                                         if (!isspace((unsigned char) *cp))
2452                                                 break;
2453                                         cp++;
2454                                 }
2455                                 break;
2456                         }
2457                         cp++;
2458                 }
2459
2460                 /* Check that there is a following '=' */
2461                 if (*cp != '=')
2462                 {
2463                         printfPQExpBuffer(errorMessage,
2464                                                           libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
2465                                                           pname);
2466                         PQconninfoFree(options);
2467                         free(buf);
2468                         return NULL;
2469                 }
2470                 *cp++ = '\0';
2471
2472                 /* Skip blanks after the '=' */
2473                 while (*cp)
2474                 {
2475                         if (!isspace((unsigned char) *cp))
2476                                 break;
2477                         cp++;
2478                 }
2479
2480                 /* Get the parameter value */
2481                 pval = cp;
2482
2483                 if (*cp != '\'')
2484                 {
2485                         cp2 = pval;
2486                         while (*cp)
2487                         {
2488                                 if (isspace((unsigned char) *cp))
2489                                 {
2490                                         *cp++ = '\0';
2491                                         break;
2492                                 }
2493                                 if (*cp == '\\')
2494                                 {
2495                                         cp++;
2496                                         if (*cp != '\0')
2497                                                 *cp2++ = *cp++;
2498                                 }
2499                                 else
2500                                         *cp2++ = *cp++;
2501                         }
2502                         *cp2 = '\0';
2503                 }
2504                 else
2505                 {
2506                         cp2 = pval;
2507                         cp++;
2508                         for (;;)
2509                         {
2510                                 if (*cp == '\0')
2511                                 {
2512                                         printfPQExpBuffer(errorMessage,
2513                                                                           libpq_gettext("unterminated quoted string in connection info string\n"));
2514                                         PQconninfoFree(options);
2515                                         free(buf);
2516                                         return NULL;
2517                                 }
2518                                 if (*cp == '\\')
2519                                 {
2520                                         cp++;
2521                                         if (*cp != '\0')
2522                                                 *cp2++ = *cp++;
2523                                         continue;
2524                                 }
2525                                 if (*cp == '\'')
2526                                 {
2527                                         *cp2 = '\0';
2528                                         cp++;
2529                                         break;
2530                                 }
2531                                 *cp2++ = *cp++;
2532                         }
2533                 }
2534
2535                 /*
2536                  * Now we have the name and the value. Search for the param
2537                  * record.
2538                  */
2539                 for (option = options; option->keyword != NULL; option++)
2540                 {
2541                         if (strcmp(option->keyword, pname) == 0)
2542                                 break;
2543                 }
2544                 if (option->keyword == NULL)
2545                 {
2546                         printfPQExpBuffer(errorMessage,
2547                                          libpq_gettext("invalid connection option \"%s\"\n"),
2548                                                           pname);
2549                         PQconninfoFree(options);
2550                         free(buf);
2551                         return NULL;
2552                 }
2553
2554                 /*
2555                  * Store the value
2556                  */
2557                 if (option->val)
2558                         free(option->val);
2559                 option->val = strdup(pval);
2560
2561         }
2562
2563         /* Now check for service info */
2564         if (parseServiceInfo(options, errorMessage))
2565         {
2566                 PQconninfoFree(options);
2567                 free(buf);
2568                 return NULL;
2569         }
2570
2571         /* Done with the modifiable input string */
2572         free(buf);
2573
2574         /*
2575          * Get the fallback resources for parameters not specified in the
2576          * conninfo string.
2577          */
2578         for (option = options; option->keyword != NULL; option++)
2579         {
2580                 if (option->val != NULL)
2581                         continue;                       /* Value was in conninfo */
2582
2583                 /*
2584                  * Try to get the environment variable fallback
2585                  */
2586                 if (option->envvar != NULL)
2587                 {
2588                         if ((tmp = getenv(option->envvar)) != NULL)
2589                         {
2590                                 option->val = strdup(tmp);
2591                                 continue;
2592                         }
2593                 }
2594
2595                 /*
2596                  * No environment variable specified or this one isn't set - try
2597                  * compiled in
2598                  */
2599                 if (option->compiled != NULL)
2600                 {
2601                         option->val = strdup(option->compiled);
2602                         continue;
2603                 }
2604
2605                 /*
2606                  * Special handling for user
2607                  */
2608                 if (strcmp(option->keyword, "user") == 0)
2609                 {
2610                         option->val = fe_getauthname(errortmp);
2611                         /* note any error message is thrown away */
2612                         continue;
2613                 }
2614
2615                 /*
2616                  * Special handling for dbname
2617                  */
2618                 if (strcmp(option->keyword, "dbname") == 0)
2619                 {
2620                         tmp = conninfo_getval(options, "user");
2621                         if (tmp)
2622                                 option->val = strdup(tmp);
2623                         continue;
2624                 }
2625         }
2626
2627         return options;
2628 }
2629
2630
2631 static char *
2632 conninfo_getval(PQconninfoOption *connOptions,
2633                                 const char *keyword)
2634 {
2635         PQconninfoOption *option;
2636
2637         for (option = connOptions; option->keyword != NULL; option++)
2638         {
2639                 if (strcmp(option->keyword, keyword) == 0)
2640                         return option->val;
2641         }
2642
2643         return NULL;
2644 }
2645
2646
2647 void
2648 PQconninfoFree(PQconninfoOption *connOptions)
2649 {
2650         PQconninfoOption *option;
2651
2652         if (connOptions == NULL)
2653                 return;
2654
2655         for (option = connOptions; option->keyword != NULL; option++)
2656         {
2657                 if (option->val != NULL)
2658                         free(option->val);
2659         }
2660         free(connOptions);
2661 }
2662
2663
2664 /* =========== accessor functions for PGconn ========= */
2665 char *
2666 PQdb(const PGconn *conn)
2667 {
2668         if (!conn)
2669                 return (char *) NULL;
2670         return conn->dbName;
2671 }
2672
2673 char *
2674 PQuser(const PGconn *conn)
2675 {
2676         if (!conn)
2677                 return (char *) NULL;
2678         return conn->pguser;
2679 }
2680
2681 char *
2682 PQpass(const PGconn *conn)
2683 {
2684         if (!conn)
2685                 return (char *) NULL;
2686         return conn->pgpass;
2687 }
2688
2689 char *
2690 PQhost(const PGconn *conn)
2691 {
2692         if (!conn)
2693                 return (char *) NULL;
2694         return conn->pghost ? conn->pghost : conn->pgunixsocket;
2695 }
2696
2697 char *
2698 PQport(const PGconn *conn)
2699 {
2700         if (!conn)
2701                 return (char *) NULL;
2702         return conn->pgport;
2703 }
2704
2705 char *
2706 PQtty(const PGconn *conn)
2707 {
2708         if (!conn)
2709                 return (char *) NULL;
2710         return conn->pgtty;
2711 }
2712
2713 char *
2714 PQoptions(const PGconn *conn)
2715 {
2716         if (!conn)
2717                 return (char *) NULL;
2718         return conn->pgoptions;
2719 }
2720
2721 ConnStatusType
2722 PQstatus(const PGconn *conn)
2723 {
2724         if (!conn)
2725                 return CONNECTION_BAD;
2726         return conn->status;
2727 }
2728
2729 char *
2730 PQerrorMessage(const PGconn *conn)
2731 {
2732         if (!conn)
2733                 return libpq_gettext("connection pointer is NULL\n");
2734
2735         return conn->errorMessage.data;
2736 }
2737
2738 int
2739 PQsocket(const PGconn *conn)
2740 {
2741         if (!conn)
2742                 return -1;
2743         return conn->sock;
2744 }
2745
2746 int
2747 PQbackendPID(const PGconn *conn)
2748 {
2749         if (!conn || conn->status != CONNECTION_OK)
2750                 return 0;
2751         return conn->be_pid;
2752 }
2753
2754 int
2755 PQclientEncoding(const PGconn *conn)
2756 {
2757         if (!conn || conn->status != CONNECTION_OK)
2758                 return -1;
2759         return conn->client_encoding;
2760 }
2761
2762 int
2763 PQsetClientEncoding(PGconn *conn, const char *encoding)
2764 {
2765         char            qbuf[128];
2766         static char query[] = "set client_encoding to '%s'";
2767         PGresult   *res;
2768         int                     status;
2769
2770         if (!conn || conn->status != CONNECTION_OK)
2771                 return -1;
2772
2773         if (!encoding)
2774                 return -1;
2775
2776         /* check query buffer overflow */
2777         if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
2778                 return -1;
2779
2780         /* ok, now send a query */
2781         sprintf(qbuf, query, encoding);
2782         res = PQexec(conn, qbuf);
2783
2784         if (res == (PGresult *) NULL)
2785                 return -1;
2786         if (res->resultStatus != PGRES_COMMAND_OK)
2787                 status = -1;
2788         else
2789         {
2790                 /* change libpq internal encoding */
2791                 conn->client_encoding = pg_char_to_encoding(encoding);
2792                 status = 0;                             /* everything is ok */
2793         }
2794         PQclear(res);
2795         return (status);
2796 }
2797
2798 void
2799 PQtrace(PGconn *conn, FILE *debug_port)
2800 {
2801         if (conn == NULL ||
2802                 conn->status == CONNECTION_BAD)
2803                 return;
2804         PQuntrace(conn);
2805         conn->Pfdebug = debug_port;
2806 }
2807
2808 void
2809 PQuntrace(PGconn *conn)
2810 {
2811         /* note: better allow untrace even when connection bad */
2812         if (conn == NULL)
2813                 return;
2814         if (conn->Pfdebug)
2815         {
2816                 fflush(conn->Pfdebug);
2817                 conn->Pfdebug = NULL;
2818         }
2819 }
2820
2821 PQnoticeProcessor
2822 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
2823 {
2824         PQnoticeProcessor old;
2825
2826         if (conn == NULL)
2827                 return NULL;
2828
2829         old = conn->noticeHook;
2830         if (proc)
2831         {
2832                 conn->noticeHook = proc;
2833                 conn->noticeArg = arg;
2834         }
2835         return old;
2836 }
2837
2838 /*
2839  * The default notice/error message processor just prints the
2840  * message on stderr.  Applications can override this if they
2841  * want the messages to go elsewhere (a window, for example).
2842  * Note that simply discarding notices is probably a bad idea.
2843  */
2844
2845 static void
2846 defaultNoticeProcessor(void *arg, const char *message)
2847 {
2848         (void) arg;                                     /* not used */
2849         /* Note: we expect the supplied string to end with a newline already. */
2850         fprintf(stderr, "%s", message);
2851 }
2852
2853 /* returns a pointer to the next token or NULL if the current
2854  * token doesn't match */
2855 char *
2856 pwdfMatchesString(char *buf, char *token)
2857 {
2858         char       *tbuf,
2859                            *ttok;
2860         bool            bslash = false;
2861
2862         if (buf == NULL || token == NULL)
2863                 return NULL;
2864         tbuf = buf;
2865         ttok = token;
2866         if (*tbuf == '*')
2867                 return tbuf + 2;
2868         while (*tbuf != 0)
2869         {
2870                 if (*tbuf == '\\' && !bslash)
2871                 {
2872                         tbuf++;
2873                         bslash = true;
2874                 }
2875                 if (*tbuf == ':' && *ttok == 0 && !bslash)
2876                         return tbuf + 1;
2877                 bslash = false;
2878                 if (*ttok == 0)
2879                         return NULL;
2880                 if (*tbuf == *ttok)
2881                 {
2882                         tbuf++;
2883                         ttok++;
2884                 }
2885                 else
2886                         return NULL;
2887         }
2888         return NULL;
2889 }
2890
2891 /* Get a password from the password file. Return value is malloc'd. */
2892 char *
2893 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
2894 {
2895         FILE       *fp;
2896         char       *pgpassfile;
2897         char       *home;
2898         struct stat stat_buf;
2899
2900 #define LINELEN NAMEDATALEN*5
2901         char            buf[LINELEN];
2902
2903         if (dbname == NULL || strlen(dbname) == 0)
2904                 return NULL;
2905
2906         if (username == NULL || strlen(username) == 0)
2907                 return NULL;
2908
2909         if (hostname == NULL)
2910                 hostname = DefaultHost;
2911
2912         if (port == NULL)
2913                 port = DEF_PGPORT_STR;
2914
2915         /* Look for it in the home dir */
2916         home = getenv("HOME");
2917         if (!home)
2918                 return NULL;
2919
2920         pgpassfile = malloc(strlen(home) + 1 + strlen(PGPASSFILE) + 1);
2921         if (!pgpassfile)
2922         {
2923                 fprintf(stderr, libpq_gettext("out of memory\n"));
2924                 return NULL;
2925         }
2926
2927         sprintf(pgpassfile, "%s/%s", home, PGPASSFILE);
2928
2929         /* If password file cannot be opened, ignore it. */
2930         if (stat(pgpassfile, &stat_buf) == -1)
2931         {
2932                 free(pgpassfile);
2933                 return NULL;
2934         }
2935
2936 #ifndef WIN32
2937         /* If password file is insecure, alert the user and ignore it. */
2938         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
2939         {
2940                 fprintf(stderr,
2941                                 libpq_gettext("WARNING: Password file %s has world or group read access; permission should be u=rw (0600)\n"),
2942                                 pgpassfile);
2943                 free(pgpassfile);
2944                 return NULL;
2945         }
2946 #endif
2947
2948         fp = fopen(pgpassfile, "r");
2949         free(pgpassfile);
2950         if (fp == NULL)
2951                 return NULL;
2952
2953         while (!feof(fp))
2954         {
2955                 char       *t = buf,
2956                                    *ret;
2957                 int                     len;
2958
2959                 fgets(buf, LINELEN - 1, fp);
2960
2961                 len = strlen(buf);
2962                 if (len == 0)
2963                         continue;
2964
2965                 /* Remove trailing newline */
2966                 if (buf[len - 1] == '\n')
2967                         buf[len - 1] = 0;
2968
2969                 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
2970                         (t = pwdfMatchesString(t, port)) == NULL ||
2971                         (t = pwdfMatchesString(t, dbname)) == NULL ||
2972                         (t = pwdfMatchesString(t, username)) == NULL)
2973                         continue;
2974                 ret = strdup(t);
2975                 fclose(fp);
2976                 return ret;
2977         }
2978
2979         fclose(fp);
2980         return NULL;
2981
2982 #undef LINELEN
2983 }