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