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