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