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