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