Debian Codegraph @

contrib/postgres_fdw/connection.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * connection.c
4 * Connection management functions for postgres_fdw
5 *
6 * Portions Copyright (c) 2012-2025, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * contrib/postgres_fdw/connection.c
10 *
11 *-------------------------------------------------------------------------
12 */
13 #include "postgres.h"
14
15 #if HAVE_POLL_H
16 #include <poll.h>
17 #endif
18
19 #include "access/xact.h"
20 #include "catalog/pg_user_mapping.h"
21 #include "commands/defrem.h"
22 #include "common/base64.h"
23 #include "funcapi.h"
24 #include "libpq/libpq-be.h"
25 #include "libpq/libpq-be-fe-helpers.h"
26 #include "mb/pg_wchar.h"
27 #include "miscadmin.h"
28 #include "pgstat.h"
29 #include "postgres_fdw.h"
30 #include "storage/latch.h"
31 #include "utils/builtins.h"
32 #include "utils/hsearch.h"
33 #include "utils/inval.h"
34 #include "utils/syscache.h"
35
36 /*
37 * Connection cache hash table entry
38 *
39 * The lookup key in this hash table is the user mapping OID. We use just one
40 * connection per user mapping ID, which ensures that all the scans use the
41 * same snapshot during a query. Using the user mapping OID rather than
42 * the foreign server OID + user OID avoids creating multiple connections when
43 * the public user mapping applies to all user OIDs.
44 *
45 * The "conn" pointer can be NULL if we don't currently have a live connection.
46 * When we do have a connection, xact_depth tracks the current depth of
47 * transactions and subtransactions open on the remote side. We need to issue
48 * commands at the same nesting depth on the remote as we're executing at
49 * ourselves, so that rolling back a subtransaction will kill the right
50 * queries and not the wrong ones.
51 */
52 typedef Oid ConnCacheKey;
53
54 typedef struct ConnCacheEntry
55 {
56 ConnCacheKey key; /* hash key (must be first) */
57 PGconn *conn; /* connection to foreign server, or NULL */
58 /* Remaining fields are invalid when conn is NULL: */
59 int xact_depth; /* 0 = no xact open, 1 = main xact open, 2 =
60 * one level of subxact open, etc */
61 bool have_prep_stmt; /* have we prepared any stmts in this xact? */
62 bool have_error; /* have any subxacts aborted in this xact? */
63 bool changing_xact_state; /* xact state change in process */
64 bool parallel_commit; /* do we commit (sub)xacts in parallel? */
65 bool parallel_abort; /* do we abort (sub)xacts in parallel? */
66 bool invalidated; /* true if reconnect is pending */
67 bool keep_connections; /* setting value of keep_connections
68 * server option */
69 Oid serverid; /* foreign server OID used to get server name */
70 uint32 server_hashvalue; /* hash value of foreign server OID */
71 uint32 mapping_hashvalue; /* hash value of user mapping OID */
72 PgFdwConnState state; /* extra per-connection state */
73 } ConnCacheEntry;
74
75 /*
76 * Connection cache (initialized on first use)
77 */
78 static HTAB *ConnectionHash = NULL;
79
80 /* for assigning cursor numbers and prepared statement numbers */
81 static unsigned int cursor_number = 0;
82 static unsigned int prep_stmt_number = 0;
83
84 /* tracks whether any work is needed in callback functions */
85 static bool xact_got_connection = false;
86
87 /* custom wait event values, retrieved from shared memory */
88 static uint32 pgfdw_we_cleanup_result = 0;
89 static uint32 pgfdw_we_connect = 0;
90 static uint32 pgfdw_we_get_result = 0;
91
92 /*
93 * Milliseconds to wait to cancel an in-progress query or execute a cleanup
94 * query; if it takes longer than 30 seconds to do these, we assume the
95 * connection is dead.
96 */
97 #define CONNECTION_CLEANUP_TIMEOUT 30000
98
99 /*
100 * Milliseconds to wait before issuing another cancel request. This covers
101 * the race condition where the remote session ignored our cancel request
102 * because it arrived while idle.
103 */
104 #define RETRY_CANCEL_TIMEOUT 1000
105
106 /* Macro for constructing abort command to be sent */
107 #define CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel) \
108 do { \
109 if (toplevel) \
110 snprintf((sql), sizeof(sql), \
111 "ABORT TRANSACTION"); \
112 else \
113 snprintf((sql), sizeof(sql), \
114 "ROLLBACK TO SAVEPOINT s%d; RELEASE SAVEPOINT s%d", \
115 (entry)->xact_depth, (entry)->xact_depth); \
116 } while(0)
117
118 /*
119 * Extension version number, for supporting older extension versions' objects
120 */
121 enum pgfdwVersion
122 {
123 PGFDW_V1_1 = 0,
124 PGFDW_V1_2,
125 };
126
127 /*
128 * SQL functions
129 */
130 PG_FUNCTION_INFO_V1(postgres_fdw_get_connections);
131 PG_FUNCTION_INFO_V1(postgres_fdw_get_connections_1_2);
132 PG_FUNCTION_INFO_V1(postgres_fdw_disconnect);
133 PG_FUNCTION_INFO_V1(postgres_fdw_disconnect_all);
134
135 /* prototypes of private functions */
136 static void make_new_connection(ConnCacheEntry *entry, UserMapping *user);
137 static PGconn *connect_pg_server(ForeignServer *server, UserMapping *user);
138 static void disconnect_pg_server(ConnCacheEntry *entry);
139 static void check_conn_params(const char **keywords, const char **values, UserMapping *user);
140 static void configure_remote_session(PGconn *conn);
141 static void do_sql_command_begin(PGconn *conn, const char *sql);
142 static void do_sql_command_end(PGconn *conn, const char *sql,
143 bool consume_input);
144 static void begin_remote_xact(ConnCacheEntry *entry);
145 static void pgfdw_xact_callback(XactEvent event, void *arg);
146 static void pgfdw_subxact_callback(SubXactEvent event,
147 SubTransactionId mySubid,
148 SubTransactionId parentSubid,
149 void *arg);
150 static void pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue);
151 static void pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry);
152 static void pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel);
153 static bool pgfdw_cancel_query(PGconn *conn);
154 static bool pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime);
155 static bool pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime,
156 TimestampTz retrycanceltime,
157 bool consume_input);
158 static bool pgfdw_exec_cleanup_query(PGconn *conn, const char *query,
159 bool ignore_errors);
160 static bool pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query);
161 static bool pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query,
162 TimestampTz endtime,
163 bool consume_input,
164 bool ignore_errors);
165 static bool pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime,
166 TimestampTz retrycanceltime,
167 PGresult **result, bool *timed_out);
168 static void pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel);
169 static bool pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel,
170 List **pending_entries,
171 List **cancel_requested);
172 static void pgfdw_finish_pre_commit_cleanup(List *pending_entries);
173 static void pgfdw_finish_pre_subcommit_cleanup(List *pending_entries,
174 int curlevel);
175 static void pgfdw_finish_abort_cleanup(List *pending_entries,
176 List *cancel_requested,
177 bool toplevel);
178 static void pgfdw_security_check(const char **keywords, const char **values,
179 UserMapping *user, PGconn *conn);
180 static bool UserMappingPasswordRequired(UserMapping *user);
181 static bool UseScramPassthrough(ForeignServer *server, UserMapping *user);
182 static bool disconnect_cached_connections(Oid serverid);
183 static void postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo,
184 enum pgfdwVersion api_version);
185 static int pgfdw_conn_check(PGconn *conn);
186 static bool pgfdw_conn_checkable(void);
187 static bool pgfdw_has_required_scram_options(const char **keywords, const char **values);
188
189 /*
190 * Get a PGconn which can be used to execute queries on the remote PostgreSQL
191 * server with the user's authorization. A new connection is established
192 * if we don't already have a suitable one, and a transaction is opened at
193 * the right subtransaction nesting depth if we didn't do that already.
194 *
195 * will_prep_stmt must be true if caller intends to create any prepared
196 * statements. Since those don't go away automatically at transaction end
197 * (not even on error), we need this flag to cue manual cleanup.
198 *
199 * If state is not NULL, *state receives the per-connection state associated
200 * with the PGconn.
201 */
202 PGconn *
203 GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
204 {
205 bool found;
206 bool retry = false;
207 ConnCacheEntry *entry;
208 ConnCacheKey key;
209 MemoryContext ccxt = CurrentMemoryContext;
210
211 /* First time through, initialize connection cache hashtable */
212 if (ConnectionHash == NULL)
213 {
214 HASHCTL ctl;
215
216 if (pgfdw_we_get_result == 0)
217 pgfdw_we_get_result =
218 WaitEventExtensionNew("PostgresFdwGetResult");
219
220 ctl.keysize = sizeof(ConnCacheKey);
221 ctl.entrysize = sizeof(ConnCacheEntry);
222 ConnectionHash = hash_create("postgres_fdw connections", 8,
223 &ctl,
224 HASH_ELEM | HASH_BLOBS);
225
226 /*
227 * Register some callback functions that manage connection cleanup.
228 * This should be done just once in each backend.
229 */
230 RegisterXactCallback(pgfdw_xact_callback, NULL);
231 RegisterSubXactCallback(pgfdw_subxact_callback, NULL);
232 CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
233 pgfdw_inval_callback, (Datum) 0);
234 CacheRegisterSyscacheCallback(USERMAPPINGOID,
235 pgfdw_inval_callback, (Datum) 0);
236 }
237
238 /* Set flag that we did GetConnection during the current transaction */
239 xact_got_connection = true;
240
241 /* Create hash key for the entry. Assume no pad bytes in key struct */
242 key = user->umid;
243
244 /*
245 * Find or create cached entry for requested connection.
246 */
247 entry = hash_search(ConnectionHash, &key, HASH_ENTER, &found);
248 if (!found)
249 {
250 /*
251 * We need only clear "conn" here; remaining fields will be filled
252 * later when "conn" is set.
253 */
254 entry->conn = NULL;
255 }
256
257 /* Reject further use of connections which failed abort cleanup. */
258 pgfdw_reject_incomplete_xact_state_change(entry);
259
260 /*
261 * If the connection needs to be remade due to invalidation, disconnect as
262 * soon as we're out of all transactions.
263 */
264 if (entry->conn != NULL && entry->invalidated && entry->xact_depth == 0)
265 {
266 elog(DEBUG3, "closing connection %p for option changes to take effect",
267 entry->conn);
268 disconnect_pg_server(entry);
269 }
270
271 /*
272 * If cache entry doesn't have a connection, we have to establish a new
273 * connection. (If connect_pg_server throws an error, the cache entry
274 * will remain in a valid empty state, ie conn == NULL.)
275 */
276 if (entry->conn == NULL)
277 make_new_connection(entry, user);
278
279 /*
280 * We check the health of the cached connection here when using it. In
281 * cases where we're out of all transactions, if a broken connection is
282 * detected, we try to reestablish a new connection later.
283 */
284 PG_TRY();
285 {
286 /* Process a pending asynchronous request if any. */
287 if (entry->state.pendingAreq)
288 process_pending_request(entry->state.pendingAreq);
289 /* Start a new transaction or subtransaction if needed. */
290 begin_remote_xact(entry);
291 }
292 PG_CATCH();
293 {
294 MemoryContext ecxt = MemoryContextSwitchTo(ccxt);
295 ErrorData *errdata = CopyErrorData();
296
297 /*
298 * Determine whether to try to reestablish the connection.
299 *
300 * After a broken connection is detected in libpq, any error other
301 * than connection failure (e.g., out-of-memory) can be thrown
302 * somewhere between return from libpq and the expected ereport() call
303 * in pgfdw_report_error(). In this case, since PQstatus() indicates
304 * CONNECTION_BAD, checking only PQstatus() causes the false detection
305 * of connection failure. To avoid this, we also verify that the
306 * error's sqlstate is ERRCODE_CONNECTION_FAILURE. Note that also
307 * checking only the sqlstate can cause another false detection
308 * because pgfdw_report_error() may report ERRCODE_CONNECTION_FAILURE
309 * for any libpq-originated error condition.
310 */
311 if (errdata->sqlerrcode != ERRCODE_CONNECTION_FAILURE ||
312 PQstatus(entry->conn) != CONNECTION_BAD ||
313 entry->xact_depth > 0)
314 {
315 MemoryContextSwitchTo(ecxt);
316 PG_RE_THROW();
317 }
318
319 /* Clean up the error state */
320 FlushErrorState();
321 FreeErrorData(errdata);
322 errdata = NULL;
323
324 retry = true;
325 }
326 PG_END_TRY();
327
328 /*
329 * If a broken connection is detected, disconnect it, reestablish a new
330 * connection and retry a new remote transaction. If connection failure is
331 * reported again, we give up getting a connection.
332 */
333 if (retry)
334 {
335 Assert(entry->xact_depth == 0);
336
337 ereport(DEBUG3,
338 (errmsg_internal("could not start remote transaction on connection %p",
339 entry->conn)),
340 errdetail_internal("%s", pchomp(PQerrorMessage(entry->conn))));
341
342 elog(DEBUG3, "closing connection %p to reestablish a new one",
343 entry->conn);
344 disconnect_pg_server(entry);
345
346 make_new_connection(entry, user);
347
348 begin_remote_xact(entry);
349 }
350
351 /* Remember if caller will prepare statements */
352 entry->have_prep_stmt |= will_prep_stmt;
353
354 /* If caller needs access to the per-connection state, return it. */
355 if (state)
356 *state = &entry->state;
357
358 return entry->conn;
359 }
360
361 /*
362 * Reset all transient state fields in the cached connection entry and
363 * establish new connection to the remote server.
364 */
365 static void
366 make_new_connection(ConnCacheEntry *entry, UserMapping *user)
367 {
368 ForeignServer *server = GetForeignServer(user->serverid);
369 ListCell *lc;
370
371 Assert(entry->conn == NULL);
372
373 /* Reset all transient state fields, to be sure all are clean */
374 entry->xact_depth = 0;
375 entry->have_prep_stmt = false;
376 entry->have_error = false;
377 entry->changing_xact_state = false;
378 entry->invalidated = false;
379 entry->serverid = server->serverid;
380 entry->server_hashvalue =
381 GetSysCacheHashValue1(FOREIGNSERVEROID,
382 ObjectIdGetDatum(server->serverid));
383 entry->mapping_hashvalue =
384 GetSysCacheHashValue1(USERMAPPINGOID,
385 ObjectIdGetDatum(user->umid));
386 memset(&entry->state, 0, sizeof(entry->state));
387
388 /*
389 * Determine whether to keep the connection that we're about to make here
390 * open even after the transaction using it ends, so that the subsequent
391 * transactions can re-use it.
392 *
393 * By default, all the connections to any foreign servers are kept open.
394 *
395 * Also determine whether to commit/abort (sub)transactions opened on the
396 * remote server in parallel at (sub)transaction end, which is disabled by
397 * default.
398 *
399 * Note: it's enough to determine these only when making a new connection
400 * because if these settings for it are changed, it will be closed and
401 * re-made later.
402 */
403 entry->keep_connections = true;
404 entry->parallel_commit = false;
405 entry->parallel_abort = false;
406 foreach(lc, server->options)
407 {
408 DefElem *def = (DefElem *) lfirst(lc);
409
410 if (strcmp(def->defname, "keep_connections") == 0)
411 entry->keep_connections = defGetBoolean(def);
412 else if (strcmp(def->defname, "parallel_commit") == 0)
413 entry->parallel_commit = defGetBoolean(def);
414 else if (strcmp(def->defname, "parallel_abort") == 0)
415 entry->parallel_abort = defGetBoolean(def);
416 }
417
418 /* Now try to make the connection */
419 entry->conn = connect_pg_server(server, user);
420
421 elog(DEBUG3, "new postgres_fdw connection %p for server \"%s\" (user mapping oid %u, userid %u)",
422 entry->conn, server->servername, user->umid, user->userid);
423 }
424
425 /*
426 * Check that non-superuser has used password or delegated credentials
427 * to establish connection; otherwise, he's piggybacking on the
428 * postgres server's user identity. See also dblink_security_check()
429 * in contrib/dblink and check_conn_params.
430 */
431 static void
432 pgfdw_security_check(const char **keywords, const char **values, UserMapping *user, PGconn *conn)
433 {
434 /* Superusers bypass the check */
435 if (superuser_arg(user->userid))
436 return;
437
438 #ifdef ENABLE_GSS
439 /* Connected via GSSAPI with delegated credentials- all good. */
440 if (PQconnectionUsedGSSAPI(conn) && be_gssapi_get_delegation(MyProcPort))
441 return;
442 #endif
443
444 /* Ok if superuser set PW required false. */
445 if (!UserMappingPasswordRequired(user))
446 return;
447
448 /* Connected via PW, with PW required true, and provided non-empty PW. */
449 if (PQconnectionUsedPassword(conn))
450 {
451 /* ok if params contain a non-empty password */
452 for (int i = 0; keywords[i] != NULL; i++)
453 {
454 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
455 return;
456 }
457 }
458
459 /*
460 * Ok if SCRAM pass-through is being used and all required SCRAM options
461 * are set correctly. If pgfdw_has_required_scram_options returns true we
462 * assume that UseScramPassthrough is also true since SCRAM options are
463 * only set when UseScramPassthrough is enabled.
464 */
465 if (MyProcPort != NULL && MyProcPort->has_scram_keys && pgfdw_has_required_scram_options(keywords, values))
466 return;
467
468 ereport(ERROR,
469 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
470 errmsg("password or GSSAPI delegated credentials required"),
471 errdetail("Non-superuser cannot connect if the server does not request a password or use GSSAPI with delegated credentials."),
472 errhint("Target server's authentication method must be changed or password_required=false set in the user mapping attributes.")));
473 }
474
475 /*
476 * Connect to remote server using specified server and user mapping properties.
477 */
478 static PGconn *
479 connect_pg_server(ForeignServer *server, UserMapping *user)
480 {
481 PGconn *volatile conn = NULL;
482
483 /*
484 * Use PG_TRY block to ensure closing connection on error.
485 */
486 PG_TRY();
487 {
488 const char **keywords;
489 const char **values;
490 char *appname = NULL;
491 int n;
492
493 /*
494 * Construct connection params from generic options of ForeignServer
495 * and UserMapping. (Some of them might not be libpq options, in
496 * which case we'll just waste a few array slots.) Add 4 extra slots
497 * for application_name, fallback_application_name, client_encoding,
498 * end marker, and 3 extra slots for scram keys and required scram
499 * pass-through options.
500 */
501 n = list_length(server->options) + list_length(user->options) + 4 + 3;
502 keywords = (const char **) palloc(n * sizeof(char *));
503 values = (const char **) palloc(n * sizeof(char *));
504
505 n = 0;
506 n += ExtractConnectionOptions(server->options,
507 keywords + n, values + n);
508 n += ExtractConnectionOptions(user->options,
509 keywords + n, values + n);
510
511 /*
512 * Use pgfdw_application_name as application_name if set.
513 *
514 * PQconnectdbParams() processes the parameter arrays from start to
515 * end. If any key word is repeated, the last value is used. Therefore
516 * note that pgfdw_application_name must be added to the arrays after
517 * options of ForeignServer are, so that it can override
518 * application_name set in ForeignServer.
519 */
520 if (pgfdw_application_name && *pgfdw_application_name != '\0')
521 {
522 keywords[n] = "application_name";
523 values[n] = pgfdw_application_name;
524 n++;
525 }
526
527 /*
528 * Search the parameter arrays to find application_name setting, and
529 * replace escape sequences in it with status information if found.
530 * The arrays are searched backwards because the last value is used if
531 * application_name is repeatedly set.
532 */
533 for (int i = n - 1; i >= 0; i--)
534 {
535 if (strcmp(keywords[i], "application_name") == 0 &&
536 *(values[i]) != '\0')
537 {
538 /*
539 * Use this application_name setting if it's not empty string
540 * even after any escape sequences in it are replaced.
541 */
542 appname = process_pgfdw_appname(values[i]);
543 if (appname[0] != '\0')
544 {
545 values[i] = appname;
546 break;
547 }
548
549 /*
550 * This empty application_name is not used, so we set
551 * values[i] to NULL and keep searching the array to find the
552 * next one.
553 */
554 values[i] = NULL;
555 pfree(appname);
556 appname = NULL;
557 }
558 }
559
560 /* Use "postgres_fdw" as fallback_application_name */
561 keywords[n] = "fallback_application_name";
562 values[n] = "postgres_fdw";
563 n++;
564
565 /* Set client_encoding so that libpq can convert encoding properly. */
566 keywords[n] = "client_encoding";
567 values[n] = GetDatabaseEncodingName();
568 n++;
569
570 /* Add required SCRAM pass-through connection options if it's enabled. */
571 if (MyProcPort != NULL && MyProcPort->has_scram_keys && UseScramPassthrough(server, user))
572 {
573 int len;
574 int encoded_len;
575
576 keywords[n] = "scram_client_key";
577 len = pg_b64_enc_len(sizeof(MyProcPort->scram_ClientKey));
578 /* don't forget the zero-terminator */
579 values[n] = palloc0(len + 1);
580 encoded_len = pg_b64_encode(MyProcPort->scram_ClientKey,
581 sizeof(MyProcPort->scram_ClientKey),
582 (char *) values[n], len);
583 if (encoded_len < 0)
584 elog(ERROR, "could not encode SCRAM client key");
585 n++;
586
587 keywords[n] = "scram_server_key";
588 len = pg_b64_enc_len(sizeof(MyProcPort->scram_ServerKey));
589 /* don't forget the zero-terminator */
590 values[n] = palloc0(len + 1);
591 encoded_len = pg_b64_encode(MyProcPort->scram_ServerKey,
592 sizeof(MyProcPort->scram_ServerKey),
593 (char *) values[n], len);
594 if (encoded_len < 0)
595 elog(ERROR, "could not encode SCRAM server key");
596 n++;
597
598 /*
599 * Require scram-sha-256 to ensure that no other auth method is
600 * used when connecting with foreign server.
601 */
602 keywords[n] = "require_auth";
603 values[n] = "scram-sha-256";
604 n++;
605 }
606
607 keywords[n] = values[n] = NULL;
608
609 /* Verify the set of connection parameters. */
610 check_conn_params(keywords, values, user);
611
612 /* first time, allocate or get the custom wait event */
613 if (pgfdw_we_connect == 0)
614 pgfdw_we_connect = WaitEventExtensionNew("PostgresFdwConnect");
615
616 /* OK to make connection */
617 conn = libpqsrv_connect_params(keywords, values,
618 false, /* expand_dbname */
619 pgfdw_we_connect);
620
621 if (!conn || PQstatus(conn) != CONNECTION_OK)
622 ereport(ERROR,
623 (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
624 errmsg("could not connect to server \"%s\"",
625 server->servername),
626 errdetail_internal("%s", pchomp(PQerrorMessage(conn)))));
627
628 /* Perform post-connection security checks. */
629 pgfdw_security_check(keywords, values, user, conn);
630
631 /* Prepare new session for use */
632 configure_remote_session(conn);
633
634 if (appname != NULL)
635 pfree(appname);
636 pfree(keywords);
637 pfree(values);
638 }
639 PG_CATCH();
640 {
641 libpqsrv_disconnect(conn);
642 PG_RE_THROW();
643 }
644 PG_END_TRY();
645
646 return conn;
647 }
648
649 /*
650 * Disconnect any open connection for a connection cache entry.
651 */
652 static void
653 disconnect_pg_server(ConnCacheEntry *entry)
654 {
655 if (entry->conn != NULL)
656 {
657 libpqsrv_disconnect(entry->conn);
658 entry->conn = NULL;
659 }
660 }
661
662 /*
663 * Check and return the value of password_required, if defined; otherwise,
664 * return true, which is the default value of it. The mapping has been
665 * pre-validated.
666 */
667 static bool
668 UserMappingPasswordRequired(UserMapping *user)
669 {
670 ListCell *cell;
671
672 foreach(cell, user->options)
673 {
674 DefElem *def = (DefElem *) lfirst(cell);
675
676 if (strcmp(def->defname, "password_required") == 0)
677 return defGetBoolean(def);
678 }
679
680 return true;
681 }
682
683 /*
684 * Return whether SCRAM pass-through is enabled.
685 *
686 * If use_scram_passthrough is specified in both the foreign server
687 * and the user mapping, the user mapping setting takes precedence.
688 */
689 static bool
690 UseScramPassthrough(ForeignServer *server, UserMapping *user)
691 {
692 ListCell *cell;
693
694 foreach(cell, user->options)
695 {
696 DefElem *def = (DefElem *) lfirst(cell);
697
698 if (strcmp(def->defname, "use_scram_passthrough") == 0)
699 return defGetBoolean(def);
700 }
701
702 foreach(cell, server->options)
703 {
704 DefElem *def = (DefElem *) lfirst(cell);
705
706 if (strcmp(def->defname, "use_scram_passthrough") == 0)
707 return defGetBoolean(def);
708 }
709
710 return false;
711 }
712
713 /*
714 * For non-superusers, insist that the connstr specify a password or that the
715 * user provided their own GSSAPI delegated credentials. This
716 * prevents a password from being picked up from .pgpass, a service file, the
717 * environment, etc. We don't want the postgres user's passwords,
718 * certificates, etc to be accessible to non-superusers. (See also
719 * dblink_connstr_check in contrib/dblink.)
720 */
721 static void
722 check_conn_params(const char **keywords, const char **values, UserMapping *user)
723 {
724 int i;
725
726 /* no check required if superuser */
727 if (superuser_arg(user->userid))
728 return;
729
730 #ifdef ENABLE_GSS
731 /* ok if the user provided their own delegated credentials */
732 if (be_gssapi_get_delegation(MyProcPort))
733 return;
734 #endif
735
736 /* ok if params contain a non-empty password */
737 for (i = 0; keywords[i] != NULL; i++)
738 {
739 if (strcmp(keywords[i], "password") == 0 && values[i][0] != '\0')
740 return;
741 }
742
743 /* ok if the superuser explicitly said so at user mapping creation time */
744 if (!UserMappingPasswordRequired(user))
745 return;
746
747 /*
748 * Ok if SCRAM pass-through is being used and all required scram options
749 * are set correctly. If pgfdw_has_required_scram_options returns true we
750 * assume that UseScramPassthrough is also true since SCRAM options are
751 * only set when UseScramPassthrough is enabled.
752 */
753 if (MyProcPort != NULL && MyProcPort->has_scram_keys && pgfdw_has_required_scram_options(keywords, values))
754 return;
755
756 ereport(ERROR,
757 (errcode(ERRCODE_S_R_E_PROHIBITED_SQL_STATEMENT_ATTEMPTED),
758 errmsg("password or GSSAPI delegated credentials required"),
759 errdetail("Non-superusers must delegate GSSAPI credentials, provide a password, or enable SCRAM pass-through in user mapping.")));
760 }
761
762 /*
763 * Issue SET commands to make sure remote session is configured properly.
764 *
765 * We do this just once at connection, assuming nothing will change the
766 * values later. Since we'll never send volatile function calls to the
767 * remote, there shouldn't be any way to break this assumption from our end.
768 * It's possible to think of ways to break it at the remote end, eg making
769 * a foreign table point to a view that includes a set_config call ---
770 * but once you admit the possibility of a malicious view definition,
771 * there are any number of ways to break things.
772 */
773 static void
774 configure_remote_session(PGconn *conn)
775 {
776 int remoteversion = PQserverVersion(conn);
777
778 /* Force the search path to contain only pg_catalog (see deparse.c) */
779 do_sql_command(conn, "SET search_path = pg_catalog");
780
781 /*
782 * Set remote timezone; this is basically just cosmetic, since all
783 * transmitted and returned timestamptzs should specify a zone explicitly
784 * anyway. However it makes the regression test outputs more predictable.
785 *
786 * We don't risk setting remote zone equal to ours, since the remote
787 * server might use a different timezone database. Instead, use GMT
788 * (quoted, because very old servers are picky about case). That's
789 * guaranteed to work regardless of the remote's timezone database,
790 * because pg_tzset() hard-wires it (at least in PG 9.2 and later).
791 */
792 do_sql_command(conn, "SET timezone = 'GMT'");
793
794 /*
795 * Set values needed to ensure unambiguous data output from remote. (This
796 * logic should match what pg_dump does. See also set_transmission_modes
797 * in postgres_fdw.c.)
798 */
799 do_sql_command(conn, "SET datestyle = ISO");
800 if (remoteversion >= 80400)
801 do_sql_command(conn, "SET intervalstyle = postgres");
802 if (remoteversion >= 90000)
803 do_sql_command(conn, "SET extra_float_digits = 3");
804 else
805 do_sql_command(conn, "SET extra_float_digits = 2");
806 }
807
808 /*
809 * Convenience subroutine to issue a non-data-returning SQL command to remote
810 */
811 void
812 do_sql_command(PGconn *conn, const char *sql)
813 {
814 do_sql_command_begin(conn, sql);
815 do_sql_command_end(conn, sql, false);
816 }
817
818 static void
819 do_sql_command_begin(PGconn *conn, const char *sql)
820 {
821 if (!PQsendQuery(conn, sql))
822 pgfdw_report_error(ERROR, NULL, conn, false, sql);
823 }
824
825 static void
826 do_sql_command_end(PGconn *conn, const char *sql, bool consume_input)
827 {
828 PGresult *res;
829
830 /*
831 * If requested, consume whatever data is available from the socket. (Note
832 * that if all data is available, this allows pgfdw_get_result to call
833 * PQgetResult without forcing the overhead of WaitLatchOrSocket, which
834 * would be large compared to the overhead of PQconsumeInput.)
835 */
836 if (consume_input && !PQconsumeInput(conn))
837 pgfdw_report_error(ERROR, NULL, conn, false, sql);
838 res = pgfdw_get_result(conn);
839 if (PQresultStatus(res) != PGRES_COMMAND_OK)
840 pgfdw_report_error(ERROR, res, conn, true, sql);
841 PQclear(res);
842 }
843
844 /*
845 * Start remote transaction or subtransaction, if needed.
846 *
847 * Note that we always use at least REPEATABLE READ in the remote session.
848 * This is so that, if a query initiates multiple scans of the same or
849 * different foreign tables, we will get snapshot-consistent results from
850 * those scans. A disadvantage is that we can't provide sane emulation of
851 * READ COMMITTED behavior --- it would be nice if we had some other way to
852 * control which remote queries share a snapshot.
853 */
854 static void
855 begin_remote_xact(ConnCacheEntry *entry)
856 {
857 int curlevel = GetCurrentTransactionNestLevel();
858
859 /* Start main transaction if we haven't yet */
860 if (entry->xact_depth <= 0)
861 {
862 const char *sql;
863
864 elog(DEBUG3, "starting remote transaction on connection %p",
865 entry->conn);
866
867 if (IsolationIsSerializable())
868 sql = "START TRANSACTION ISOLATION LEVEL SERIALIZABLE";
869 else
870 sql = "START TRANSACTION ISOLATION LEVEL REPEATABLE READ";
871 entry->changing_xact_state = true;
872 do_sql_command(entry->conn, sql);
873 entry->xact_depth = 1;
874 entry->changing_xact_state = false;
875 }
876
877 /*
878 * If we're in a subtransaction, stack up savepoints to match our level.
879 * This ensures we can rollback just the desired effects when a
880 * subtransaction aborts.
881 */
882 while (entry->xact_depth < curlevel)
883 {
884 char sql[64];
885
886 snprintf(sql, sizeof(sql), "SAVEPOINT s%d", entry->xact_depth + 1);
887 entry->changing_xact_state = true;
888 do_sql_command(entry->conn, sql);
889 entry->xact_depth++;
890 entry->changing_xact_state = false;
891 }
892 }
893
894 /*
895 * Release connection reference count created by calling GetConnection.
896 */
897 void
898 ReleaseConnection(PGconn *conn)
899 {
900 /*
901 * Currently, we don't actually track connection references because all
902 * cleanup is managed on a transaction or subtransaction basis instead. So
903 * there's nothing to do here.
904 */
905 }
906
907 /*
908 * Assign a "unique" number for a cursor.
909 *
910 * These really only need to be unique per connection within a transaction.
911 * For the moment we ignore the per-connection point and assign them across
912 * all connections in the transaction, but we ask for the connection to be
913 * supplied in case we want to refine that.
914 *
915 * Note that even if wraparound happens in a very long transaction, actual
916 * collisions are highly improbable; just be sure to use %u not %d to print.
917 */
918 unsigned int
919 GetCursorNumber(PGconn *conn)
920 {
921 return ++cursor_number;
922 }
923
924 /*
925 * Assign a "unique" number for a prepared statement.
926 *
927 * This works much like GetCursorNumber, except that we never reset the counter
928 * within a session. That's because we can't be 100% sure we've gotten rid
929 * of all prepared statements on all connections, and it's not really worth
930 * increasing the risk of prepared-statement name collisions by resetting.
931 */
932 unsigned int
933 GetPrepStmtNumber(PGconn *conn)
934 {
935 return ++prep_stmt_number;
936 }
937
938 /*
939 * Submit a query and wait for the result.
940 *
941 * Since we don't use non-blocking mode, this can't process interrupts while
942 * pushing the query text to the server. That risk is relatively small, so we
943 * ignore that for now.
944 *
945 * Caller is responsible for the error handling on the result.
946 */
947 PGresult *
948 pgfdw_exec_query(PGconn *conn, const char *query, PgFdwConnState *state)
949 {
950 /* First, process a pending asynchronous request, if any. */
951 if (state && state->pendingAreq)
952 process_pending_request(state->pendingAreq);
953
954 if (!PQsendQuery(conn, query))
955 return NULL;
956 return pgfdw_get_result(conn);
957 }
958
959 /*
960 * Wrap libpqsrv_get_result_last(), adding wait event.
961 *
962 * Caller is responsible for the error handling on the result.
963 */
964 PGresult *
965 pgfdw_get_result(PGconn *conn)
966 {
967 return libpqsrv_get_result_last(conn, pgfdw_we_get_result);
968 }
969
970 /*
971 * Report an error we got from the remote server.
972 *
973 * elevel: error level to use (typically ERROR, but might be less)
974 * res: PGresult containing the error
975 * conn: connection we did the query on
976 * clear: if true, PQclear the result (otherwise caller will handle it)
977 * sql: NULL, or text of remote command we tried to execute
978 *
979 * Note: callers that choose not to throw ERROR for a remote error are
980 * responsible for making sure that the associated ConnCacheEntry gets
981 * marked with have_error = true.
982 */
983 void
984 pgfdw_report_error(int elevel, PGresult *res, PGconn *conn,
985 bool clear, const char *sql)
986 {
987 /* If requested, PGresult must be released before leaving this function. */
988 PG_TRY();
989 {
990 char *diag_sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
991 char *message_primary = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
992 char *message_detail = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
993 char *message_hint = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
994 char *message_context = PQresultErrorField(res, PG_DIAG_CONTEXT);
995 int sqlstate;
996
997 if (diag_sqlstate)
998 sqlstate = MAKE_SQLSTATE(diag_sqlstate[0],
999 diag_sqlstate[1],
1000 diag_sqlstate[2],
1001 diag_sqlstate[3],
1002 diag_sqlstate[4]);
1003 else
1004 sqlstate = ERRCODE_CONNECTION_FAILURE;
1005
1006 /*
1007 * If we don't get a message from the PGresult, try the PGconn. This
1008 * is needed because for connection-level failures, PQgetResult may
1009 * just return NULL, not a PGresult at all.
1010 */
1011 if (message_primary == NULL)
1012 message_primary = pchomp(PQerrorMessage(conn));
1013
1014 ereport(elevel,
1015 (errcode(sqlstate),
1016 (message_primary != NULL && message_primary[0] != '\0') ?
1017 errmsg_internal("%s", message_primary) :
1018 errmsg("could not obtain message string for remote error"),
1019 message_detail ? errdetail_internal("%s", message_detail) : 0,
1020 message_hint ? errhint("%s", message_hint) : 0,
1021 message_context ? errcontext("%s", message_context) : 0,
1022 sql ? errcontext("remote SQL command: %s", sql) : 0));
1023 }
1024 PG_FINALLY();
1025 {
1026 if (clear)
1027 PQclear(res);
1028 }
1029 PG_END_TRY();
1030 }
1031
1032 /*
1033 * pgfdw_xact_callback --- cleanup at main-transaction end.
1034 *
1035 * This runs just late enough that it must not enter user-defined code
1036 * locally. (Entering such code on the remote side is fine. Its remote
1037 * COMMIT TRANSACTION may run deferred triggers.)
1038 */
1039 static void
1040 pgfdw_xact_callback(XactEvent event, void *arg)
1041 {
1042 HASH_SEQ_STATUS scan;
1043 ConnCacheEntry *entry;
1044 List *pending_entries = NIL;
1045 List *cancel_requested = NIL;
1046
1047 /* Quick exit if no connections were touched in this transaction. */
1048 if (!xact_got_connection)
1049 return;
1050
1051 /*
1052 * Scan all connection cache entries to find open remote transactions, and
1053 * close them.
1054 */
1055 hash_seq_init(&scan, ConnectionHash);
1056 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1057 {
1058 PGresult *res;
1059
1060 /* Ignore cache entry if no open connection right now */
1061 if (entry->conn == NULL)
1062 continue;
1063
1064 /* If it has an open remote transaction, try to close it */
1065 if (entry->xact_depth > 0)
1066 {
1067 elog(DEBUG3, "closing remote transaction on connection %p",
1068 entry->conn);
1069
1070 switch (event)
1071 {
1072 case XACT_EVENT_PARALLEL_PRE_COMMIT:
1073 case XACT_EVENT_PRE_COMMIT:
1074
1075 /*
1076 * If abort cleanup previously failed for this connection,
1077 * we can't issue any more commands against it.
1078 */
1079 pgfdw_reject_incomplete_xact_state_change(entry);
1080
1081 /* Commit all remote transactions during pre-commit */
1082 entry->changing_xact_state = true;
1083 if (entry->parallel_commit)
1084 {
1085 do_sql_command_begin(entry->conn, "COMMIT TRANSACTION");
1086 pending_entries = lappend(pending_entries, entry);
1087 continue;
1088 }
1089 do_sql_command(entry->conn, "COMMIT TRANSACTION");
1090 entry->changing_xact_state = false;
1091
1092 /*
1093 * If there were any errors in subtransactions, and we
1094 * made prepared statements, do a DEALLOCATE ALL to make
1095 * sure we get rid of all prepared statements. This is
1096 * annoying and not terribly bulletproof, but it's
1097 * probably not worth trying harder.
1098 *
1099 * DEALLOCATE ALL only exists in 8.3 and later, so this
1100 * constrains how old a server postgres_fdw can
1101 * communicate with. We intentionally ignore errors in
1102 * the DEALLOCATE, so that we can hobble along to some
1103 * extent with older servers (leaking prepared statements
1104 * as we go; but we don't really support update operations
1105 * pre-8.3 anyway).
1106 */
1107 if (entry->have_prep_stmt && entry->have_error)
1108 {
1109 res = pgfdw_exec_query(entry->conn, "DEALLOCATE ALL",
1110 NULL);
1111 PQclear(res);
1112 }
1113 entry->have_prep_stmt = false;
1114 entry->have_error = false;
1115 break;
1116 case XACT_EVENT_PRE_PREPARE:
1117
1118 /*
1119 * We disallow any remote transactions, since it's not
1120 * very reasonable to hold them open until the prepared
1121 * transaction is committed. For the moment, throw error
1122 * unconditionally; later we might allow read-only cases.
1123 * Note that the error will cause us to come right back
1124 * here with event == XACT_EVENT_ABORT, so we'll clean up
1125 * the connection state at that point.
1126 */
1127 ereport(ERROR,
1128 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1129 errmsg("cannot PREPARE a transaction that has operated on postgres_fdw foreign tables")));
1130 break;
1131 case XACT_EVENT_PARALLEL_COMMIT:
1132 case XACT_EVENT_COMMIT:
1133 case XACT_EVENT_PREPARE:
1134 /* Pre-commit should have closed the open transaction */
1135 elog(ERROR, "missed cleaning up connection during pre-commit");
1136 break;
1137 case XACT_EVENT_PARALLEL_ABORT:
1138 case XACT_EVENT_ABORT:
1139 /* Rollback all remote transactions during abort */
1140 if (entry->parallel_abort)
1141 {
1142 if (pgfdw_abort_cleanup_begin(entry, true,
1143 &pending_entries,
1144 &cancel_requested))
1145 continue;
1146 }
1147 else
1148 pgfdw_abort_cleanup(entry, true);
1149 break;
1150 }
1151 }
1152
1153 /* Reset state to show we're out of a transaction */
1154 pgfdw_reset_xact_state(entry, true);
1155 }
1156
1157 /* If there are any pending connections, finish cleaning them up */
1158 if (pending_entries || cancel_requested)
1159 {
1160 if (event == XACT_EVENT_PARALLEL_PRE_COMMIT ||
1161 event == XACT_EVENT_PRE_COMMIT)
1162 {
1163 Assert(cancel_requested == NIL);
1164 pgfdw_finish_pre_commit_cleanup(pending_entries);
1165 }
1166 else
1167 {
1168 Assert(event == XACT_EVENT_PARALLEL_ABORT ||
1169 event == XACT_EVENT_ABORT);
1170 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1171 true);
1172 }
1173 }
1174
1175 /*
1176 * Regardless of the event type, we can now mark ourselves as out of the
1177 * transaction. (Note: if we are here during PRE_COMMIT or PRE_PREPARE,
1178 * this saves a useless scan of the hashtable during COMMIT or PREPARE.)
1179 */
1180 xact_got_connection = false;
1181
1182 /* Also reset cursor numbering for next transaction */
1183 cursor_number = 0;
1184 }
1185
1186 /*
1187 * pgfdw_subxact_callback --- cleanup at subtransaction end.
1188 */
1189 static void
1190 pgfdw_subxact_callback(SubXactEvent event, SubTransactionId mySubid,
1191 SubTransactionId parentSubid, void *arg)
1192 {
1193 HASH_SEQ_STATUS scan;
1194 ConnCacheEntry *entry;
1195 int curlevel;
1196 List *pending_entries = NIL;
1197 List *cancel_requested = NIL;
1198
1199 /* Nothing to do at subxact start, nor after commit. */
1200 if (!(event == SUBXACT_EVENT_PRE_COMMIT_SUB ||
1201 event == SUBXACT_EVENT_ABORT_SUB))
1202 return;
1203
1204 /* Quick exit if no connections were touched in this transaction. */
1205 if (!xact_got_connection)
1206 return;
1207
1208 /*
1209 * Scan all connection cache entries to find open remote subtransactions
1210 * of the current level, and close them.
1211 */
1212 curlevel = GetCurrentTransactionNestLevel();
1213 hash_seq_init(&scan, ConnectionHash);
1214 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1215 {
1216 char sql[100];
1217
1218 /*
1219 * We only care about connections with open remote subtransactions of
1220 * the current level.
1221 */
1222 if (entry->conn == NULL || entry->xact_depth < curlevel)
1223 continue;
1224
1225 if (entry->xact_depth > curlevel)
1226 elog(ERROR, "missed cleaning up remote subtransaction at level %d",
1227 entry->xact_depth);
1228
1229 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1230 {
1231 /*
1232 * If abort cleanup previously failed for this connection, we
1233 * can't issue any more commands against it.
1234 */
1235 pgfdw_reject_incomplete_xact_state_change(entry);
1236
1237 /* Commit all remote subtransactions during pre-commit */
1238 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1239 entry->changing_xact_state = true;
1240 if (entry->parallel_commit)
1241 {
1242 do_sql_command_begin(entry->conn, sql);
1243 pending_entries = lappend(pending_entries, entry);
1244 continue;
1245 }
1246 do_sql_command(entry->conn, sql);
1247 entry->changing_xact_state = false;
1248 }
1249 else
1250 {
1251 /* Rollback all remote subtransactions during abort */
1252 if (entry->parallel_abort)
1253 {
1254 if (pgfdw_abort_cleanup_begin(entry, false,
1255 &pending_entries,
1256 &cancel_requested))
1257 continue;
1258 }
1259 else
1260 pgfdw_abort_cleanup(entry, false);
1261 }
1262
1263 /* OK, we're outta that level of subtransaction */
1264 pgfdw_reset_xact_state(entry, false);
1265 }
1266
1267 /* If there are any pending connections, finish cleaning them up */
1268 if (pending_entries || cancel_requested)
1269 {
1270 if (event == SUBXACT_EVENT_PRE_COMMIT_SUB)
1271 {
1272 Assert(cancel_requested == NIL);
1273 pgfdw_finish_pre_subcommit_cleanup(pending_entries, curlevel);
1274 }
1275 else
1276 {
1277 Assert(event == SUBXACT_EVENT_ABORT_SUB);
1278 pgfdw_finish_abort_cleanup(pending_entries, cancel_requested,
1279 false);
1280 }
1281 }
1282 }
1283
1284 /*
1285 * Connection invalidation callback function
1286 *
1287 * After a change to a pg_foreign_server or pg_user_mapping catalog entry,
1288 * close connections depending on that entry immediately if current transaction
1289 * has not used those connections yet. Otherwise, mark those connections as
1290 * invalid and then make pgfdw_xact_callback() close them at the end of current
1291 * transaction, since they cannot be closed in the midst of the transaction
1292 * using them. Closed connections will be remade at the next opportunity if
1293 * necessary.
1294 *
1295 * Although most cache invalidation callbacks blow away all the related stuff
1296 * regardless of the given hashvalue, connections are expensive enough that
1297 * it's worth trying to avoid that.
1298 *
1299 * NB: We could avoid unnecessary disconnection more strictly by examining
1300 * individual option values, but it seems too much effort for the gain.
1301 */
1302 static void
1303 pgfdw_inval_callback(Datum arg, int cacheid, uint32 hashvalue)
1304 {
1305 HASH_SEQ_STATUS scan;
1306 ConnCacheEntry *entry;
1307
1308 Assert(cacheid == FOREIGNSERVEROID || cacheid == USERMAPPINGOID);
1309
1310 /* ConnectionHash must exist already, if we're registered */
1311 hash_seq_init(&scan, ConnectionHash);
1312 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
1313 {
1314 /* Ignore invalid entries */
1315 if (entry->conn == NULL)
1316 continue;
1317
1318 /* hashvalue == 0 means a cache reset, must clear all state */
1319 if (hashvalue == 0 ||
1320 (cacheid == FOREIGNSERVEROID &&
1321 entry->server_hashvalue == hashvalue) ||
1322 (cacheid == USERMAPPINGOID &&
1323 entry->mapping_hashvalue == hashvalue))
1324 {
1325 /*
1326 * Close the connection immediately if it's not used yet in this
1327 * transaction. Otherwise mark it as invalid so that
1328 * pgfdw_xact_callback() can close it at the end of this
1329 * transaction.
1330 */
1331 if (entry->xact_depth == 0)
1332 {
1333 elog(DEBUG3, "discarding connection %p", entry->conn);
1334 disconnect_pg_server(entry);
1335 }
1336 else
1337 entry->invalidated = true;
1338 }
1339 }
1340 }
1341
1342 /*
1343 * Raise an error if the given connection cache entry is marked as being
1344 * in the middle of an xact state change. This should be called at which no
1345 * such change is expected to be in progress; if one is found to be in
1346 * progress, it means that we aborted in the middle of a previous state change
1347 * and now don't know what the remote transaction state actually is.
1348 * Such connections can't safely be further used. Re-establishing the
1349 * connection would change the snapshot and roll back any writes already
1350 * performed, so that's not an option, either. Thus, we must abort.
1351 *
1352 * Note: there might be open cursors that use the connection, so even if the
1353 * connection cache entry is marked as such, we will retain it until abort
1354 * cleanup of the main transaction, to ensure such open cursors can safely
1355 * refer to the PGconn for the connection.
1356 */
1357 static void
1358 pgfdw_reject_incomplete_xact_state_change(ConnCacheEntry *entry)
1359 {
1360 ForeignServer *server;
1361
1362 /* nothing to do for inactive entries and entries of sane state */
1363 if (entry->conn == NULL || !entry->changing_xact_state)
1364 return;
1365
1366 /* find server name to be shown in the message below */
1367 server = GetForeignServer(entry->serverid);
1368
1369 ereport(ERROR,
1370 (errcode(ERRCODE_CONNECTION_EXCEPTION),
1371 errmsg("connection to server \"%s\" cannot be used due to abort cleanup failure",
1372 server->servername)));
1373 }
1374
1375 /*
1376 * Reset state to show we're out of a (sub)transaction.
1377 */
1378 static void
1379 pgfdw_reset_xact_state(ConnCacheEntry *entry, bool toplevel)
1380 {
1381 if (toplevel)
1382 {
1383 /* Reset state to show we're out of a transaction */
1384 entry->xact_depth = 0;
1385
1386 /*
1387 * If the connection isn't in a good idle state, it is marked as
1388 * invalid or keep_connections option of its server is disabled, then
1389 * discard it to recover. Next GetConnection will open a new
1390 * connection.
1391 */
1392 if (PQstatus(entry->conn) != CONNECTION_OK ||
1393 PQtransactionStatus(entry->conn) != PQTRANS_IDLE ||
1394 entry->changing_xact_state ||
1395 entry->invalidated ||
1396 !entry->keep_connections)
1397 {
1398 elog(DEBUG3, "discarding connection %p", entry->conn);
1399 disconnect_pg_server(entry);
1400 }
1401 }
1402 else
1403 {
1404 /* Reset state to show we're out of a subtransaction */
1405 entry->xact_depth--;
1406 }
1407 }
1408
1409 /*
1410 * Cancel the currently-in-progress query (whose query text we do not have)
1411 * and ignore the result. Returns true if we successfully cancel the query
1412 * and discard any pending result, and false if not.
1413 *
1414 * It's not a huge problem if we throw an ERROR here, but if we get into error
1415 * recursion trouble, we'll end up slamming the connection shut, which will
1416 * necessitate failing the entire toplevel transaction even if subtransactions
1417 * were used. Try to use WARNING where we can.
1418 *
1419 * XXX: if the query was one sent by fetch_more_data_begin(), we could get the
1420 * query text from the pendingAreq saved in the per-connection state, then
1421 * report the query using it.
1422 */
1423 static bool
1424 pgfdw_cancel_query(PGconn *conn)
1425 {
1426 TimestampTz now = GetCurrentTimestamp();
1427 TimestampTz endtime;
1428 TimestampTz retrycanceltime;
1429
1430 /*
1431 * If it takes too long to cancel the query and discard the result, assume
1432 * the connection is dead.
1433 */
1434 endtime = TimestampTzPlusMilliseconds(now, CONNECTION_CLEANUP_TIMEOUT);
1435
1436 /*
1437 * Also, lose patience and re-issue the cancel request after a little bit.
1438 * (This serves to close some race conditions.)
1439 */
1440 retrycanceltime = TimestampTzPlusMilliseconds(now, RETRY_CANCEL_TIMEOUT);
1441
1442 if (!pgfdw_cancel_query_begin(conn, endtime))
1443 return false;
1444 return pgfdw_cancel_query_end(conn, endtime, retrycanceltime, false);
1445 }
1446
1447 /*
1448 * Submit a cancel request to the given connection, waiting only until
1449 * the given time.
1450 *
1451 * We sleep interruptibly until we receive confirmation that the cancel
1452 * request has been accepted, and if it is, return true; if the timeout
1453 * lapses without that, or the request fails for whatever reason, return
1454 * false.
1455 */
1456 static bool
1457 pgfdw_cancel_query_begin(PGconn *conn, TimestampTz endtime)
1458 {
1459 const char *errormsg = libpqsrv_cancel(conn, endtime);
1460
1461 if (errormsg != NULL)
1462 ereport(WARNING,
1463 errcode(ERRCODE_CONNECTION_FAILURE),
1464 errmsg("could not send cancel request: %s", errormsg));
1465
1466 return errormsg == NULL;
1467 }
1468
1469 static bool
1470 pgfdw_cancel_query_end(PGconn *conn, TimestampTz endtime,
1471 TimestampTz retrycanceltime, bool consume_input)
1472 {
1473 PGresult *result;
1474 bool timed_out;
1475
1476 /*
1477 * If requested, consume whatever data is available from the socket. (Note
1478 * that if all data is available, this allows pgfdw_get_cleanup_result to
1479 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1480 * which would be large compared to the overhead of PQconsumeInput.)
1481 */
1482 if (consume_input && !PQconsumeInput(conn))
1483 {
1484 ereport(WARNING,
1485 (errcode(ERRCODE_CONNECTION_FAILURE),
1486 errmsg("could not get result of cancel request: %s",
1487 pchomp(PQerrorMessage(conn)))));
1488 return false;
1489 }
1490
1491 /* Get and discard the result of the query. */
1492 if (pgfdw_get_cleanup_result(conn, endtime, retrycanceltime,
1493 &result, &timed_out))
1494 {
1495 if (timed_out)
1496 ereport(WARNING,
1497 (errmsg("could not get result of cancel request due to timeout")));
1498 else
1499 ereport(WARNING,
1500 (errcode(ERRCODE_CONNECTION_FAILURE),
1501 errmsg("could not get result of cancel request: %s",
1502 pchomp(PQerrorMessage(conn)))));
1503
1504 return false;
1505 }
1506 PQclear(result);
1507
1508 return true;
1509 }
1510
1511 /*
1512 * Submit a query during (sub)abort cleanup and wait up to 30 seconds for the
1513 * result. If the query is executed without error, the return value is true.
1514 * If the query is executed successfully but returns an error, the return
1515 * value is true if and only if ignore_errors is set. If the query can't be
1516 * sent or times out, the return value is false.
1517 *
1518 * It's not a huge problem if we throw an ERROR here, but if we get into error
1519 * recursion trouble, we'll end up slamming the connection shut, which will
1520 * necessitate failing the entire toplevel transaction even if subtransactions
1521 * were used. Try to use WARNING where we can.
1522 */
1523 static bool
1524 pgfdw_exec_cleanup_query(PGconn *conn, const char *query, bool ignore_errors)
1525 {
1526 TimestampTz endtime;
1527
1528 /*
1529 * If it takes too long to execute a cleanup query, assume the connection
1530 * is dead. It's fairly likely that this is why we aborted in the first
1531 * place (e.g. statement timeout, user cancel), so the timeout shouldn't
1532 * be too long.
1533 */
1534 endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
1535 CONNECTION_CLEANUP_TIMEOUT);
1536
1537 if (!pgfdw_exec_cleanup_query_begin(conn, query))
1538 return false;
1539 return pgfdw_exec_cleanup_query_end(conn, query, endtime,
1540 false, ignore_errors);
1541 }
1542
1543 static bool
1544 pgfdw_exec_cleanup_query_begin(PGconn *conn, const char *query)
1545 {
1546 Assert(query != NULL);
1547
1548 /*
1549 * Submit a query. Since we don't use non-blocking mode, this also can
1550 * block. But its risk is relatively small, so we ignore that for now.
1551 */
1552 if (!PQsendQuery(conn, query))
1553 {
1554 pgfdw_report_error(WARNING, NULL, conn, false, query);
1555 return false;
1556 }
1557
1558 return true;
1559 }
1560
1561 static bool
1562 pgfdw_exec_cleanup_query_end(PGconn *conn, const char *query,
1563 TimestampTz endtime, bool consume_input,
1564 bool ignore_errors)
1565 {
1566 PGresult *result;
1567 bool timed_out;
1568
1569 Assert(query != NULL);
1570
1571 /*
1572 * If requested, consume whatever data is available from the socket. (Note
1573 * that if all data is available, this allows pgfdw_get_cleanup_result to
1574 * call PQgetResult without forcing the overhead of WaitLatchOrSocket,
1575 * which would be large compared to the overhead of PQconsumeInput.)
1576 */
1577 if (consume_input && !PQconsumeInput(conn))
1578 {
1579 pgfdw_report_error(WARNING, NULL, conn, false, query);
1580 return false;
1581 }
1582
1583 /* Get the result of the query. */
1584 if (pgfdw_get_cleanup_result(conn, endtime, endtime, &result, &timed_out))
1585 {
1586 if (timed_out)
1587 ereport(WARNING,
1588 (errmsg("could not get query result due to timeout"),
1589 errcontext("remote SQL command: %s", query)));
1590 else
1591 pgfdw_report_error(WARNING, NULL, conn, false, query);
1592
1593 return false;
1594 }
1595
1596 /* Issue a warning if not successful. */
1597 if (PQresultStatus(result) != PGRES_COMMAND_OK)
1598 {
1599 pgfdw_report_error(WARNING, result, conn, true, query);
1600 return ignore_errors;
1601 }
1602 PQclear(result);
1603
1604 return true;
1605 }
1606
1607 /*
1608 * Get, during abort cleanup, the result of a query that is in progress.
1609 * This might be a query that is being interrupted by a cancel request or by
1610 * transaction abort, or it might be a query that was initiated as part of
1611 * transaction abort to get the remote side back to the appropriate state.
1612 *
1613 * endtime is the time at which we should give up and assume the remote side
1614 * is dead. retrycanceltime is the time at which we should issue a fresh
1615 * cancel request (pass the same value as endtime if this is not wanted).
1616 *
1617 * Returns true if the timeout expired or connection trouble occurred,
1618 * false otherwise. Sets *result except in case of a true result.
1619 * Sets *timed_out to true only when the timeout expired.
1620 */
1621 static bool
1622 pgfdw_get_cleanup_result(PGconn *conn, TimestampTz endtime,
1623 TimestampTz retrycanceltime,
1624 PGresult **result,
1625 bool *timed_out)
1626 {
1627 volatile bool failed = false;
1628 PGresult *volatile last_res = NULL;
1629
1630 *result = NULL;
1631 *timed_out = false;
1632
1633 /* In what follows, do not leak any PGresults on an error. */
1634 PG_TRY();
1635 {
1636 int canceldelta = RETRY_CANCEL_TIMEOUT * 2;
1637
1638 for (;;)
1639 {
1640 PGresult *res;
1641
1642 while (PQisBusy(conn))
1643 {
1644 int wc;
1645 TimestampTz now = GetCurrentTimestamp();
1646 long cur_timeout;
1647
1648 /* If timeout has expired, give up. */
1649 if (now >= endtime)
1650 {
1651 *timed_out = true;
1652 failed = true;
1653 goto exit;
1654 }
1655
1656 /* If we need to re-issue the cancel request, do that. */
1657 if (now >= retrycanceltime)
1658 {
1659 /* We ignore failure to issue the repeated request. */
1660 (void) libpqsrv_cancel(conn, endtime);
1661
1662 /* Recompute "now" in case that took measurable time. */
1663 now = GetCurrentTimestamp();
1664
1665 /* Adjust re-cancel timeout in increasing steps. */
1666 retrycanceltime = TimestampTzPlusMilliseconds(now,
1667 canceldelta);
1668 canceldelta += canceldelta;
1669 }
1670
1671 /* If timeout has expired, give up, else get sleep time. */
1672 cur_timeout = TimestampDifferenceMilliseconds(now,
1673 Min(endtime,
1674 retrycanceltime));
1675 if (cur_timeout <= 0)
1676 {
1677 *timed_out = true;
1678 failed = true;
1679 goto exit;
1680 }
1681
1682 /* first time, allocate or get the custom wait event */
1683 if (pgfdw_we_cleanup_result == 0)
1684 pgfdw_we_cleanup_result = WaitEventExtensionNew("PostgresFdwCleanupResult");
1685
1686 /* Sleep until there's something to do */
1687 wc = WaitLatchOrSocket(MyLatch,
1688 WL_LATCH_SET | WL_SOCKET_READABLE |
1689 WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1690 PQsocket(conn),
1691 cur_timeout, pgfdw_we_cleanup_result);
1692 ResetLatch(MyLatch);
1693
1694 CHECK_FOR_INTERRUPTS();
1695
1696 /* Data available in socket? */
1697 if (wc & WL_SOCKET_READABLE)
1698 {
1699 if (!PQconsumeInput(conn))
1700 {
1701 /* connection trouble */
1702 failed = true;
1703 goto exit;
1704 }
1705 }
1706 }
1707
1708 res = PQgetResult(conn);
1709 if (res == NULL)
1710 break; /* query is complete */
1711
1712 PQclear(last_res);
1713 last_res = res;
1714 }
1715 exit: ;
1716 }
1717 PG_CATCH();
1718 {
1719 PQclear(last_res);
1720 PG_RE_THROW();
1721 }
1722 PG_END_TRY();
1723
1724 if (failed)
1725 PQclear(last_res);
1726 else
1727 *result = last_res;
1728 return failed;
1729 }
1730
1731 /*
1732 * Abort remote transaction or subtransaction.
1733 *
1734 * "toplevel" should be set to true if toplevel (main) transaction is
1735 * rollbacked, false otherwise.
1736 *
1737 * Set entry->changing_xact_state to false on success, true on failure.
1738 */
1739 static void
1740 pgfdw_abort_cleanup(ConnCacheEntry *entry, bool toplevel)
1741 {
1742 char sql[100];
1743
1744 /*
1745 * Don't try to clean up the connection if we're already in error
1746 * recursion trouble.
1747 */
1748 if (in_error_recursion_trouble())
1749 entry->changing_xact_state = true;
1750
1751 /*
1752 * If connection is already unsalvageable, don't touch it further.
1753 */
1754 if (entry->changing_xact_state)
1755 return;
1756
1757 /*
1758 * Mark this connection as in the process of changing transaction state.
1759 */
1760 entry->changing_xact_state = true;
1761
1762 /* Assume we might have lost track of prepared statements */
1763 entry->have_error = true;
1764
1765 /*
1766 * If a command has been submitted to the remote server by using an
1767 * asynchronous execution function, the command might not have yet
1768 * completed. Check to see if a command is still being processed by the
1769 * remote server, and if so, request cancellation of the command.
1770 */
1771 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE &&
1772 !pgfdw_cancel_query(entry->conn))
1773 return; /* Unable to cancel running query */
1774
1775 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1776 if (!pgfdw_exec_cleanup_query(entry->conn, sql, false))
1777 return; /* Unable to abort remote (sub)transaction */
1778
1779 if (toplevel)
1780 {
1781 if (entry->have_prep_stmt && entry->have_error &&
1782 !pgfdw_exec_cleanup_query(entry->conn,
1783 "DEALLOCATE ALL",
1784 true))
1785 return; /* Trouble clearing prepared statements */
1786
1787 entry->have_prep_stmt = false;
1788 entry->have_error = false;
1789 }
1790
1791 /*
1792 * If pendingAreq of the per-connection state is not NULL, it means that
1793 * an asynchronous fetch begun by fetch_more_data_begin() was not done
1794 * successfully and thus the per-connection state was not reset in
1795 * fetch_more_data(); in that case reset the per-connection state here.
1796 */
1797 if (entry->state.pendingAreq)
1798 memset(&entry->state, 0, sizeof(entry->state));
1799
1800 /* Disarm changing_xact_state if it all worked */
1801 entry->changing_xact_state = false;
1802 }
1803
1804 /*
1805 * Like pgfdw_abort_cleanup, submit an abort command or cancel request, but
1806 * don't wait for the result.
1807 *
1808 * Returns true if the abort command or cancel request is successfully issued,
1809 * false otherwise. If the abort command is successfully issued, the given
1810 * connection cache entry is appended to *pending_entries. Otherwise, if the
1811 * cancel request is successfully issued, it is appended to *cancel_requested.
1812 */
1813 static bool
1814 pgfdw_abort_cleanup_begin(ConnCacheEntry *entry, bool toplevel,
1815 List **pending_entries, List **cancel_requested)
1816 {
1817 /*
1818 * Don't try to clean up the connection if we're already in error
1819 * recursion trouble.
1820 */
1821 if (in_error_recursion_trouble())
1822 entry->changing_xact_state = true;
1823
1824 /*
1825 * If connection is already unsalvageable, don't touch it further.
1826 */
1827 if (entry->changing_xact_state)
1828 return false;
1829
1830 /*
1831 * Mark this connection as in the process of changing transaction state.
1832 */
1833 entry->changing_xact_state = true;
1834
1835 /* Assume we might have lost track of prepared statements */
1836 entry->have_error = true;
1837
1838 /*
1839 * If a command has been submitted to the remote server by using an
1840 * asynchronous execution function, the command might not have yet
1841 * completed. Check to see if a command is still being processed by the
1842 * remote server, and if so, request cancellation of the command.
1843 */
1844 if (PQtransactionStatus(entry->conn) == PQTRANS_ACTIVE)
1845 {
1846 TimestampTz endtime;
1847
1848 endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
1849 CONNECTION_CLEANUP_TIMEOUT);
1850 if (!pgfdw_cancel_query_begin(entry->conn, endtime))
1851 return false; /* Unable to cancel running query */
1852 *cancel_requested = lappend(*cancel_requested, entry);
1853 }
1854 else
1855 {
1856 char sql[100];
1857
1858 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
1859 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
1860 return false; /* Unable to abort remote transaction */
1861 *pending_entries = lappend(*pending_entries, entry);
1862 }
1863
1864 return true;
1865 }
1866
1867 /*
1868 * Finish pre-commit cleanup of connections on each of which we've sent a
1869 * COMMIT command to the remote server.
1870 */
1871 static void
1872 pgfdw_finish_pre_commit_cleanup(List *pending_entries)
1873 {
1874 ConnCacheEntry *entry;
1875 List *pending_deallocs = NIL;
1876 ListCell *lc;
1877
1878 Assert(pending_entries);
1879
1880 /*
1881 * Get the result of the COMMIT command for each of the pending entries
1882 */
1883 foreach(lc, pending_entries)
1884 {
1885 entry = (ConnCacheEntry *) lfirst(lc);
1886
1887 Assert(entry->changing_xact_state);
1888
1889 /*
1890 * We might already have received the result on the socket, so pass
1891 * consume_input=true to try to consume it first
1892 */
1893 do_sql_command_end(entry->conn, "COMMIT TRANSACTION", true);
1894 entry->changing_xact_state = false;
1895
1896 /* Do a DEALLOCATE ALL in parallel if needed */
1897 if (entry->have_prep_stmt && entry->have_error)
1898 {
1899 /* Ignore errors (see notes in pgfdw_xact_callback) */
1900 if (PQsendQuery(entry->conn, "DEALLOCATE ALL"))
1901 {
1902 pending_deallocs = lappend(pending_deallocs, entry);
1903 continue;
1904 }
1905 }
1906 entry->have_prep_stmt = false;
1907 entry->have_error = false;
1908
1909 pgfdw_reset_xact_state(entry, true);
1910 }
1911
1912 /* No further work if no pending entries */
1913 if (!pending_deallocs)
1914 return;
1915
1916 /*
1917 * Get the result of the DEALLOCATE command for each of the pending
1918 * entries
1919 */
1920 foreach(lc, pending_deallocs)
1921 {
1922 PGresult *res;
1923
1924 entry = (ConnCacheEntry *) lfirst(lc);
1925
1926 /* Ignore errors (see notes in pgfdw_xact_callback) */
1927 while ((res = PQgetResult(entry->conn)) != NULL)
1928 {
1929 PQclear(res);
1930 /* Stop if the connection is lost (else we'll loop infinitely) */
1931 if (PQstatus(entry->conn) == CONNECTION_BAD)
1932 break;
1933 }
1934 entry->have_prep_stmt = false;
1935 entry->have_error = false;
1936
1937 pgfdw_reset_xact_state(entry, true);
1938 }
1939 }
1940
1941 /*
1942 * Finish pre-subcommit cleanup of connections on each of which we've sent a
1943 * RELEASE command to the remote server.
1944 */
1945 static void
1946 pgfdw_finish_pre_subcommit_cleanup(List *pending_entries, int curlevel)
1947 {
1948 ConnCacheEntry *entry;
1949 char sql[100];
1950 ListCell *lc;
1951
1952 Assert(pending_entries);
1953
1954 /*
1955 * Get the result of the RELEASE command for each of the pending entries
1956 */
1957 snprintf(sql, sizeof(sql), "RELEASE SAVEPOINT s%d", curlevel);
1958 foreach(lc, pending_entries)
1959 {
1960 entry = (ConnCacheEntry *) lfirst(lc);
1961
1962 Assert(entry->changing_xact_state);
1963
1964 /*
1965 * We might already have received the result on the socket, so pass
1966 * consume_input=true to try to consume it first
1967 */
1968 do_sql_command_end(entry->conn, sql, true);
1969 entry->changing_xact_state = false;
1970
1971 pgfdw_reset_xact_state(entry, false);
1972 }
1973 }
1974
1975 /*
1976 * Finish abort cleanup of connections on each of which we've sent an abort
1977 * command or cancel request to the remote server.
1978 */
1979 static void
1980 pgfdw_finish_abort_cleanup(List *pending_entries, List *cancel_requested,
1981 bool toplevel)
1982 {
1983 List *pending_deallocs = NIL;
1984 ListCell *lc;
1985
1986 /*
1987 * For each of the pending cancel requests (if any), get and discard the
1988 * result of the query, and submit an abort command to the remote server.
1989 */
1990 if (cancel_requested)
1991 {
1992 foreach(lc, cancel_requested)
1993 {
1994 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
1995 TimestampTz now = GetCurrentTimestamp();
1996 TimestampTz endtime;
1997 TimestampTz retrycanceltime;
1998 char sql[100];
1999
2000 Assert(entry->changing_xact_state);
2001
2002 /*
2003 * Set end time. You might think we should do this before issuing
2004 * cancel request like in normal mode, but that is problematic,
2005 * because if, for example, it took longer than 30 seconds to
2006 * process the first few entries in the cancel_requested list, it
2007 * would cause a timeout error when processing each of the
2008 * remaining entries in the list, leading to slamming that entry's
2009 * connection shut.
2010 */
2011 endtime = TimestampTzPlusMilliseconds(now,
2012 CONNECTION_CLEANUP_TIMEOUT);
2013 retrycanceltime = TimestampTzPlusMilliseconds(now,
2014 RETRY_CANCEL_TIMEOUT);
2015
2016 if (!pgfdw_cancel_query_end(entry->conn, endtime,
2017 retrycanceltime, true))
2018 {
2019 /* Unable to cancel running query */
2020 pgfdw_reset_xact_state(entry, toplevel);
2021 continue;
2022 }
2023
2024 /* Send an abort command in parallel if needed */
2025 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2026 if (!pgfdw_exec_cleanup_query_begin(entry->conn, sql))
2027 {
2028 /* Unable to abort remote (sub)transaction */
2029 pgfdw_reset_xact_state(entry, toplevel);
2030 }
2031 else
2032 pending_entries = lappend(pending_entries, entry);
2033 }
2034 }
2035
2036 /* No further work if no pending entries */
2037 if (!pending_entries)
2038 return;
2039
2040 /*
2041 * Get the result of the abort command for each of the pending entries
2042 */
2043 foreach(lc, pending_entries)
2044 {
2045 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2046 TimestampTz endtime;
2047 char sql[100];
2048
2049 Assert(entry->changing_xact_state);
2050
2051 /*
2052 * Set end time. We do this now, not before issuing the command like
2053 * in normal mode, for the same reason as for the cancel_requested
2054 * entries.
2055 */
2056 endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
2057 CONNECTION_CLEANUP_TIMEOUT);
2058
2059 CONSTRUCT_ABORT_COMMAND(sql, entry, toplevel);
2060 if (!pgfdw_exec_cleanup_query_end(entry->conn, sql, endtime,
2061 true, false))
2062 {
2063 /* Unable to abort remote (sub)transaction */
2064 pgfdw_reset_xact_state(entry, toplevel);
2065 continue;
2066 }
2067
2068 if (toplevel)
2069 {
2070 /* Do a DEALLOCATE ALL in parallel if needed */
2071 if (entry->have_prep_stmt && entry->have_error)
2072 {
2073 if (!pgfdw_exec_cleanup_query_begin(entry->conn,
2074 "DEALLOCATE ALL"))
2075 {
2076 /* Trouble clearing prepared statements */
2077 pgfdw_reset_xact_state(entry, toplevel);
2078 }
2079 else
2080 pending_deallocs = lappend(pending_deallocs, entry);
2081 continue;
2082 }
2083 entry->have_prep_stmt = false;
2084 entry->have_error = false;
2085 }
2086
2087 /* Reset the per-connection state if needed */
2088 if (entry->state.pendingAreq)
2089 memset(&entry->state, 0, sizeof(entry->state));
2090
2091 /* We're done with this entry; unset the changing_xact_state flag */
2092 entry->changing_xact_state = false;
2093 pgfdw_reset_xact_state(entry, toplevel);
2094 }
2095
2096 /* No further work if no pending entries */
2097 if (!pending_deallocs)
2098 return;
2099 Assert(toplevel);
2100
2101 /*
2102 * Get the result of the DEALLOCATE command for each of the pending
2103 * entries
2104 */
2105 foreach(lc, pending_deallocs)
2106 {
2107 ConnCacheEntry *entry = (ConnCacheEntry *) lfirst(lc);
2108 TimestampTz endtime;
2109
2110 Assert(entry->changing_xact_state);
2111 Assert(entry->have_prep_stmt);
2112 Assert(entry->have_error);
2113
2114 /*
2115 * Set end time. We do this now, not before issuing the command like
2116 * in normal mode, for the same reason as for the cancel_requested
2117 * entries.
2118 */
2119 endtime = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
2120 CONNECTION_CLEANUP_TIMEOUT);
2121
2122 if (!pgfdw_exec_cleanup_query_end(entry->conn, "DEALLOCATE ALL",
2123 endtime, true, true))
2124 {
2125 /* Trouble clearing prepared statements */
2126 pgfdw_reset_xact_state(entry, toplevel);
2127 continue;
2128 }
2129 entry->have_prep_stmt = false;
2130 entry->have_error = false;
2131
2132 /* Reset the per-connection state if needed */
2133 if (entry->state.pendingAreq)
2134 memset(&entry->state, 0, sizeof(entry->state));
2135
2136 /* We're done with this entry; unset the changing_xact_state flag */
2137 entry->changing_xact_state = false;
2138 pgfdw_reset_xact_state(entry, toplevel);
2139 }
2140 }
2141
2142 /* Number of output arguments (columns) for various API versions */
2143 #define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1 2
2144 #define POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2 6
2145 #define POSTGRES_FDW_GET_CONNECTIONS_COLS 6 /* maximum of above */
2146
2147 /*
2148 * Internal function used by postgres_fdw_get_connections variants.
2149 *
2150 * For API version 1.1, this function takes no input parameter and
2151 * returns a set of records with the following values:
2152 *
2153 * - server_name - server name of active connection. In case the foreign server
2154 * is dropped but still the connection is active, then the server name will
2155 * be NULL in output.
2156 * - valid - true/false representing whether the connection is valid or not.
2157 * Note that connections can become invalid in pgfdw_inval_callback.
2158 *
2159 * For API version 1.2 and later, this function takes an input parameter
2160 * to check a connection status and returns the following
2161 * additional values along with the four values from version 1.1:
2162 *
2163 * - user_name - the local user name of the active connection. In case the
2164 * user mapping is dropped but the connection is still active, then the
2165 * user name will be NULL in the output.
2166 * - used_in_xact - true if the connection is used in the current transaction.
2167 * - closed - true if the connection is closed.
2168 * - remote_backend_pid - process ID of the remote backend, on the foreign
2169 * server, handling the connection.
2170 *
2171 * No records are returned when there are no cached connections at all.
2172 */
2173 static void
2174 postgres_fdw_get_connections_internal(FunctionCallInfo fcinfo,
2175 enum pgfdwVersion api_version)
2176 {
2177 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
2178 HASH_SEQ_STATUS scan;
2179 ConnCacheEntry *entry;
2180
2181 InitMaterializedSRF(fcinfo, 0);
2182
2183 /* If cache doesn't exist, we return no records */
2184 if (!ConnectionHash)
2185 return;
2186
2187 /* Check we have the expected number of output arguments */
2188 switch (rsinfo->setDesc->natts)
2189 {
2190 case POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_1:
2191 if (api_version != PGFDW_V1_1)
2192 elog(ERROR, "incorrect number of output arguments");
2193 break;
2194 case POSTGRES_FDW_GET_CONNECTIONS_COLS_V1_2:
2195 if (api_version != PGFDW_V1_2)
2196 elog(ERROR, "incorrect number of output arguments");
2197 break;
2198 default:
2199 elog(ERROR, "incorrect number of output arguments");
2200 }
2201
2202 hash_seq_init(&scan, ConnectionHash);
2203 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2204 {
2205 ForeignServer *server;
2206 Datum values[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2207 bool nulls[POSTGRES_FDW_GET_CONNECTIONS_COLS] = {0};
2208 int i = 0;
2209
2210 /* We only look for open remote connections */
2211 if (!entry->conn)
2212 continue;
2213
2214 server = GetForeignServerExtended(entry->serverid, FSV_MISSING_OK);
2215
2216 /*
2217 * The foreign server may have been dropped in current explicit
2218 * transaction. It is not possible to drop the server from another
2219 * session when the connection associated with it is in use in the
2220 * current transaction, if tried so, the drop query in another session
2221 * blocks until the current transaction finishes.
2222 *
2223 * Even though the server is dropped in the current transaction, the
2224 * cache can still have associated active connection entry, say we
2225 * call such connections dangling. Since we can not fetch the server
2226 * name from system catalogs for dangling connections, instead we show
2227 * NULL value for server name in output.
2228 *
2229 * We could have done better by storing the server name in the cache
2230 * entry instead of server oid so that it could be used in the output.
2231 * But the server name in each cache entry requires 64 bytes of
2232 * memory, which is huge, when there are many cached connections and
2233 * the use case i.e. dropping the foreign server within the explicit
2234 * current transaction seems rare. So, we chose to show NULL value for
2235 * server name in output.
2236 *
2237 * Such dangling connections get closed either in next use or at the
2238 * end of current explicit transaction in pgfdw_xact_callback.
2239 */
2240 if (!server)
2241 {
2242 /*
2243 * If the server has been dropped in the current explicit
2244 * transaction, then this entry would have been invalidated in
2245 * pgfdw_inval_callback at the end of drop server command. Note
2246 * that this connection would not have been closed in
2247 * pgfdw_inval_callback because it is still being used in the
2248 * current explicit transaction. So, assert that here.
2249 */
2250 Assert(entry->conn && entry->xact_depth > 0 && entry->invalidated);
2251
2252 /* Show null, if no server name was found */
2253 nulls[i++] = true;
2254 }
2255 else
2256 values[i++] = CStringGetTextDatum(server->servername);
2257
2258 if (api_version >= PGFDW_V1_2)
2259 {
2260 HeapTuple tp;
2261
2262 /* Use the system cache to obtain the user mapping */
2263 tp = SearchSysCache1(USERMAPPINGOID, ObjectIdGetDatum(entry->key));
2264
2265 /*
2266 * Just like in the foreign server case, user mappings can also be
2267 * dropped in the current explicit transaction. Therefore, the
2268 * similar check as in the server case is required.
2269 */
2270 if (!HeapTupleIsValid(tp))
2271 {
2272 /*
2273 * If we reach here, this entry must have been invalidated in
2274 * pgfdw_inval_callback, same as in the server case.
2275 */
2276 Assert(entry->conn && entry->xact_depth > 0 &&
2277 entry->invalidated);
2278
2279 nulls[i++] = true;
2280 }
2281 else
2282 {
2283 Oid userid;
2284
2285 userid = ((Form_pg_user_mapping) GETSTRUCT(tp))->umuser;
2286 values[i++] = CStringGetTextDatum(MappingUserName(userid));
2287 ReleaseSysCache(tp);
2288 }
2289 }
2290
2291 values[i++] = BoolGetDatum(!entry->invalidated);
2292
2293 if (api_version >= PGFDW_V1_2)
2294 {
2295 bool check_conn = PG_GETARG_BOOL(0);
2296
2297 /* Is this connection used in the current transaction? */
2298 values[i++] = BoolGetDatum(entry->xact_depth > 0);
2299
2300 /*
2301 * If a connection status check is requested and supported, return
2302 * whether the connection is closed. Otherwise, return NULL.
2303 */
2304 if (check_conn && pgfdw_conn_checkable())
2305 values[i++] = BoolGetDatum(pgfdw_conn_check(entry->conn) != 0);
2306 else
2307 nulls[i++] = true;
2308
2309 /* Return process ID of remote backend */
2310 values[i++] = Int32GetDatum(PQbackendPID(entry->conn));
2311 }
2312
2313 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
2314 }
2315 }
2316
2317 /*
2318 * List active foreign server connections.
2319 *
2320 * The SQL API of this function has changed multiple times, and will likely
2321 * do so again in future. To support the case where a newer version of this
2322 * loadable module is being used with an old SQL declaration of the function,
2323 * we continue to support the older API versions.
2324 */
2325 Datum
2326 postgres_fdw_get_connections_1_2(PG_FUNCTION_ARGS)
2327 {
2328 postgres_fdw_get_connections_internal(fcinfo, PGFDW_V1_2);
2329
2330 PG_RETURN_VOID();
2331 }
2332
2333 Datum
2334 postgres_fdw_get_connections(PG_FUNCTION_ARGS)
2335 {
2336 postgres_fdw_get_connections_internal(fcinfo, PGFDW_V1_1);
2337
2338 PG_RETURN_VOID();
2339 }
2340
2341 /*
2342 * Disconnect the specified cached connections.
2343 *
2344 * This function discards the open connections that are established by
2345 * postgres_fdw from the local session to the foreign server with
2346 * the given name. Note that there can be multiple connections to
2347 * the given server using different user mappings. If the connections
2348 * are used in the current local transaction, they are not disconnected
2349 * and warning messages are reported. This function returns true
2350 * if it disconnects at least one connection, otherwise false. If no
2351 * foreign server with the given name is found, an error is reported.
2352 */
2353 Datum
2354 postgres_fdw_disconnect(PG_FUNCTION_ARGS)
2355 {
2356 ForeignServer *server;
2357 char *servername;
2358
2359 servername = text_to_cstring(PG_GETARG_TEXT_PP(0));
2360 server = GetForeignServerByName(servername, false);
2361
2362 PG_RETURN_BOOL(disconnect_cached_connections(server->serverid));
2363 }
2364
2365 /*
2366 * Disconnect all the cached connections.
2367 *
2368 * This function discards all the open connections that are established by
2369 * postgres_fdw from the local session to the foreign servers.
2370 * If the connections are used in the current local transaction, they are
2371 * not disconnected and warning messages are reported. This function
2372 * returns true if it disconnects at least one connection, otherwise false.
2373 */
2374 Datum
2375 postgres_fdw_disconnect_all(PG_FUNCTION_ARGS)
2376 {
2377 PG_RETURN_BOOL(disconnect_cached_connections(InvalidOid));
2378 }
2379
2380 /*
2381 * Workhorse to disconnect cached connections.
2382 *
2383 * This function scans all the connection cache entries and disconnects
2384 * the open connections whose foreign server OID matches with
2385 * the specified one. If InvalidOid is specified, it disconnects all
2386 * the cached connections.
2387 *
2388 * This function emits a warning for each connection that's used in
2389 * the current transaction and doesn't close it. It returns true if
2390 * it disconnects at least one connection, otherwise false.
2391 *
2392 * Note that this function disconnects even the connections that are
2393 * established by other users in the same local session using different
2394 * user mappings. This leads even non-superuser to be able to close
2395 * the connections established by superusers in the same local session.
2396 *
2397 * XXX As of now we don't see any security risk doing this. But we should
2398 * set some restrictions on that, for example, prevent non-superuser
2399 * from closing the connections established by superusers even
2400 * in the same session?
2401 */
2402 static bool
2403 disconnect_cached_connections(Oid serverid)
2404 {
2405 HASH_SEQ_STATUS scan;
2406 ConnCacheEntry *entry;
2407 bool all = !OidIsValid(serverid);
2408 bool result = false;
2409
2410 /*
2411 * Connection cache hashtable has not been initialized yet in this
2412 * session, so return false.
2413 */
2414 if (!ConnectionHash)
2415 return false;
2416
2417 hash_seq_init(&scan, ConnectionHash);
2418 while ((entry = (ConnCacheEntry *) hash_seq_search(&scan)))
2419 {
2420 /* Ignore cache entry if no open connection right now. */
2421 if (!entry->conn)
2422 continue;
2423
2424 if (all || entry->serverid == serverid)
2425 {
2426 /*
2427 * Emit a warning because the connection to close is used in the
2428 * current transaction and cannot be disconnected right now.
2429 */
2430 if (entry->xact_depth > 0)
2431 {
2432 ForeignServer *server;
2433
2434 server = GetForeignServerExtended(entry->serverid,
2435 FSV_MISSING_OK);
2436
2437 if (!server)
2438 {
2439 /*
2440 * If the foreign server was dropped while its connection
2441 * was used in the current transaction, the connection
2442 * must have been marked as invalid by
2443 * pgfdw_inval_callback at the end of DROP SERVER command.
2444 */
2445 Assert(entry->invalidated);
2446
2447 ereport(WARNING,
2448 (errmsg("cannot close dropped server connection because it is still in use")));
2449 }
2450 else
2451 ereport(WARNING,
2452 (errmsg("cannot close connection for server \"%s\" because it is still in use",
2453 server->servername)));
2454 }
2455 else
2456 {
2457 elog(DEBUG3, "discarding connection %p", entry->conn);
2458 disconnect_pg_server(entry);
2459 result = true;
2460 }
2461 }
2462 }
2463
2464 return result;
2465 }
2466
2467 /*
2468 * Check if the remote server closed the connection.
2469 *
2470 * Returns 1 if the connection is closed, -1 if an error occurred,
2471 * and 0 if it's not closed or if the connection check is unavailable
2472 * on this platform.
2473 */
2474 static int
2475 pgfdw_conn_check(PGconn *conn)
2476 {
2477 int sock = PQsocket(conn);
2478
2479 if (PQstatus(conn) != CONNECTION_OK || sock == -1)
2480 return -1;
2481
2482 #if (defined(HAVE_POLL) && defined(POLLRDHUP))
2483 {
2484 struct pollfd input_fd;
2485 int result;
2486
2487 input_fd.fd = sock;
2488 input_fd.events = POLLRDHUP;
2489 input_fd.revents = 0;
2490
2491 do
2492 result = poll(&input_fd, 1, 0);
2493 while (result < 0 && errno == EINTR);
2494
2495 if (result < 0)
2496 return -1;
2497
2498 return (input_fd.revents &
2499 (POLLRDHUP | POLLHUP | POLLERR | POLLNVAL)) ? 1 : 0;
2500 }
2501 #else
2502 return 0;
2503 #endif
2504 }
2505
2506 /*
2507 * Check if connection status checking is available on this platform.
2508 *
2509 * Returns true if available, false otherwise.
2510 */
2511 static bool
2512 pgfdw_conn_checkable(void)
2513 {
2514 #if (defined(HAVE_POLL) && defined(POLLRDHUP))
2515 return true;
2516 #else
2517 return false;
2518 #endif
2519 }
2520
2521 /*
2522 * Ensure that require_auth and SCRAM keys are correctly set on values. SCRAM
2523 * keys used to pass-through are coming from the initial connection from the
2524 * client with the server.
2525 *
2526 * All required SCRAM options are set by postgres_fdw, so we just need to
2527 * ensure that these options are not overwritten by the user.
2528 */
2529 static bool
2530 pgfdw_has_required_scram_options(const char **keywords, const char **values)
2531 {
2532 bool has_scram_server_key = false;
2533 bool has_scram_client_key = false;
2534 bool has_require_auth = false;
2535 bool has_scram_keys = false;
2536
2537 /*
2538 * Continue iterating even if we found the keys that we need to validate
2539 * to make sure that there is no other declaration of these keys that can
2540 * overwrite the first.
2541 */
2542 for (int i = 0; keywords[i] != NULL; i++)
2543 {
2544 if (strcmp(keywords[i], "scram_client_key") == 0)
2545 {
2546 if (values[i] != NULL && values[i][0] != '\0')
2547 has_scram_client_key = true;
2548 else
2549 has_scram_client_key = false;
2550 }
2551
2552 if (strcmp(keywords[i], "scram_server_key") == 0)
2553 {
2554 if (values[i] != NULL && values[i][0] != '\0')
2555 has_scram_server_key = true;
2556 else
2557 has_scram_server_key = false;
2558 }
2559
2560 if (strcmp(keywords[i], "require_auth") == 0)
2561 {
2562 if (values[i] != NULL && strcmp(values[i], "scram-sha-256") == 0)
2563 has_require_auth = true;
2564 else
2565 has_require_auth = false;
2566 }
2567 }
2568
2569 has_scram_keys = has_scram_client_key && has_scram_server_key && MyProcPort != NULL && MyProcPort->has_scram_keys;
2570
2571 return (has_scram_keys && has_require_auth);
2572 }