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