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