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