]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-connect.c
Fix initialization of fake LSN for unlogged relations
[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-2019, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/interfaces/libpq/fe-connect.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres_fe.h"
17
18 #include <sys/stat.h>
19 #include <fcntl.h>
20 #include <ctype.h>
21 #include <time.h>
22 #include <unistd.h>
23
24 #include "common/ip.h"
25 #include "common/link-canary.h"
26 #include "common/scram-common.h"
27 #include "common/string.h"
28 #include "fe-auth.h"
29 #include "libpq-fe.h"
30 #include "libpq-int.h"
31 #include "mb/pg_wchar.h"
32 #include "pg_config_paths.h"
33 #include "port/pg_bswap.h"
34
35 #ifdef WIN32
36 #include "win32.h"
37 #ifdef _WIN32_IE
38 #undef _WIN32_IE
39 #endif
40 #define _WIN32_IE 0x0500
41 #ifdef near
42 #undef near
43 #endif
44 #define near
45 #include <shlobj.h>
46 #ifdef _MSC_VER                                 /* mstcpip.h is missing on mingw */
47 #include <mstcpip.h>
48 #endif
49 #else
50 #include <sys/socket.h>
51 #include <netdb.h>
52 #include <netinet/in.h>
53 #ifdef HAVE_NETINET_TCP_H
54 #include <netinet/tcp.h>
55 #endif
56 #endif
57
58 #ifdef ENABLE_THREAD_SAFETY
59 #ifdef WIN32
60 #include "pthread-win32.h"
61 #else
62 #include <pthread.h>
63 #endif
64 #endif
65
66 #ifdef USE_LDAP
67 #ifdef WIN32
68 #include <winldap.h>
69 #else
70 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
71 #define LDAP_DEPRECATED 1
72 #include <ldap.h>
73 typedef struct timeval LDAP_TIMEVAL;
74 #endif
75 static int      ldapServiceLookup(const char *purl, PQconninfoOption *options,
76                                                           PQExpBuffer errorMessage);
77 #endif
78
79 #ifndef WIN32
80 #define PGPASSFILE ".pgpass"
81 #else
82 #define PGPASSFILE "pgpass.conf"
83 #endif
84
85 /*
86  * Pre-9.0 servers will return this SQLSTATE if asked to set
87  * application_name in a startup packet.  We hard-wire the value rather
88  * than looking into errcodes.h since it reflects historical behavior
89  * rather than that of the current code.
90  */
91 #define ERRCODE_APPNAME_UNKNOWN "42704"
92
93 /* This is part of the protocol so just define it */
94 #define ERRCODE_INVALID_PASSWORD "28P01"
95 /* This too */
96 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
97
98 /*
99  * Cope with the various platform-specific ways to spell TCP keepalive socket
100  * options.  This doesn't cover Windows, which as usual does its own thing.
101  */
102 #if defined(TCP_KEEPIDLE)
103 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
104 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
105 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
106 #elif defined(TCP_KEEPALIVE_THRESHOLD)
107 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
108 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
109 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
110 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
111 /* TCP_KEEPALIVE is the name of this option on macOS */
112 /* Caution: Solaris has this symbol but it means something different */
113 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
114 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
115 #endif
116
117 /*
118  * fall back options if they are not specified by arguments or defined
119  * by environment variables
120  */
121 #define DefaultHost             "localhost"
122 #define DefaultTty              ""
123 #define DefaultOption   ""
124 #define DefaultAuthtype           ""
125 #ifdef USE_SSL
126 #define DefaultChannelBinding   "prefer"
127 #else
128 #define DefaultChannelBinding   "disable"
129 #endif
130 #define DefaultTargetSessionAttrs       "any"
131 #ifdef USE_SSL
132 #define DefaultSSLMode "prefer"
133 #else
134 #define DefaultSSLMode  "disable"
135 #endif
136 #ifdef ENABLE_GSS
137 #include "fe-gssapi-common.h"
138 #define DefaultGSSMode "prefer"
139 #else
140 #define DefaultGSSMode "disable"
141 #endif
142
143 /* ----------
144  * Definition of the conninfo parameters and their fallback resources.
145  *
146  * If Environment-Var and Compiled-in are specified as NULL, no
147  * fallback is available. If after all no value can be determined
148  * for an option, an error is returned.
149  *
150  * The value for the username is treated specially in conninfo_add_defaults.
151  * If the value is not obtained any other way, the username is determined
152  * by pg_fe_getauthname().
153  *
154  * The Label and Disp-Char entries are provided for applications that
155  * want to use PQconndefaults() to create a generic database connection
156  * dialog. Disp-Char is defined as follows:
157  *              ""              Normal input field
158  *              "*"             Password field - hide value
159  *              "D"             Debug option - don't show by default
160  *
161  * PQconninfoOptions[] is a constant static array that we use to initialize
162  * a dynamically allocated working copy.  All the "val" fields in
163  * PQconninfoOptions[] *must* be NULL.  In a working copy, non-null "val"
164  * fields point to malloc'd strings that should be freed when the working
165  * array is freed (see PQconninfoFree).
166  *
167  * The first part of each struct is identical to the one in libpq-fe.h,
168  * which is required since we memcpy() data between the two!
169  * ----------
170  */
171 typedef struct _internalPQconninfoOption
172 {
173         char       *keyword;            /* The keyword of the option                    */
174         char       *envvar;                     /* Fallback environment variable name   */
175         char       *compiled;           /* Fallback compiled in default value   */
176         char       *val;                        /* Option's current value, or NULL              */
177         char       *label;                      /* Label for field in connect dialog    */
178         char       *dispchar;           /* Indicates how to display this field in a
179                                                                  * connect dialog. Values are: "" Display
180                                                                  * entered value as is "*" Password field -
181                                                                  * hide value "D"  Debug option - don't show
182                                                                  * by default */
183         int                     dispsize;               /* Field size in characters for dialog  */
184         /* ---
185          * Anything above this comment must be synchronized with
186          * PQconninfoOption in libpq-fe.h, since we memcpy() data
187          * between them!
188          * ---
189          */
190         off_t           connofs;                /* Offset into PGconn struct, -1 if not there */
191 } internalPQconninfoOption;
192
193 static const internalPQconninfoOption PQconninfoOptions[] = {
194         /*
195          * "authtype" is no longer used, so mark it "don't show".  We keep it in
196          * the array so as not to reject conninfo strings from old apps that might
197          * still try to set it.
198          */
199         {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
200         "Database-Authtype", "D", 20, -1},
201
202         {"service", "PGSERVICE", NULL, NULL,
203         "Database-Service", "", 20, -1},
204
205         {"user", "PGUSER", NULL, NULL,
206                 "Database-User", "", 20,
207         offsetof(struct pg_conn, pguser)},
208
209         {"password", "PGPASSWORD", NULL, NULL,
210                 "Database-Password", "*", 20,
211         offsetof(struct pg_conn, pgpass)},
212
213         {"passfile", "PGPASSFILE", NULL, NULL,
214                 "Database-Password-File", "", 64,
215         offsetof(struct pg_conn, pgpassfile)},
216
217         {"channel_binding", "PGCHANNELBINDING", NULL, NULL,
218                 "Channel-Binding", "", 7,       /* sizeof("require") */
219         offsetof(struct pg_conn, channel_binding)},
220
221         {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
222                 "Connect-timeout", "", 10,      /* strlen(INT32_MAX) == 10 */
223         offsetof(struct pg_conn, connect_timeout)},
224
225         {"dbname", "PGDATABASE", NULL, NULL,
226                 "Database-Name", "", 20,
227         offsetof(struct pg_conn, dbName)},
228
229         {"host", "PGHOST", NULL, NULL,
230                 "Database-Host", "", 40,
231         offsetof(struct pg_conn, pghost)},
232
233         {"hostaddr", "PGHOSTADDR", NULL, NULL,
234                 "Database-Host-IP-Address", "", 45,
235         offsetof(struct pg_conn, pghostaddr)},
236
237         {"port", "PGPORT", DEF_PGPORT_STR, NULL,
238                 "Database-Port", "", 6,
239         offsetof(struct pg_conn, pgport)},
240
241         {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
242                 "Client-Encoding", "", 10,
243         offsetof(struct pg_conn, client_encoding_initial)},
244
245         /*
246          * "tty" is no longer used either, but keep it present for backwards
247          * compatibility.
248          */
249         {"tty", "PGTTY", DefaultTty, NULL,
250                 "Backend-Debug-TTY", "D", 40,
251         offsetof(struct pg_conn, pgtty)},
252
253         {"options", "PGOPTIONS", DefaultOption, NULL,
254                 "Backend-Options", "", 40,
255         offsetof(struct pg_conn, pgoptions)},
256
257         {"application_name", "PGAPPNAME", NULL, NULL,
258                 "Application-Name", "", 64,
259         offsetof(struct pg_conn, appname)},
260
261         {"fallback_application_name", NULL, NULL, NULL,
262                 "Fallback-Application-Name", "", 64,
263         offsetof(struct pg_conn, fbappname)},
264
265         {"keepalives", NULL, NULL, NULL,
266                 "TCP-Keepalives", "", 1,        /* should be just '0' or '1' */
267         offsetof(struct pg_conn, keepalives)},
268
269         {"keepalives_idle", NULL, NULL, NULL,
270                 "TCP-Keepalives-Idle", "", 10,  /* strlen(INT32_MAX) == 10 */
271         offsetof(struct pg_conn, keepalives_idle)},
272
273         {"keepalives_interval", NULL, NULL, NULL,
274                 "TCP-Keepalives-Interval", "", 10,      /* strlen(INT32_MAX) == 10 */
275         offsetof(struct pg_conn, keepalives_interval)},
276
277         {"keepalives_count", NULL, NULL, NULL,
278                 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
279         offsetof(struct pg_conn, keepalives_count)},
280
281         {"tcp_user_timeout", NULL, NULL, NULL,
282                 "TCP-User-Timeout", "", 10, /* strlen(INT32_MAX) == 10 */
283         offsetof(struct pg_conn, pgtcp_user_timeout)},
284
285         /*
286          * ssl options are allowed even without client SSL support because the
287          * client can still handle SSL modes "disable" and "allow". Other
288          * parameters have no effect on non-SSL connections, so there is no reason
289          * to exclude them since none of them are mandatory.
290          */
291         {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
292                 "SSL-Mode", "", 12,             /* sizeof("verify-full") == 12 */
293         offsetof(struct pg_conn, sslmode)},
294
295         {"sslcompression", "PGSSLCOMPRESSION", "0", NULL,
296                 "SSL-Compression", "", 1,
297         offsetof(struct pg_conn, sslcompression)},
298
299         {"sslcert", "PGSSLCERT", NULL, NULL,
300                 "SSL-Client-Cert", "", 64,
301         offsetof(struct pg_conn, sslcert)},
302
303         {"sslkey", "PGSSLKEY", NULL, NULL,
304                 "SSL-Client-Key", "", 64,
305         offsetof(struct pg_conn, sslkey)},
306
307         {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
308                 "SSL-Root-Certificate", "", 64,
309         offsetof(struct pg_conn, sslrootcert)},
310
311         {"sslcrl", "PGSSLCRL", NULL, NULL,
312                 "SSL-Revocation-List", "", 64,
313         offsetof(struct pg_conn, sslcrl)},
314
315         {"requirepeer", "PGREQUIREPEER", NULL, NULL,
316                 "Require-Peer", "", 10,
317         offsetof(struct pg_conn, requirepeer)},
318
319         /*
320          * Expose gssencmode similarly to sslmode - we can still handle "disable"
321          * and "prefer".
322          */
323         {"gssencmode", "PGGSSENCMODE", DefaultGSSMode, NULL,
324                 "GSSENC-Mode", "", 7,   /* sizeof("disable") == 7 */
325         offsetof(struct pg_conn, gssencmode)},
326
327 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
328         /* Kerberos and GSSAPI authentication support specifying the service name */
329         {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
330                 "Kerberos-service-name", "", 20,
331         offsetof(struct pg_conn, krbsrvname)},
332 #endif
333
334 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
335
336         /*
337          * GSSAPI and SSPI both enabled, give a way to override which is used by
338          * default
339          */
340         {"gsslib", "PGGSSLIB", NULL, NULL,
341                 "GSS-library", "", 7,   /* sizeof("gssapi") = 7 */
342         offsetof(struct pg_conn, gsslib)},
343 #endif
344
345         {"replication", NULL, NULL, NULL,
346                 "Replication", "D", 5,
347         offsetof(struct pg_conn, replication)},
348
349         {"target_session_attrs", "PGTARGETSESSIONATTRS",
350                 DefaultTargetSessionAttrs, NULL,
351                 "Target-Session-Attrs", "", 11, /* sizeof("read-write") = 11 */
352         offsetof(struct pg_conn, target_session_attrs)},
353
354         /* Terminating entry --- MUST BE LAST */
355         {NULL, NULL, NULL, NULL,
356         NULL, NULL, 0}
357 };
358
359 static const PQEnvironmentOption EnvironmentOptions[] =
360 {
361         /* common user-interface settings */
362         {
363                 "PGDATESTYLE", "datestyle"
364         },
365         {
366                 "PGTZ", "timezone"
367         },
368         /* internal performance-related settings */
369         {
370                 "PGGEQO", "geqo"
371         },
372         {
373                 NULL, NULL
374         }
375 };
376
377 /* The connection URI must start with either of the following designators: */
378 static const char uri_designator[] = "postgresql://";
379 static const char short_uri_designator[] = "postgres://";
380
381 static bool connectOptions1(PGconn *conn, const char *conninfo);
382 static bool connectOptions2(PGconn *conn);
383 static int      connectDBStart(PGconn *conn);
384 static int      connectDBComplete(PGconn *conn);
385 static PGPing internal_ping(PGconn *conn);
386 static PGconn *makeEmptyPGconn(void);
387 static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
388 static void freePGconn(PGconn *conn);
389 static void closePGconn(PGconn *conn);
390 static void release_conn_addrinfo(PGconn *conn);
391 static void sendTerminateConn(PGconn *conn);
392 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
393 static PQconninfoOption *parse_connection_string(const char *conninfo,
394                                                                                                  PQExpBuffer errorMessage, bool use_defaults);
395 static int      uri_prefix_length(const char *connstr);
396 static bool recognized_connection_string(const char *connstr);
397 static PQconninfoOption *conninfo_parse(const char *conninfo,
398                                                                                 PQExpBuffer errorMessage, bool use_defaults);
399 static PQconninfoOption *conninfo_array_parse(const char *const *keywords,
400                                                                                           const char *const *values, PQExpBuffer errorMessage,
401                                                                                           bool use_defaults, int expand_dbname);
402 static bool conninfo_add_defaults(PQconninfoOption *options,
403                                                                   PQExpBuffer errorMessage);
404 static PQconninfoOption *conninfo_uri_parse(const char *uri,
405                                                                                         PQExpBuffer errorMessage, bool use_defaults);
406 static bool conninfo_uri_parse_options(PQconninfoOption *options,
407                                                                            const char *uri, PQExpBuffer errorMessage);
408 static bool conninfo_uri_parse_params(char *params,
409                                                                           PQconninfoOption *connOptions,
410                                                                           PQExpBuffer errorMessage);
411 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
412 static bool get_hexdigit(char digit, int *value);
413 static const char *conninfo_getval(PQconninfoOption *connOptions,
414                                                                    const char *keyword);
415 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
416                                                                                    const char *keyword, const char *value,
417                                                                                    PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
418 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
419                                                                            const char *keyword);
420 static void defaultNoticeReceiver(void *arg, const PGresult *res);
421 static void defaultNoticeProcessor(void *arg, const char *message);
422 static int      parseServiceInfo(PQconninfoOption *options,
423                                                          PQExpBuffer errorMessage);
424 static int      parseServiceFile(const char *serviceFile,
425                                                          const char *service,
426                                                          PQconninfoOption *options,
427                                                          PQExpBuffer errorMessage,
428                                                          bool *group_found);
429 static char *pwdfMatchesString(char *buf, const char *token);
430 static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
431                                                           const char *username, const char *pgpassfile);
432 static void pgpassfileWarning(PGconn *conn);
433 static void default_threadlock(int acquire);
434
435
436 /* global variable because fe-auth.c needs to access it */
437 pgthreadlock_t pg_g_threadlock = default_threadlock;
438
439
440 /*
441  *              pqDropConnection
442  *
443  * Close any physical connection to the server, and reset associated
444  * state inside the connection object.  We don't release state that
445  * would be needed to reconnect, though, nor local state that might still
446  * be useful later.
447  *
448  * We can always flush the output buffer, since there's no longer any hope
449  * of sending that data.  However, unprocessed input data might still be
450  * valuable, so the caller must tell us whether to flush that or not.
451  */
452 void
453 pqDropConnection(PGconn *conn, bool flushInput)
454 {
455         /* Drop any SSL state */
456         pqsecure_close(conn);
457
458         /* Close the socket itself */
459         if (conn->sock != PGINVALID_SOCKET)
460                 closesocket(conn->sock);
461         conn->sock = PGINVALID_SOCKET;
462
463         /* Optionally discard any unread data */
464         if (flushInput)
465                 conn->inStart = conn->inCursor = conn->inEnd = 0;
466
467         /* Always discard any unsent data */
468         conn->outCount = 0;
469
470         /* Free authentication state */
471 #ifdef ENABLE_GSS
472         {
473                 OM_uint32       min_s;
474
475                 if (conn->gctx)
476                         gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
477                 if (conn->gtarg_nam)
478                         gss_release_name(&min_s, &conn->gtarg_nam);
479         }
480 #endif
481 #ifdef ENABLE_SSPI
482         if (conn->sspitarget)
483         {
484                 free(conn->sspitarget);
485                 conn->sspitarget = NULL;
486         }
487         if (conn->sspicred)
488         {
489                 FreeCredentialsHandle(conn->sspicred);
490                 free(conn->sspicred);
491                 conn->sspicred = NULL;
492         }
493         if (conn->sspictx)
494         {
495                 DeleteSecurityContext(conn->sspictx);
496                 free(conn->sspictx);
497                 conn->sspictx = NULL;
498         }
499         conn->usesspi = 0;
500 #endif
501         if (conn->sasl_state)
502         {
503                 /*
504                  * XXX: if support for more authentication mechanisms is added, this
505                  * needs to call the right 'free' function.
506                  */
507                 pg_fe_scram_free(conn->sasl_state);
508                 conn->sasl_state = NULL;
509         }
510 }
511
512
513 /*
514  *              pqDropServerData
515  *
516  * Clear all connection state data that was received from (or deduced about)
517  * the server.  This is essential to do between connection attempts to
518  * different servers, else we may incorrectly hold over some data from the
519  * old server.
520  *
521  * It would be better to merge this into pqDropConnection, perhaps, but
522  * right now we cannot because that function is called immediately on
523  * detection of connection loss (cf. pqReadData, for instance).  This data
524  * should be kept until we are actually starting a new connection.
525  */
526 static void
527 pqDropServerData(PGconn *conn)
528 {
529         PGnotify   *notify;
530         pgParameterStatus *pstatus;
531
532         /* Forget pending notifies */
533         notify = conn->notifyHead;
534         while (notify != NULL)
535         {
536                 PGnotify   *prev = notify;
537
538                 notify = notify->next;
539                 free(prev);
540         }
541         conn->notifyHead = conn->notifyTail = NULL;
542
543         /* Reset ParameterStatus data, as well as variables deduced from it */
544         pstatus = conn->pstatus;
545         while (pstatus != NULL)
546         {
547                 pgParameterStatus *prev = pstatus;
548
549                 pstatus = pstatus->next;
550                 free(prev);
551         }
552         conn->pstatus = NULL;
553         conn->client_encoding = PG_SQL_ASCII;
554         conn->std_strings = false;
555         conn->sversion = 0;
556
557         /* Drop large-object lookup data */
558         if (conn->lobjfuncs)
559                 free(conn->lobjfuncs);
560         conn->lobjfuncs = NULL;
561
562         /* Reset assorted other per-connection state */
563         conn->last_sqlstate[0] = '\0';
564         conn->auth_req_received = false;
565         conn->password_needed = false;
566         conn->write_failed = false;
567         if (conn->write_err_msg)
568                 free(conn->write_err_msg);
569         conn->write_err_msg = NULL;
570         conn->be_pid = 0;
571         conn->be_key = 0;
572 }
573
574
575 /*
576  *              Connecting to a Database
577  *
578  * There are now six different ways a user of this API can connect to the
579  * database.  Two are not recommended for use in new code, because of their
580  * lack of extensibility with respect to the passing of options to the
581  * backend.  These are PQsetdb and PQsetdbLogin (the former now being a macro
582  * to the latter).
583  *
584  * If it is desired to connect in a synchronous (blocking) manner, use the
585  * function PQconnectdb or PQconnectdbParams. The former accepts a string of
586  * option = value pairs (or a URI) which must be parsed; the latter takes two
587  * NULL terminated arrays instead.
588  *
589  * To connect in an asynchronous (non-blocking) manner, use the functions
590  * PQconnectStart or PQconnectStartParams (which differ in the same way as
591  * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
592  *
593  * Internally, the static functions connectDBStart, connectDBComplete
594  * are part of the connection procedure.
595  */
596
597 /*
598  *              PQconnectdbParams
599  *
600  * establishes a connection to a postgres backend through the postmaster
601  * using connection information in two arrays.
602  *
603  * The keywords array is defined as
604  *
605  *         const char *params[] = {"option1", "option2", NULL}
606  *
607  * The values array is defined as
608  *
609  *         const char *values[] = {"value1", "value2", NULL}
610  *
611  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
612  * if a memory allocation failed.
613  * If the status field of the connection returned is CONNECTION_BAD,
614  * then some fields may be null'ed out instead of having valid values.
615  *
616  * You should call PQfinish (if conn is not NULL) regardless of whether this
617  * call succeeded.
618  */
619 PGconn *
620 PQconnectdbParams(const char *const *keywords,
621                                   const char *const *values,
622                                   int expand_dbname)
623 {
624         PGconn     *conn = PQconnectStartParams(keywords, values, expand_dbname);
625
626         if (conn && conn->status != CONNECTION_BAD)
627                 (void) connectDBComplete(conn);
628
629         return conn;
630
631 }
632
633 /*
634  *              PQpingParams
635  *
636  * check server status, accepting parameters identical to PQconnectdbParams
637  */
638 PGPing
639 PQpingParams(const char *const *keywords,
640                          const char *const *values,
641                          int expand_dbname)
642 {
643         PGconn     *conn = PQconnectStartParams(keywords, values, expand_dbname);
644         PGPing          ret;
645
646         ret = internal_ping(conn);
647         PQfinish(conn);
648
649         return ret;
650 }
651
652 /*
653  *              PQconnectdb
654  *
655  * establishes a connection to a postgres backend through the postmaster
656  * using connection information in a string.
657  *
658  * The conninfo string is either a whitespace-separated list of
659  *
660  *         option = value
661  *
662  * definitions or a URI (refer to the documentation for details.) Value
663  * might be a single value containing no whitespaces or a single quoted
664  * string. If a single quote should appear anywhere in the value, it must be
665  * escaped with a backslash like \'
666  *
667  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
668  * if a memory allocation failed.
669  * If the status field of the connection returned is CONNECTION_BAD,
670  * then some fields may be null'ed out instead of having valid values.
671  *
672  * You should call PQfinish (if conn is not NULL) regardless of whether this
673  * call succeeded.
674  */
675 PGconn *
676 PQconnectdb(const char *conninfo)
677 {
678         PGconn     *conn = PQconnectStart(conninfo);
679
680         if (conn && conn->status != CONNECTION_BAD)
681                 (void) connectDBComplete(conn);
682
683         return conn;
684 }
685
686 /*
687  *              PQping
688  *
689  * check server status, accepting parameters identical to PQconnectdb
690  */
691 PGPing
692 PQping(const char *conninfo)
693 {
694         PGconn     *conn = PQconnectStart(conninfo);
695         PGPing          ret;
696
697         ret = internal_ping(conn);
698         PQfinish(conn);
699
700         return ret;
701 }
702
703 /*
704  *              PQconnectStartParams
705  *
706  * Begins the establishment of a connection to a postgres backend through the
707  * postmaster using connection information in a struct.
708  *
709  * See comment for PQconnectdbParams for the definition of the string format.
710  *
711  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
712  * you should not attempt to proceed with this connection.  If the status
713  * field of the connection returned is CONNECTION_BAD, an error has
714  * occurred. In this case you should call PQfinish on the result, (perhaps
715  * inspecting the error message first).  Other fields of the structure may not
716  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
717  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
718  * this is necessary.
719  *
720  * See PQconnectPoll for more info.
721  */
722 PGconn *
723 PQconnectStartParams(const char *const *keywords,
724                                          const char *const *values,
725                                          int expand_dbname)
726 {
727         PGconn     *conn;
728         PQconninfoOption *connOptions;
729
730         /*
731          * Allocate memory for the conn structure
732          */
733         conn = makeEmptyPGconn();
734         if (conn == NULL)
735                 return NULL;
736
737         /*
738          * Parse the conninfo arrays
739          */
740         connOptions = conninfo_array_parse(keywords, values,
741                                                                            &conn->errorMessage,
742                                                                            true, expand_dbname);
743         if (connOptions == NULL)
744         {
745                 conn->status = CONNECTION_BAD;
746                 /* errorMessage is already set */
747                 return conn;
748         }
749
750         /*
751          * Move option values into conn structure
752          */
753         if (!fillPGconn(conn, connOptions))
754         {
755                 PQconninfoFree(connOptions);
756                 return conn;
757         }
758
759         /*
760          * Free the option info - all is in conn now
761          */
762         PQconninfoFree(connOptions);
763
764         /*
765          * Compute derived options
766          */
767         if (!connectOptions2(conn))
768                 return conn;
769
770         /*
771          * Connect to the database
772          */
773         if (!connectDBStart(conn))
774         {
775                 /* Just in case we failed to set it in connectDBStart */
776                 conn->status = CONNECTION_BAD;
777         }
778
779         return conn;
780 }
781
782 /*
783  *              PQconnectStart
784  *
785  * Begins the establishment of a connection to a postgres backend through the
786  * postmaster using connection information in a string.
787  *
788  * See comment for PQconnectdb for the definition of the string format.
789  *
790  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
791  * you should not attempt to proceed with this connection.  If the status
792  * field of the connection returned is CONNECTION_BAD, an error has
793  * occurred. In this case you should call PQfinish on the result, (perhaps
794  * inspecting the error message first).  Other fields of the structure may not
795  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
796  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
797  * this is necessary.
798  *
799  * See PQconnectPoll for more info.
800  */
801 PGconn *
802 PQconnectStart(const char *conninfo)
803 {
804         PGconn     *conn;
805
806         /*
807          * Allocate memory for the conn structure
808          */
809         conn = makeEmptyPGconn();
810         if (conn == NULL)
811                 return NULL;
812
813         /*
814          * Parse the conninfo string
815          */
816         if (!connectOptions1(conn, conninfo))
817                 return conn;
818
819         /*
820          * Compute derived options
821          */
822         if (!connectOptions2(conn))
823                 return conn;
824
825         /*
826          * Connect to the database
827          */
828         if (!connectDBStart(conn))
829         {
830                 /* Just in case we failed to set it in connectDBStart */
831                 conn->status = CONNECTION_BAD;
832         }
833
834         return conn;
835 }
836
837 /*
838  * Move option values into conn structure
839  *
840  * Don't put anything cute here --- intelligence should be in
841  * connectOptions2 ...
842  *
843  * Returns true on success. On failure, returns false and sets error message.
844  */
845 static bool
846 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
847 {
848         const internalPQconninfoOption *option;
849
850         for (option = PQconninfoOptions; option->keyword; option++)
851         {
852                 if (option->connofs >= 0)
853                 {
854                         const char *tmp = conninfo_getval(connOptions, option->keyword);
855
856                         if (tmp)
857                         {
858                                 char      **connmember = (char **) ((char *) conn + option->connofs);
859
860                                 if (*connmember)
861                                         free(*connmember);
862                                 *connmember = strdup(tmp);
863                                 if (*connmember == NULL)
864                                 {
865                                         printfPQExpBuffer(&conn->errorMessage,
866                                                                           libpq_gettext("out of memory\n"));
867                                         return false;
868                                 }
869                         }
870                 }
871         }
872
873         return true;
874 }
875
876 /*
877  *              connectOptions1
878  *
879  * Internal subroutine to set up connection parameters given an already-
880  * created PGconn and a conninfo string.  Derived settings should be
881  * processed by calling connectOptions2 next.  (We split them because
882  * PQsetdbLogin overrides defaults in between.)
883  *
884  * Returns true if OK, false if trouble (in which case errorMessage is set
885  * and so is conn->status).
886  */
887 static bool
888 connectOptions1(PGconn *conn, const char *conninfo)
889 {
890         PQconninfoOption *connOptions;
891
892         /*
893          * Parse the conninfo string
894          */
895         connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
896         if (connOptions == NULL)
897         {
898                 conn->status = CONNECTION_BAD;
899                 /* errorMessage is already set */
900                 return false;
901         }
902
903         /*
904          * Move option values into conn structure
905          */
906         if (!fillPGconn(conn, connOptions))
907         {
908                 conn->status = CONNECTION_BAD;
909                 PQconninfoFree(connOptions);
910                 return false;
911         }
912
913         /*
914          * Free the option info - all is in conn now
915          */
916         PQconninfoFree(connOptions);
917
918         return true;
919 }
920
921 /*
922  * Count the number of elements in a simple comma-separated list.
923  */
924 static int
925 count_comma_separated_elems(const char *input)
926 {
927         int                     n;
928
929         n = 1;
930         for (; *input != '\0'; input++)
931         {
932                 if (*input == ',')
933                         n++;
934         }
935
936         return n;
937 }
938
939 /*
940  * Parse a simple comma-separated list.
941  *
942  * On each call, returns a malloc'd copy of the next element, and sets *more
943  * to indicate whether there are any more elements in the list after this,
944  * and updates *startptr to point to the next element, if any.
945  *
946  * On out of memory, returns NULL.
947  */
948 static char *
949 parse_comma_separated_list(char **startptr, bool *more)
950 {
951         char       *p;
952         char       *s = *startptr;
953         char       *e;
954         int                     len;
955
956         /*
957          * Search for the end of the current element; a comma or end-of-string
958          * acts as a terminator.
959          */
960         e = s;
961         while (*e != '\0' && *e != ',')
962                 ++e;
963         *more = (*e == ',');
964
965         len = e - s;
966         p = (char *) malloc(sizeof(char) * (len + 1));
967         if (p)
968         {
969                 memcpy(p, s, len);
970                 p[len] = '\0';
971         }
972         *startptr = e + 1;
973
974         return p;
975 }
976
977 /*
978  *              connectOptions2
979  *
980  * Compute derived connection options after absorbing all user-supplied info.
981  *
982  * Returns true if OK, false if trouble (in which case errorMessage is set
983  * and so is conn->status).
984  */
985 static bool
986 connectOptions2(PGconn *conn)
987 {
988         int                     i;
989
990         /*
991          * Allocate memory for details about each host to which we might possibly
992          * try to connect.  For that, count the number of elements in the hostaddr
993          * or host options.  If neither is given, assume one host.
994          */
995         conn->whichhost = 0;
996         if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
997                 conn->nconnhost = count_comma_separated_elems(conn->pghostaddr);
998         else if (conn->pghost && conn->pghost[0] != '\0')
999                 conn->nconnhost = count_comma_separated_elems(conn->pghost);
1000         else
1001                 conn->nconnhost = 1;
1002         conn->connhost = (pg_conn_host *)
1003                 calloc(conn->nconnhost, sizeof(pg_conn_host));
1004         if (conn->connhost == NULL)
1005                 goto oom_error;
1006
1007         /*
1008          * We now have one pg_conn_host structure per possible host.  Fill in the
1009          * host and hostaddr fields for each, by splitting the parameter strings.
1010          */
1011         if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1012         {
1013                 char       *s = conn->pghostaddr;
1014                 bool            more = true;
1015
1016                 for (i = 0; i < conn->nconnhost && more; i++)
1017                 {
1018                         conn->connhost[i].hostaddr = parse_comma_separated_list(&s, &more);
1019                         if (conn->connhost[i].hostaddr == NULL)
1020                                 goto oom_error;
1021                 }
1022
1023                 /*
1024                  * If hostaddr was given, the array was allocated according to the
1025                  * number of elements in the hostaddr list, so it really should be the
1026                  * right size.
1027                  */
1028                 Assert(!more);
1029                 Assert(i == conn->nconnhost);
1030         }
1031
1032         if (conn->pghost != NULL && conn->pghost[0] != '\0')
1033         {
1034                 char       *s = conn->pghost;
1035                 bool            more = true;
1036
1037                 for (i = 0; i < conn->nconnhost && more; i++)
1038                 {
1039                         conn->connhost[i].host = parse_comma_separated_list(&s, &more);
1040                         if (conn->connhost[i].host == NULL)
1041                                 goto oom_error;
1042                 }
1043
1044                 /* Check for wrong number of host items. */
1045                 if (more || i != conn->nconnhost)
1046                 {
1047                         conn->status = CONNECTION_BAD;
1048                         printfPQExpBuffer(&conn->errorMessage,
1049                                                           libpq_gettext("could not match %d host names to %d hostaddr values\n"),
1050                                                           count_comma_separated_elems(conn->pghost), conn->nconnhost);
1051                         return false;
1052                 }
1053         }
1054
1055         /*
1056          * Now, for each host slot, identify the type of address spec, and fill in
1057          * the default address if nothing was given.
1058          */
1059         for (i = 0; i < conn->nconnhost; i++)
1060         {
1061                 pg_conn_host *ch = &conn->connhost[i];
1062
1063                 if (ch->hostaddr != NULL && ch->hostaddr[0] != '\0')
1064                         ch->type = CHT_HOST_ADDRESS;
1065                 else if (ch->host != NULL && ch->host[0] != '\0')
1066                 {
1067                         ch->type = CHT_HOST_NAME;
1068 #ifdef HAVE_UNIX_SOCKETS
1069                         if (is_absolute_path(ch->host))
1070                                 ch->type = CHT_UNIX_SOCKET;
1071 #endif
1072                 }
1073                 else
1074                 {
1075                         if (ch->host)
1076                                 free(ch->host);
1077 #ifdef HAVE_UNIX_SOCKETS
1078                         ch->host = strdup(DEFAULT_PGSOCKET_DIR);
1079                         ch->type = CHT_UNIX_SOCKET;
1080 #else
1081                         ch->host = strdup(DefaultHost);
1082                         ch->type = CHT_HOST_NAME;
1083 #endif
1084                         if (ch->host == NULL)
1085                                 goto oom_error;
1086                 }
1087         }
1088
1089         /*
1090          * Next, work out the port number corresponding to each host name.
1091          *
1092          * Note: unlike the above for host names, this could leave the port fields
1093          * as null or empty strings.  We will substitute DEF_PGPORT whenever we
1094          * read such a port field.
1095          */
1096         if (conn->pgport != NULL && conn->pgport[0] != '\0')
1097         {
1098                 char       *s = conn->pgport;
1099                 bool            more = true;
1100
1101                 for (i = 0; i < conn->nconnhost && more; i++)
1102                 {
1103                         conn->connhost[i].port = parse_comma_separated_list(&s, &more);
1104                         if (conn->connhost[i].port == NULL)
1105                                 goto oom_error;
1106                 }
1107
1108                 /*
1109                  * If exactly one port was given, use it for every host.  Otherwise,
1110                  * there must be exactly as many ports as there were hosts.
1111                  */
1112                 if (i == 1 && !more)
1113                 {
1114                         for (i = 1; i < conn->nconnhost; i++)
1115                         {
1116                                 conn->connhost[i].port = strdup(conn->connhost[0].port);
1117                                 if (conn->connhost[i].port == NULL)
1118                                         goto oom_error;
1119                         }
1120                 }
1121                 else if (more || i != conn->nconnhost)
1122                 {
1123                         conn->status = CONNECTION_BAD;
1124                         printfPQExpBuffer(&conn->errorMessage,
1125                                                           libpq_gettext("could not match %d port numbers to %d hosts\n"),
1126                                                           count_comma_separated_elems(conn->pgport), conn->nconnhost);
1127                         return false;
1128                 }
1129         }
1130
1131         /*
1132          * If user name was not given, fetch it.  (Most likely, the fetch will
1133          * fail, since the only way we get here is if pg_fe_getauthname() failed
1134          * during conninfo_add_defaults().  But now we want an error message.)
1135          */
1136         if (conn->pguser == NULL || conn->pguser[0] == '\0')
1137         {
1138                 if (conn->pguser)
1139                         free(conn->pguser);
1140                 conn->pguser = pg_fe_getauthname(&conn->errorMessage);
1141                 if (!conn->pguser)
1142                 {
1143                         conn->status = CONNECTION_BAD;
1144                         return false;
1145                 }
1146         }
1147
1148         /*
1149          * If database name was not given, default it to equal user name
1150          */
1151         if (conn->dbName == NULL || conn->dbName[0] == '\0')
1152         {
1153                 if (conn->dbName)
1154                         free(conn->dbName);
1155                 conn->dbName = strdup(conn->pguser);
1156                 if (!conn->dbName)
1157                         goto oom_error;
1158         }
1159
1160         /*
1161          * If password was not given, try to look it up in password file.  Note
1162          * that the result might be different for each host/port pair.
1163          */
1164         if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
1165         {
1166                 /* If password file wasn't specified, use ~/PGPASSFILE */
1167                 if (conn->pgpassfile == NULL || conn->pgpassfile[0] == '\0')
1168                 {
1169                         char            homedir[MAXPGPATH];
1170
1171                         if (pqGetHomeDirectory(homedir, sizeof(homedir)))
1172                         {
1173                                 if (conn->pgpassfile)
1174                                         free(conn->pgpassfile);
1175                                 conn->pgpassfile = malloc(MAXPGPATH);
1176                                 if (!conn->pgpassfile)
1177                                         goto oom_error;
1178                                 snprintf(conn->pgpassfile, MAXPGPATH, "%s/%s",
1179                                                  homedir, PGPASSFILE);
1180                         }
1181                 }
1182
1183                 if (conn->pgpassfile != NULL && conn->pgpassfile[0] != '\0')
1184                 {
1185                         for (i = 0; i < conn->nconnhost; i++)
1186                         {
1187                                 /*
1188                                  * Try to get a password for this host from file.  We use host
1189                                  * for the hostname search key if given, else hostaddr (at
1190                                  * least one of them is guaranteed nonempty by now).
1191                                  */
1192                                 const char *pwhost = conn->connhost[i].host;
1193
1194                                 if (pwhost == NULL || pwhost[0] == '\0')
1195                                         pwhost = conn->connhost[i].hostaddr;
1196
1197                                 conn->connhost[i].password =
1198                                         passwordFromFile(pwhost,
1199                                                                          conn->connhost[i].port,
1200                                                                          conn->dbName,
1201                                                                          conn->pguser,
1202                                                                          conn->pgpassfile);
1203                         }
1204                 }
1205         }
1206
1207         /*
1208          * validate channel_binding option
1209          */
1210         if (conn->channel_binding)
1211         {
1212                 if (strcmp(conn->channel_binding, "disable") != 0
1213                         && strcmp(conn->channel_binding, "prefer") != 0
1214                         && strcmp(conn->channel_binding, "require") != 0)
1215                 {
1216                         conn->status = CONNECTION_BAD;
1217                         printfPQExpBuffer(&conn->errorMessage,
1218                                                           libpq_gettext("invalid channel_binding value: \"%s\"\n"),
1219                                                           conn->channel_binding);
1220                         return false;
1221                 }
1222         }
1223         else
1224         {
1225                 conn->channel_binding = strdup(DefaultChannelBinding);
1226                 if (!conn->channel_binding)
1227                         goto oom_error;
1228         }
1229
1230         /*
1231          * validate sslmode option
1232          */
1233         if (conn->sslmode)
1234         {
1235                 if (strcmp(conn->sslmode, "disable") != 0
1236                         && strcmp(conn->sslmode, "allow") != 0
1237                         && strcmp(conn->sslmode, "prefer") != 0
1238                         && strcmp(conn->sslmode, "require") != 0
1239                         && strcmp(conn->sslmode, "verify-ca") != 0
1240                         && strcmp(conn->sslmode, "verify-full") != 0)
1241                 {
1242                         conn->status = CONNECTION_BAD;
1243                         printfPQExpBuffer(&conn->errorMessage,
1244                                                           libpq_gettext("invalid sslmode value: \"%s\"\n"),
1245                                                           conn->sslmode);
1246                         return false;
1247                 }
1248
1249 #ifndef USE_SSL
1250                 switch (conn->sslmode[0])
1251                 {
1252                         case 'a':                       /* "allow" */
1253                         case 'p':                       /* "prefer" */
1254
1255                                 /*
1256                                  * warn user that an SSL connection will never be negotiated
1257                                  * since SSL was not compiled in?
1258                                  */
1259                                 break;
1260
1261                         case 'r':                       /* "require" */
1262                         case 'v':                       /* "verify-ca" or "verify-full" */
1263                                 conn->status = CONNECTION_BAD;
1264                                 printfPQExpBuffer(&conn->errorMessage,
1265                                                                   libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
1266                                                                   conn->sslmode);
1267                                 return false;
1268                 }
1269 #endif
1270         }
1271         else
1272         {
1273                 conn->sslmode = strdup(DefaultSSLMode);
1274                 if (!conn->sslmode)
1275                         goto oom_error;
1276         }
1277
1278         /*
1279          * validate gssencmode option
1280          */
1281         if (conn->gssencmode)
1282         {
1283                 if (strcmp(conn->gssencmode, "disable") != 0 &&
1284                         strcmp(conn->gssencmode, "prefer") != 0 &&
1285                         strcmp(conn->gssencmode, "require") != 0)
1286                 {
1287                         conn->status = CONNECTION_BAD;
1288                         printfPQExpBuffer(&conn->errorMessage,
1289                                                           libpq_gettext("invalid gssencmode value: \"%s\"\n"),
1290                                                           conn->gssencmode);
1291                         return false;
1292                 }
1293 #ifndef ENABLE_GSS
1294                 if (strcmp(conn->gssencmode, "require") == 0)
1295                 {
1296                         conn->status = CONNECTION_BAD;
1297                         printfPQExpBuffer(&conn->errorMessage,
1298                                                           libpq_gettext("gssencmode value \"%s\" invalid when GSSAPI support is not compiled in\n"),
1299                                                           conn->gssencmode);
1300                         return false;
1301                 }
1302 #endif
1303         }
1304         else
1305         {
1306                 conn->gssencmode = strdup(DefaultGSSMode);
1307                 if (!conn->gssencmode)
1308                         goto oom_error;
1309         }
1310
1311         /*
1312          * Resolve special "auto" client_encoding from the locale
1313          */
1314         if (conn->client_encoding_initial &&
1315                 strcmp(conn->client_encoding_initial, "auto") == 0)
1316         {
1317                 free(conn->client_encoding_initial);
1318                 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
1319                 if (!conn->client_encoding_initial)
1320                         goto oom_error;
1321         }
1322
1323         /*
1324          * Validate target_session_attrs option.
1325          */
1326         if (conn->target_session_attrs)
1327         {
1328                 if (strcmp(conn->target_session_attrs, "any") != 0
1329                         && strcmp(conn->target_session_attrs, "read-write") != 0)
1330                 {
1331                         conn->status = CONNECTION_BAD;
1332                         printfPQExpBuffer(&conn->errorMessage,
1333                                                           libpq_gettext("invalid target_session_attrs value: \"%s\"\n"),
1334                                                           conn->target_session_attrs);
1335                         return false;
1336                 }
1337         }
1338
1339         /*
1340          * Only if we get this far is it appropriate to try to connect. (We need a
1341          * state flag, rather than just the boolean result of this function, in
1342          * case someone tries to PQreset() the PGconn.)
1343          */
1344         conn->options_valid = true;
1345
1346         return true;
1347
1348 oom_error:
1349         conn->status = CONNECTION_BAD;
1350         printfPQExpBuffer(&conn->errorMessage,
1351                                           libpq_gettext("out of memory\n"));
1352         return false;
1353 }
1354
1355 /*
1356  *              PQconndefaults
1357  *
1358  * Construct a default connection options array, which identifies all the
1359  * available options and shows any default values that are available from the
1360  * environment etc.  On error (eg out of memory), NULL is returned.
1361  *
1362  * Using this function, an application may determine all possible options
1363  * and their current default values.
1364  *
1365  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
1366  * and should be freed when no longer needed via PQconninfoFree().  (In prior
1367  * versions, the returned array was static, but that's not thread-safe.)
1368  * Pre-7.0 applications that use this function will see a small memory leak
1369  * until they are updated to call PQconninfoFree.
1370  */
1371 PQconninfoOption *
1372 PQconndefaults(void)
1373 {
1374         PQExpBufferData errorBuf;
1375         PQconninfoOption *connOptions;
1376
1377         /* We don't actually report any errors here, but callees want a buffer */
1378         initPQExpBuffer(&errorBuf);
1379         if (PQExpBufferDataBroken(errorBuf))
1380                 return NULL;                    /* out of memory already :-( */
1381
1382         connOptions = conninfo_init(&errorBuf);
1383         if (connOptions != NULL)
1384         {
1385                 /* pass NULL errorBuf to ignore errors */
1386                 if (!conninfo_add_defaults(connOptions, NULL))
1387                 {
1388                         PQconninfoFree(connOptions);
1389                         connOptions = NULL;
1390                 }
1391         }
1392
1393         termPQExpBuffer(&errorBuf);
1394         return connOptions;
1395 }
1396
1397 /* ----------------
1398  *              PQsetdbLogin
1399  *
1400  * establishes a connection to a postgres backend through the postmaster
1401  * at the specified host and port.
1402  *
1403  * returns a PGconn* which is needed for all subsequent libpq calls
1404  *
1405  * if the status field of the connection returned is CONNECTION_BAD,
1406  * then only the errorMessage is likely to be useful.
1407  * ----------------
1408  */
1409 PGconn *
1410 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
1411                          const char *pgtty, const char *dbName, const char *login,
1412                          const char *pwd)
1413 {
1414         PGconn     *conn;
1415
1416         /*
1417          * Allocate memory for the conn structure
1418          */
1419         conn = makeEmptyPGconn();
1420         if (conn == NULL)
1421                 return NULL;
1422
1423         /*
1424          * If the dbName parameter contains what looks like a connection string,
1425          * parse it into conn struct using connectOptions1.
1426          */
1427         if (dbName && recognized_connection_string(dbName))
1428         {
1429                 if (!connectOptions1(conn, dbName))
1430                         return conn;
1431         }
1432         else
1433         {
1434                 /*
1435                  * Old-style path: first, parse an empty conninfo string in order to
1436                  * set up the same defaults that PQconnectdb() would use.
1437                  */
1438                 if (!connectOptions1(conn, ""))
1439                         return conn;
1440
1441                 /* Insert dbName parameter value into struct */
1442                 if (dbName && dbName[0] != '\0')
1443                 {
1444                         if (conn->dbName)
1445                                 free(conn->dbName);
1446                         conn->dbName = strdup(dbName);
1447                         if (!conn->dbName)
1448                                 goto oom_error;
1449                 }
1450         }
1451
1452         /*
1453          * Insert remaining parameters into struct, overriding defaults (as well
1454          * as any conflicting data from dbName taken as a conninfo).
1455          */
1456         if (pghost && pghost[0] != '\0')
1457         {
1458                 if (conn->pghost)
1459                         free(conn->pghost);
1460                 conn->pghost = strdup(pghost);
1461                 if (!conn->pghost)
1462                         goto oom_error;
1463         }
1464
1465         if (pgport && pgport[0] != '\0')
1466         {
1467                 if (conn->pgport)
1468                         free(conn->pgport);
1469                 conn->pgport = strdup(pgport);
1470                 if (!conn->pgport)
1471                         goto oom_error;
1472         }
1473
1474         if (pgoptions && pgoptions[0] != '\0')
1475         {
1476                 if (conn->pgoptions)
1477                         free(conn->pgoptions);
1478                 conn->pgoptions = strdup(pgoptions);
1479                 if (!conn->pgoptions)
1480                         goto oom_error;
1481         }
1482
1483         if (pgtty && pgtty[0] != '\0')
1484         {
1485                 if (conn->pgtty)
1486                         free(conn->pgtty);
1487                 conn->pgtty = strdup(pgtty);
1488                 if (!conn->pgtty)
1489                         goto oom_error;
1490         }
1491
1492         if (login && login[0] != '\0')
1493         {
1494                 if (conn->pguser)
1495                         free(conn->pguser);
1496                 conn->pguser = strdup(login);
1497                 if (!conn->pguser)
1498                         goto oom_error;
1499         }
1500
1501         if (pwd && pwd[0] != '\0')
1502         {
1503                 if (conn->pgpass)
1504                         free(conn->pgpass);
1505                 conn->pgpass = strdup(pwd);
1506                 if (!conn->pgpass)
1507                         goto oom_error;
1508         }
1509
1510         /*
1511          * Compute derived options
1512          */
1513         if (!connectOptions2(conn))
1514                 return conn;
1515
1516         /*
1517          * Connect to the database
1518          */
1519         if (connectDBStart(conn))
1520                 (void) connectDBComplete(conn);
1521
1522         return conn;
1523
1524 oom_error:
1525         conn->status = CONNECTION_BAD;
1526         printfPQExpBuffer(&conn->errorMessage,
1527                                           libpq_gettext("out of memory\n"));
1528         return conn;
1529 }
1530
1531
1532 /* ----------
1533  * connectNoDelay -
1534  * Sets the TCP_NODELAY socket option.
1535  * Returns 1 if successful, 0 if not.
1536  * ----------
1537  */
1538 static int
1539 connectNoDelay(PGconn *conn)
1540 {
1541 #ifdef  TCP_NODELAY
1542         int                     on = 1;
1543
1544         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1545                                    (char *) &on,
1546                                    sizeof(on)) < 0)
1547         {
1548                 char            sebuf[PG_STRERROR_R_BUFLEN];
1549
1550                 appendPQExpBuffer(&conn->errorMessage,
1551                                                   libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1552                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1553                 return 0;
1554         }
1555 #endif
1556
1557         return 1;
1558 }
1559
1560 /* ----------
1561  * Write currently connected IP address into host_addr (of len host_addr_len).
1562  * If unable to, set it to the empty string.
1563  * ----------
1564  */
1565 static void
1566 getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
1567 {
1568         struct sockaddr_storage *addr = &conn->raddr.addr;
1569
1570         if (addr->ss_family == AF_INET)
1571         {
1572                 if (pg_inet_net_ntop(AF_INET,
1573                                                          &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1574                                                          32,
1575                                                          host_addr, host_addr_len) == NULL)
1576                         host_addr[0] = '\0';
1577         }
1578 #ifdef HAVE_IPV6
1579         else if (addr->ss_family == AF_INET6)
1580         {
1581                 if (pg_inet_net_ntop(AF_INET6,
1582                                                          &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1583                                                          128,
1584                                                          host_addr, host_addr_len) == NULL)
1585                         host_addr[0] = '\0';
1586         }
1587 #endif
1588         else
1589                 host_addr[0] = '\0';
1590 }
1591
1592 /* ----------
1593  * connectFailureMessage -
1594  * create a friendly error message on connection failure.
1595  * ----------
1596  */
1597 static void
1598 connectFailureMessage(PGconn *conn, int errorno)
1599 {
1600         char            sebuf[PG_STRERROR_R_BUFLEN];
1601
1602 #ifdef HAVE_UNIX_SOCKETS
1603         if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1604         {
1605                 char            service[NI_MAXHOST];
1606
1607                 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1608                                                    NULL, 0,
1609                                                    service, sizeof(service),
1610                                                    NI_NUMERICSERV);
1611                 appendPQExpBuffer(&conn->errorMessage,
1612                                                   libpq_gettext("could not connect to server: %s\n"
1613                                                                                 "\tIs the server running locally and accepting\n"
1614                                                                                 "\tconnections on Unix domain socket \"%s\"?\n"),
1615                                                   SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1616                                                   service);
1617         }
1618         else
1619 #endif                                                  /* HAVE_UNIX_SOCKETS */
1620         {
1621                 char            host_addr[NI_MAXHOST];
1622                 const char *displayed_host;
1623                 const char *displayed_port;
1624
1625                 /*
1626                  * Optionally display the network address with the hostname. This is
1627                  * useful to distinguish between IPv4 and IPv6 connections.
1628                  */
1629                 getHostaddr(conn, host_addr, NI_MAXHOST);
1630
1631                 /* To which host and port were we actually connecting? */
1632                 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
1633                         displayed_host = conn->connhost[conn->whichhost].hostaddr;
1634                 else
1635                         displayed_host = conn->connhost[conn->whichhost].host;
1636                 displayed_port = conn->connhost[conn->whichhost].port;
1637                 if (displayed_port == NULL || displayed_port[0] == '\0')
1638                         displayed_port = DEF_PGPORT_STR;
1639
1640                 /*
1641                  * If the user did not supply an IP address using 'hostaddr', and
1642                  * 'host' was missing or does not match our lookup, display the
1643                  * looked-up IP address.
1644                  */
1645                 if (conn->connhost[conn->whichhost].type != CHT_HOST_ADDRESS &&
1646                         strlen(host_addr) > 0 &&
1647                         strcmp(displayed_host, host_addr) != 0)
1648                         appendPQExpBuffer(&conn->errorMessage,
1649                                                           libpq_gettext("could not connect to server: %s\n"
1650                                                                                         "\tIs the server running on host \"%s\" (%s) and accepting\n"
1651                                                                                         "\tTCP/IP connections on port %s?\n"),
1652                                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1653                                                           displayed_host, host_addr,
1654                                                           displayed_port);
1655                 else
1656                         appendPQExpBuffer(&conn->errorMessage,
1657                                                           libpq_gettext("could not connect to server: %s\n"
1658                                                                                         "\tIs the server running on host \"%s\" and accepting\n"
1659                                                                                         "\tTCP/IP connections on port %s?\n"),
1660                                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1661                                                           displayed_host,
1662                                                           displayed_port);
1663         }
1664 }
1665
1666 /*
1667  * Should we use keepalives?  Returns 1 if yes, 0 if no, and -1 if
1668  * conn->keepalives is set to a value which is not parseable as an
1669  * integer.
1670  */
1671 static int
1672 useKeepalives(PGconn *conn)
1673 {
1674         char       *ep;
1675         int                     val;
1676
1677         if (conn->keepalives == NULL)
1678                 return 1;
1679         val = strtol(conn->keepalives, &ep, 10);
1680         if (*ep)
1681                 return -1;
1682         return val != 0 ? 1 : 0;
1683 }
1684
1685 /*
1686  * Parse and try to interpret "value" as an integer value, and if successful,
1687  * store it in *result, complaining if there is any trailing garbage or an
1688  * overflow.  This allows any number of leading and trailing whitespaces.
1689  */
1690 static bool
1691 parse_int_param(const char *value, int *result, PGconn *conn,
1692                                 const char *context)
1693 {
1694         char       *end;
1695         long            numval;
1696
1697         Assert(value != NULL);
1698
1699         *result = 0;
1700
1701         /* strtol(3) skips leading whitespaces */
1702         errno = 0;
1703         numval = strtol(value, &end, 10);
1704
1705         /*
1706          * If no progress was done during the parsing or an error happened, fail.
1707          * This tests properly for overflows of the result.
1708          */
1709         if (value == end || errno != 0 || numval != (int) numval)
1710                 goto error;
1711
1712         /*
1713          * Skip any trailing whitespace; if anything but whitespace remains before
1714          * the terminating character, fail
1715          */
1716         while (*end != '\0' && isspace((unsigned char) *end))
1717                 end++;
1718
1719         if (*end != '\0')
1720                 goto error;
1721
1722         *result = numval;
1723         return true;
1724
1725 error:
1726         appendPQExpBuffer(&conn->errorMessage,
1727                                           libpq_gettext("invalid integer value \"%s\" for connection option \"%s\"\n"),
1728                                           value, context);
1729         return false;
1730 }
1731
1732 #ifndef WIN32
1733 /*
1734  * Set the keepalive idle timer.
1735  */
1736 static int
1737 setKeepalivesIdle(PGconn *conn)
1738 {
1739         int                     idle;
1740
1741         if (conn->keepalives_idle == NULL)
1742                 return 1;
1743
1744         if (!parse_int_param(conn->keepalives_idle, &idle, conn,
1745                                                  "keepalives_idle"))
1746                 return 0;
1747         if (idle < 0)
1748                 idle = 0;
1749
1750 #ifdef PG_TCP_KEEPALIVE_IDLE
1751         if (setsockopt(conn->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1752                                    (char *) &idle, sizeof(idle)) < 0)
1753         {
1754                 char            sebuf[PG_STRERROR_R_BUFLEN];
1755
1756                 appendPQExpBuffer(&conn->errorMessage,
1757                                                   libpq_gettext("setsockopt(%s) failed: %s\n"),
1758                                                   PG_TCP_KEEPALIVE_IDLE_STR,
1759                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1760                 return 0;
1761         }
1762 #endif
1763
1764         return 1;
1765 }
1766
1767 /*
1768  * Set the keepalive interval.
1769  */
1770 static int
1771 setKeepalivesInterval(PGconn *conn)
1772 {
1773         int                     interval;
1774
1775         if (conn->keepalives_interval == NULL)
1776                 return 1;
1777
1778         if (!parse_int_param(conn->keepalives_interval, &interval, conn,
1779                                                  "keepalives_interval"))
1780                 return 0;
1781         if (interval < 0)
1782                 interval = 0;
1783
1784 #ifdef TCP_KEEPINTVL
1785         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1786                                    (char *) &interval, sizeof(interval)) < 0)
1787         {
1788                 char            sebuf[PG_STRERROR_R_BUFLEN];
1789
1790                 appendPQExpBuffer(&conn->errorMessage,
1791                                                   libpq_gettext("setsockopt(%s) failed: %s\n"),
1792                                                   "TCP_KEEPINTVL",
1793                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1794                 return 0;
1795         }
1796 #endif
1797
1798         return 1;
1799 }
1800
1801 /*
1802  * Set the count of lost keepalive packets that will trigger a connection
1803  * break.
1804  */
1805 static int
1806 setKeepalivesCount(PGconn *conn)
1807 {
1808         int                     count;
1809
1810         if (conn->keepalives_count == NULL)
1811                 return 1;
1812
1813         if (!parse_int_param(conn->keepalives_count, &count, conn,
1814                                                  "keepalives_count"))
1815                 return 0;
1816         if (count < 0)
1817                 count = 0;
1818
1819 #ifdef TCP_KEEPCNT
1820         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1821                                    (char *) &count, sizeof(count)) < 0)
1822         {
1823                 char            sebuf[PG_STRERROR_R_BUFLEN];
1824
1825                 appendPQExpBuffer(&conn->errorMessage,
1826                                                   libpq_gettext("setsockopt(%s) failed: %s\n"),
1827                                                   "TCP_KEEPCNT",
1828                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1829                 return 0;
1830         }
1831 #endif
1832
1833         return 1;
1834 }
1835 #else                                                   /* WIN32 */
1836 #ifdef SIO_KEEPALIVE_VALS
1837 /*
1838  * Enable keepalives and set the keepalive values on Win32,
1839  * where they are always set in one batch.
1840  */
1841 static int
1842 setKeepalivesWin32(PGconn *conn)
1843 {
1844         struct tcp_keepalive ka;
1845         DWORD           retsize;
1846         int                     idle = 0;
1847         int                     interval = 0;
1848
1849         if (conn->keepalives_idle &&
1850                 !parse_int_param(conn->keepalives_idle, &idle, conn,
1851                                                  "keepalives_idle"))
1852                 return 0;
1853         if (idle <= 0)
1854                 idle = 2 * 60 * 60;             /* 2 hours = default */
1855
1856         if (conn->keepalives_interval &&
1857                 !parse_int_param(conn->keepalives_interval, &interval, conn,
1858                                                  "keepalives_interval"))
1859                 return 0;
1860         if (interval <= 0)
1861                 interval = 1;                   /* 1 second = default */
1862
1863         ka.onoff = 1;
1864         ka.keepalivetime = idle * 1000;
1865         ka.keepaliveinterval = interval * 1000;
1866
1867         if (WSAIoctl(conn->sock,
1868                                  SIO_KEEPALIVE_VALS,
1869                                  (LPVOID) &ka,
1870                                  sizeof(ka),
1871                                  NULL,
1872                                  0,
1873                                  &retsize,
1874                                  NULL,
1875                                  NULL)
1876                 != 0)
1877         {
1878                 appendPQExpBuffer(&conn->errorMessage,
1879                                                   libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1880                                                   WSAGetLastError());
1881                 return 0;
1882         }
1883         return 1;
1884 }
1885 #endif                                                  /* SIO_KEEPALIVE_VALS */
1886 #endif                                                  /* WIN32 */
1887
1888 /*
1889  * Set the TCP user timeout.
1890  */
1891 static int
1892 setTCPUserTimeout(PGconn *conn)
1893 {
1894         int                     timeout;
1895
1896         if (conn->pgtcp_user_timeout == NULL)
1897                 return 1;
1898
1899         if (!parse_int_param(conn->pgtcp_user_timeout, &timeout, conn,
1900                                                  "tcp_user_timeout"))
1901                 return 0;
1902
1903         if (timeout < 0)
1904                 timeout = 0;
1905
1906 #ifdef TCP_USER_TIMEOUT
1907         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1908                                    (char *) &timeout, sizeof(timeout)) < 0)
1909         {
1910                 char            sebuf[256];
1911
1912                 appendPQExpBuffer(&conn->errorMessage,
1913                                                   libpq_gettext("setsockopt(%s) failed: %s\n"),
1914                                                   "TCP_USER_TIMEOUT",
1915                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1916                 return 0;
1917         }
1918 #endif
1919
1920         return 1;
1921 }
1922
1923 /* ----------
1924  * connectDBStart -
1925  *              Begin the process of making a connection to the backend.
1926  *
1927  * Returns 1 if successful, 0 if not.
1928  * ----------
1929  */
1930 static int
1931 connectDBStart(PGconn *conn)
1932 {
1933         if (!conn)
1934                 return 0;
1935
1936         if (!conn->options_valid)
1937                 goto connect_errReturn;
1938
1939         /*
1940          * Check for bad linking to backend-internal versions of src/common
1941          * functions (see comments in link-canary.c for the reason we need this).
1942          * Nobody but developers should see this message, so we don't bother
1943          * translating it.
1944          */
1945         if (!pg_link_canary_is_frontend())
1946         {
1947                 printfPQExpBuffer(&conn->errorMessage,
1948                                                   "libpq is incorrectly linked to backend functions\n");
1949                 goto connect_errReturn;
1950         }
1951
1952         /* Ensure our buffers are empty */
1953         conn->inStart = conn->inCursor = conn->inEnd = 0;
1954         conn->outCount = 0;
1955
1956         /*
1957          * Ensure errorMessage is empty, too.  PQconnectPoll will append messages
1958          * to it in the process of scanning for a working server.  Thus, if we
1959          * fail to connect to multiple hosts, the final error message will include
1960          * details about each failure.
1961          */
1962         resetPQExpBuffer(&conn->errorMessage);
1963
1964 #ifdef ENABLE_GSS
1965         if (conn->gssencmode[0] == 'd') /* "disable" */
1966                 conn->try_gss = false;
1967 #endif
1968
1969         /*
1970          * Set up to try to connect to the first host.  (Setting whichhost = -1 is
1971          * a bit of a cheat, but PQconnectPoll will advance it to 0 before
1972          * anything else looks at it.)
1973          */
1974         conn->whichhost = -1;
1975         conn->try_next_addr = false;
1976         conn->try_next_host = true;
1977         conn->status = CONNECTION_NEEDED;
1978
1979         /*
1980          * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1981          * so that it can easily be re-executed if needed again during the
1982          * asynchronous startup process.  However, we must run it once here,
1983          * because callers expect a success return from this routine to mean that
1984          * we are in PGRES_POLLING_WRITING connection state.
1985          */
1986         if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1987                 return 1;
1988
1989 connect_errReturn:
1990
1991         /*
1992          * If we managed to open a socket, close it immediately rather than
1993          * waiting till PQfinish.  (The application cannot have gotten the socket
1994          * from PQsocket yet, so this doesn't risk breaking anything.)
1995          */
1996         pqDropConnection(conn, true);
1997         conn->status = CONNECTION_BAD;
1998         return 0;
1999 }
2000
2001
2002 /*
2003  *              connectDBComplete
2004  *
2005  * Block and complete a connection.
2006  *
2007  * Returns 1 on success, 0 on failure.
2008  */
2009 static int
2010 connectDBComplete(PGconn *conn)
2011 {
2012         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
2013         time_t          finish_time = ((time_t) -1);
2014         int                     timeout = 0;
2015         int                     last_whichhost = -2;    /* certainly different from whichhost */
2016         struct addrinfo *last_addr_cur = NULL;
2017
2018         if (conn == NULL || conn->status == CONNECTION_BAD)
2019                 return 0;
2020
2021         /*
2022          * Set up a time limit, if connect_timeout isn't zero.
2023          */
2024         if (conn->connect_timeout != NULL)
2025         {
2026                 if (!parse_int_param(conn->connect_timeout, &timeout, conn,
2027                                                          "connect_timeout"))
2028                 {
2029                         /* mark the connection as bad to report the parsing failure */
2030                         conn->status = CONNECTION_BAD;
2031                         return 0;
2032                 }
2033
2034                 if (timeout > 0)
2035                 {
2036                         /*
2037                          * Rounding could cause connection to fail unexpectedly quickly;
2038                          * to prevent possibly waiting hardly-at-all, insist on at least
2039                          * two seconds.
2040                          */
2041                         if (timeout < 2)
2042                                 timeout = 2;
2043                 }
2044                 else                                    /* negative means 0 */
2045                         timeout = 0;
2046         }
2047
2048         for (;;)
2049         {
2050                 int                     ret = 0;
2051
2052                 /*
2053                  * (Re)start the connect_timeout timer if it's active and we are
2054                  * considering a different host than we were last time through.  If
2055                  * we've already succeeded, though, needn't recalculate.
2056                  */
2057                 if (flag != PGRES_POLLING_OK &&
2058                         timeout > 0 &&
2059                         (conn->whichhost != last_whichhost ||
2060                          conn->addr_cur != last_addr_cur))
2061                 {
2062                         finish_time = time(NULL) + timeout;
2063                         last_whichhost = conn->whichhost;
2064                         last_addr_cur = conn->addr_cur;
2065                 }
2066
2067                 /*
2068                  * Wait, if necessary.  Note that the initial state (just after
2069                  * PQconnectStart) is to wait for the socket to select for writing.
2070                  */
2071                 switch (flag)
2072                 {
2073                         case PGRES_POLLING_OK:
2074
2075                                 /*
2076                                  * Reset stored error messages since we now have a working
2077                                  * connection
2078                                  */
2079                                 resetPQExpBuffer(&conn->errorMessage);
2080                                 return 1;               /* success! */
2081
2082                         case PGRES_POLLING_READING:
2083                                 ret = pqWaitTimed(1, 0, conn, finish_time);
2084                                 if (ret == -1)
2085                                 {
2086                                         /* hard failure, eg select() problem, aborts everything */
2087                                         conn->status = CONNECTION_BAD;
2088                                         return 0;
2089                                 }
2090                                 break;
2091
2092                         case PGRES_POLLING_WRITING:
2093                                 ret = pqWaitTimed(0, 1, conn, finish_time);
2094                                 if (ret == -1)
2095                                 {
2096                                         /* hard failure, eg select() problem, aborts everything */
2097                                         conn->status = CONNECTION_BAD;
2098                                         return 0;
2099                                 }
2100                                 break;
2101
2102                         default:
2103                                 /* Just in case we failed to set it in PQconnectPoll */
2104                                 conn->status = CONNECTION_BAD;
2105                                 return 0;
2106                 }
2107
2108                 if (ret == 1)                   /* connect_timeout elapsed */
2109                 {
2110                         /*
2111                          * Give up on current server/address, try the next one.
2112                          */
2113                         conn->try_next_addr = true;
2114                         conn->status = CONNECTION_NEEDED;
2115                 }
2116
2117                 /*
2118                  * Now try to advance the state machine.
2119                  */
2120                 flag = PQconnectPoll(conn);
2121         }
2122 }
2123
2124 /*
2125  * This subroutine saves conn->errorMessage, which will be restored back by
2126  * restoreErrorMessage subroutine.  Returns false on OOM failure.
2127  */
2128 static bool
2129 saveErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
2130 {
2131         initPQExpBuffer(savedMessage);
2132         appendPQExpBufferStr(savedMessage,
2133                                                  conn->errorMessage.data);
2134         if (PQExpBufferBroken(savedMessage))
2135         {
2136                 printfPQExpBuffer(&conn->errorMessage,
2137                                                   libpq_gettext("out of memory\n"));
2138                 return false;
2139         }
2140         /* Clear whatever is in errorMessage now */
2141         resetPQExpBuffer(&conn->errorMessage);
2142         return true;
2143 }
2144
2145 /*
2146  * Restores saved error messages back to conn->errorMessage, prepending them
2147  * to whatever is in conn->errorMessage already.  (This does the right thing
2148  * if anything's been added to conn->errorMessage since saveErrorMessage.)
2149  */
2150 static void
2151 restoreErrorMessage(PGconn *conn, PQExpBuffer savedMessage)
2152 {
2153         appendPQExpBufferStr(savedMessage, conn->errorMessage.data);
2154         resetPQExpBuffer(&conn->errorMessage);
2155         appendPQExpBufferStr(&conn->errorMessage, savedMessage->data);
2156         /* If any step above hit OOM, just report that */
2157         if (PQExpBufferBroken(savedMessage) ||
2158                 PQExpBufferBroken(&conn->errorMessage))
2159                 printfPQExpBuffer(&conn->errorMessage,
2160                                                   libpq_gettext("out of memory\n"));
2161         termPQExpBuffer(savedMessage);
2162 }
2163
2164 /* ----------------
2165  *              PQconnectPoll
2166  *
2167  * Poll an asynchronous connection.
2168  *
2169  * Returns a PostgresPollingStatusType.
2170  * Before calling this function, use select(2) to determine when data
2171  * has arrived..
2172  *
2173  * You must call PQfinish whether or not this fails.
2174  *
2175  * This function and PQconnectStart are intended to allow connections to be
2176  * made without blocking the execution of your program on remote I/O. However,
2177  * there are a number of caveats:
2178  *
2179  *       o      If you call PQtrace, ensure that the stream object into which you trace
2180  *              will not block.
2181  *       o      If you do not supply an IP address for the remote host (i.e. you
2182  *              supply a host name instead) then PQconnectStart will block on
2183  *              gethostbyname.  You will be fine if using Unix sockets (i.e. by
2184  *              supplying neither a host name nor a host address).
2185  *       o      If your backend wants to use Kerberos authentication then you must
2186  *              supply both a host name and a host address, otherwise this function
2187  *              may block on gethostname.
2188  *
2189  * ----------------
2190  */
2191 PostgresPollingStatusType
2192 PQconnectPoll(PGconn *conn)
2193 {
2194         bool            reset_connection_state_machine = false;
2195         bool            need_new_connection = false;
2196         PGresult   *res;
2197         char            sebuf[PG_STRERROR_R_BUFLEN];
2198         int                     optval;
2199         PQExpBufferData savedMessage;
2200
2201         if (conn == NULL)
2202                 return PGRES_POLLING_FAILED;
2203
2204         /* Get the new data */
2205         switch (conn->status)
2206         {
2207                         /*
2208                          * We really shouldn't have been polled in these two cases, but we
2209                          * can handle it.
2210                          */
2211                 case CONNECTION_BAD:
2212                         return PGRES_POLLING_FAILED;
2213                 case CONNECTION_OK:
2214                         return PGRES_POLLING_OK;
2215
2216                         /* These are reading states */
2217                 case CONNECTION_AWAITING_RESPONSE:
2218                 case CONNECTION_AUTH_OK:
2219                         {
2220                                 /* Load waiting data */
2221                                 int                     n = pqReadData(conn);
2222
2223                                 if (n < 0)
2224                                         goto error_return;
2225                                 if (n == 0)
2226                                         return PGRES_POLLING_READING;
2227
2228                                 break;
2229                         }
2230
2231                         /* These are writing states, so we just proceed. */
2232                 case CONNECTION_STARTED:
2233                 case CONNECTION_MADE:
2234                         break;
2235
2236                         /* We allow pqSetenvPoll to decide whether to proceed. */
2237                 case CONNECTION_SETENV:
2238                         break;
2239
2240                         /* Special cases: proceed without waiting. */
2241                 case CONNECTION_SSL_STARTUP:
2242                 case CONNECTION_NEEDED:
2243                 case CONNECTION_CHECK_WRITABLE:
2244                 case CONNECTION_CONSUME:
2245                 case CONNECTION_GSS_STARTUP:
2246                         break;
2247
2248                 default:
2249                         appendPQExpBufferStr(&conn->errorMessage,
2250                                                                  libpq_gettext(
2251                                                                                            "invalid connection state, "
2252                                                                                            "probably indicative of memory corruption\n"
2253                                                                                            ));
2254                         goto error_return;
2255         }
2256
2257
2258 keep_going:                                             /* We will come back to here until there is
2259                                                                  * nothing left to do. */
2260
2261         /* Time to advance to next address, or next host if no more addresses? */
2262         if (conn->try_next_addr)
2263         {
2264                 if (conn->addr_cur && conn->addr_cur->ai_next)
2265                 {
2266                         conn->addr_cur = conn->addr_cur->ai_next;
2267                         reset_connection_state_machine = true;
2268                 }
2269                 else
2270                         conn->try_next_host = true;
2271                 conn->try_next_addr = false;
2272         }
2273
2274         /* Time to advance to next connhost[] entry? */
2275         if (conn->try_next_host)
2276         {
2277                 pg_conn_host *ch;
2278                 struct addrinfo hint;
2279                 int                     thisport;
2280                 int                     ret;
2281                 char            portstr[MAXPGPATH];
2282
2283                 if (conn->whichhost + 1 >= conn->nconnhost)
2284                 {
2285                         /*
2286                          * Oops, no more hosts.  An appropriate error message is already
2287                          * set up, so just set the right status.
2288                          */
2289                         goto error_return;
2290                 }
2291                 conn->whichhost++;
2292
2293                 /* Drop any address info for previous host */
2294                 release_conn_addrinfo(conn);
2295
2296                 /*
2297                  * Look up info for the new host.  On failure, log the problem in
2298                  * conn->errorMessage, then loop around to try the next host.  (Note
2299                  * we don't clear try_next_host until we've succeeded.)
2300                  */
2301                 ch = &conn->connhost[conn->whichhost];
2302
2303                 /* Initialize hint structure */
2304                 MemSet(&hint, 0, sizeof(hint));
2305                 hint.ai_socktype = SOCK_STREAM;
2306                 conn->addrlist_family = hint.ai_family = AF_UNSPEC;
2307
2308                 /* Figure out the port number we're going to use. */
2309                 if (ch->port == NULL || ch->port[0] == '\0')
2310                         thisport = DEF_PGPORT;
2311                 else
2312                 {
2313                         if (!parse_int_param(ch->port, &thisport, conn, "port"))
2314                                 goto error_return;
2315
2316                         if (thisport < 1 || thisport > 65535)
2317                         {
2318                                 appendPQExpBuffer(&conn->errorMessage,
2319                                                                   libpq_gettext("invalid port number: \"%s\"\n"),
2320                                                                   ch->port);
2321                                 goto keep_going;
2322                         }
2323                 }
2324                 snprintf(portstr, sizeof(portstr), "%d", thisport);
2325
2326                 /* Use pg_getaddrinfo_all() to resolve the address */
2327                 switch (ch->type)
2328                 {
2329                         case CHT_HOST_NAME:
2330                                 ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2331                                                                                  &conn->addrlist);
2332                                 if (ret || !conn->addrlist)
2333                                 {
2334                                         appendPQExpBuffer(&conn->errorMessage,
2335                                                                           libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
2336                                                                           ch->host, gai_strerror(ret));
2337                                         goto keep_going;
2338                                 }
2339                                 break;
2340
2341                         case CHT_HOST_ADDRESS:
2342                                 hint.ai_flags = AI_NUMERICHOST;
2343                                 ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2344                                                                                  &conn->addrlist);
2345                                 if (ret || !conn->addrlist)
2346                                 {
2347                                         appendPQExpBuffer(&conn->errorMessage,
2348                                                                           libpq_gettext("could not parse network address \"%s\": %s\n"),
2349                                                                           ch->hostaddr, gai_strerror(ret));
2350                                         goto keep_going;
2351                                 }
2352                                 break;
2353
2354                         case CHT_UNIX_SOCKET:
2355 #ifdef HAVE_UNIX_SOCKETS
2356                                 conn->addrlist_family = hint.ai_family = AF_UNIX;
2357                                 UNIXSOCK_PATH(portstr, thisport, ch->host);
2358                                 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2359                                 {
2360                                         appendPQExpBuffer(&conn->errorMessage,
2361                                                                           libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
2362                                                                           portstr,
2363                                                                           (int) (UNIXSOCK_PATH_BUFLEN - 1));
2364                                         goto keep_going;
2365                                 }
2366
2367                                 /*
2368                                  * NULL hostname tells pg_getaddrinfo_all to parse the service
2369                                  * name as a Unix-domain socket path.
2370                                  */
2371                                 ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2372                                                                                  &conn->addrlist);
2373                                 if (ret || !conn->addrlist)
2374                                 {
2375                                         appendPQExpBuffer(&conn->errorMessage,
2376                                                                           libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
2377                                                                           portstr, gai_strerror(ret));
2378                                         goto keep_going;
2379                                 }
2380 #else
2381                                 Assert(false);
2382 #endif
2383                                 break;
2384                 }
2385
2386                 /* OK, scan this addrlist for a working server address */
2387                 conn->addr_cur = conn->addrlist;
2388                 reset_connection_state_machine = true;
2389                 conn->try_next_host = false;
2390         }
2391
2392         /* Reset connection state machine? */
2393         if (reset_connection_state_machine)
2394         {
2395                 /*
2396                  * (Re) initialize our connection control variables for a set of
2397                  * connection attempts to a single server address.  These variables
2398                  * must persist across individual connection attempts, but we must
2399                  * reset them when we start to consider a new server.
2400                  */
2401                 conn->pversion = PG_PROTOCOL(3, 0);
2402                 conn->send_appname = true;
2403 #ifdef USE_SSL
2404                 /* initialize these values based on SSL mode */
2405                 conn->allow_ssl_try = (conn->sslmode[0] != 'd');        /* "disable" */
2406                 conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2407 #endif
2408
2409                 reset_connection_state_machine = false;
2410                 need_new_connection = true;
2411         }
2412
2413         /* Force a new connection (perhaps to the same server as before)? */
2414         if (need_new_connection)
2415         {
2416                 /* Drop any existing connection */
2417                 pqDropConnection(conn, true);
2418
2419                 /* Reset all state obtained from old server */
2420                 pqDropServerData(conn);
2421
2422                 /* Drop any PGresult we might have, too */
2423                 conn->asyncStatus = PGASYNC_IDLE;
2424                 conn->xactStatus = PQTRANS_IDLE;
2425                 pqClearAsyncResult(conn);
2426
2427                 /* Reset conn->status to put the state machine in the right state */
2428                 conn->status = CONNECTION_NEEDED;
2429
2430                 need_new_connection = false;
2431         }
2432
2433         /* Now try to advance the state machine for this connection */
2434         switch (conn->status)
2435         {
2436                 case CONNECTION_NEEDED:
2437                         {
2438                                 /*
2439                                  * Try to initiate a connection to one of the addresses
2440                                  * returned by pg_getaddrinfo_all().  conn->addr_cur is the
2441                                  * next one to try.
2442                                  *
2443                                  * The extra level of braces here is historical.  It's not
2444                                  * worth reindenting this whole switch case to remove 'em.
2445                                  */
2446                                 {
2447                                         struct addrinfo *addr_cur = conn->addr_cur;
2448                                         char            host_addr[NI_MAXHOST];
2449
2450                                         /*
2451                                          * Advance to next possible host, if we've tried all of
2452                                          * the addresses for the current host.
2453                                          */
2454                                         if (addr_cur == NULL)
2455                                         {
2456                                                 conn->try_next_host = true;
2457                                                 goto keep_going;
2458                                         }
2459
2460                                         /* Remember current address for possible error msg */
2461                                         memcpy(&conn->raddr.addr, addr_cur->ai_addr,
2462                                                    addr_cur->ai_addrlen);
2463                                         conn->raddr.salen = addr_cur->ai_addrlen;
2464
2465                                         /* set connip */
2466                                         if (conn->connip != NULL)
2467                                         {
2468                                                 free(conn->connip);
2469                                                 conn->connip = NULL;
2470                                         }
2471
2472                                         getHostaddr(conn, host_addr, NI_MAXHOST);
2473                                         if (strlen(host_addr) > 0)
2474                                                 conn->connip = strdup(host_addr);
2475
2476                                         /*
2477                                          * purposely ignore strdup failure; not a big problem if
2478                                          * it fails anyway.
2479                                          */
2480
2481                                         conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
2482                                         if (conn->sock == PGINVALID_SOCKET)
2483                                         {
2484                                                 /*
2485                                                  * Silently ignore socket() failure if we have more
2486                                                  * addresses to try; this reduces useless chatter in
2487                                                  * cases where the address list includes both IPv4 and
2488                                                  * IPv6 but kernel only accepts one family.
2489                                                  */
2490                                                 if (addr_cur->ai_next != NULL ||
2491                                                         conn->whichhost + 1 < conn->nconnhost)
2492                                                 {
2493                                                         conn->try_next_addr = true;
2494                                                         goto keep_going;
2495                                                 }
2496                                                 appendPQExpBuffer(&conn->errorMessage,
2497                                                                                   libpq_gettext("could not create socket: %s\n"),
2498                                                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2499                                                 goto error_return;
2500                                         }
2501
2502                                         /*
2503                                          * Select socket options: no delay of outgoing data for
2504                                          * TCP sockets, nonblock mode, close-on-exec.  Try the
2505                                          * next address if any of this fails.
2506                                          */
2507                                         if (!IS_AF_UNIX(addr_cur->ai_family))
2508                                         {
2509                                                 if (!connectNoDelay(conn))
2510                                                 {
2511                                                         /* error message already created */
2512                                                         conn->try_next_addr = true;
2513                                                         goto keep_going;
2514                                                 }
2515                                         }
2516                                         if (!pg_set_noblock(conn->sock))
2517                                         {
2518                                                 appendPQExpBuffer(&conn->errorMessage,
2519                                                                                   libpq_gettext("could not set socket to nonblocking mode: %s\n"),
2520                                                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2521                                                 conn->try_next_addr = true;
2522                                                 goto keep_going;
2523                                         }
2524
2525 #ifdef F_SETFD
2526                                         if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2527                                         {
2528                                                 appendPQExpBuffer(&conn->errorMessage,
2529                                                                                   libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
2530                                                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2531                                                 conn->try_next_addr = true;
2532                                                 goto keep_going;
2533                                         }
2534 #endif                                                  /* F_SETFD */
2535
2536                                         if (!IS_AF_UNIX(addr_cur->ai_family))
2537                                         {
2538 #ifndef WIN32
2539                                                 int                     on = 1;
2540 #endif
2541                                                 int                     usekeepalives = useKeepalives(conn);
2542                                                 int                     err = 0;
2543
2544                                                 if (usekeepalives < 0)
2545                                                 {
2546                                                         appendPQExpBufferStr(&conn->errorMessage,
2547                                                                                                  libpq_gettext("keepalives parameter must be an integer\n"));
2548                                                         err = 1;
2549                                                 }
2550                                                 else if (usekeepalives == 0)
2551                                                 {
2552                                                         /* Do nothing */
2553                                                 }
2554 #ifndef WIN32
2555                                                 else if (setsockopt(conn->sock,
2556                                                                                         SOL_SOCKET, SO_KEEPALIVE,
2557                                                                                         (char *) &on, sizeof(on)) < 0)
2558                                                 {
2559                                                         appendPQExpBuffer(&conn->errorMessage,
2560                                                                                           libpq_gettext("setsockopt(%s) failed: %s\n"),
2561                                                                                           "SO_KEEPALIVE",
2562                                                                                           SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2563                                                         err = 1;
2564                                                 }
2565                                                 else if (!setKeepalivesIdle(conn)
2566                                                                  || !setKeepalivesInterval(conn)
2567                                                                  || !setKeepalivesCount(conn))
2568                                                         err = 1;
2569 #else                                                   /* WIN32 */
2570 #ifdef SIO_KEEPALIVE_VALS
2571                                                 else if (!setKeepalivesWin32(conn))
2572                                                         err = 1;
2573 #endif                                                  /* SIO_KEEPALIVE_VALS */
2574 #endif                                                  /* WIN32 */
2575                                                 else if (!setTCPUserTimeout(conn))
2576                                                         err = 1;
2577
2578                                                 if (err)
2579                                                 {
2580                                                         conn->try_next_addr = true;
2581                                                         goto keep_going;
2582                                                 }
2583                                         }
2584
2585                                         /*----------
2586                                          * We have three methods of blocking SIGPIPE during
2587                                          * send() calls to this socket:
2588                                          *
2589                                          *      - setsockopt(sock, SO_NOSIGPIPE)
2590                                          *      - send(sock, ..., MSG_NOSIGNAL)
2591                                          *      - setting the signal mask to SIG_IGN during send()
2592                                          *
2593                                          * The third method requires three syscalls per send,
2594                                          * so we prefer either of the first two, but they are
2595                                          * less portable.  The state is tracked in the following
2596                                          * members of PGconn:
2597                                          *
2598                                          * conn->sigpipe_so             - we have set up SO_NOSIGPIPE
2599                                          * conn->sigpipe_flag   - we're specifying MSG_NOSIGNAL
2600                                          *
2601                                          * If we can use SO_NOSIGPIPE, then set sigpipe_so here
2602                                          * and we're done.  Otherwise, set sigpipe_flag so that
2603                                          * we will try MSG_NOSIGNAL on sends.  If we get an error
2604                                          * with MSG_NOSIGNAL, we'll clear that flag and revert to
2605                                          * signal masking.
2606                                          *----------
2607                                          */
2608                                         conn->sigpipe_so = false;
2609 #ifdef MSG_NOSIGNAL
2610                                         conn->sigpipe_flag = true;
2611 #else
2612                                         conn->sigpipe_flag = false;
2613 #endif                                                  /* MSG_NOSIGNAL */
2614
2615 #ifdef SO_NOSIGPIPE
2616                                         optval = 1;
2617                                         if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
2618                                                                    (char *) &optval, sizeof(optval)) == 0)
2619                                         {
2620                                                 conn->sigpipe_so = true;
2621                                                 conn->sigpipe_flag = false;
2622                                         }
2623 #endif                                                  /* SO_NOSIGPIPE */
2624
2625                                         /*
2626                                          * Start/make connection.  This should not block, since we
2627                                          * are in nonblock mode.  If it does, well, too bad.
2628                                          */
2629                                         if (connect(conn->sock, addr_cur->ai_addr,
2630                                                                 addr_cur->ai_addrlen) < 0)
2631                                         {
2632                                                 if (SOCK_ERRNO == EINPROGRESS ||
2633 #ifdef WIN32
2634                                                         SOCK_ERRNO == EWOULDBLOCK ||
2635 #endif
2636                                                         SOCK_ERRNO == EINTR)
2637                                                 {
2638                                                         /*
2639                                                          * This is fine - we're in non-blocking mode, and
2640                                                          * the connection is in progress.  Tell caller to
2641                                                          * wait for write-ready on socket.
2642                                                          */
2643                                                         conn->status = CONNECTION_STARTED;
2644                                                         return PGRES_POLLING_WRITING;
2645                                                 }
2646                                                 /* otherwise, trouble */
2647                                         }
2648                                         else
2649                                         {
2650                                                 /*
2651                                                  * Hm, we're connected already --- seems the "nonblock
2652                                                  * connection" wasn't.  Advance the state machine and
2653                                                  * go do the next stuff.
2654                                                  */
2655                                                 conn->status = CONNECTION_STARTED;
2656                                                 goto keep_going;
2657                                         }
2658
2659                                         /*
2660                                          * This connection failed.  Add the error report to
2661                                          * conn->errorMessage, then try the next address if any.
2662                                          */
2663                                         connectFailureMessage(conn, SOCK_ERRNO);
2664                                         conn->try_next_addr = true;
2665                                         goto keep_going;
2666                                 }
2667                         }
2668
2669                 case CONNECTION_STARTED:
2670                         {
2671                                 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
2672
2673                                 /*
2674                                  * Write ready, since we've made it here, so the connection
2675                                  * has been made ... or has failed.
2676                                  */
2677
2678                                 /*
2679                                  * Now check (using getsockopt) that there is not an error
2680                                  * state waiting for us on the socket.
2681                                  */
2682
2683                                 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
2684                                                            (char *) &optval, &optlen) == -1)
2685                                 {
2686                                         appendPQExpBuffer(&conn->errorMessage,
2687                                                                           libpq_gettext("could not get socket error status: %s\n"),
2688                                                                           SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2689                                         goto error_return;
2690                                 }
2691                                 else if (optval != 0)
2692                                 {
2693                                         /*
2694                                          * When using a nonblocking connect, we will typically see
2695                                          * connect failures at this point, so provide a friendly
2696                                          * error message.
2697                                          */
2698                                         connectFailureMessage(conn, optval);
2699
2700                                         /*
2701                                          * Try the next address if any, just as in the case where
2702                                          * connect() returned failure immediately.
2703                                          */
2704                                         conn->try_next_addr = true;
2705                                         goto keep_going;
2706                                 }
2707
2708                                 /* Fill in the client address */
2709                                 conn->laddr.salen = sizeof(conn->laddr.addr);
2710                                 if (getsockname(conn->sock,
2711                                                                 (struct sockaddr *) &conn->laddr.addr,
2712                                                                 &conn->laddr.salen) < 0)
2713                                 {
2714                                         appendPQExpBuffer(&conn->errorMessage,
2715                                                                           libpq_gettext("could not get client address from socket: %s\n"),
2716                                                                           SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2717                                         goto error_return;
2718                                 }
2719
2720                                 /*
2721                                  * Make sure we can write before advancing to next step.
2722                                  */
2723                                 conn->status = CONNECTION_MADE;
2724                                 return PGRES_POLLING_WRITING;
2725                         }
2726
2727                 case CONNECTION_MADE:
2728                         {
2729                                 char       *startpacket;
2730                                 int                     packetlen;
2731
2732 #ifdef HAVE_UNIX_SOCKETS
2733
2734                                 /*
2735                                  * Implement requirepeer check, if requested and it's a
2736                                  * Unix-domain socket.
2737                                  */
2738                                 if (conn->requirepeer && conn->requirepeer[0] &&
2739                                         IS_AF_UNIX(conn->raddr.addr.ss_family))
2740                                 {
2741                                         char            pwdbuf[BUFSIZ];
2742                                         struct passwd pass_buf;
2743                                         struct passwd *pass;
2744                                         int                     passerr;
2745                                         uid_t           uid;
2746                                         gid_t           gid;
2747
2748                                         errno = 0;
2749                                         if (getpeereid(conn->sock, &uid, &gid) != 0)
2750                                         {
2751                                                 /*
2752                                                  * Provide special error message if getpeereid is a
2753                                                  * stub
2754                                                  */
2755                                                 if (errno == ENOSYS)
2756                                                         appendPQExpBufferStr(&conn->errorMessage,
2757                                                                                                  libpq_gettext("requirepeer parameter is not supported on this platform\n"));
2758                                                 else
2759                                                         appendPQExpBuffer(&conn->errorMessage,
2760                                                                                           libpq_gettext("could not get peer credentials: %s\n"),
2761                                                                                           strerror_r(errno, sebuf, sizeof(sebuf)));
2762                                                 goto error_return;
2763                                         }
2764
2765                                         passerr = pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
2766                                         if (pass == NULL)
2767                                         {
2768                                                 if (passerr != 0)
2769                                                         appendPQExpBuffer(&conn->errorMessage,
2770                                                                                           libpq_gettext("could not look up local user ID %d: %s\n"),
2771                                                                                           (int) uid,
2772                                                                                           strerror_r(passerr, sebuf, sizeof(sebuf)));
2773                                                 else
2774                                                         appendPQExpBuffer(&conn->errorMessage,
2775                                                                                           libpq_gettext("local user with ID %d does not exist\n"),
2776                                                                                           (int) uid);
2777                                                 goto error_return;
2778                                         }
2779
2780                                         if (strcmp(pass->pw_name, conn->requirepeer) != 0)
2781                                         {
2782                                                 appendPQExpBuffer(&conn->errorMessage,
2783                                                                                   libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
2784                                                                                   conn->requirepeer, pass->pw_name);
2785                                                 goto error_return;
2786                                         }
2787                                 }
2788 #endif                                                  /* HAVE_UNIX_SOCKETS */
2789
2790                                 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
2791                                 {
2792                                         /* Don't request SSL or GSSAPI over Unix sockets */
2793 #ifdef USE_SSL
2794                                         conn->allow_ssl_try = false;
2795 #endif
2796 #ifdef ENABLE_GSS
2797                                         conn->try_gss = false;
2798 #endif
2799                                 }
2800
2801 #ifdef ENABLE_GSS
2802
2803                                 /*
2804                                  * If GSSAPI is enabled and we have a credential cache, try to
2805                                  * set it up before sending startup messages.  If it's already
2806                                  * operating, don't try SSL and instead just build the startup
2807                                  * packet.
2808                                  */
2809                                 if (conn->try_gss && !conn->gctx)
2810                                         conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
2811                                 if (conn->try_gss && !conn->gctx)
2812                                 {
2813                                         ProtocolVersion pv = pg_hton32(NEGOTIATE_GSS_CODE);
2814
2815                                         if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2816                                         {
2817                                                 appendPQExpBuffer(&conn->errorMessage,
2818                                                                                   libpq_gettext("could not send GSSAPI negotiation packet: %s\n"),
2819                                                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2820                                                 goto error_return;
2821                                         }
2822
2823                                         /* Ok, wait for response */
2824                                         conn->status = CONNECTION_GSS_STARTUP;
2825                                         return PGRES_POLLING_READING;
2826                                 }
2827                                 else if (!conn->gctx && conn->gssencmode[0] == 'r')
2828                                 {
2829                                         appendPQExpBufferStr(&conn->errorMessage,
2830                                                                                  libpq_gettext("GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)\n"));
2831                                         goto error_return;
2832                                 }
2833 #endif
2834
2835 #ifdef USE_SSL
2836
2837                                 /*
2838                                  * If SSL is enabled and we haven't already got it running,
2839                                  * request it instead of sending the startup message.
2840                                  */
2841                                 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
2842                                         !conn->ssl_in_use)
2843                                 {
2844                                         ProtocolVersion pv;
2845
2846                                         /*
2847                                          * Send the SSL request packet.
2848                                          *
2849                                          * Theoretically, this could block, but it really
2850                                          * shouldn't since we only got here if the socket is
2851                                          * write-ready.
2852                                          */
2853                                         pv = pg_hton32(NEGOTIATE_SSL_CODE);
2854                                         if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
2855                                         {
2856                                                 appendPQExpBuffer(&conn->errorMessage,
2857                                                                                   libpq_gettext("could not send SSL negotiation packet: %s\n"),
2858                                                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2859                                                 goto error_return;
2860                                         }
2861                                         /* Ok, wait for response */
2862                                         conn->status = CONNECTION_SSL_STARTUP;
2863                                         return PGRES_POLLING_READING;
2864                                 }
2865 #endif                                                  /* USE_SSL */
2866
2867                                 /*
2868                                  * Build the startup packet.
2869                                  */
2870                                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2871                                         startpacket = pqBuildStartupPacket3(conn, &packetlen,
2872                                                                                                                 EnvironmentOptions);
2873                                 else
2874                                         startpacket = pqBuildStartupPacket2(conn, &packetlen,
2875                                                                                                                 EnvironmentOptions);
2876                                 if (!startpacket)
2877                                 {
2878                                         /*
2879                                          * will not appendbuffer here, since it's likely to also
2880                                          * run out of memory
2881                                          */
2882                                         printfPQExpBuffer(&conn->errorMessage,
2883                                                                           libpq_gettext("out of memory\n"));
2884                                         goto error_return;
2885                                 }
2886
2887                                 /*
2888                                  * Send the startup packet.
2889                                  *
2890                                  * Theoretically, this could block, but it really shouldn't
2891                                  * since we only got here if the socket is write-ready.
2892                                  */
2893                                 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2894                                 {
2895                                         appendPQExpBuffer(&conn->errorMessage,
2896                                                                           libpq_gettext("could not send startup packet: %s\n"),
2897                                                                           SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2898                                         free(startpacket);
2899                                         goto error_return;
2900                                 }
2901
2902                                 free(startpacket);
2903
2904                                 conn->status = CONNECTION_AWAITING_RESPONSE;
2905                                 return PGRES_POLLING_READING;
2906                         }
2907
2908                         /*
2909                          * Handle SSL negotiation: wait for postmaster messages and
2910                          * respond as necessary.
2911                          */
2912                 case CONNECTION_SSL_STARTUP:
2913                         {
2914 #ifdef USE_SSL
2915                                 PostgresPollingStatusType pollres;
2916
2917                                 /*
2918                                  * On first time through, get the postmaster's response to our
2919                                  * SSL negotiation packet.
2920                                  */
2921                                 if (!conn->ssl_in_use)
2922                                 {
2923                                         /*
2924                                          * We use pqReadData here since it has the logic to
2925                                          * distinguish no-data-yet from connection closure. Since
2926                                          * conn->ssl isn't set, a plain recv() will occur.
2927                                          */
2928                                         char            SSLok;
2929                                         int                     rdresult;
2930
2931                                         rdresult = pqReadData(conn);
2932                                         if (rdresult < 0)
2933                                         {
2934                                                 /* errorMessage is already filled in */
2935                                                 goto error_return;
2936                                         }
2937                                         if (rdresult == 0)
2938                                         {
2939                                                 /* caller failed to wait for data */
2940                                                 return PGRES_POLLING_READING;
2941                                         }
2942                                         if (pqGetc(&SSLok, conn) < 0)
2943                                         {
2944                                                 /* should not happen really */
2945                                                 return PGRES_POLLING_READING;
2946                                         }
2947                                         if (SSLok == 'S')
2948                                         {
2949                                                 /* mark byte consumed */
2950                                                 conn->inStart = conn->inCursor;
2951                                                 /* Set up global SSL state if required */
2952                                                 if (pqsecure_initialize(conn) != 0)
2953                                                         goto error_return;
2954                                         }
2955                                         else if (SSLok == 'N')
2956                                         {
2957                                                 /* mark byte consumed */
2958                                                 conn->inStart = conn->inCursor;
2959                                                 /* OK to do without SSL? */
2960                                                 if (conn->sslmode[0] == 'r' ||  /* "require" */
2961                                                         conn->sslmode[0] == 'v')        /* "verify-ca" or
2962                                                                                                                  * "verify-full" */
2963                                                 {
2964                                                         /* Require SSL, but server does not want it */
2965                                                         appendPQExpBufferStr(&conn->errorMessage,
2966                                                                                                  libpq_gettext("server does not support SSL, but SSL was required\n"));
2967                                                         goto error_return;
2968                                                 }
2969                                                 /* Otherwise, proceed with normal startup */
2970                                                 conn->allow_ssl_try = false;
2971                                                 conn->status = CONNECTION_MADE;
2972                                                 return PGRES_POLLING_WRITING;
2973                                         }
2974                                         else if (SSLok == 'E')
2975                                         {
2976                                                 /*
2977                                                  * Server failure of some sort, such as failure to
2978                                                  * fork a backend process.  We need to process and
2979                                                  * report the error message, which might be formatted
2980                                                  * according to either protocol 2 or protocol 3.
2981                                                  * Rather than duplicate the code for that, we flip
2982                                                  * into AWAITING_RESPONSE state and let the code there
2983                                                  * deal with it.  Note we have *not* consumed the "E"
2984                                                  * byte here.
2985                                                  */
2986                                                 conn->status = CONNECTION_AWAITING_RESPONSE;
2987                                                 goto keep_going;
2988                                         }
2989                                         else
2990                                         {
2991                                                 appendPQExpBuffer(&conn->errorMessage,
2992                                                                                   libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2993                                                                                   SSLok);
2994                                                 goto error_return;
2995                                         }
2996                                 }
2997
2998                                 /*
2999                                  * Begin or continue the SSL negotiation process.
3000                                  */
3001                                 pollres = pqsecure_open_client(conn);
3002                                 if (pollres == PGRES_POLLING_OK)
3003                                 {
3004                                         /* SSL handshake done, ready to send startup packet */
3005                                         conn->status = CONNECTION_MADE;
3006                                         return PGRES_POLLING_WRITING;
3007                                 }
3008                                 if (pollres == PGRES_POLLING_FAILED)
3009                                 {
3010                                         /*
3011                                          * Failed ... if sslmode is "prefer" then do a non-SSL
3012                                          * retry
3013                                          */
3014                                         if (conn->sslmode[0] == 'p' /* "prefer" */
3015                                                 && conn->allow_ssl_try  /* redundant? */
3016                                                 && !conn->wait_ssl_try) /* redundant? */
3017                                         {
3018                                                 /* only retry once */
3019                                                 conn->allow_ssl_try = false;
3020                                                 need_new_connection = true;
3021                                                 goto keep_going;
3022                                         }
3023                                         /* Else it's a hard failure */
3024                                         goto error_return;
3025                                 }
3026                                 /* Else, return POLLING_READING or POLLING_WRITING status */
3027                                 return pollres;
3028 #else                                                   /* !USE_SSL */
3029                                 /* can't get here */
3030                                 goto error_return;
3031 #endif                                                  /* USE_SSL */
3032                         }
3033
3034                 case CONNECTION_GSS_STARTUP:
3035                         {
3036 #ifdef ENABLE_GSS
3037                                 PostgresPollingStatusType pollres;
3038
3039                                 /*
3040                                  * If we haven't yet, get the postmaster's response to our
3041                                  * negotiation packet
3042                                  */
3043                                 if (conn->try_gss && !conn->gctx)
3044                                 {
3045                                         char            gss_ok;
3046                                         int                     rdresult = pqReadData(conn);
3047
3048                                         if (rdresult < 0)
3049                                                 /* pqReadData fills in error message */
3050                                                 goto error_return;
3051                                         else if (rdresult == 0)
3052                                                 /* caller failed to wait for data */
3053                                                 return PGRES_POLLING_READING;
3054                                         if (pqGetc(&gss_ok, conn) < 0)
3055                                                 /* shouldn't happen... */
3056                                                 return PGRES_POLLING_READING;
3057
3058                                         if (gss_ok == 'E')
3059                                         {
3060                                                 /*
3061                                                  * Server failure of some sort.  Assume it's a
3062                                                  * protocol version support failure, and let's see if
3063                                                  * we can't recover (if it's not, we'll get a better
3064                                                  * error message on retry).  Server gets fussy if we
3065                                                  * don't hang up the socket, though.
3066                                                  */
3067                                                 conn->try_gss = false;
3068                                                 pqDropConnection(conn, true);
3069                                                 conn->status = CONNECTION_NEEDED;
3070                                                 goto keep_going;
3071                                         }
3072
3073                                         /* mark byte consumed */
3074                                         conn->inStart = conn->inCursor;
3075
3076                                         if (gss_ok == 'N')
3077                                         {
3078                                                 /* Server doesn't want GSSAPI; fall back if we can */
3079                                                 if (conn->gssencmode[0] == 'r')
3080                                                 {
3081                                                         appendPQExpBufferStr(&conn->errorMessage,
3082                                                                                                  libpq_gettext("server doesn't support GSSAPI encryption, but it was required\n"));
3083                                                         goto error_return;
3084                                                 }
3085
3086                                                 conn->try_gss = false;
3087                                                 conn->status = CONNECTION_MADE;
3088                                                 return PGRES_POLLING_WRITING;
3089                                         }
3090                                         else if (gss_ok != 'G')
3091                                         {
3092                                                 appendPQExpBuffer(&conn->errorMessage,
3093                                                                                   libpq_gettext("received invalid response to GSSAPI negotiation: %c\n"),
3094                                                                                   gss_ok);
3095                                                 goto error_return;
3096                                         }
3097                                 }
3098
3099                                 /* Begin or continue GSSAPI negotiation */
3100                                 pollres = pqsecure_open_gss(conn);
3101                                 if (pollres == PGRES_POLLING_OK)
3102                                 {
3103                                         /* All set for startup packet */
3104                                         conn->status = CONNECTION_MADE;
3105                                         return PGRES_POLLING_WRITING;
3106                                 }
3107                                 else if (pollres == PGRES_POLLING_FAILED &&
3108                                                  conn->gssencmode[0] == 'p')
3109                                 {
3110                                         /*
3111                                          * We failed, but we can retry on "prefer".  Have to drop
3112                                          * the current connection to do so, though.
3113                                          */
3114                                         conn->try_gss = false;
3115                                         pqDropConnection(conn, true);
3116                                         conn->status = CONNECTION_NEEDED;
3117                                         goto keep_going;
3118                                 }
3119                                 return pollres;
3120 #else                                                   /* !ENABLE_GSS */
3121                                 /* unreachable */
3122                                 goto error_return;
3123 #endif                                                  /* ENABLE_GSS */
3124                         }
3125
3126                         /*
3127                          * Handle authentication exchange: wait for postmaster messages
3128                          * and respond as necessary.
3129                          */
3130                 case CONNECTION_AWAITING_RESPONSE:
3131                         {
3132                                 char            beresp;
3133                                 int                     msgLength;
3134                                 int                     avail;
3135                                 AuthRequest areq;
3136                                 int                     res;
3137
3138                                 /*
3139                                  * Scan the message from current point (note that if we find
3140                                  * the message is incomplete, we will return without advancing
3141                                  * inStart, and resume here next time).
3142                                  */
3143                                 conn->inCursor = conn->inStart;
3144
3145                                 /* Read type byte */
3146                                 if (pqGetc(&beresp, conn))
3147                                 {
3148                                         /* We'll come back when there is more data */
3149                                         return PGRES_POLLING_READING;
3150                                 }
3151
3152                                 /*
3153                                  * Validate message type: we expect only an authentication
3154                                  * request or an error here.  Anything else probably means
3155                                  * it's not Postgres on the other end at all.
3156                                  */
3157                                 if (!(beresp == 'R' || beresp == 'E'))
3158                                 {
3159                                         appendPQExpBuffer(&conn->errorMessage,
3160                                                                           libpq_gettext(
3161                                                                                                         "expected authentication request from "
3162                                                                                                         "server, but received %c\n"),
3163                                                                           beresp);
3164                                         goto error_return;
3165                                 }
3166
3167                                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3168                                 {
3169                                         /* Read message length word */
3170                                         if (pqGetInt(&msgLength, 4, conn))
3171                                         {
3172                                                 /* We'll come back when there is more data */
3173                                                 return PGRES_POLLING_READING;
3174                                         }
3175                                 }
3176                                 else
3177                                 {
3178                                         /* Set phony message length to disable checks below */
3179                                         msgLength = 8;
3180                                 }
3181
3182                                 /*
3183                                  * Try to validate message length before using it.
3184                                  * Authentication requests can't be very large, although GSS
3185                                  * auth requests may not be that small.  Errors can be a
3186                                  * little larger, but not huge.  If we see a large apparent
3187                                  * length in an error, it means we're really talking to a
3188                                  * pre-3.0-protocol server; cope.
3189                                  */
3190                                 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
3191                                 {
3192                                         appendPQExpBuffer(&conn->errorMessage,
3193                                                                           libpq_gettext(
3194                                                                                                         "expected authentication request from "
3195                                                                                                         "server, but received %c\n"),
3196                                                                           beresp);
3197                                         goto error_return;
3198                                 }
3199
3200                                 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
3201                                 {
3202                                         /* Handle error from a pre-3.0 server */
3203                                         conn->inCursor = conn->inStart + 1; /* reread data */
3204                                         if (pqGets_append(&conn->errorMessage, conn))
3205                                         {
3206                                                 /* We'll come back when there is more data */
3207                                                 return PGRES_POLLING_READING;
3208                                         }
3209                                         /* OK, we read the message; mark data consumed */
3210                                         conn->inStart = conn->inCursor;
3211
3212                                         /*
3213                                          * The postmaster typically won't end its message with a
3214                                          * newline, so add one to conform to libpq conventions.
3215                                          */
3216                                         appendPQExpBufferChar(&conn->errorMessage, '\n');
3217
3218                                         /*
3219                                          * If we tried to open the connection in 3.0 protocol,
3220                                          * fall back to 2.0 protocol.
3221                                          */
3222                                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3223                                         {
3224                                                 conn->pversion = PG_PROTOCOL(2, 0);
3225                                                 need_new_connection = true;
3226                                                 goto keep_going;
3227                                         }
3228
3229                                         goto error_return;
3230                                 }
3231
3232                                 /*
3233                                  * Can't process if message body isn't all here yet.
3234                                  *
3235                                  * (In protocol 2.0 case, we are assuming messages carry at
3236                                  * least 4 bytes of data.)
3237                                  */
3238                                 msgLength -= 4;
3239                                 avail = conn->inEnd - conn->inCursor;
3240                                 if (avail < msgLength)
3241                                 {
3242                                         /*
3243                                          * Before returning, try to enlarge the input buffer if
3244                                          * needed to hold the whole message; see notes in
3245                                          * pqParseInput3.
3246                                          */
3247                                         if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3248                                                                                          conn))
3249                                                 goto error_return;
3250                                         /* We'll come back when there is more data */
3251                                         return PGRES_POLLING_READING;
3252                                 }
3253
3254                                 /* Handle errors. */
3255                                 if (beresp == 'E')
3256                                 {
3257                                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
3258                                         {
3259                                                 if (pqGetErrorNotice3(conn, true))
3260                                                 {
3261                                                         /* We'll come back when there is more data */
3262                                                         return PGRES_POLLING_READING;
3263                                                 }
3264                                         }
3265                                         else
3266                                         {
3267                                                 if (pqGets_append(&conn->errorMessage, conn))
3268                                                 {
3269                                                         /* We'll come back when there is more data */
3270                                                         return PGRES_POLLING_READING;
3271                                                 }
3272                                         }
3273                                         /* OK, we read the message; mark data consumed */
3274                                         conn->inStart = conn->inCursor;
3275
3276                                         /* Check to see if we should mention pgpassfile */
3277                                         pgpassfileWarning(conn);
3278
3279 #ifdef ENABLE_GSS
3280
3281                                         /*
3282                                          * If gssencmode is "prefer" and we're using GSSAPI, retry
3283                                          * without it.
3284                                          */
3285                                         if (conn->gssenc && conn->gssencmode[0] == 'p')
3286                                         {
3287                                                 OM_uint32       minor;
3288
3289                                                 /* postmaster expects us to drop the connection */
3290                                                 conn->try_gss = false;
3291                                                 conn->gssenc = false;
3292                                                 gss_delete_sec_context(&minor, &conn->gctx, NULL);
3293                                                 pqDropConnection(conn, true);
3294                                                 conn->status = CONNECTION_NEEDED;
3295                                                 goto keep_going;
3296                                         }
3297 #endif
3298
3299 #ifdef USE_SSL
3300
3301                                         /*
3302                                          * if sslmode is "allow" and we haven't tried an SSL
3303                                          * connection already, then retry with an SSL connection
3304                                          */
3305                                         if (conn->sslmode[0] == 'a' /* "allow" */
3306                                                 && !conn->ssl_in_use
3307                                                 && conn->allow_ssl_try
3308                                                 && conn->wait_ssl_try)
3309                                         {
3310                                                 /* only retry once */
3311                                                 conn->wait_ssl_try = false;
3312                                                 need_new_connection = true;
3313                                                 goto keep_going;
3314                                         }
3315
3316                                         /*
3317                                          * if sslmode is "prefer" and we're in an SSL connection,
3318                                          * then do a non-SSL retry
3319                                          */
3320                                         if (conn->sslmode[0] == 'p' /* "prefer" */
3321                                                 && conn->ssl_in_use
3322                                                 && conn->allow_ssl_try  /* redundant? */
3323                                                 && !conn->wait_ssl_try) /* redundant? */
3324                                         {
3325                                                 /* only retry once */
3326                                                 conn->allow_ssl_try = false;
3327                                                 need_new_connection = true;
3328                                                 goto keep_going;
3329                                         }
3330 #endif
3331
3332                                         goto error_return;
3333                                 }
3334
3335                                 /* It is an authentication request. */
3336                                 conn->auth_req_received = true;
3337
3338                                 /* Get the type of request. */
3339                                 if (pqGetInt((int *) &areq, 4, conn))
3340                                 {
3341                                         /* We'll come back when there are more data */
3342                                         return PGRES_POLLING_READING;
3343                                 }
3344                                 msgLength -= 4;
3345
3346                                 /*
3347                                  * Ensure the password salt is in the input buffer, if it's an
3348                                  * MD5 request.  All the other authentication methods that
3349                                  * contain extra data in the authentication request are only
3350                                  * supported in protocol version 3, in which case we already
3351                                  * read the whole message above.
3352                                  */
3353                                 if (areq == AUTH_REQ_MD5 && PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3354                                 {
3355                                         msgLength += 4;
3356
3357                                         avail = conn->inEnd - conn->inCursor;
3358                                         if (avail < 4)
3359                                         {
3360                                                 /*
3361                                                  * Before returning, try to enlarge the input buffer
3362                                                  * if needed to hold the whole message; see notes in
3363                                                  * pqParseInput3.
3364                                                  */
3365                                                 if (pqCheckInBufferSpace(conn->inCursor + (size_t) 4,
3366                                                                                                  conn))
3367                                                         goto error_return;
3368                                                 /* We'll come back when there is more data */
3369                                                 return PGRES_POLLING_READING;
3370                                         }
3371                                 }
3372
3373                                 /*
3374                                  * Process the rest of the authentication request message, and
3375                                  * respond to it if necessary.
3376                                  *
3377                                  * Note that conn->pghost must be non-NULL if we are going to
3378                                  * avoid the Kerberos code doing a hostname look-up.
3379                                  */
3380                                 res = pg_fe_sendauth(areq, msgLength, conn);
3381                                 conn->errorMessage.len = strlen(conn->errorMessage.data);
3382
3383                                 /* OK, we have processed the message; mark data consumed */
3384                                 conn->inStart = conn->inCursor;
3385
3386                                 if (res != STATUS_OK)
3387                                         goto error_return;
3388
3389                                 /*
3390                                  * Just make sure that any data sent by pg_fe_sendauth is
3391                                  * flushed out.  Although this theoretically could block, it
3392                                  * really shouldn't since we don't send large auth responses.
3393                                  */
3394                                 if (pqFlush(conn))
3395                                         goto error_return;
3396
3397                                 if (areq == AUTH_REQ_OK)
3398                                 {
3399                                         /* We are done with authentication exchange */
3400                                         conn->status = CONNECTION_AUTH_OK;
3401
3402                                         /*
3403                                          * Set asyncStatus so that PQgetResult will think that
3404                                          * what comes back next is the result of a query.  See
3405                                          * below.
3406                                          */
3407                                         conn->asyncStatus = PGASYNC_BUSY;
3408                                 }
3409
3410                                 /* Look to see if we have more data yet. */
3411                                 goto keep_going;
3412                         }
3413
3414                 case CONNECTION_AUTH_OK:
3415                         {
3416                                 /*
3417                                  * Now we expect to hear from the backend. A ReadyForQuery
3418                                  * message indicates that startup is successful, but we might
3419                                  * also get an Error message indicating failure. (Notice
3420                                  * messages indicating nonfatal warnings are also allowed by
3421                                  * the protocol, as are ParameterStatus and BackendKeyData
3422                                  * messages.) Easiest way to handle this is to let
3423                                  * PQgetResult() read the messages. We just have to fake it
3424                                  * out about the state of the connection, by setting
3425                                  * asyncStatus = PGASYNC_BUSY (done above).
3426                                  */
3427
3428                                 if (PQisBusy(conn))
3429                                         return PGRES_POLLING_READING;
3430
3431                                 res = PQgetResult(conn);
3432
3433                                 /*
3434                                  * NULL return indicating we have gone to IDLE state is
3435                                  * expected
3436                                  */
3437                                 if (res)
3438                                 {
3439                                         if (res->resultStatus != PGRES_FATAL_ERROR)
3440                                                 appendPQExpBufferStr(&conn->errorMessage,
3441                                                                                          libpq_gettext("unexpected message from server during startup\n"));
3442                                         else if (conn->send_appname &&
3443                                                          (conn->appname || conn->fbappname))
3444                                         {
3445                                                 /*
3446                                                  * If we tried to send application_name, check to see
3447                                                  * if the error is about that --- pre-9.0 servers will
3448                                                  * reject it at this stage of the process.  If so,
3449                                                  * close the connection and retry without sending
3450                                                  * application_name.  We could possibly get a false
3451                                                  * SQLSTATE match here and retry uselessly, but there
3452                                                  * seems no great harm in that; we'll just get the
3453                                                  * same error again if it's unrelated.
3454                                                  */
3455                                                 const char *sqlstate;
3456
3457                                                 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
3458                                                 if (sqlstate &&
3459                                                         strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3460                                                 {
3461                                                         PQclear(res);
3462                                                         conn->send_appname = false;
3463                                                         need_new_connection = true;
3464                                                         goto keep_going;
3465                                                 }
3466                                         }
3467
3468                                         /*
3469                                          * if the resultStatus is FATAL, then conn->errorMessage
3470                                          * already has a copy of the error; needn't copy it back.
3471                                          * But add a newline if it's not there already, since
3472                                          * postmaster error messages may not have one.
3473                                          */
3474                                         if (conn->errorMessage.len <= 0 ||
3475                                                 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3476                                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
3477                                         PQclear(res);
3478                                         goto error_return;
3479                                 }
3480
3481                                 /* Fire up post-connection housekeeping if needed */
3482                                 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
3483                                 {
3484                                         conn->status = CONNECTION_SETENV;
3485                                         conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
3486                                         conn->next_eo = EnvironmentOptions;
3487                                         return PGRES_POLLING_WRITING;
3488                                 }
3489
3490                                 /* Almost there now ... */
3491                                 conn->status = CONNECTION_CHECK_TARGET;
3492                                 goto keep_going;
3493                         }
3494
3495                 case CONNECTION_CHECK_TARGET:
3496                         {
3497                                 /*
3498                                  * If a read-write connection is required, see if we have one.
3499                                  *
3500                                  * Servers before 7.4 lack the transaction_read_only GUC, but
3501                                  * by the same token they don't have any read-only mode, so we
3502                                  * may just skip the test in that case.
3503                                  */
3504                                 if (conn->sversion >= 70400 &&
3505                                         conn->target_session_attrs != NULL &&
3506                                         strcmp(conn->target_session_attrs, "read-write") == 0)
3507                                 {
3508                                         /*
3509                                          * Save existing error messages across the PQsendQuery
3510                                          * attempt.  This is necessary because PQsendQuery is
3511                                          * going to reset conn->errorMessage, so we would lose
3512                                          * error messages related to previous hosts we have tried
3513                                          * and failed to connect to.
3514                                          */
3515                                         if (!saveErrorMessage(conn, &savedMessage))
3516                                                 goto error_return;
3517
3518                                         conn->status = CONNECTION_OK;
3519                                         if (!PQsendQuery(conn,
3520                                                                          "SHOW transaction_read_only"))
3521                                         {
3522                                                 restoreErrorMessage(conn, &savedMessage);
3523                                                 goto error_return;
3524                                         }
3525                                         conn->status = CONNECTION_CHECK_WRITABLE;
3526                                         restoreErrorMessage(conn, &savedMessage);
3527                                         return PGRES_POLLING_READING;
3528                                 }
3529
3530                                 /* We can release the address list now. */
3531                                 release_conn_addrinfo(conn);
3532
3533                                 /* We are open for business! */
3534                                 conn->status = CONNECTION_OK;
3535                                 return PGRES_POLLING_OK;
3536                         }
3537
3538                 case CONNECTION_SETENV:
3539                         {
3540                                 /*
3541                                  * Do post-connection housekeeping (only needed in protocol
3542                                  * 2.0).
3543                                  *
3544                                  * We pretend that the connection is OK for the duration of
3545                                  * these queries.
3546                                  */
3547                                 conn->status = CONNECTION_OK;
3548
3549                                 switch (pqSetenvPoll(conn))
3550                                 {
3551                                         case PGRES_POLLING_OK:  /* Success */
3552                                                 break;
3553
3554                                         case PGRES_POLLING_READING: /* Still going */
3555                                                 conn->status = CONNECTION_SETENV;
3556                                                 return PGRES_POLLING_READING;
3557
3558                                         case PGRES_POLLING_WRITING: /* Still going */
3559                                                 conn->status = CONNECTION_SETENV;
3560                                                 return PGRES_POLLING_WRITING;
3561
3562                                         default:
3563                                                 goto error_return;
3564                                 }
3565
3566                                 /* Almost there now ... */
3567                                 conn->status = CONNECTION_CHECK_TARGET;
3568                                 goto keep_going;
3569                         }
3570
3571                 case CONNECTION_CONSUME:
3572                         {
3573                                 conn->status = CONNECTION_OK;
3574                                 if (!PQconsumeInput(conn))
3575                                         goto error_return;
3576
3577                                 if (PQisBusy(conn))
3578                                 {
3579                                         conn->status = CONNECTION_CONSUME;
3580                                         return PGRES_POLLING_READING;
3581                                 }
3582
3583                                 /*
3584                                  * Call PQgetResult() again to consume NULL result.
3585                                  */
3586                                 res = PQgetResult(conn);
3587                                 if (res != NULL)
3588                                 {
3589                                         PQclear(res);
3590                                         conn->status = CONNECTION_CONSUME;
3591                                         goto keep_going;
3592                                 }
3593
3594                                 /* We can release the address list now. */
3595                                 release_conn_addrinfo(conn);
3596
3597                                 /* We are open for business! */
3598                                 conn->status = CONNECTION_OK;
3599                                 return PGRES_POLLING_OK;
3600                         }
3601                 case CONNECTION_CHECK_WRITABLE:
3602                         {
3603                                 const char *displayed_host;
3604                                 const char *displayed_port;
3605
3606                                 if (!saveErrorMessage(conn, &savedMessage))
3607                                         goto error_return;
3608
3609                                 conn->status = CONNECTION_OK;
3610                                 if (!PQconsumeInput(conn))
3611                                 {
3612                                         restoreErrorMessage(conn, &savedMessage);
3613                                         goto error_return;
3614                                 }
3615
3616                                 if (PQisBusy(conn))
3617                                 {
3618                                         conn->status = CONNECTION_CHECK_WRITABLE;
3619                                         restoreErrorMessage(conn, &savedMessage);
3620                                         return PGRES_POLLING_READING;
3621                                 }
3622
3623                                 res = PQgetResult(conn);
3624                                 if (res && (PQresultStatus(res) == PGRES_TUPLES_OK) &&
3625                                         PQntuples(res) == 1)
3626                                 {
3627                                         char       *val;
3628
3629                                         val = PQgetvalue(res, 0, 0);
3630                                         if (strncmp(val, "on", 2) == 0)
3631                                         {
3632                                                 /* Not writable; fail this connection. */
3633                                                 PQclear(res);
3634                                                 restoreErrorMessage(conn, &savedMessage);
3635
3636                                                 /* Append error report to conn->errorMessage. */
3637                                                 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3638                                                         displayed_host = conn->connhost[conn->whichhost].hostaddr;
3639                                                 else
3640                                                         displayed_host = conn->connhost[conn->whichhost].host;
3641                                                 displayed_port = conn->connhost[conn->whichhost].port;
3642                                                 if (displayed_port == NULL || displayed_port[0] == '\0')
3643                                                         displayed_port = DEF_PGPORT_STR;
3644
3645                                                 appendPQExpBuffer(&conn->errorMessage,
3646                                                                                   libpq_gettext("could not make a writable "
3647                                                                                                                 "connection to server "
3648                                                                                                                 "\"%s:%s\"\n"),
3649                                                                                   displayed_host, displayed_port);
3650
3651                                                 /* Close connection politely. */
3652                                                 conn->status = CONNECTION_OK;
3653                                                 sendTerminateConn(conn);
3654
3655                                                 /*
3656                                                  * Try next host if any, but we don't want to consider
3657                                                  * additional addresses for this host.
3658                                                  */
3659                                                 conn->try_next_host = true;
3660                                                 goto keep_going;
3661                                         }
3662
3663                                         /* Session is read-write, so we're good. */
3664                                         PQclear(res);
3665                                         termPQExpBuffer(&savedMessage);
3666
3667                                         /*
3668                                          * Finish reading any remaining messages before being
3669                                          * considered as ready.
3670                                          */
3671                                         conn->status = CONNECTION_CONSUME;
3672                                         goto keep_going;
3673                                 }
3674
3675                                 /*
3676                                  * Something went wrong with "SHOW transaction_read_only". We
3677                                  * should try next addresses.
3678                                  */
3679                                 if (res)
3680                                         PQclear(res);
3681                                 restoreErrorMessage(conn, &savedMessage);
3682
3683                                 /* Append error report to conn->errorMessage. */
3684                                 if (conn->connhost[conn->whichhost].type == CHT_HOST_ADDRESS)
3685                                         displayed_host = conn->connhost[conn->whichhost].hostaddr;
3686                                 else
3687                                         displayed_host = conn->connhost[conn->whichhost].host;
3688                                 displayed_port = conn->connhost[conn->whichhost].port;
3689                                 if (displayed_port == NULL || displayed_port[0] == '\0')
3690                                         displayed_port = DEF_PGPORT_STR;
3691                                 appendPQExpBuffer(&conn->errorMessage,
3692                                                                   libpq_gettext("test \"SHOW transaction_read_only\" failed "
3693                                                                                                 "on server \"%s:%s\"\n"),
3694                                                                   displayed_host, displayed_port);
3695
3696                                 /* Close connection politely. */
3697                                 conn->status = CONNECTION_OK;
3698                                 sendTerminateConn(conn);
3699
3700                                 /* Try next address */
3701                                 conn->try_next_addr = true;
3702                                 goto keep_going;
3703                         }
3704
3705                 default:
3706                         appendPQExpBuffer(&conn->errorMessage,
3707                                                           libpq_gettext("invalid connection state %d, "
3708                                                                                         "probably indicative of memory corruption\n"),
3709                                                           conn->status);
3710                         goto error_return;
3711         }
3712
3713         /* Unreachable */
3714
3715 error_return:
3716
3717         /*
3718          * We used to close the socket at this point, but that makes it awkward
3719          * for those above us if they wish to remove this socket from their own
3720          * records (an fd_set for example).  We'll just have this socket closed
3721          * when PQfinish is called (which is compulsory even after an error, since
3722          * the connection structure must be freed).
3723          */
3724         conn->status = CONNECTION_BAD;
3725         return PGRES_POLLING_FAILED;
3726 }
3727
3728
3729 /*
3730  * internal_ping
3731  *              Determine if a server is running and if we can connect to it.
3732  *
3733  * The argument is a connection that's been started, but not completed.
3734  */
3735 static PGPing
3736 internal_ping(PGconn *conn)
3737 {
3738         /* Say "no attempt" if we never got to PQconnectPoll */
3739         if (!conn || !conn->options_valid)
3740                 return PQPING_NO_ATTEMPT;
3741
3742         /* Attempt to complete the connection */
3743         if (conn->status != CONNECTION_BAD)
3744                 (void) connectDBComplete(conn);
3745
3746         /* Definitely OK if we succeeded */
3747         if (conn->status != CONNECTION_BAD)
3748                 return PQPING_OK;
3749
3750         /*
3751          * Here begins the interesting part of "ping": determine the cause of the
3752          * failure in sufficient detail to decide what to return.  We do not want
3753          * to report that the server is not up just because we didn't have a valid
3754          * password, for example.  In fact, any sort of authentication request
3755          * implies the server is up.  (We need this check since the libpq side of
3756          * things might have pulled the plug on the connection before getting an
3757          * error as such from the postmaster.)
3758          */
3759         if (conn->auth_req_received)
3760                 return PQPING_OK;
3761
3762         /*
3763          * If we failed to get any ERROR response from the postmaster, report
3764          * PQPING_NO_RESPONSE.  This result could be somewhat misleading for a
3765          * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
3766          * out of support.  Another corner case where the server could return a
3767          * failure without a SQLSTATE is fork failure, but PQPING_NO_RESPONSE
3768          * isn't totally unreasonable for that anyway.  We expect that every other
3769          * failure case in a modern server will produce a report with a SQLSTATE.
3770          *
3771          * NOTE: whenever we get around to making libpq generate SQLSTATEs for
3772          * client-side errors, we should either not store those into
3773          * last_sqlstate, or add an extra flag so we can tell client-side errors
3774          * apart from server-side ones.
3775          */
3776         if (strlen(conn->last_sqlstate) != 5)
3777                 return PQPING_NO_RESPONSE;
3778
3779         /*
3780          * Report PQPING_REJECT if server says it's not accepting connections. (We
3781          * distinguish this case mainly for the convenience of pg_ctl.)
3782          */
3783         if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
3784                 return PQPING_REJECT;
3785
3786         /*
3787          * Any other SQLSTATE can be taken to indicate that the server is up.
3788          * Presumably it didn't like our username, password, or database name; or
3789          * perhaps it had some transient failure, but that should not be taken as
3790          * meaning "it's down".
3791          */
3792         return PQPING_OK;
3793 }
3794
3795
3796 /*
3797  * makeEmptyPGconn
3798  *       - create a PGconn data structure with (as yet) no interesting data
3799  */
3800 static PGconn *
3801 makeEmptyPGconn(void)
3802 {
3803         PGconn     *conn;
3804
3805 #ifdef WIN32
3806
3807         /*
3808          * Make sure socket support is up and running.
3809          */
3810         WSADATA         wsaData;
3811
3812         if (WSAStartup(MAKEWORD(1, 1), &wsaData))
3813                 return NULL;
3814         WSASetLastError(0);
3815 #endif
3816
3817         conn = (PGconn *) malloc(sizeof(PGconn));
3818         if (conn == NULL)
3819         {
3820 #ifdef WIN32
3821                 WSACleanup();
3822 #endif
3823                 return conn;
3824         }
3825
3826         /* Zero all pointers and booleans */
3827         MemSet(conn, 0, sizeof(PGconn));
3828
3829         /* install default notice hooks */
3830         conn->noticeHooks.noticeRec = defaultNoticeReceiver;
3831         conn->noticeHooks.noticeProc = defaultNoticeProcessor;
3832
3833         conn->status = CONNECTION_BAD;
3834         conn->asyncStatus = PGASYNC_IDLE;
3835         conn->xactStatus = PQTRANS_IDLE;
3836         conn->options_valid = false;
3837         conn->nonblocking = false;
3838         conn->setenv_state = SETENV_STATE_IDLE;
3839         conn->client_encoding = PG_SQL_ASCII;
3840         conn->std_strings = false;      /* unless server says differently */
3841         conn->verbosity = PQERRORS_DEFAULT;
3842         conn->show_context = PQSHOW_CONTEXT_ERRORS;
3843         conn->sock = PGINVALID_SOCKET;
3844 #ifdef ENABLE_GSS
3845         conn->try_gss = true;
3846 #endif
3847
3848         /*
3849          * We try to send at least 8K at a time, which is the usual size of pipe
3850          * buffers on Unix systems.  That way, when we are sending a large amount
3851          * of data, we avoid incurring extra kernel context swaps for partial
3852          * bufferloads.  The output buffer is initially made 16K in size, and we
3853          * try to dump it after accumulating 8K.
3854          *
3855          * With the same goal of minimizing context swaps, the input buffer will
3856          * be enlarged anytime it has less than 8K free, so we initially allocate
3857          * twice that.
3858          */
3859         conn->inBufSize = 16 * 1024;
3860         conn->inBuffer = (char *) malloc(conn->inBufSize);
3861         conn->outBufSize = 16 * 1024;
3862         conn->outBuffer = (char *) malloc(conn->outBufSize);
3863         conn->rowBufLen = 32;
3864         conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
3865         initPQExpBuffer(&conn->errorMessage);
3866         initPQExpBuffer(&conn->workBuffer);
3867
3868         if (conn->inBuffer == NULL ||
3869                 conn->outBuffer == NULL ||
3870                 conn->rowBuf == NULL ||
3871                 PQExpBufferBroken(&conn->errorMessage) ||
3872                 PQExpBufferBroken(&conn->workBuffer))
3873         {
3874                 /* out of memory already :-( */
3875                 freePGconn(conn);
3876                 conn = NULL;
3877         }
3878
3879         return conn;
3880 }
3881
3882 /*
3883  * freePGconn
3884  *       - free an idle (closed) PGconn data structure
3885  *
3886  * NOTE: this should not overlap any functionality with closePGconn().
3887  * Clearing/resetting of transient state belongs there; what we do here is
3888  * release data that is to be held for the life of the PGconn structure.
3889  * If a value ought to be cleared/freed during PQreset(), do it there not here.
3890  */
3891 static void
3892 freePGconn(PGconn *conn)
3893 {
3894         int                     i;
3895
3896         /* let any event procs clean up their state data */
3897         for (i = 0; i < conn->nEvents; i++)
3898         {
3899                 PGEventConnDestroy evt;
3900
3901                 evt.conn = conn;
3902                 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
3903                                                                         conn->events[i].passThrough);
3904                 free(conn->events[i].name);
3905         }
3906
3907         /* clean up pg_conn_host structures */
3908         if (conn->connhost != NULL)
3909         {
3910                 for (i = 0; i < conn->nconnhost; ++i)
3911                 {
3912                         if (conn->connhost[i].host != NULL)
3913                                 free(conn->connhost[i].host);
3914                         if (conn->connhost[i].hostaddr != NULL)
3915                                 free(conn->connhost[i].hostaddr);
3916                         if (conn->connhost[i].port != NULL)
3917                                 free(conn->connhost[i].port);
3918                         if (conn->connhost[i].password != NULL)
3919                         {
3920                                 explicit_bzero(conn->connhost[i].password, strlen(conn->connhost[i].password));
3921                                 free(conn->connhost[i].password);
3922                         }
3923                 }
3924                 free(conn->connhost);
3925         }
3926
3927         if (conn->client_encoding_initial)
3928                 free(conn->client_encoding_initial);
3929         if (conn->events)
3930                 free(conn->events);
3931         if (conn->pghost)
3932                 free(conn->pghost);
3933         if (conn->pghostaddr)
3934                 free(conn->pghostaddr);
3935         if (conn->pgport)
3936                 free(conn->pgport);
3937         if (conn->pgtty)
3938                 free(conn->pgtty);
3939         if (conn->connect_timeout)
3940                 free(conn->connect_timeout);
3941         if (conn->pgtcp_user_timeout)
3942                 free(conn->pgtcp_user_timeout);
3943         if (conn->pgoptions)
3944                 free(conn->pgoptions);
3945         if (conn->appname)
3946                 free(conn->appname);
3947         if (conn->fbappname)
3948                 free(conn->fbappname);
3949         if (conn->dbName)
3950                 free(conn->dbName);
3951         if (conn->replication)
3952                 free(conn->replication);
3953         if (conn->pguser)
3954                 free(conn->pguser);
3955         if (conn->pgpass)
3956         {
3957                 explicit_bzero(conn->pgpass, strlen(conn->pgpass));
3958                 free(conn->pgpass);
3959         }
3960         if (conn->pgpassfile)
3961                 free(conn->pgpassfile);
3962         if (conn->channel_binding)
3963                 free(conn->channel_binding);
3964         if (conn->keepalives)
3965                 free(conn->keepalives);
3966         if (conn->keepalives_idle)
3967                 free(conn->keepalives_idle);
3968         if (conn->keepalives_interval)
3969                 free(conn->keepalives_interval);
3970         if (conn->keepalives_count)
3971                 free(conn->keepalives_count);
3972         if (conn->sslmode)
3973                 free(conn->sslmode);
3974         if (conn->sslcert)
3975                 free(conn->sslcert);
3976         if (conn->sslkey)
3977                 free(conn->sslkey);
3978         if (conn->sslrootcert)
3979                 free(conn->sslrootcert);
3980         if (conn->sslcrl)
3981                 free(conn->sslcrl);
3982         if (conn->sslcompression)
3983                 free(conn->sslcompression);
3984         if (conn->requirepeer)
3985                 free(conn->requirepeer);
3986         if (conn->connip)
3987                 free(conn->connip);
3988         if (conn->gssencmode)
3989                 free(conn->gssencmode);
3990 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
3991         if (conn->krbsrvname)
3992                 free(conn->krbsrvname);
3993 #endif
3994 #ifdef ENABLE_GSS
3995         if (conn->gcred != GSS_C_NO_CREDENTIAL)
3996         {
3997                 OM_uint32       minor;
3998
3999                 gss_release_cred(&minor, &conn->gcred);
4000                 conn->gcred = GSS_C_NO_CREDENTIAL;
4001         }
4002         if (conn->gctx)
4003         {
4004                 OM_uint32       minor;
4005
4006                 gss_delete_sec_context(&minor, &conn->gctx, GSS_C_NO_BUFFER);
4007                 conn->gctx = NULL;
4008         }
4009 #endif
4010 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
4011         if (conn->gsslib)
4012                 free(conn->gsslib);
4013 #endif
4014         /* Note that conn->Pfdebug is not ours to close or free */
4015         if (conn->last_query)
4016                 free(conn->last_query);
4017         if (conn->write_err_msg)
4018                 free(conn->write_err_msg);
4019         if (conn->inBuffer)
4020                 free(conn->inBuffer);
4021         if (conn->outBuffer)
4022                 free(conn->outBuffer);
4023         if (conn->rowBuf)
4024                 free(conn->rowBuf);
4025         if (conn->target_session_attrs)
4026                 free(conn->target_session_attrs);
4027         termPQExpBuffer(&conn->errorMessage);
4028         termPQExpBuffer(&conn->workBuffer);
4029
4030         free(conn);
4031
4032 #ifdef WIN32
4033         WSACleanup();
4034 #endif
4035 }
4036
4037 /*
4038  * release_conn_addrinfo
4039  *       - Free any addrinfo list in the PGconn.
4040  */
4041 static void
4042 release_conn_addrinfo(PGconn *conn)
4043 {
4044         if (conn->addrlist)
4045         {
4046                 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
4047                 conn->addrlist = NULL;
4048                 conn->addr_cur = NULL;  /* for safety */
4049         }
4050 }
4051
4052 /*
4053  * sendTerminateConn
4054  *       - Send a terminate message to backend.
4055  */
4056 static void
4057 sendTerminateConn(PGconn *conn)
4058 {
4059         /*
4060          * Note that the protocol doesn't allow us to send Terminate messages
4061          * during the startup phase.
4062          */
4063         if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
4064         {
4065                 /*
4066                  * Try to send "close connection" message to backend. Ignore any
4067                  * error.
4068                  */
4069                 pqPutMsgStart('X', false, conn);
4070                 pqPutMsgEnd(conn);
4071                 (void) pqFlush(conn);
4072         }
4073 }
4074
4075 /*
4076  * closePGconn
4077  *       - properly close a connection to the backend
4078  *
4079  * This should reset or release all transient state, but NOT the connection
4080  * parameters.  On exit, the PGconn should be in condition to start a fresh
4081  * connection with the same parameters (see PQreset()).
4082  */
4083 static void
4084 closePGconn(PGconn *conn)
4085 {
4086         /*
4087          * If possible, send Terminate message to close the connection politely.
4088          */
4089         sendTerminateConn(conn);
4090
4091         /*
4092          * Must reset the blocking status so a possible reconnect will work.
4093          *
4094          * Don't call PQsetnonblocking() because it will fail if it's unable to
4095          * flush the connection.
4096          */
4097         conn->nonblocking = false;
4098
4099         /*
4100          * Close the connection, reset all transient state, flush I/O buffers.
4101          */
4102         pqDropConnection(conn, true);
4103         conn->status = CONNECTION_BAD;  /* Well, not really _bad_ - just absent */
4104         conn->asyncStatus = PGASYNC_IDLE;
4105         conn->xactStatus = PQTRANS_IDLE;
4106         pqClearAsyncResult(conn);       /* deallocate result */
4107         resetPQExpBuffer(&conn->errorMessage);
4108         release_conn_addrinfo(conn);
4109
4110         /* Reset all state obtained from server, too */
4111         pqDropServerData(conn);
4112 }
4113
4114 /*
4115  * PQfinish: properly close a connection to the backend. Also frees
4116  * the PGconn data structure so it shouldn't be re-used after this.
4117  */
4118 void
4119 PQfinish(PGconn *conn)
4120 {
4121         if (conn)
4122         {
4123                 closePGconn(conn);
4124                 freePGconn(conn);
4125         }
4126 }
4127
4128 /*
4129  * PQreset: resets the connection to the backend by closing the
4130  * existing connection and creating a new one.
4131  */
4132 void
4133 PQreset(PGconn *conn)
4134 {
4135         if (conn)
4136         {
4137                 closePGconn(conn);
4138
4139                 if (connectDBStart(conn) && connectDBComplete(conn))
4140                 {
4141                         /*
4142                          * Notify event procs of successful reset.  We treat an event proc
4143                          * failure as disabling the connection ... good idea?
4144                          */
4145                         int                     i;
4146
4147                         for (i = 0; i < conn->nEvents; i++)
4148                         {
4149                                 PGEventConnReset evt;
4150
4151                                 evt.conn = conn;
4152                                 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4153                                                                                   conn->events[i].passThrough))
4154                                 {
4155                                         conn->status = CONNECTION_BAD;
4156                                         printfPQExpBuffer(&conn->errorMessage,
4157                                                                           libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4158                                                                           conn->events[i].name);
4159                                         break;
4160                                 }
4161                         }
4162                 }
4163         }
4164 }
4165
4166
4167 /*
4168  * PQresetStart:
4169  * resets the connection to the backend
4170  * closes the existing connection and makes a new one
4171  * Returns 1 on success, 0 on failure.
4172  */
4173 int
4174 PQresetStart(PGconn *conn)
4175 {
4176         if (conn)
4177         {
4178                 closePGconn(conn);
4179
4180                 return connectDBStart(conn);
4181         }
4182
4183         return 0;
4184 }
4185
4186
4187 /*
4188  * PQresetPoll:
4189  * resets the connection to the backend
4190  * closes the existing connection and makes a new one
4191  */
4192 PostgresPollingStatusType
4193 PQresetPoll(PGconn *conn)
4194 {
4195         if (conn)
4196         {
4197                 PostgresPollingStatusType status = PQconnectPoll(conn);
4198
4199                 if (status == PGRES_POLLING_OK)
4200                 {
4201                         /*
4202                          * Notify event procs of successful reset.  We treat an event proc
4203                          * failure as disabling the connection ... good idea?
4204                          */
4205                         int                     i;
4206
4207                         for (i = 0; i < conn->nEvents; i++)
4208                         {
4209                                 PGEventConnReset evt;
4210
4211                                 evt.conn = conn;
4212                                 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
4213                                                                                   conn->events[i].passThrough))
4214                                 {
4215                                         conn->status = CONNECTION_BAD;
4216                                         printfPQExpBuffer(&conn->errorMessage,
4217                                                                           libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
4218                                                                           conn->events[i].name);
4219                                         return PGRES_POLLING_FAILED;
4220                                 }
4221                         }
4222                 }
4223
4224                 return status;
4225         }
4226
4227         return PGRES_POLLING_FAILED;
4228 }
4229
4230 /*
4231  * PQgetCancel: get a PGcancel structure corresponding to a connection.
4232  *
4233  * A copy is needed to be able to cancel a running query from a different
4234  * thread. If the same structure is used all structure members would have
4235  * to be individually locked (if the entire structure was locked, it would
4236  * be impossible to cancel a synchronous query because the structure would
4237  * have to stay locked for the duration of the query).
4238  */
4239 PGcancel *
4240 PQgetCancel(PGconn *conn)
4241 {
4242         PGcancel   *cancel;
4243
4244         if (!conn)
4245                 return NULL;
4246
4247         if (conn->sock == PGINVALID_SOCKET)
4248                 return NULL;
4249
4250         cancel = malloc(sizeof(PGcancel));
4251         if (cancel == NULL)
4252                 return NULL;
4253
4254         memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
4255         cancel->be_pid = conn->be_pid;
4256         cancel->be_key = conn->be_key;
4257
4258         return cancel;
4259 }
4260
4261 /* PQfreeCancel: free a cancel structure */
4262 void
4263 PQfreeCancel(PGcancel *cancel)
4264 {
4265         if (cancel)
4266                 free(cancel);
4267 }
4268
4269
4270 /*
4271  * PQcancel and PQrequestCancel: attempt to request cancellation of the
4272  * current operation.
4273  *
4274  * The return value is true if the cancel request was successfully
4275  * dispatched, false if not (in which case an error message is available).
4276  * Note: successful dispatch is no guarantee that there will be any effect at
4277  * the backend.  The application must read the operation result as usual.
4278  *
4279  * CAUTION: we want this routine to be safely callable from a signal handler
4280  * (for example, an application might want to call it in a SIGINT handler).
4281  * This means we cannot use any C library routine that might be non-reentrant.
4282  * malloc/free are often non-reentrant, and anything that might call them is
4283  * just as dangerous.  We avoid sprintf here for that reason.  Building up
4284  * error messages with strcpy/strcat is tedious but should be quite safe.
4285  * We also save/restore errno in case the signal handler support doesn't.
4286  *
4287  * internal_cancel() is an internal helper function to make code-sharing
4288  * between the two versions of the cancel function possible.
4289  */
4290 static int
4291 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
4292                                 char *errbuf, int errbufsize)
4293 {
4294         int                     save_errno = SOCK_ERRNO;
4295         pgsocket        tmpsock = PGINVALID_SOCKET;
4296         char            sebuf[PG_STRERROR_R_BUFLEN];
4297         int                     maxlen;
4298         struct
4299         {
4300                 uint32          packetlen;
4301                 CancelRequestPacket cp;
4302         }                       crp;
4303
4304         /*
4305          * We need to open a temporary connection to the postmaster. Do this with
4306          * only kernel calls.
4307          */
4308         if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4309         {
4310                 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4311                 goto cancel_errReturn;
4312         }
4313 retry3:
4314         if (connect(tmpsock, (struct sockaddr *) &raddr->addr,
4315                                 raddr->salen) < 0)
4316         {
4317                 if (SOCK_ERRNO == EINTR)
4318                         /* Interrupted system call - we'll just try again */
4319                         goto retry3;
4320                 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4321                 goto cancel_errReturn;
4322         }
4323
4324         /*
4325          * We needn't set nonblocking I/O or NODELAY options here.
4326          */
4327
4328         /* Create and send the cancel request packet. */
4329
4330         crp.packetlen = pg_hton32((uint32) sizeof(crp));
4331         crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4332         crp.cp.backendPID = pg_hton32(be_pid);
4333         crp.cp.cancelAuthCode = pg_hton32(be_key);
4334
4335 retry4:
4336         if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4337         {
4338                 if (SOCK_ERRNO == EINTR)
4339                         /* Interrupted system call - we'll just try again */
4340                         goto retry4;
4341                 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4342                 goto cancel_errReturn;
4343         }
4344
4345         /*
4346          * Wait for the postmaster to close the connection, which indicates that
4347          * it's processed the request.  Without this delay, we might issue another
4348          * command only to find that our cancel zaps that command instead of the
4349          * one we thought we were canceling.  Note we don't actually expect this
4350          * read to obtain any data, we are just waiting for EOF to be signaled.
4351          */
4352 retry5:
4353         if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4354         {
4355                 if (SOCK_ERRNO == EINTR)
4356                         /* Interrupted system call - we'll just try again */
4357                         goto retry5;
4358                 /* we ignore other error conditions */
4359         }
4360
4361         /* All done */
4362         closesocket(tmpsock);
4363         SOCK_ERRNO_SET(save_errno);
4364         return true;
4365
4366 cancel_errReturn:
4367
4368         /*
4369          * Make sure we don't overflow the error buffer. Leave space for the \n at
4370          * the end, and for the terminating zero.
4371          */
4372         maxlen = errbufsize - strlen(errbuf) - 2;
4373         if (maxlen >= 0)
4374         {
4375                 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
4376                                 maxlen);
4377                 strcat(errbuf, "\n");
4378         }
4379         if (tmpsock != PGINVALID_SOCKET)
4380                 closesocket(tmpsock);
4381         SOCK_ERRNO_SET(save_errno);
4382         return false;
4383 }
4384
4385 /*
4386  * PQcancel: request query cancel
4387  *
4388  * Returns true if able to send the cancel request, false if not.
4389  *
4390  * On failure, an error message is stored in *errbuf, which must be of size
4391  * errbufsize (recommended size is 256 bytes).  *errbuf is not changed on
4392  * success return.
4393  */
4394 int
4395 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
4396 {
4397         if (!cancel)
4398         {
4399                 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4400                 return false;
4401         }
4402
4403         return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
4404                                                    errbuf, errbufsize);
4405 }
4406
4407 /*
4408  * PQrequestCancel: old, not thread-safe function for requesting query cancel
4409  *
4410  * Returns true if able to send the cancel request, false if not.
4411  *
4412  * On failure, the error message is saved in conn->errorMessage; this means
4413  * that this can't be used when there might be other active operations on
4414  * the connection object.
4415  *
4416  * NOTE: error messages will be cut off at the current size of the
4417  * error message buffer, since we dare not try to expand conn->errorMessage!
4418  */
4419 int
4420 PQrequestCancel(PGconn *conn)
4421 {
4422         int                     r;
4423
4424         /* Check we have an open connection */
4425         if (!conn)
4426                 return false;
4427
4428         if (conn->sock == PGINVALID_SOCKET)
4429         {
4430                 strlcpy(conn->errorMessage.data,
4431                                 "PQrequestCancel() -- connection is not open\n",
4432                                 conn->errorMessage.maxlen);
4433                 conn->errorMessage.len = strlen(conn->errorMessage.data);
4434
4435                 return false;
4436         }
4437
4438         r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
4439                                                 conn->errorMessage.data, conn->errorMessage.maxlen);
4440
4441         if (!r)
4442                 conn->errorMessage.len = strlen(conn->errorMessage.data);
4443
4444         return r;
4445 }
4446
4447
4448 /*
4449  * pqPacketSend() -- convenience routine to send a message to server.
4450  *
4451  * pack_type: the single-byte message type code.  (Pass zero for startup
4452  * packets, which have no message type code.)
4453  *
4454  * buf, buf_len: contents of message.  The given length includes only what
4455  * is in buf; the message type and message length fields are added here.
4456  *
4457  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
4458  * SIDE_EFFECTS: may block.
4459  *
4460  * Note: all messages sent with this routine have a length word, whether
4461  * it's protocol 2.0 or 3.0.
4462  */
4463 int
4464 pqPacketSend(PGconn *conn, char pack_type,
4465                          const void *buf, size_t buf_len)
4466 {
4467         /* Start the message. */
4468         if (pqPutMsgStart(pack_type, true, conn))
4469                 return STATUS_ERROR;
4470
4471         /* Send the message body. */
4472         if (pqPutnchar(buf, buf_len, conn))
4473                 return STATUS_ERROR;
4474
4475         /* Finish the message. */
4476         if (pqPutMsgEnd(conn))
4477                 return STATUS_ERROR;
4478
4479         /* Flush to ensure backend gets it. */
4480         if (pqFlush(conn))
4481                 return STATUS_ERROR;
4482
4483         return STATUS_OK;
4484 }
4485
4486 #ifdef USE_LDAP
4487
4488 #define LDAP_URL        "ldap://"
4489 #define LDAP_DEF_PORT   389
4490 #define PGLDAP_TIMEOUT 2
4491
4492 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
4493 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
4494
4495
4496 /*
4497  *              ldapServiceLookup
4498  *
4499  * Search the LDAP URL passed as first argument, treat the result as a
4500  * string of connection options that are parsed and added to the array of
4501  * options passed as second argument.
4502  *
4503  * LDAP URLs must conform to RFC 1959 without escape sequences.
4504  *      ldap://host:port/dn?attributes?scope?filter?extensions
4505  *
4506  * Returns
4507  *      0 if the lookup was successful,
4508  *      1 if the connection to the LDAP server could be established but
4509  *        the search was unsuccessful,
4510  *      2 if a connection could not be established, and
4511  *      3 if a fatal error occurred.
4512  *
4513  * An error message is returned in the third argument for return codes 1 and 3.
4514  */
4515 static int
4516 ldapServiceLookup(const char *purl, PQconninfoOption *options,
4517                                   PQExpBuffer errorMessage)
4518 {
4519         int                     port = LDAP_DEF_PORT,
4520                                 scope,
4521                                 rc,
4522                                 size,
4523                                 state,
4524                                 oldstate,
4525                                 i;
4526 #ifndef WIN32
4527         int                     msgid;
4528 #endif
4529         bool            found_keyword;
4530         char       *url,
4531                            *hostname,
4532                            *portstr,
4533                            *endptr,
4534                            *dn,
4535                            *scopestr,
4536                            *filter,
4537                            *result,
4538                            *p,
4539                            *p1 = NULL,
4540                            *optname = NULL,
4541                            *optval = NULL;
4542         char       *attrs[2] = {NULL, NULL};
4543         LDAP       *ld = NULL;
4544         LDAPMessage *res,
4545                            *entry;
4546         struct berval **values;
4547         LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
4548
4549         if ((url = strdup(purl)) == NULL)
4550         {
4551                 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4552                 return 3;
4553         }
4554
4555         /*
4556          * Parse URL components, check for correctness.  Basically, url has '\0'
4557          * placed at component boundaries and variables are pointed at each
4558          * component.
4559          */
4560
4561         if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
4562         {
4563                 printfPQExpBuffer(errorMessage,
4564                                                   libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
4565                 free(url);
4566                 return 3;
4567         }
4568
4569         /* hostname */
4570         hostname = url + strlen(LDAP_URL);
4571         if (*hostname == '/')           /* no hostname? */
4572                 hostname = DefaultHost; /* the default */
4573
4574         /* dn, "distinguished name" */
4575         p = strchr(url + strlen(LDAP_URL), '/');
4576         if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4577         {
4578                 printfPQExpBuffer(errorMessage, libpq_gettext(
4579                                                                                                           "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
4580                 free(url);
4581                 return 3;
4582         }
4583         *p = '\0';                                      /* terminate hostname */
4584         dn = p + 1;
4585
4586         /* attribute */
4587         if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4588         {
4589                 printfPQExpBuffer(errorMessage, libpq_gettext(
4590                                                                                                           "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
4591                 free(url);
4592                 return 3;
4593         }
4594         *p = '\0';
4595         attrs[0] = p + 1;
4596
4597         /* scope */
4598         if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4599         {
4600                 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4601                 free(url);
4602                 return 3;
4603         }
4604         *p = '\0';
4605         scopestr = p + 1;
4606
4607         /* filter */
4608         if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
4609         {
4610                 printfPQExpBuffer(errorMessage,
4611                                                   libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
4612                 free(url);
4613                 return 3;
4614         }
4615         *p = '\0';
4616         filter = p + 1;
4617         if ((p = strchr(filter, '?')) != NULL)
4618                 *p = '\0';
4619
4620         /* port number? */
4621         if ((p1 = strchr(hostname, ':')) != NULL)
4622         {
4623                 long            lport;
4624
4625                 *p1 = '\0';
4626                 portstr = p1 + 1;
4627                 errno = 0;
4628                 lport = strtol(portstr, &endptr, 10);
4629                 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
4630                 {
4631                         printfPQExpBuffer(errorMessage, libpq_gettext(
4632                                                                                                                   "invalid LDAP URL \"%s\": invalid port number\n"), purl);
4633                         free(url);
4634                         return 3;
4635                 }
4636                 port = (int) lport;
4637         }
4638
4639         /* Allow only one attribute */
4640         if (strchr(attrs[0], ',') != NULL)
4641         {
4642                 printfPQExpBuffer(errorMessage, libpq_gettext(
4643                                                                                                           "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
4644                 free(url);
4645                 return 3;
4646         }
4647
4648         /* set scope */
4649         if (pg_strcasecmp(scopestr, "base") == 0)
4650                 scope = LDAP_SCOPE_BASE;
4651         else if (pg_strcasecmp(scopestr, "one") == 0)
4652                 scope = LDAP_SCOPE_ONELEVEL;
4653         else if (pg_strcasecmp(scopestr, "sub") == 0)
4654                 scope = LDAP_SCOPE_SUBTREE;
4655         else
4656         {
4657                 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
4658                 free(url);
4659                 return 3;
4660         }
4661
4662         /* initialize LDAP structure */
4663         if ((ld = ldap_init(hostname, port)) == NULL)
4664         {
4665                 printfPQExpBuffer(errorMessage,
4666                                                   libpq_gettext("could not create LDAP structure\n"));
4667                 free(url);
4668                 return 3;
4669         }
4670
4671         /*
4672          * Perform an explicit anonymous bind.
4673          *
4674          * LDAP does not require that an anonymous bind is performed explicitly,
4675          * but we want to distinguish between the case where LDAP bind does not
4676          * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing the
4677          * service control file) and the case where querying the LDAP server fails
4678          * (return 1 to end parsing).
4679          *
4680          * Unfortunately there is no way of setting a timeout that works for both
4681          * Windows and OpenLDAP.
4682          */
4683 #ifdef WIN32
4684         /* the nonstandard ldap_connect function performs an anonymous bind */
4685         if (ldap_connect(ld, &time) != LDAP_SUCCESS)
4686         {
4687                 /* error or timeout in ldap_connect */
4688                 free(url);
4689                 ldap_unbind(ld);
4690                 return 2;
4691         }
4692 #else                                                   /* !WIN32 */
4693         /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
4694         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4695         {
4696                 free(url);
4697                 ldap_unbind(ld);
4698                 return 3;
4699         }
4700
4701         /* anonymous bind */
4702         if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
4703         {
4704                 /* error or network timeout */
4705                 free(url);
4706                 ldap_unbind(ld);
4707                 return 2;
4708         }
4709
4710         /* wait some time for the connection to succeed */
4711         res = NULL;
4712         if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
4713                 res == NULL)
4714         {
4715                 /* error or timeout */
4716                 if (res != NULL)
4717                         ldap_msgfree(res);
4718                 free(url);
4719                 ldap_unbind(ld);
4720                 return 2;
4721         }
4722         ldap_msgfree(res);
4723
4724         /* reset timeout */
4725         time.tv_sec = -1;
4726         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
4727         {
4728                 free(url);
4729                 ldap_unbind(ld);
4730                 return 3;
4731         }
4732 #endif                                                  /* WIN32 */
4733
4734         /* search */
4735         res = NULL;
4736         if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
4737                 != LDAP_SUCCESS)
4738         {
4739                 if (res != NULL)
4740                         ldap_msgfree(res);
4741                 printfPQExpBuffer(errorMessage,
4742                                                   libpq_gettext("lookup on LDAP server failed: %s\n"),
4743                                                   ldap_err2string(rc));
4744                 ldap_unbind(ld);
4745                 free(url);
4746                 return 1;
4747         }
4748
4749         /* complain if there was not exactly one result */
4750         if ((rc = ldap_count_entries(ld, res)) != 1)
4751         {
4752                 printfPQExpBuffer(errorMessage,
4753                                                   rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
4754                                                   : libpq_gettext("no entry found on LDAP lookup\n"));
4755                 ldap_msgfree(res);
4756                 ldap_unbind(ld);
4757                 free(url);
4758                 return 1;
4759         }
4760
4761         /* get entry */
4762         if ((entry = ldap_first_entry(ld, res)) == NULL)
4763         {
4764                 /* should never happen */
4765                 printfPQExpBuffer(errorMessage,
4766                                                   libpq_gettext("no entry found on LDAP lookup\n"));
4767                 ldap_msgfree(res);
4768                 ldap_unbind(ld);
4769                 free(url);
4770                 return 1;
4771         }
4772
4773         /* get values */
4774         if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
4775         {
4776                 printfPQExpBuffer(errorMessage,
4777                                                   libpq_gettext("attribute has no values on LDAP lookup\n"));
4778                 ldap_msgfree(res);
4779                 ldap_unbind(ld);
4780                 free(url);
4781                 return 1;
4782         }
4783
4784         ldap_msgfree(res);
4785         free(url);
4786
4787         if (values[0] == NULL)
4788         {
4789                 printfPQExpBuffer(errorMessage,
4790                                                   libpq_gettext("attribute has no values on LDAP lookup\n"));
4791                 ldap_value_free_len(values);
4792                 ldap_unbind(ld);
4793                 return 1;
4794         }
4795
4796         /* concatenate values into a single string with newline terminators */
4797         size = 1;                                       /* for the trailing null */
4798         for (i = 0; values[i] != NULL; i++)
4799                 size += values[i]->bv_len + 1;
4800         if ((result = malloc(size)) == NULL)
4801         {
4802                 printfPQExpBuffer(errorMessage,
4803                                                   libpq_gettext("out of memory\n"));
4804                 ldap_value_free_len(values);
4805                 ldap_unbind(ld);
4806                 return 3;
4807         }
4808         p = result;
4809         for (i = 0; values[i] != NULL; i++)
4810         {
4811                 memcpy(p, values[i]->bv_val, values[i]->bv_len);
4812                 p += values[i]->bv_len;
4813                 *(p++) = '\n';
4814         }
4815         *p = '\0';
4816
4817         ldap_value_free_len(values);
4818         ldap_unbind(ld);
4819
4820         /* parse result string */
4821         oldstate = state = 0;
4822         for (p = result; *p != '\0'; ++p)
4823         {
4824                 switch (state)
4825                 {
4826                         case 0:                         /* between entries */
4827                                 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
4828                                 {
4829                                         optname = p;
4830                                         state = 1;
4831                                 }
4832                                 break;
4833                         case 1:                         /* in option name */
4834                                 if (ld_is_sp_tab(*p))
4835                                 {
4836                                         *p = '\0';
4837                                         state = 2;
4838                                 }
4839                                 else if (ld_is_nl_cr(*p))
4840                                 {
4841                                         printfPQExpBuffer(errorMessage, libpq_gettext(
4842                                                                                                                                   "missing \"=\" after \"%s\" in connection info string\n"),
4843                                                                           optname);
4844                                         free(result);
4845                                         return 3;
4846                                 }
4847                                 else if (*p == '=')
4848                                 {
4849                                         *p = '\0';
4850                                         state = 3;
4851                                 }
4852                                 break;
4853                         case 2:                         /* after option name */
4854                                 if (*p == '=')
4855                                 {
4856                                         state = 3;
4857                                 }
4858                                 else if (!ld_is_sp_tab(*p))
4859                                 {
4860                                         printfPQExpBuffer(errorMessage, libpq_gettext(
4861                                                                                                                                   "missing \"=\" after \"%s\" in connection info string\n"),
4862                                                                           optname);
4863                                         free(result);
4864                                         return 3;
4865                                 }
4866                                 break;
4867                         case 3:                         /* before option value */
4868                                 if (*p == '\'')
4869                                 {
4870                                         optval = p + 1;
4871                                         p1 = p + 1;
4872                                         state = 5;
4873                                 }
4874                                 else if (ld_is_nl_cr(*p))
4875                                 {
4876                                         optval = optname + strlen(optname); /* empty */
4877                                         state = 0;
4878                                 }
4879                                 else if (!ld_is_sp_tab(*p))
4880                                 {
4881                                         optval = p;
4882                                         state = 4;
4883                                 }
4884                                 break;
4885                         case 4:                         /* in unquoted option value */
4886                                 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
4887                                 {
4888                                         *p = '\0';
4889                                         state = 0;
4890                                 }
4891                                 break;
4892                         case 5:                         /* in quoted option value */
4893                                 if (*p == '\'')
4894                                 {
4895                                         *p1 = '\0';
4896                                         state = 0;
4897                                 }
4898                                 else if (*p == '\\')
4899                                         state = 6;
4900                                 else
4901                                         *(p1++) = *p;
4902                                 break;
4903                         case 6:                         /* in quoted option value after escape */
4904                                 *(p1++) = *p;
4905                                 state = 5;
4906                                 break;
4907                 }
4908
4909                 if (state == 0 && oldstate != 0)
4910                 {
4911                         found_keyword = false;
4912                         for (i = 0; options[i].keyword; i++)
4913                         {
4914                                 if (strcmp(options[i].keyword, optname) == 0)
4915                                 {
4916                                         if (options[i].val == NULL)
4917                                         {
4918                                                 options[i].val = strdup(optval);
4919                                                 if (!options[i].val)
4920                                                 {
4921                                                         printfPQExpBuffer(errorMessage,
4922                                                                                           libpq_gettext("out of memory\n"));
4923                                                         free(result);
4924                                                         return 3;
4925                                                 }
4926                                         }
4927                                         found_keyword = true;
4928                                         break;
4929                                 }
4930                         }
4931                         if (!found_keyword)
4932                         {
4933                                 printfPQExpBuffer(errorMessage,
4934                                                                   libpq_gettext("invalid connection option \"%s\"\n"),
4935                                                                   optname);
4936                                 free(result);
4937                                 return 1;
4938                         }
4939                         optname = NULL;
4940                         optval = NULL;
4941                 }
4942                 oldstate = state;
4943         }
4944
4945         free(result);
4946
4947         if (state == 5 || state == 6)
4948         {
4949                 printfPQExpBuffer(errorMessage, libpq_gettext(
4950                                                                                                           "unterminated quoted string in connection info string\n"));
4951                 return 3;
4952         }
4953
4954         return 0;
4955 }
4956
4957 #endif                                                  /* USE_LDAP */
4958
4959 #define MAXBUFSIZE 256
4960
4961 /*
4962  * parseServiceInfo: if a service name has been given, look it up and absorb
4963  * connection options from it into *options.
4964  *
4965  * Returns 0 on success, nonzero on failure.  On failure, if errorMessage
4966  * isn't null, also store an error message there.  (Note: the only reason
4967  * this function and related ones don't dump core on errorMessage == NULL
4968  * is the undocumented fact that printfPQExpBuffer does nothing when passed
4969  * a null PQExpBuffer pointer.)
4970  */
4971 static int
4972 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
4973 {
4974         const char *service = conninfo_getval(options, "service");
4975         char            serviceFile[MAXPGPATH];
4976         char       *env;
4977         bool            group_found = false;
4978         int                     status;
4979         struct stat stat_buf;
4980
4981         /*
4982          * We have to special-case the environment variable PGSERVICE here, since
4983          * this is and should be called before inserting environment defaults for
4984          * other connection options.
4985          */
4986         if (service == NULL)
4987                 service = getenv("PGSERVICE");
4988
4989         /* If no service name given, nothing to do */
4990         if (service == NULL)
4991                 return 0;
4992
4993         /*
4994          * Try PGSERVICEFILE if specified, else try ~/.pg_service.conf (if that
4995          * exists).
4996          */
4997         if ((env = getenv("PGSERVICEFILE")) != NULL)
4998                 strlcpy(serviceFile, env, sizeof(serviceFile));
4999         else
5000         {
5001                 char            homedir[MAXPGPATH];
5002
5003                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5004                         goto next_file;
5005                 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
5006                 if (stat(serviceFile, &stat_buf) != 0)
5007                         goto next_file;
5008         }
5009
5010         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5011         if (group_found || status != 0)
5012                 return status;
5013
5014 next_file:
5015
5016         /*
5017          * This could be used by any application so we can't use the binary
5018          * location to find our config files.
5019          */
5020         snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
5021                          getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
5022         if (stat(serviceFile, &stat_buf) != 0)
5023                 goto last_file;
5024
5025         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
5026         if (status != 0)
5027                 return status;
5028
5029 last_file:
5030         if (!group_found)
5031         {
5032                 printfPQExpBuffer(errorMessage,
5033                                                   libpq_gettext("definition of service \"%s\" not found\n"), service);
5034                 return 3;
5035         }
5036
5037         return 0;
5038 }
5039
5040 static int
5041 parseServiceFile(const char *serviceFile,
5042                                  const char *service,
5043                                  PQconninfoOption *options,
5044                                  PQExpBuffer errorMessage,
5045                                  bool *group_found)
5046 {
5047         int                     linenr = 0,
5048                                 i;
5049         FILE       *f;
5050         char            buf[MAXBUFSIZE],
5051                            *line;
5052
5053         f = fopen(serviceFile, "r");
5054         if (f == NULL)
5055         {
5056                 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
5057                                                   serviceFile);
5058                 return 1;
5059         }
5060
5061         while ((line = fgets(buf, sizeof(buf), f)) != NULL)
5062         {
5063                 int                     len;
5064
5065                 linenr++;
5066
5067                 if (strlen(line) >= sizeof(buf) - 1)
5068                 {
5069                         fclose(f);
5070                         printfPQExpBuffer(errorMessage,
5071                                                           libpq_gettext("line %d too long in service file \"%s\"\n"),
5072                                                           linenr,
5073                                                           serviceFile);
5074                         return 2;
5075                 }
5076
5077                 /* ignore whitespace at end of line, especially the newline */
5078                 len = strlen(line);
5079                 while (len > 0 && isspace((unsigned char) line[len - 1]))
5080                         line[--len] = '\0';
5081
5082                 /* ignore leading whitespace too */
5083                 while (*line && isspace((unsigned char) line[0]))
5084                         line++;
5085
5086                 /* ignore comments and empty lines */
5087                 if (line[0] == '\0' || line[0] == '#')
5088                         continue;
5089
5090                 /* Check for right groupname */
5091                 if (line[0] == '[')
5092                 {
5093                         if (*group_found)
5094                         {
5095                                 /* group info already read */
5096                                 fclose(f);
5097                                 return 0;
5098                         }
5099
5100                         if (strncmp(line + 1, service, strlen(service)) == 0 &&
5101                                 line[strlen(service) + 1] == ']')
5102                                 *group_found = true;
5103                         else
5104                                 *group_found = false;
5105                 }
5106                 else
5107                 {
5108                         if (*group_found)
5109                         {
5110                                 /*
5111                                  * Finally, we are in the right group and can parse the line
5112                                  */
5113                                 char       *key,
5114                                                    *val;
5115                                 bool            found_keyword;
5116
5117 #ifdef USE_LDAP
5118                                 if (strncmp(line, "ldap", 4) == 0)
5119                                 {
5120                                         int                     rc = ldapServiceLookup(line, options, errorMessage);
5121
5122                                         /* if rc = 2, go on reading for fallback */
5123                                         switch (rc)
5124                                         {
5125                                                 case 0:
5126                                                         fclose(f);
5127                                                         return 0;
5128                                                 case 1:
5129                                                 case 3:
5130                                                         fclose(f);
5131                                                         return 3;
5132                                                 case 2:
5133                                                         continue;
5134                                         }
5135                                 }
5136 #endif
5137
5138                                 key = line;
5139                                 val = strchr(line, '=');
5140                                 if (val == NULL)
5141                                 {
5142                                         printfPQExpBuffer(errorMessage,
5143                                                                           libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5144                                                                           serviceFile,
5145                                                                           linenr);
5146                                         fclose(f);
5147                                         return 3;
5148                                 }
5149                                 *val++ = '\0';
5150
5151                                 if (strcmp(key, "service") == 0)
5152                                 {
5153                                         printfPQExpBuffer(errorMessage,
5154                                                                           libpq_gettext("nested service specifications not supported in service file \"%s\", line %d\n"),
5155                                                                           serviceFile,
5156                                                                           linenr);
5157                                         fclose(f);
5158                                         return 3;
5159                                 }
5160
5161                                 /*
5162                                  * Set the parameter --- but don't override any previous
5163                                  * explicit setting.
5164                                  */
5165                                 found_keyword = false;
5166                                 for (i = 0; options[i].keyword; i++)
5167                                 {
5168                                         if (strcmp(options[i].keyword, key) == 0)
5169                                         {
5170                                                 if (options[i].val == NULL)
5171                                                         options[i].val = strdup(val);
5172                                                 if (!options[i].val)
5173                                                 {
5174                                                         printfPQExpBuffer(errorMessage,
5175                                                                                           libpq_gettext("out of memory\n"));
5176                                                         fclose(f);
5177                                                         return 3;
5178                                                 }
5179                                                 found_keyword = true;
5180                                                 break;
5181                                         }
5182                                 }
5183
5184                                 if (!found_keyword)
5185                                 {
5186                                         printfPQExpBuffer(errorMessage,
5187                                                                           libpq_gettext("syntax error in service file \"%s\", line %d\n"),
5188                                                                           serviceFile,
5189                                                                           linenr);
5190                                         fclose(f);
5191                                         return 3;
5192                                 }
5193                         }
5194                 }
5195         }
5196
5197         fclose(f);
5198
5199         return 0;
5200 }
5201
5202
5203 /*
5204  *              PQconninfoParse
5205  *
5206  * Parse a string like PQconnectdb() would do and return the
5207  * resulting connection options array.  NULL is returned on failure.
5208  * The result contains only options specified directly in the string,
5209  * not any possible default values.
5210  *
5211  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
5212  * string on failure (use PQfreemem to free it).  In out-of-memory conditions
5213  * both *errmsg and the result could be NULL.
5214  *
5215  * NOTE: the returned array is dynamically allocated and should
5216  * be freed when no longer needed via PQconninfoFree().
5217  */
5218 PQconninfoOption *
5219 PQconninfoParse(const char *conninfo, char **errmsg)
5220 {
5221         PQExpBufferData errorBuf;
5222         PQconninfoOption *connOptions;
5223
5224         if (errmsg)
5225                 *errmsg = NULL;                 /* default */
5226         initPQExpBuffer(&errorBuf);
5227         if (PQExpBufferDataBroken(errorBuf))
5228                 return NULL;                    /* out of memory already :-( */
5229         connOptions = parse_connection_string(conninfo, &errorBuf, false);
5230         if (connOptions == NULL && errmsg)
5231                 *errmsg = errorBuf.data;
5232         else
5233                 termPQExpBuffer(&errorBuf);
5234         return connOptions;
5235 }
5236
5237 /*
5238  * Build a working copy of the constant PQconninfoOptions array.
5239  */
5240 static PQconninfoOption *
5241 conninfo_init(PQExpBuffer errorMessage)
5242 {
5243         PQconninfoOption *options;
5244         PQconninfoOption *opt_dest;
5245         const internalPQconninfoOption *cur_opt;
5246
5247         /*
5248          * Get enough memory for all options in PQconninfoOptions, even if some
5249          * end up being filtered out.
5250          */
5251         options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
5252         if (options == NULL)
5253         {
5254                 printfPQExpBuffer(errorMessage,
5255                                                   libpq_gettext("out of memory\n"));
5256                 return NULL;
5257         }
5258         opt_dest = options;
5259
5260         for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
5261         {
5262                 /* Only copy the public part of the struct, not the full internal */
5263                 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
5264                 opt_dest++;
5265         }
5266         MemSet(opt_dest, 0, sizeof(PQconninfoOption));
5267
5268         return options;
5269 }
5270
5271 /*
5272  * Connection string parser
5273  *
5274  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
5275  * Otherwise, NULL is returned and an error message is left in errorMessage.
5276  *
5277  * If use_defaults is true, default values are filled in (from a service file,
5278  * environment variables, etc).
5279  */
5280 static PQconninfoOption *
5281 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
5282                                                 bool use_defaults)
5283 {
5284         /* Parse as URI if connection string matches URI prefix */
5285         if (uri_prefix_length(connstr) != 0)
5286                 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
5287
5288         /* Parse as default otherwise */
5289         return conninfo_parse(connstr, errorMessage, use_defaults);
5290 }
5291
5292 /*
5293  * Checks if connection string starts with either of the valid URI prefix
5294  * designators.
5295  *
5296  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
5297  *
5298  * XXX this is duplicated in psql/common.c.
5299  */
5300 static int
5301 uri_prefix_length(const char *connstr)
5302 {
5303         if (strncmp(connstr, uri_designator,
5304                                 sizeof(uri_designator) - 1) == 0)
5305                 return sizeof(uri_designator) - 1;
5306
5307         if (strncmp(connstr, short_uri_designator,
5308                                 sizeof(short_uri_designator) - 1) == 0)
5309                 return sizeof(short_uri_designator) - 1;
5310
5311         return 0;
5312 }
5313
5314 /*
5315  * Recognized connection string either starts with a valid URI prefix or
5316  * contains a "=" in it.
5317  *
5318  * Must be consistent with parse_connection_string: anything for which this
5319  * returns true should at least look like it's parseable by that routine.
5320  *
5321  * XXX this is duplicated in psql/common.c
5322  */
5323 static bool
5324 recognized_connection_string(const char *connstr)
5325 {
5326         return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
5327 }
5328
5329 /*
5330  * Subroutine for parse_connection_string
5331  *
5332  * Deal with a string containing key=value pairs.
5333  */
5334 static PQconninfoOption *
5335 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
5336                            bool use_defaults)
5337 {
5338         char       *pname;
5339         char       *pval;
5340         char       *buf;
5341         char       *cp;
5342         char       *cp2;
5343         PQconninfoOption *options;
5344
5345         /* Make a working copy of PQconninfoOptions */
5346         options = conninfo_init(errorMessage);
5347         if (options == NULL)
5348                 return NULL;
5349
5350         /* Need a modifiable copy of the input string */
5351         if ((buf = strdup(conninfo)) == NULL)
5352         {
5353                 printfPQExpBuffer(errorMessage,
5354                                                   libpq_gettext("out of memory\n"));
5355                 PQconninfoFree(options);
5356                 return NULL;
5357         }
5358         cp = buf;
5359
5360         while (*cp)
5361         {
5362                 /* Skip blanks before the parameter name */
5363                 if (isspace((unsigned char) *cp))
5364                 {
5365                         cp++;
5366                         continue;
5367                 }
5368
5369                 /* Get the parameter name */
5370                 pname = cp;
5371                 while (*cp)
5372                 {
5373                         if (*cp == '=')
5374                                 break;
5375                         if (isspace((unsigned char) *cp))
5376                         {
5377                                 *cp++ = '\0';
5378                                 while (*cp)
5379                                 {
5380                                         if (!isspace((unsigned char) *cp))
5381                                                 break;
5382                                         cp++;
5383                                 }
5384                                 break;
5385                         }
5386                         cp++;
5387                 }
5388
5389                 /* Check that there is a following '=' */
5390                 if (*cp != '=')
5391                 {
5392                         printfPQExpBuffer(errorMessage,
5393                                                           libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
5394                                                           pname);
5395                         PQconninfoFree(options);
5396                         free(buf);
5397                         return NULL;
5398                 }
5399                 *cp++ = '\0';
5400
5401                 /* Skip blanks after the '=' */
5402                 while (*cp)
5403                 {
5404                         if (!isspace((unsigned char) *cp))
5405                                 break;
5406                         cp++;
5407                 }
5408
5409                 /* Get the parameter value */
5410                 pval = cp;
5411
5412                 if (*cp != '\'')
5413                 {
5414                         cp2 = pval;
5415                         while (*cp)
5416                         {
5417                                 if (isspace((unsigned char) *cp))
5418                                 {
5419                                         *cp++ = '\0';
5420                                         break;
5421                                 }
5422                                 if (*cp == '\\')
5423                                 {
5424                                         cp++;
5425                                         if (*cp != '\0')
5426                                                 *cp2++ = *cp++;
5427                                 }
5428                                 else
5429                                         *cp2++ = *cp++;
5430                         }
5431                         *cp2 = '\0';
5432                 }
5433                 else
5434                 {
5435                         cp2 = pval;
5436                         cp++;
5437                         for (;;)
5438                         {
5439                                 if (*cp == '\0')
5440                                 {
5441                                         printfPQExpBuffer(errorMessage,
5442                                                                           libpq_gettext("unterminated quoted string in connection info string\n"));
5443                                         PQconninfoFree(options);
5444                                         free(buf);
5445                                         return NULL;
5446                                 }
5447                                 if (*cp == '\\')
5448                                 {
5449                                         cp++;
5450                                         if (*cp != '\0')
5451                                                 *cp2++ = *cp++;
5452                                         continue;
5453                                 }
5454                                 if (*cp == '\'')
5455                                 {
5456                                         *cp2 = '\0';
5457                                         cp++;
5458                                         break;
5459                                 }
5460                                 *cp2++ = *cp++;
5461                         }
5462                 }
5463
5464                 /*
5465                  * Now that we have the name and the value, store the record.
5466                  */
5467                 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
5468                 {
5469                         PQconninfoFree(options);
5470                         free(buf);
5471                         return NULL;
5472                 }
5473         }
5474
5475         /* Done with the modifiable input string */
5476         free(buf);
5477
5478         /*
5479          * Add in defaults if the caller wants that.
5480          */
5481         if (use_defaults)
5482         {
5483                 if (!conninfo_add_defaults(options, errorMessage))
5484                 {
5485                         PQconninfoFree(options);
5486                         return NULL;
5487                 }
5488         }
5489
5490         return options;
5491 }
5492
5493 /*
5494  * Conninfo array parser routine
5495  *
5496  * If successful, a malloc'd PQconninfoOption array is returned.
5497  * If not successful, NULL is returned and an error message is
5498  * left in errorMessage.
5499  * Defaults are supplied (from a service file, environment variables, etc)
5500  * for unspecified options, but only if use_defaults is true.
5501  *
5502  * If expand_dbname is non-zero, and the value passed for the first occurrence
5503  * of "dbname" keyword is a connection string (as indicated by
5504  * recognized_connection_string) then parse and process it, overriding any
5505  * previously processed conflicting keywords. Subsequent keywords will take
5506  * precedence, however. In-tree programs generally specify expand_dbname=true,
5507  * so command-line arguments naming a database can use a connection string.
5508  * Some code acquires arbitrary database names from known-literal sources like
5509  * PQdb(), PQconninfoParse() and pg_database.datname.  When connecting to such
5510  * a database, in-tree code first wraps the name in a connection string.
5511  */
5512 static PQconninfoOption *
5513 conninfo_array_parse(const char *const *keywords, const char *const *values,
5514                                          PQExpBuffer errorMessage, bool use_defaults,
5515                                          int expand_dbname)
5516 {
5517         PQconninfoOption *options;
5518         PQconninfoOption *dbname_options = NULL;
5519         PQconninfoOption *option;
5520         int                     i = 0;
5521
5522         /*
5523          * If expand_dbname is non-zero, check keyword "dbname" to see if val is
5524          * actually a recognized connection string.
5525          */
5526         while (expand_dbname && keywords[i])
5527         {
5528                 const char *pname = keywords[i];
5529                 const char *pvalue = values[i];
5530
5531                 /* first find "dbname" if any */
5532                 if (strcmp(pname, "dbname") == 0 && pvalue)
5533                 {
5534                         /*
5535                          * If value is a connection string, parse it, but do not use
5536                          * defaults here -- those get picked up later. We only want to
5537                          * override for those parameters actually passed.
5538                          */
5539                         if (recognized_connection_string(pvalue))
5540                         {
5541                                 dbname_options = parse_connection_string(pvalue, errorMessage, false);
5542                                 if (dbname_options == NULL)
5543                                         return NULL;
5544                         }
5545                         break;
5546                 }
5547                 ++i;
5548         }
5549
5550         /* Make a working copy of PQconninfoOptions */
5551         options = conninfo_init(errorMessage);
5552         if (options == NULL)
5553         {
5554                 PQconninfoFree(dbname_options);
5555                 return NULL;
5556         }
5557
5558         /* Parse the keywords/values arrays */
5559         i = 0;
5560         while (keywords[i])
5561         {
5562                 const char *pname = keywords[i];
5563                 const char *pvalue = values[i];
5564
5565                 if (pvalue != NULL && pvalue[0] != '\0')
5566                 {
5567                         /* Search for the param record */
5568                         for (option = options; option->keyword != NULL; option++)
5569                         {
5570                                 if (strcmp(option->keyword, pname) == 0)
5571                                         break;
5572                         }
5573
5574                         /* Check for invalid connection option */
5575                         if (option->keyword == NULL)
5576                         {
5577                                 printfPQExpBuffer(errorMessage,
5578                                                                   libpq_gettext("invalid connection option \"%s\"\n"),
5579                                                                   pname);
5580                                 PQconninfoFree(options);
5581                                 PQconninfoFree(dbname_options);
5582                                 return NULL;
5583                         }
5584
5585                         /*
5586                          * If we are on the first dbname parameter, and we have a parsed
5587                          * connection string, copy those parameters across, overriding any
5588                          * existing previous settings.
5589                          */
5590                         if (strcmp(pname, "dbname") == 0 && dbname_options)
5591                         {
5592                                 PQconninfoOption *str_option;
5593
5594                                 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
5595                                 {
5596                                         if (str_option->val != NULL)
5597                                         {
5598                                                 int                     k;
5599
5600                                                 for (k = 0; options[k].keyword; k++)
5601                                                 {
5602                                                         if (strcmp(options[k].keyword, str_option->keyword) == 0)
5603                                                         {
5604                                                                 if (options[k].val)
5605                                                                         free(options[k].val);
5606                                                                 options[k].val = strdup(str_option->val);
5607                                                                 if (!options[k].val)
5608                                                                 {
5609                                                                         printfPQExpBuffer(errorMessage,
5610                                                                                                           libpq_gettext("out of memory\n"));
5611                                                                         PQconninfoFree(options);
5612                                                                         PQconninfoFree(dbname_options);
5613                                                                         return NULL;
5614                                                                 }
5615                                                                 break;
5616                                                         }
5617                                                 }
5618                                         }
5619                                 }
5620
5621                                 /*
5622                                  * Forget the parsed connection string, so that any subsequent
5623                                  * dbname parameters will not be expanded.
5624                                  */
5625                                 PQconninfoFree(dbname_options);
5626                                 dbname_options = NULL;
5627                         }
5628                         else
5629                         {
5630                                 /*
5631                                  * Store the value, overriding previous settings
5632                                  */
5633                                 if (option->val)
5634                                         free(option->val);
5635                                 option->val = strdup(pvalue);
5636                                 if (!option->val)
5637                                 {
5638                                         printfPQExpBuffer(errorMessage,
5639                                                                           libpq_gettext("out of memory\n"));
5640                                         PQconninfoFree(options);
5641                                         PQconninfoFree(dbname_options);
5642                                         return NULL;
5643                                 }
5644                         }
5645                 }
5646                 ++i;
5647         }
5648         PQconninfoFree(dbname_options);
5649
5650         /*
5651          * Add in defaults if the caller wants that.
5652          */
5653         if (use_defaults)
5654         {
5655                 if (!conninfo_add_defaults(options, errorMessage))
5656                 {
5657                         PQconninfoFree(options);
5658                         return NULL;
5659                 }
5660         }
5661
5662         return options;
5663 }
5664
5665 /*
5666  * Add the default values for any unspecified options to the connection
5667  * options array.
5668  *
5669  * Defaults are obtained from a service file, environment variables, etc.
5670  *
5671  * Returns true if successful, otherwise false; errorMessage, if supplied,
5672  * is filled in upon failure.  Note that failure to locate a default value
5673  * is not an error condition here --- we just leave the option's value as
5674  * NULL.
5675  */
5676 static bool
5677 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
5678 {
5679         PQconninfoOption *option;
5680         char       *tmp;
5681
5682         /*
5683          * If there's a service spec, use it to obtain any not-explicitly-given
5684          * parameters.  Ignore error if no error message buffer is passed because
5685          * there is no way to pass back the failure message.
5686          */
5687         if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
5688                 return false;
5689
5690         /*
5691          * Get the fallback resources for parameters not specified in the conninfo
5692          * string nor the service.
5693          */
5694         for (option = options; option->keyword != NULL; option++)
5695         {
5696                 if (option->val != NULL)
5697                         continue;                       /* Value was in conninfo or service */
5698
5699                 /*
5700                  * Try to get the environment variable fallback
5701                  */
5702                 if (option->envvar != NULL)
5703                 {
5704                         if ((tmp = getenv(option->envvar)) != NULL)
5705                         {
5706                                 option->val = strdup(tmp);
5707                                 if (!option->val)
5708                                 {
5709                                         if (errorMessage)
5710                                                 printfPQExpBuffer(errorMessage,
5711                                                                                   libpq_gettext("out of memory\n"));
5712                                         return false;
5713                                 }
5714                                 continue;
5715                         }
5716                 }
5717
5718                 /*
5719                  * Interpret the deprecated PGREQUIRESSL environment variable.  Per
5720                  * tradition, translate values starting with "1" to sslmode=require,
5721                  * and ignore other values.  Given both PGREQUIRESSL=1 and PGSSLMODE,
5722                  * PGSSLMODE takes precedence; the opposite was true before v9.3.
5723                  */
5724                 if (strcmp(option->keyword, "sslmode") == 0)
5725                 {
5726                         const char *requiresslenv = getenv("PGREQUIRESSL");
5727
5728                         if (requiresslenv != NULL && requiresslenv[0] == '1')
5729                         {
5730                                 option->val = strdup("require");
5731                                 if (!option->val)
5732                                 {
5733                                         if (errorMessage)
5734                                                 printfPQExpBuffer(errorMessage,
5735                                                                                   libpq_gettext("out of memory\n"));
5736                                         return false;
5737                                 }
5738                                 continue;
5739                         }
5740                 }
5741
5742                 /*
5743                  * No environment variable specified or the variable isn't set - try
5744                  * compiled-in default
5745                  */
5746                 if (option->compiled != NULL)
5747                 {
5748                         option->val = strdup(option->compiled);
5749                         if (!option->val)
5750                         {
5751                                 if (errorMessage)
5752                                         printfPQExpBuffer(errorMessage,
5753                                                                           libpq_gettext("out of memory\n"));
5754                                 return false;
5755                         }
5756                         continue;
5757                 }
5758
5759                 /*
5760                  * Special handling for "user" option.  Note that if pg_fe_getauthname
5761                  * fails, we just leave the value as NULL; there's no need for this to
5762                  * be an error condition if the caller provides a user name.  The only
5763                  * reason we do this now at all is so that callers of PQconndefaults
5764                  * will see a correct default (barring error, of course).
5765                  */
5766                 if (strcmp(option->keyword, "user") == 0)
5767                 {
5768                         option->val = pg_fe_getauthname(NULL);
5769                         continue;
5770                 }
5771         }
5772
5773         return true;
5774 }
5775
5776 /*
5777  * Subroutine for parse_connection_string
5778  *
5779  * Deal with a URI connection string.
5780  */
5781 static PQconninfoOption *
5782 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
5783                                    bool use_defaults)
5784 {
5785         PQconninfoOption *options;
5786
5787         /* Make a working copy of PQconninfoOptions */
5788         options = conninfo_init(errorMessage);
5789         if (options == NULL)
5790                 return NULL;
5791
5792         if (!conninfo_uri_parse_options(options, uri, errorMessage))
5793         {
5794                 PQconninfoFree(options);
5795                 return NULL;
5796         }
5797
5798         /*
5799          * Add in defaults if the caller wants that.
5800          */
5801         if (use_defaults)
5802         {
5803                 if (!conninfo_add_defaults(options, errorMessage))
5804                 {
5805                         PQconninfoFree(options);
5806                         return NULL;
5807                 }
5808         }
5809
5810         return options;
5811 }
5812
5813 /*
5814  * conninfo_uri_parse_options
5815  *              Actual URI parser.
5816  *
5817  * If successful, returns true while the options array is filled with parsed
5818  * options from the URI.
5819  * If not successful, returns false and fills errorMessage accordingly.
5820  *
5821  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
5822  * 3986):
5823  *
5824  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
5825  *
5826  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
5827  * by literal square brackets.  As an extension, we also allow multiple
5828  * netloc[:port] specifications, separated by commas:
5829  *
5830  * postgresql://[user[:password]@][netloc][:port][,...][/dbname][?param1=value1&...]
5831  *
5832  * Any of the URI parts might use percent-encoding (%xy).
5833  */
5834 static bool
5835 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
5836                                                    PQExpBuffer errorMessage)
5837 {
5838         int                     prefix_len;
5839         char       *p;
5840         char       *buf = NULL;
5841         char       *start;
5842         char            prevchar = '\0';
5843         char       *user = NULL;
5844         char       *host = NULL;
5845         bool            retval = false;
5846         PQExpBufferData hostbuf;
5847         PQExpBufferData portbuf;
5848
5849         initPQExpBuffer(&hostbuf);
5850         initPQExpBuffer(&portbuf);
5851         if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
5852         {
5853                 printfPQExpBuffer(errorMessage,
5854                                                   libpq_gettext("out of memory\n"));
5855                 goto cleanup;
5856         }
5857
5858         /* need a modifiable copy of the input URI */
5859         buf = strdup(uri);
5860         if (buf == NULL)
5861         {
5862                 printfPQExpBuffer(errorMessage,
5863                                                   libpq_gettext("out of memory\n"));
5864                 goto cleanup;
5865         }
5866         start = buf;
5867
5868         /* Skip the URI prefix */
5869         prefix_len = uri_prefix_length(uri);
5870         if (prefix_len == 0)
5871         {
5872                 /* Should never happen */
5873                 printfPQExpBuffer(errorMessage,
5874                                                   libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
5875                                                   uri);
5876                 goto cleanup;
5877         }
5878         start += prefix_len;
5879         p = start;
5880
5881         /* Look ahead for possible user credentials designator */
5882         while (*p && *p != '@' && *p != '/')
5883                 ++p;
5884         if (*p == '@')
5885         {
5886                 /*
5887                  * Found username/password designator, so URI should be of the form
5888                  * "scheme://user[:password]@[netloc]".
5889                  */
5890                 user = start;
5891
5892                 p = user;
5893                 while (*p != ':' && *p != '@')
5894                         ++p;
5895
5896                 /* Save last char and cut off at end of user name */
5897                 prevchar = *p;
5898                 *p = '\0';
5899
5900                 if (*user &&
5901                         !conninfo_storeval(options, "user", user,
5902                                                            errorMessage, false, true))
5903                         goto cleanup;
5904
5905                 if (prevchar == ':')
5906                 {
5907                         const char *password = p + 1;
5908
5909                         while (*p != '@')
5910                                 ++p;
5911                         *p = '\0';
5912
5913                         if (*password &&
5914                                 !conninfo_storeval(options, "password", password,
5915                                                                    errorMessage, false, true))
5916                                 goto cleanup;
5917                 }
5918
5919                 /* Advance past end of parsed user name or password token */
5920                 ++p;
5921         }
5922         else
5923         {
5924                 /*
5925                  * No username/password designator found.  Reset to start of URI.
5926                  */
5927                 p = start;
5928         }
5929
5930         /*
5931          * There may be multiple netloc[:port] pairs, each separated from the next
5932          * by a comma.  When we initially enter this loop, "p" has been
5933          * incremented past optional URI credential information at this point and
5934          * now points at the "netloc" part of the URI.  On subsequent loop
5935          * iterations, "p" has been incremented past the comma separator and now
5936          * points at the start of the next "netloc".
5937          */
5938         for (;;)
5939         {
5940                 /*
5941                  * Look for IPv6 address.
5942                  */
5943                 if (*p == '[')
5944                 {
5945                         host = ++p;
5946                         while (*p && *p != ']')
5947                                 ++p;
5948                         if (!*p)
5949                         {
5950                                 printfPQExpBuffer(errorMessage,
5951                                                                   libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
5952                                                                   uri);
5953                                 goto cleanup;
5954                         }
5955                         if (p == host)
5956                         {
5957                                 printfPQExpBuffer(errorMessage,
5958                                                                   libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
5959                                                                   uri);
5960                                 goto cleanup;
5961                         }
5962
5963                         /* Cut off the bracket and advance */
5964                         *(p++) = '\0';
5965
5966                         /*
5967                          * The address may be followed by a port specifier or a slash or a
5968                          * query or a separator comma.
5969                          */
5970                         if (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
5971                         {
5972                                 printfPQExpBuffer(errorMessage,
5973                                                                   libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
5974                                                                   *p, (int) (p - buf + 1), uri);
5975                                 goto cleanup;
5976                         }
5977                 }
5978                 else
5979                 {
5980                         /* not an IPv6 address: DNS-named or IPv4 netloc */
5981                         host = p;
5982
5983                         /*
5984                          * Look for port specifier (colon) or end of host specifier
5985                          * (slash) or query (question mark) or host separator (comma).
5986                          */
5987                         while (*p && *p != ':' && *p != '/' && *p != '?' && *p != ',')
5988                                 ++p;
5989                 }
5990
5991                 /* Save the hostname terminator before we null it */
5992                 prevchar = *p;
5993                 *p = '\0';
5994
5995                 appendPQExpBufferStr(&hostbuf, host);
5996
5997                 if (prevchar == ':')
5998                 {
5999                         const char *port = ++p; /* advance past host terminator */
6000
6001                         while (*p && *p != '/' && *p != '?' && *p != ',')
6002                                 ++p;
6003
6004                         prevchar = *p;
6005                         *p = '\0';
6006
6007                         appendPQExpBufferStr(&portbuf, port);
6008                 }
6009
6010                 if (prevchar != ',')
6011                         break;
6012                 ++p;                                    /* advance past comma separator */
6013                 appendPQExpBufferChar(&hostbuf, ',');
6014                 appendPQExpBufferChar(&portbuf, ',');
6015         }
6016
6017         /* Save final values for host and port. */
6018         if (PQExpBufferDataBroken(hostbuf) || PQExpBufferDataBroken(portbuf))
6019                 goto cleanup;
6020         if (hostbuf.data[0] &&
6021                 !conninfo_storeval(options, "host", hostbuf.data,
6022                                                    errorMessage, false, true))
6023                 goto cleanup;
6024         if (portbuf.data[0] &&
6025                 !conninfo_storeval(options, "port", portbuf.data,
6026                                                    errorMessage, false, true))
6027                 goto cleanup;
6028
6029         if (prevchar && prevchar != '?')
6030         {
6031                 const char *dbname = ++p;       /* advance past host terminator */
6032
6033                 /* Look for query parameters */
6034                 while (*p && *p != '?')
6035                         ++p;
6036
6037                 prevchar = *p;
6038                 *p = '\0';
6039
6040                 /*
6041                  * Avoid setting dbname to an empty string, as it forces the default
6042                  * value (username) and ignores $PGDATABASE, as opposed to not setting
6043                  * it at all.
6044                  */
6045                 if (*dbname &&
6046                         !conninfo_storeval(options, "dbname", dbname,
6047                                                            errorMessage, false, true))
6048                         goto cleanup;
6049         }
6050
6051         if (prevchar)
6052         {
6053                 ++p;                                    /* advance past terminator */
6054
6055                 if (!conninfo_uri_parse_params(p, options, errorMessage))
6056                         goto cleanup;
6057         }
6058
6059         /* everything parsed okay */
6060         retval = true;
6061
6062 cleanup:
6063         termPQExpBuffer(&hostbuf);
6064         termPQExpBuffer(&portbuf);
6065         if (buf)
6066                 free(buf);
6067         return retval;
6068 }
6069
6070 /*
6071  * Connection URI parameters parser routine
6072  *
6073  * If successful, returns true while connOptions is filled with parsed
6074  * parameters.  Otherwise, returns false and fills errorMessage appropriately.
6075  *
6076  * Destructively modifies 'params' buffer.
6077  */
6078 static bool
6079 conninfo_uri_parse_params(char *params,
6080                                                   PQconninfoOption *connOptions,
6081                                                   PQExpBuffer errorMessage)
6082 {
6083         while (*params)
6084         {
6085                 char       *keyword = params;
6086                 char       *value = NULL;
6087                 char       *p = params;
6088                 bool            malloced = false;
6089
6090                 /*
6091                  * Scan the params string for '=' and '&', marking the end of keyword
6092                  * and value respectively.
6093                  */
6094                 for (;;)
6095                 {
6096                         if (*p == '=')
6097                         {
6098                                 /* Was there '=' already? */
6099                                 if (value != NULL)
6100                                 {
6101                                         printfPQExpBuffer(errorMessage,
6102                                                                           libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
6103                                                                           keyword);
6104                                         return false;
6105                                 }
6106                                 /* Cut off keyword, advance to value */
6107                                 *p++ = '\0';
6108                                 value = p;
6109                         }
6110                         else if (*p == '&' || *p == '\0')
6111                         {
6112                                 /*
6113                                  * If not at the end, cut off value and advance; leave p
6114                                  * pointing to start of the next parameter, if any.
6115                                  */
6116                                 if (*p != '\0')
6117                                         *p++ = '\0';
6118                                 /* Was there '=' at all? */
6119                                 if (value == NULL)
6120                                 {
6121                                         printfPQExpBuffer(errorMessage,
6122                                                                           libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
6123                                                                           keyword);
6124                                         return false;
6125                                 }
6126                                 /* Got keyword and value, go process them. */
6127                                 break;
6128                         }
6129                         else
6130                                 ++p;                    /* Advance over all other bytes. */
6131                 }
6132
6133                 keyword = conninfo_uri_decode(keyword, errorMessage);
6134                 if (keyword == NULL)
6135                 {
6136                         /* conninfo_uri_decode already set an error message */
6137                         return false;
6138                 }
6139                 value = conninfo_uri_decode(value, errorMessage);
6140                 if (value == NULL)
6141                 {
6142                         /* conninfo_uri_decode already set an error message */
6143                         free(keyword);
6144                         return false;
6145                 }
6146                 malloced = true;
6147
6148                 /*
6149                  * Special keyword handling for improved JDBC compatibility.
6150                  */
6151                 if (strcmp(keyword, "ssl") == 0 &&
6152                         strcmp(value, "true") == 0)
6153                 {
6154                         free(keyword);
6155                         free(value);
6156                         malloced = false;
6157
6158                         keyword = "sslmode";
6159                         value = "require";
6160                 }
6161
6162                 /*
6163                  * Store the value if the corresponding option exists; ignore
6164                  * otherwise.  At this point both keyword and value are not
6165                  * URI-encoded.
6166                  */
6167                 if (!conninfo_storeval(connOptions, keyword, value,
6168                                                            errorMessage, true, false))
6169                 {
6170                         /* Insert generic message if conninfo_storeval didn't give one. */
6171                         if (errorMessage->len == 0)
6172                                 printfPQExpBuffer(errorMessage,
6173                                                                   libpq_gettext("invalid URI query parameter: \"%s\"\n"),
6174                                                                   keyword);
6175                         /* And fail. */
6176                         if (malloced)
6177                         {
6178                                 free(keyword);
6179                                 free(value);
6180                         }
6181                         return false;
6182                 }
6183
6184                 if (malloced)
6185                 {
6186                         free(keyword);
6187                         free(value);
6188                 }
6189
6190                 /* Proceed to next key=value pair, if any */
6191                 params = p;
6192         }
6193
6194         return true;
6195 }
6196
6197 /*
6198  * Connection URI decoder routine
6199  *
6200  * If successful, returns the malloc'd decoded string.
6201  * If not successful, returns NULL and fills errorMessage accordingly.
6202  *
6203  * The string is decoded by replacing any percent-encoded tokens with
6204  * corresponding characters, while preserving any non-encoded characters.  A
6205  * percent-encoded token is a character triplet: a percent sign, followed by a
6206  * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
6207  * treated identically.
6208  */
6209 static char *
6210 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
6211 {
6212         char       *buf;
6213         char       *p;
6214         const char *q = str;
6215
6216         buf = malloc(strlen(str) + 1);
6217         if (buf == NULL)
6218         {
6219                 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
6220                 return NULL;
6221         }
6222         p = buf;
6223
6224         for (;;)
6225         {
6226                 if (*q != '%')
6227                 {
6228                         /* copy and check for NUL terminator */
6229                         if (!(*(p++) = *(q++)))
6230                                 break;
6231                 }
6232                 else
6233                 {
6234                         int                     hi;
6235                         int                     lo;
6236                         int                     c;
6237
6238                         ++q;                            /* skip the percent sign itself */
6239
6240                         /*
6241                          * Possible EOL will be caught by the first call to
6242                          * get_hexdigit(), so we never dereference an invalid q pointer.
6243                          */
6244                         if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
6245                         {
6246                                 printfPQExpBuffer(errorMessage,
6247                                                                   libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
6248                                                                   str);
6249                                 free(buf);
6250                                 return NULL;
6251                         }
6252
6253                         c = (hi << 4) | lo;
6254                         if (c == 0)
6255                         {
6256                                 printfPQExpBuffer(errorMessage,
6257                                                                   libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
6258                                                                   str);
6259                                 free(buf);
6260                                 return NULL;
6261                         }
6262                         *(p++) = c;
6263                 }
6264         }
6265
6266         return buf;
6267 }
6268
6269 /*
6270  * Convert hexadecimal digit character to its integer value.
6271  *
6272  * If successful, returns true and value is filled with digit's base 16 value.
6273  * If not successful, returns false.
6274  *
6275  * Lower- and upper-case letters in the range A-F are treated identically.
6276  */
6277 static bool
6278 get_hexdigit(char digit, int *value)
6279 {
6280         if ('0' <= digit && digit <= '9')
6281                 *value = digit - '0';
6282         else if ('A' <= digit && digit <= 'F')
6283                 *value = digit - 'A' + 10;
6284         else if ('a' <= digit && digit <= 'f')
6285                 *value = digit - 'a' + 10;
6286         else
6287                 return false;
6288
6289         return true;
6290 }
6291
6292 /*
6293  * Find an option value corresponding to the keyword in the connOptions array.
6294  *
6295  * If successful, returns a pointer to the corresponding option's value.
6296  * If not successful, returns NULL.
6297  */
6298 static const char *
6299 conninfo_getval(PQconninfoOption *connOptions,
6300                                 const char *keyword)
6301 {
6302         PQconninfoOption *option;
6303
6304         option = conninfo_find(connOptions, keyword);
6305
6306         return option ? option->val : NULL;
6307 }
6308
6309 /*
6310  * Store a (new) value for an option corresponding to the keyword in
6311  * connOptions array.
6312  *
6313  * If uri_decode is true, the value is URI-decoded.  The keyword is always
6314  * assumed to be non URI-encoded.
6315  *
6316  * If successful, returns a pointer to the corresponding PQconninfoOption,
6317  * which value is replaced with a strdup'd copy of the passed value string.
6318  * The existing value for the option is free'd before replacing, if any.
6319  *
6320  * If not successful, returns NULL and fills errorMessage accordingly.
6321  * However, if the reason of failure is an invalid keyword being passed and
6322  * ignoreMissing is true, errorMessage will be left untouched.
6323  */
6324 static PQconninfoOption *
6325 conninfo_storeval(PQconninfoOption *connOptions,
6326                                   const char *keyword, const char *value,
6327                                   PQExpBuffer errorMessage, bool ignoreMissing,
6328                                   bool uri_decode)
6329 {
6330         PQconninfoOption *option;
6331         char       *value_copy;
6332
6333         /*
6334          * For backwards compatibility, requiressl=1 gets translated to
6335          * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
6336          * (which is the default for sslmode).
6337          */
6338         if (strcmp(keyword, "requiressl") == 0)
6339         {
6340                 keyword = "sslmode";
6341                 if (value[0] == '1')
6342                         value = "require";
6343                 else
6344                         value = "prefer";
6345         }
6346
6347         option = conninfo_find(connOptions, keyword);
6348         if (option == NULL)
6349         {
6350                 if (!ignoreMissing)
6351                         printfPQExpBuffer(errorMessage,
6352                                                           libpq_gettext("invalid connection option \"%s\"\n"),
6353                                                           keyword);
6354                 return NULL;
6355         }
6356
6357         if (uri_decode)
6358         {
6359                 value_copy = conninfo_uri_decode(value, errorMessage);
6360                 if (value_copy == NULL)
6361                         /* conninfo_uri_decode already set an error message */
6362                         return NULL;
6363         }
6364         else
6365         {
6366                 value_copy = strdup(value);
6367                 if (value_copy == NULL)
6368                 {
6369                         printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
6370                         return NULL;
6371                 }
6372         }
6373
6374         if (option->val)
6375                 free(option->val);
6376         option->val = value_copy;
6377
6378         return option;
6379 }
6380
6381 /*
6382  * Find a PQconninfoOption option corresponding to the keyword in the
6383  * connOptions array.
6384  *
6385  * If successful, returns a pointer to the corresponding PQconninfoOption
6386  * structure.
6387  * If not successful, returns NULL.
6388  */
6389 static PQconninfoOption *
6390 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
6391 {
6392         PQconninfoOption *option;
6393
6394         for (option = connOptions; option->keyword != NULL; option++)
6395         {
6396                 if (strcmp(option->keyword, keyword) == 0)
6397                         return option;
6398         }
6399
6400         return NULL;
6401 }
6402
6403
6404 /*
6405  * Return the connection options used for the connection
6406  */
6407 PQconninfoOption *
6408 PQconninfo(PGconn *conn)
6409 {
6410         PQExpBufferData errorBuf;
6411         PQconninfoOption *connOptions;
6412
6413         if (conn == NULL)
6414                 return NULL;
6415
6416         /* We don't actually report any errors here, but callees want a buffer */
6417         initPQExpBuffer(&errorBuf);
6418         if (PQExpBufferDataBroken(errorBuf))
6419                 return NULL;                    /* out of memory already :-( */
6420
6421         connOptions = conninfo_init(&errorBuf);
6422
6423         if (connOptions != NULL)
6424         {
6425                 const internalPQconninfoOption *option;
6426
6427                 for (option = PQconninfoOptions; option->keyword; option++)
6428                 {
6429                         char      **connmember;
6430
6431                         if (option->connofs < 0)
6432                                 continue;
6433
6434                         connmember = (char **) ((char *) conn + option->connofs);
6435
6436                         if (*connmember)
6437                                 conninfo_storeval(connOptions, option->keyword, *connmember,
6438                                                                   &errorBuf, true, false);
6439                 }
6440         }
6441
6442         termPQExpBuffer(&errorBuf);
6443
6444         return connOptions;
6445 }
6446
6447
6448 void
6449 PQconninfoFree(PQconninfoOption *connOptions)
6450 {
6451         PQconninfoOption *option;
6452
6453         if (connOptions == NULL)
6454                 return;
6455
6456         for (option = connOptions; option->keyword != NULL; option++)
6457         {
6458                 if (option->val != NULL)
6459                         free(option->val);
6460         }
6461         free(connOptions);
6462 }
6463
6464
6465 /* =========== accessor functions for PGconn ========= */
6466 char *
6467 PQdb(const PGconn *conn)
6468 {
6469         if (!conn)
6470                 return NULL;
6471         return conn->dbName;
6472 }
6473
6474 char *
6475 PQuser(const PGconn *conn)
6476 {
6477         if (!conn)
6478                 return NULL;
6479         return conn->pguser;
6480 }
6481
6482 char *
6483 PQpass(const PGconn *conn)
6484 {
6485         char       *password = NULL;
6486
6487         if (!conn)
6488                 return NULL;
6489         if (conn->connhost != NULL)
6490                 password = conn->connhost[conn->whichhost].password;
6491         if (password == NULL)
6492                 password = conn->pgpass;
6493         /* Historically we've returned "" not NULL for no password specified */
6494         if (password == NULL)
6495                 password = "";
6496         return password;
6497 }
6498
6499 char *
6500 PQhost(const PGconn *conn)
6501 {
6502         if (!conn)
6503                 return NULL;
6504
6505         if (conn->connhost != NULL)
6506         {
6507                 /*
6508                  * Return the verbatim host value provided by user, or hostaddr in its
6509                  * lack.
6510                  */
6511                 if (conn->connhost[conn->whichhost].host != NULL &&
6512                         conn->connhost[conn->whichhost].host[0] != '\0')
6513                         return conn->connhost[conn->whichhost].host;
6514                 else if (conn->connhost[conn->whichhost].hostaddr != NULL &&
6515                                  conn->connhost[conn->whichhost].hostaddr[0] != '\0')
6516                         return conn->connhost[conn->whichhost].hostaddr;
6517         }
6518
6519         return "";
6520 }
6521
6522 char *
6523 PQhostaddr(const PGconn *conn)
6524 {
6525         if (!conn)
6526                 return NULL;
6527
6528         /* Return the parsed IP address */
6529         if (conn->connhost != NULL && conn->connip != NULL)
6530                 return conn->connip;
6531
6532         return "";
6533 }
6534
6535 char *
6536 PQport(const PGconn *conn)
6537 {
6538         if (!conn)
6539                 return NULL;
6540
6541         if (conn->connhost != NULL)
6542                 return conn->connhost[conn->whichhost].port;
6543
6544         return "";
6545 }
6546
6547 char *
6548 PQtty(const PGconn *conn)
6549 {
6550         if (!conn)
6551                 return NULL;
6552         return conn->pgtty;
6553 }
6554
6555 char *
6556 PQoptions(const PGconn *conn)
6557 {
6558         if (!conn)
6559                 return NULL;
6560         return conn->pgoptions;
6561 }
6562
6563 ConnStatusType
6564 PQstatus(const PGconn *conn)
6565 {
6566         if (!conn)
6567                 return CONNECTION_BAD;
6568         return conn->status;
6569 }
6570
6571 PGTransactionStatusType
6572 PQtransactionStatus(const PGconn *conn)
6573 {
6574         if (!conn || conn->status != CONNECTION_OK)
6575                 return PQTRANS_UNKNOWN;
6576         if (conn->asyncStatus != PGASYNC_IDLE)
6577                 return PQTRANS_ACTIVE;
6578         return conn->xactStatus;
6579 }
6580
6581 const char *
6582 PQparameterStatus(const PGconn *conn, const char *paramName)
6583 {
6584         const pgParameterStatus *pstatus;
6585
6586         if (!conn || !paramName)
6587                 return NULL;
6588         for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
6589         {
6590                 if (strcmp(pstatus->name, paramName) == 0)
6591                         return pstatus->value;
6592         }
6593         return NULL;
6594 }
6595
6596 int
6597 PQprotocolVersion(const PGconn *conn)
6598 {
6599         if (!conn)
6600                 return 0;
6601         if (conn->status == CONNECTION_BAD)
6602                 return 0;
6603         return PG_PROTOCOL_MAJOR(conn->pversion);
6604 }
6605
6606 int
6607 PQserverVersion(const PGconn *conn)
6608 {
6609         if (!conn)
6610                 return 0;
6611         if (conn->status == CONNECTION_BAD)
6612                 return 0;
6613         return conn->sversion;
6614 }
6615
6616 char *
6617 PQerrorMessage(const PGconn *conn)
6618 {
6619         if (!conn)
6620                 return libpq_gettext("connection pointer is NULL\n");
6621
6622         return conn->errorMessage.data;
6623 }
6624
6625 /*
6626  * In Windows, socket values are unsigned, and an invalid socket value
6627  * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
6628  * warning). Ideally we would return an unsigned value for PQsocket() on
6629  * Windows, but that would cause the function's return value to differ from
6630  * Unix, so we just return -1 for invalid sockets.
6631  * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
6632  * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
6633  */
6634 int
6635 PQsocket(const PGconn *conn)
6636 {
6637         if (!conn)
6638                 return -1;
6639         return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
6640 }
6641
6642 int
6643 PQbackendPID(const PGconn *conn)
6644 {
6645         if (!conn || conn->status != CONNECTION_OK)
6646                 return 0;
6647         return conn->be_pid;
6648 }
6649
6650 int
6651 PQconnectionNeedsPassword(const PGconn *conn)
6652 {
6653         char       *password;
6654
6655         if (!conn)
6656                 return false;
6657         password = PQpass(conn);
6658         if (conn->password_needed &&
6659                 (password == NULL || password[0] == '\0'))
6660                 return true;
6661         else
6662                 return false;
6663 }
6664
6665 int
6666 PQconnectionUsedPassword(const PGconn *conn)
6667 {
6668         if (!conn)
6669                 return false;
6670         if (conn->password_needed)
6671                 return true;
6672         else
6673                 return false;
6674 }
6675
6676 int
6677 PQclientEncoding(const PGconn *conn)
6678 {
6679         if (!conn || conn->status != CONNECTION_OK)
6680                 return -1;
6681         return conn->client_encoding;
6682 }
6683
6684 int
6685 PQsetClientEncoding(PGconn *conn, const char *encoding)
6686 {
6687         char            qbuf[128];
6688         static const char query[] = "set client_encoding to '%s'";
6689         PGresult   *res;
6690         int                     status;
6691
6692         if (!conn || conn->status != CONNECTION_OK)
6693                 return -1;
6694
6695         if (!encoding)
6696                 return -1;
6697
6698         /* Resolve special "auto" value from the locale */
6699         if (strcmp(encoding, "auto") == 0)
6700                 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
6701
6702         /* check query buffer overflow */
6703         if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
6704                 return -1;
6705
6706         /* ok, now send a query */
6707         sprintf(qbuf, query, encoding);
6708         res = PQexec(conn, qbuf);
6709
6710         if (res == NULL)
6711                 return -1;
6712         if (res->resultStatus != PGRES_COMMAND_OK)
6713                 status = -1;
6714         else
6715         {
6716                 /*
6717                  * In protocol 2 we have to assume the setting will stick, and adjust
6718                  * our state immediately.  In protocol 3 and up we can rely on the
6719                  * backend to report the parameter value, and we'll change state at
6720                  * that time.
6721                  */
6722                 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
6723                         pqSaveParameterStatus(conn, "client_encoding", encoding);
6724                 status = 0;                             /* everything is ok */
6725         }
6726         PQclear(res);
6727         return status;
6728 }
6729
6730 PGVerbosity
6731 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
6732 {
6733         PGVerbosity old;
6734
6735         if (!conn)
6736                 return PQERRORS_DEFAULT;
6737         old = conn->verbosity;
6738         conn->verbosity = verbosity;
6739         return old;
6740 }
6741
6742 PGContextVisibility
6743 PQsetErrorContextVisibility(PGconn *conn, PGContextVisibility show_context)
6744 {
6745         PGContextVisibility old;
6746
6747         if (!conn)
6748                 return PQSHOW_CONTEXT_ERRORS;
6749         old = conn->show_context;
6750         conn->show_context = show_context;
6751         return old;
6752 }
6753
6754 void
6755 PQtrace(PGconn *conn, FILE *debug_port)
6756 {
6757         if (conn == NULL)
6758                 return;
6759         PQuntrace(conn);
6760         conn->Pfdebug = debug_port;
6761 }
6762
6763 void
6764 PQuntrace(PGconn *conn)
6765 {
6766         if (conn == NULL)
6767                 return;
6768         if (conn->Pfdebug)
6769         {
6770                 fflush(conn->Pfdebug);
6771                 conn->Pfdebug = NULL;
6772         }
6773 }
6774
6775 PQnoticeReceiver
6776 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
6777 {
6778         PQnoticeReceiver old;
6779
6780         if (conn == NULL)
6781                 return NULL;
6782
6783         old = conn->noticeHooks.noticeRec;
6784         if (proc)
6785         {
6786                 conn->noticeHooks.noticeRec = proc;
6787                 conn->noticeHooks.noticeRecArg = arg;
6788         }
6789         return old;
6790 }
6791
6792 PQnoticeProcessor
6793 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
6794 {
6795         PQnoticeProcessor old;
6796
6797         if (conn == NULL)
6798                 return NULL;
6799
6800         old = conn->noticeHooks.noticeProc;
6801         if (proc)
6802         {
6803                 conn->noticeHooks.noticeProc = proc;
6804                 conn->noticeHooks.noticeProcArg = arg;
6805         }
6806         return old;
6807 }
6808
6809 /*
6810  * The default notice message receiver just gets the standard notice text
6811  * and sends it to the notice processor.  This two-level setup exists
6812  * mostly for backwards compatibility; perhaps we should deprecate use of
6813  * PQsetNoticeProcessor?
6814  */
6815 static void
6816 defaultNoticeReceiver(void *arg, const PGresult *res)
6817 {
6818         (void) arg;                                     /* not used */
6819         if (res->noticeHooks.noticeProc != NULL)
6820                 res->noticeHooks.noticeProc(res->noticeHooks.noticeProcArg,
6821                                                                         PQresultErrorMessage(res));
6822 }
6823
6824 /*
6825  * The default notice message processor just prints the
6826  * message on stderr.  Applications can override this if they
6827  * want the messages to go elsewhere (a window, for example).
6828  * Note that simply discarding notices is probably a bad idea.
6829  */
6830 static void
6831 defaultNoticeProcessor(void *arg, const char *message)
6832 {
6833         (void) arg;                                     /* not used */
6834         /* Note: we expect the supplied string to end with a newline already. */
6835         fprintf(stderr, "%s", message);
6836 }
6837
6838 /*
6839  * returns a pointer to the next token or NULL if the current
6840  * token doesn't match
6841  */
6842 static char *
6843 pwdfMatchesString(char *buf, const char *token)
6844 {
6845         char       *tbuf;
6846         const char *ttok;
6847         bool            bslash = false;
6848
6849         if (buf == NULL || token == NULL)
6850                 return NULL;
6851         tbuf = buf;
6852         ttok = token;
6853         if (tbuf[0] == '*' && tbuf[1] == ':')
6854                 return tbuf + 2;
6855         while (*tbuf != 0)
6856         {
6857                 if (*tbuf == '\\' && !bslash)
6858                 {
6859                         tbuf++;
6860                         bslash = true;
6861                 }
6862                 if (*tbuf == ':' && *ttok == 0 && !bslash)
6863                         return tbuf + 1;
6864                 bslash = false;
6865                 if (*ttok == 0)
6866                         return NULL;
6867                 if (*tbuf == *ttok)
6868                 {
6869                         tbuf++;
6870                         ttok++;
6871                 }
6872                 else
6873                         return NULL;
6874         }
6875         return NULL;
6876 }
6877
6878 /* Get a password from the password file. Return value is malloc'd. */
6879 static char *
6880 passwordFromFile(const char *hostname, const char *port, const char *dbname,
6881                                  const char *username, const char *pgpassfile)
6882 {
6883         FILE       *fp;
6884         struct stat stat_buf;
6885
6886 #define LINELEN NAMEDATALEN*5
6887         char            buf[LINELEN];
6888
6889         if (dbname == NULL || dbname[0] == '\0')
6890                 return NULL;
6891
6892         if (username == NULL || username[0] == '\0')
6893                 return NULL;
6894
6895         /* 'localhost' matches pghost of '' or the default socket directory */
6896         if (hostname == NULL || hostname[0] == '\0')
6897                 hostname = DefaultHost;
6898         else if (is_absolute_path(hostname))
6899
6900                 /*
6901                  * We should probably use canonicalize_path(), but then we have to
6902                  * bring path.c into libpq, and it doesn't seem worth it.
6903                  */
6904                 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
6905                         hostname = DefaultHost;
6906
6907         if (port == NULL || port[0] == '\0')
6908                 port = DEF_PGPORT_STR;
6909
6910         /* If password file cannot be opened, ignore it. */
6911         if (stat(pgpassfile, &stat_buf) != 0)
6912                 return NULL;
6913
6914 #ifndef WIN32
6915         if (!S_ISREG(stat_buf.st_mode))
6916         {
6917                 fprintf(stderr,
6918                                 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
6919                                 pgpassfile);
6920                 return NULL;
6921         }
6922
6923         /* If password file is insecure, alert the user and ignore it. */
6924         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
6925         {
6926                 fprintf(stderr,
6927                                 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
6928                                 pgpassfile);
6929                 return NULL;
6930         }
6931 #else
6932
6933         /*
6934          * On Win32, the directory is protected, so we don't have to check the
6935          * file.
6936          */
6937 #endif
6938
6939         fp = fopen(pgpassfile, "r");
6940         if (fp == NULL)
6941                 return NULL;
6942
6943         while (!feof(fp) && !ferror(fp))
6944         {
6945                 char       *t = buf,
6946                                    *ret,
6947                                    *p1,
6948                                    *p2;
6949                 int                     len;
6950
6951                 if (fgets(buf, sizeof(buf), fp) == NULL)
6952                         break;
6953
6954                 /* strip trailing newline and carriage return */
6955                 len = pg_strip_crlf(buf);
6956
6957                 if (len == 0)
6958                         continue;
6959
6960                 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
6961                         (t = pwdfMatchesString(t, port)) == NULL ||
6962                         (t = pwdfMatchesString(t, dbname)) == NULL ||
6963                         (t = pwdfMatchesString(t, username)) == NULL)
6964                         continue;
6965
6966                 /* Found a match. */
6967                 ret = strdup(t);
6968                 fclose(fp);
6969
6970                 if (!ret)
6971                 {
6972                         /* Out of memory. XXX: an error message would be nice. */
6973                         explicit_bzero(buf, sizeof(buf));
6974                         return NULL;
6975                 }
6976
6977                 /* De-escape password. */
6978                 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
6979                 {
6980                         if (*p1 == '\\' && p1[1] != '\0')
6981                                 ++p1;
6982                         *p2 = *p1;
6983                 }
6984                 *p2 = '\0';
6985
6986                 return ret;
6987         }
6988
6989         fclose(fp);
6990         explicit_bzero(buf, sizeof(buf));
6991         return NULL;
6992
6993 #undef LINELEN
6994 }
6995
6996
6997 /*
6998  *      If the connection failed due to bad password, we should mention
6999  *      if we got the password from the pgpassfile.
7000  */
7001 static void
7002 pgpassfileWarning(PGconn *conn)
7003 {
7004         /* If it was 'invalid authorization', add pgpassfile mention */
7005         /* only works with >= 9.0 servers */
7006         if (conn->password_needed &&
7007                 conn->connhost[conn->whichhost].password != NULL &&
7008                 conn->result)
7009         {
7010                 const char *sqlstate = PQresultErrorField(conn->result,
7011                                                                                                   PG_DIAG_SQLSTATE);
7012
7013                 if (sqlstate && strcmp(sqlstate, ERRCODE_INVALID_PASSWORD) == 0)
7014                         appendPQExpBuffer(&conn->errorMessage,
7015                                                           libpq_gettext("password retrieved from file \"%s\"\n"),
7016                                                           conn->pgpassfile);
7017         }
7018 }
7019
7020
7021 /*
7022  * Obtain user's home directory, return in given buffer
7023  *
7024  * On Unix, this actually returns the user's home directory.  On Windows
7025  * it returns the PostgreSQL-specific application data folder.
7026  *
7027  * This is essentially the same as get_home_path(), but we don't use that
7028  * because we don't want to pull path.c into libpq (it pollutes application
7029  * namespace).
7030  *
7031  * Returns true on success, false on failure to obtain the directory name.
7032  *
7033  * CAUTION: although in most situations failure is unexpected, there are users
7034  * who like to run applications in a home-directory-less environment.  On
7035  * failure, you almost certainly DO NOT want to report an error.  Just act as
7036  * though whatever file you were hoping to find in the home directory isn't
7037  * there (which it isn't).
7038  */
7039 bool
7040 pqGetHomeDirectory(char *buf, int bufsize)
7041 {
7042 #ifndef WIN32
7043         char            pwdbuf[BUFSIZ];
7044         struct passwd pwdstr;
7045         struct passwd *pwd = NULL;
7046
7047         (void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
7048         if (pwd == NULL)
7049                 return false;
7050         strlcpy(buf, pwd->pw_dir, bufsize);
7051         return true;
7052 #else
7053         char            tmppath[MAX_PATH];
7054
7055         ZeroMemory(tmppath, sizeof(tmppath));
7056         if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
7057                 return false;
7058         snprintf(buf, bufsize, "%s/postgresql", tmppath);
7059         return true;
7060 #endif
7061 }
7062
7063 /*
7064  * To keep the API consistent, the locking stubs are always provided, even
7065  * if they are not required.
7066  */
7067
7068 static void
7069 default_threadlock(int acquire)
7070 {
7071 #ifdef ENABLE_THREAD_SAFETY
7072 #ifndef WIN32
7073         static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
7074 #else
7075         static pthread_mutex_t singlethread_lock = NULL;
7076         static long mutex_initlock = 0;
7077
7078         if (singlethread_lock == NULL)
7079         {
7080                 while (InterlockedExchange(&mutex_initlock, 1) == 1)
7081                          /* loop, another thread own the lock */ ;
7082                 if (singlethread_lock == NULL)
7083                 {
7084                         if (pthread_mutex_init(&singlethread_lock, NULL))
7085                                 PGTHREAD_ERROR("failed to initialize mutex");
7086                 }
7087                 InterlockedExchange(&mutex_initlock, 0);
7088         }
7089 #endif
7090         if (acquire)
7091         {
7092                 if (pthread_mutex_lock(&singlethread_lock))
7093                         PGTHREAD_ERROR("failed to lock mutex");
7094         }
7095         else
7096         {
7097                 if (pthread_mutex_unlock(&singlethread_lock))
7098                         PGTHREAD_ERROR("failed to unlock mutex");
7099         }
7100 #endif
7101 }
7102
7103 pgthreadlock_t
7104 PQregisterThreadLock(pgthreadlock_t newhandler)
7105 {
7106         pgthreadlock_t prev = pg_g_threadlock;
7107
7108         if (newhandler)
7109                 pg_g_threadlock = newhandler;
7110         else
7111                 pg_g_threadlock = default_threadlock;
7112
7113         return prev;
7114 }