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