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