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