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