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