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