OSDN Git Service

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