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