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