Debian Codegraph @

contrib/postgres_fdw/option.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * option.c
4 * FDW and GUC option handling for postgres_fdw
5 *
6 * Portions Copyright (c) 2012-2025, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * contrib/postgres_fdw/option.c
10 *
11 *-------------------------------------------------------------------------
12 */
13 #include "postgres.h"
14
15 #include "access/reloptions.h"
16 #include "catalog/pg_foreign_server.h"
17 #include "catalog/pg_foreign_table.h"
18 #include "catalog/pg_user_mapping.h"
19 #include "commands/defrem.h"
20 #include "commands/extension.h"
21 #include "libpq/libpq-be.h"
22 #include "postgres_fdw.h"
23 #include "utils/guc.h"
24 #include "utils/varlena.h"
25
26 /*
27 * Describes the valid options for objects that this wrapper uses.
28 */
29 typedef struct PgFdwOption
30 {
31 const char *keyword;
32 Oid optcontext; /* OID of catalog in which option may appear */
33 bool is_libpq_opt; /* true if it's used in libpq */
34 } PgFdwOption;
35
36 /*
37 * Valid options for postgres_fdw.
38 * Allocated and filled in InitPgFdwOptions.
39 */
40 static PgFdwOption *postgres_fdw_options;
41
42 /*
43 * Valid options for libpq.
44 * Allocated and filled in InitPgFdwOptions.
45 */
46 static PQconninfoOption *libpq_options;
47
48 /*
49 * GUC parameters
50 */
51 char *pgfdw_application_name = NULL;
52
53 /*
54 * Helper functions
55 */
56 static void InitPgFdwOptions(void);
57 static bool is_valid_option(const char *keyword, Oid context);
58 static bool is_libpq_option(const char *keyword);
59
60 #include "miscadmin.h"
61
62 /*
63 * Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
64 * USER MAPPING or FOREIGN TABLE that uses postgres_fdw.
65 *
66 * Raise an ERROR if the option or its value is considered invalid.
67 */
68 PG_FUNCTION_INFO_V1(postgres_fdw_validator);
69
70 Datum
71 postgres_fdw_validator(PG_FUNCTION_ARGS)
72 {
73 List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
74 Oid catalog = PG_GETARG_OID(1);
75 ListCell *cell;
76
77 /* Build our options lists if we didn't yet. */
78 InitPgFdwOptions();
79
80 /*
81 * Check that only options supported by postgres_fdw, and allowed for the
82 * current object type, are given.
83 */
84 foreach(cell, options_list)
85 {
86 DefElem *def = (DefElem *) lfirst(cell);
87
88 if (!is_valid_option(def->defname, catalog))
89 {
90 /*
91 * Unknown option specified, complain about it. Provide a hint
92 * with a valid option that looks similar, if there is one.
93 */
94 PgFdwOption *opt;
95 const char *closest_match;
96 ClosestMatchState match_state;
97 bool has_valid_options = false;
98
99 initClosestMatch(&match_state, def->defname, 4);
100 for (opt = postgres_fdw_options; opt->keyword; opt++)
101 {
102 if (catalog == opt->optcontext)
103 {
104 has_valid_options = true;
105 updateClosestMatch(&match_state, opt->keyword);
106 }
107 }
108
109 closest_match = getClosestMatch(&match_state);
110 ereport(ERROR,
111 (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
112 errmsg("invalid option \"%s\"", def->defname),
113 has_valid_options ? closest_match ?
114 errhint("Perhaps you meant the option \"%s\".",
115 closest_match) : 0 :
116 errhint("There are no valid options in this context.")));
117 }
118
119 /*
120 * Validate option value, when we can do so without any context.
121 */
122 if (strcmp(def->defname, "use_remote_estimate") == 0 ||
123 strcmp(def->defname, "updatable") == 0 ||
124 strcmp(def->defname, "truncatable") == 0 ||
125 strcmp(def->defname, "async_capable") == 0 ||
126 strcmp(def->defname, "parallel_commit") == 0 ||
127 strcmp(def->defname, "parallel_abort") == 0 ||
128 strcmp(def->defname, "keep_connections") == 0 ||
129 strcmp(def->defname, "use_scram_passthrough") == 0)
130 {
131 /* these accept only boolean values */
132 (void) defGetBoolean(def);
133 }
134 else if (strcmp(def->defname, "fdw_startup_cost") == 0 ||
135 strcmp(def->defname, "fdw_tuple_cost") == 0)
136 {
137 /*
138 * These must have a floating point value greater than or equal to
139 * zero.
140 */
141 char *value;
142 double real_val;
143 bool is_parsed;
144
145 value = defGetString(def);
146 is_parsed = parse_real(value, &real_val, 0, NULL);
147
148 if (!is_parsed)
149 ereport(ERROR,
150 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
151 errmsg("invalid value for floating point option \"%s\": %s",
152 def->defname, value)));
153
154 if (real_val < 0)
155 ereport(ERROR,
156 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
157 errmsg("\"%s\" must be a floating point value greater than or equal to zero",
158 def->defname)));
159 }
160 else if (strcmp(def->defname, "extensions") == 0)
161 {
162 /* check list syntax, warn about uninstalled extensions */
163 (void) ExtractExtensionList(defGetString(def), true);
164 }
165 else if (strcmp(def->defname, "fetch_size") == 0 ||
166 strcmp(def->defname, "batch_size") == 0)
167 {
168 char *value;
169 int int_val;
170 bool is_parsed;
171
172 value = defGetString(def);
173 is_parsed = parse_int(value, &int_val, 0, NULL);
174
175 if (!is_parsed)
176 ereport(ERROR,
177 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
178 errmsg("invalid value for integer option \"%s\": %s",
179 def->defname, value)));
180
181 if (int_val <= 0)
182 ereport(ERROR,
183 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
184 errmsg("\"%s\" must be an integer value greater than zero",
185 def->defname)));
186 }
187 else if (strcmp(def->defname, "password_required") == 0)
188 {
189 bool pw_required = defGetBoolean(def);
190
191 /*
192 * Only the superuser may set this option on a user mapping, or
193 * alter a user mapping on which this option is set. We allow a
194 * user to clear this option if it's set - in fact, we don't have
195 * a choice since we can't see the old mapping when validating an
196 * alter.
197 */
198 if (!superuser() && !pw_required)
199 ereport(ERROR,
200 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
201 errmsg("password_required=false is superuser-only"),
202 errhint("User mappings with the password_required option set to false may only be created or modified by the superuser.")));
203 }
204 else if (strcmp(def->defname, "sslcert") == 0 ||
205 strcmp(def->defname, "sslkey") == 0)
206 {
207 /* similarly for sslcert / sslkey on user mapping */
208 if (catalog == UserMappingRelationId && !superuser())
209 ereport(ERROR,
210 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
211 errmsg("sslcert and sslkey are superuser-only"),
212 errhint("User mappings with the sslcert or sslkey options set may only be created or modified by the superuser.")));
213 }
214 else if (strcmp(def->defname, "analyze_sampling") == 0)
215 {
216 char *value;
217
218 value = defGetString(def);
219
220 /* we recognize off/auto/random/system/bernoulli */
221 if (strcmp(value, "off") != 0 &&
222 strcmp(value, "auto") != 0 &&
223 strcmp(value, "random") != 0 &&
224 strcmp(value, "system") != 0 &&
225 strcmp(value, "bernoulli") != 0)
226 ereport(ERROR,
227 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
228 errmsg("invalid value for string option \"%s\": %s",
229 def->defname, value)));
230 }
231 }
232
233 PG_RETURN_VOID();
234 }
235
236 /*
237 * Initialize option lists.
238 */
239 static void
240 InitPgFdwOptions(void)
241 {
242 int num_libpq_opts;
243 PQconninfoOption *lopt;
244 PgFdwOption *popt;
245
246 /* non-libpq FDW-specific FDW options */
247 static const PgFdwOption non_libpq_options[] = {
248 {"schema_name", ForeignTableRelationId, false},
249 {"table_name", ForeignTableRelationId, false},
250 {"column_name", AttributeRelationId, false},
251 /* use_remote_estimate is available on both server and table */
252 {"use_remote_estimate", ForeignServerRelationId, false},
253 {"use_remote_estimate", ForeignTableRelationId, false},
254 /* cost factors */
255 {"fdw_startup_cost", ForeignServerRelationId, false},
256 {"fdw_tuple_cost", ForeignServerRelationId, false},
257 /* shippable extensions */
258 {"extensions", ForeignServerRelationId, false},
259 /* updatable is available on both server and table */
260 {"updatable", ForeignServerRelationId, false},
261 {"updatable", ForeignTableRelationId, false},
262 /* truncatable is available on both server and table */
263 {"truncatable", ForeignServerRelationId, false},
264 {"truncatable", ForeignTableRelationId, false},
265 /* fetch_size is available on both server and table */
266 {"fetch_size", ForeignServerRelationId, false},
267 {"fetch_size", ForeignTableRelationId, false},
268 /* batch_size is available on both server and table */
269 {"batch_size", ForeignServerRelationId, false},
270 {"batch_size", ForeignTableRelationId, false},
271 /* async_capable is available on both server and table */
272 {"async_capable", ForeignServerRelationId, false},
273 {"async_capable", ForeignTableRelationId, false},
274 {"parallel_commit", ForeignServerRelationId, false},
275 {"parallel_abort", ForeignServerRelationId, false},
276 {"keep_connections", ForeignServerRelationId, false},
277 {"password_required", UserMappingRelationId, false},
278
279 /* sampling is available on both server and table */
280 {"analyze_sampling", ForeignServerRelationId, false},
281 {"analyze_sampling", ForeignTableRelationId, false},
282
283 {"use_scram_passthrough", ForeignServerRelationId, false},
284 {"use_scram_passthrough", UserMappingRelationId, false},
285
286 /*
287 * sslcert and sslkey are in fact libpq options, but we repeat them
288 * here to allow them to appear in both foreign server context (when
289 * we generate libpq options) and user mapping context (from here).
290 */
291 {"sslcert", UserMappingRelationId, true},
292 {"sslkey", UserMappingRelationId, true},
293
294 /*
295 * gssdelegation is also a libpq option but should be allowed in a
296 * user mapping context too
297 */
298 {"gssdelegation", UserMappingRelationId, true},
299
300 {NULL, InvalidOid, false}
301 };
302
303 /* Prevent redundant initialization. */
304 if (postgres_fdw_options)
305 return;
306
307 /*
308 * Get list of valid libpq options.
309 *
310 * To avoid unnecessary work, we get the list once and use it throughout
311 * the lifetime of this backend process. We don't need to care about
312 * memory context issues, because PQconndefaults allocates with malloc.
313 */
314 libpq_options = PQconndefaults();
315 if (!libpq_options) /* assume reason for failure is OOM */
316 ereport(ERROR,
317 (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
318 errmsg("out of memory"),
319 errdetail("Could not get libpq's default connection options.")));
320
321 /* Count how many libpq options are available. */
322 num_libpq_opts = 0;
323 for (lopt = libpq_options; lopt->keyword; lopt++)
324 num_libpq_opts++;
325
326 /*
327 * Construct an array which consists of all valid options for
328 * postgres_fdw, by appending FDW-specific options to libpq options.
329 *
330 * We use plain malloc here to allocate postgres_fdw_options because it
331 * lives as long as the backend process does. Besides, keeping
332 * libpq_options in memory allows us to avoid copying every keyword
333 * string.
334 */
335 postgres_fdw_options = (PgFdwOption *)
336 malloc(sizeof(PgFdwOption) * num_libpq_opts +
337 sizeof(non_libpq_options));
338 if (postgres_fdw_options == NULL)
339 ereport(ERROR,
340 (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
341 errmsg("out of memory")));
342
343 popt = postgres_fdw_options;
344 for (lopt = libpq_options; lopt->keyword; lopt++)
345 {
346 /* Hide debug options, as well as settings we override internally. */
347 if (strchr(lopt->dispchar, 'D') ||
348 strcmp(lopt->keyword, "fallback_application_name") == 0 ||
349 strcmp(lopt->keyword, "client_encoding") == 0)
350 continue;
351
352 /*
353 * Disallow OAuth options for now, since the builtin flow communicates
354 * on stderr by default and can't cache tokens yet.
355 */
356 if (strncmp(lopt->keyword, "oauth_", strlen("oauth_")) == 0)
357 continue;
358
359 /* We don't have to copy keyword string, as described above. */
360 popt->keyword = lopt->keyword;
361
362 /*
363 * "user" and any secret options are allowed only on user mappings.
364 * Everything else is a server option.
365 */
366 if (strcmp(lopt->keyword, "user") == 0 || strchr(lopt->dispchar, '*'))
367 popt->optcontext = UserMappingRelationId;
368 else
369 popt->optcontext = ForeignServerRelationId;
370 popt->is_libpq_opt = true;
371
372 popt++;
373 }
374
375 /* Append FDW-specific options and dummy terminator. */
376 memcpy(popt, non_libpq_options, sizeof(non_libpq_options));
377 }
378
379 /*
380 * Check whether the given option is one of the valid postgres_fdw options.
381 * context is the Oid of the catalog holding the object the option is for.
382 */
383 static bool
384 is_valid_option(const char *keyword, Oid context)
385 {
386 PgFdwOption *opt;
387
388 Assert(postgres_fdw_options); /* must be initialized already */
389
390 for (opt = postgres_fdw_options; opt->keyword; opt++)
391 {
392 if (context == opt->optcontext && strcmp(opt->keyword, keyword) == 0)
393 return true;
394 }
395
396 return false;
397 }
398
399 /*
400 * Check whether the given option is one of the valid libpq options.
401 */
402 static bool
403 is_libpq_option(const char *keyword)
404 {
405 PgFdwOption *opt;
406
407 Assert(postgres_fdw_options); /* must be initialized already */
408
409 for (opt = postgres_fdw_options; opt->keyword; opt++)
410 {
411 if (opt->is_libpq_opt && strcmp(opt->keyword, keyword) == 0)
412 return true;
413 }
414
415 return false;
416 }
417
418 /*
419 * Generate key-value arrays which include only libpq options from the
420 * given list (which can contain any kind of options). Caller must have
421 * allocated large-enough arrays. Returns number of options found.
422 */
423 int
424 ExtractConnectionOptions(List *defelems, const char **keywords,
425 const char **values)
426 {
427 ListCell *lc;
428 int i;
429
430 /* Build our options lists if we didn't yet. */
431 InitPgFdwOptions();
432
433 i = 0;
434 foreach(lc, defelems)
435 {
436 DefElem *d = (DefElem *) lfirst(lc);
437
438 if (is_libpq_option(d->defname))
439 {
440 keywords[i] = d->defname;
441 values[i] = defGetString(d);
442 i++;
443 }
444 }
445 return i;
446 }
447
448 /*
449 * Parse a comma-separated string and return a List of the OIDs of the
450 * extensions named in the string. If any names in the list cannot be
451 * found, report a warning if warnOnMissing is true, else just silently
452 * ignore them.
453 */
454 List *
455 ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
456 {
457 List *extensionOids = NIL;
458 List *extlist;
459 ListCell *lc;
460
461 /* SplitIdentifierString scribbles on its input, so pstrdup first */
462 if (!SplitIdentifierString(pstrdup(extensionsString), ',', &extlist))
463 {
464 /* syntax error in name list */
465 ereport(ERROR,
466 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
467 errmsg("parameter \"%s\" must be a list of extension names",
468 "extensions")));
469 }
470
471 foreach(lc, extlist)
472 {
473 const char *extension_name = (const char *) lfirst(lc);
474 Oid extension_oid = get_extension_oid(extension_name, true);
475
476 if (OidIsValid(extension_oid))
477 {
478 extensionOids = lappend_oid(extensionOids, extension_oid);
479 }
480 else if (warnOnMissing)
481 {
482 ereport(WARNING,
483 (errcode(ERRCODE_UNDEFINED_OBJECT),
484 errmsg("extension \"%s\" is not installed",
485 extension_name)));
486 }
487 }
488
489 list_free(extlist);
490 return extensionOids;
491 }
492
493 /*
494 * Replace escape sequences beginning with % character in the given
495 * application_name with status information, and return it.
496 *
497 * This function always returns a palloc'd string, so the caller is
498 * responsible for pfreeing it.
499 */
500 char *
501 process_pgfdw_appname(const char *appname)
502 {
503 const char *p;
504 StringInfoData buf;
505
506 initStringInfo(&buf);
507
508 for (p = appname; *p != '\0'; p++)
509 {
510 if (*p != '%')
511 {
512 /* literal char, just copy */
513 appendStringInfoChar(&buf, *p);
514 continue;
515 }
516
517 /* must be a '%', so skip to the next char */
518 p++;
519 if (*p == '\0')
520 break; /* format error - ignore it */
521 else if (*p == '%')
522 {
523 /* string contains %% */
524 appendStringInfoChar(&buf, '%');
525 continue;
526 }
527
528 /* process the option */
529 switch (*p)
530 {
531 case 'a':
532 appendStringInfoString(&buf, application_name);
533 break;
534 case 'c':
535 appendStringInfo(&buf, "%" PRIx64 ".%x", MyStartTime, MyProcPid);
536 break;
537 case 'C':
538 appendStringInfoString(&buf, cluster_name);
539 break;
540 case 'd':
541 if (MyProcPort)
542 {
543 const char *dbname = MyProcPort->database_name;
544
545 if (dbname)
546 appendStringInfoString(&buf, dbname);
547 else
548 appendStringInfoString(&buf, "[unknown]");
549 }
550 break;
551 case 'p':
552 appendStringInfo(&buf, "%d", MyProcPid);
553 break;
554 case 'u':
555 if (MyProcPort)
556 {
557 const char *username = MyProcPort->user_name;
558
559 if (username)
560 appendStringInfoString(&buf, username);
561 else
562 appendStringInfoString(&buf, "[unknown]");
563 }
564 break;
565 default:
566 /* format error - ignore it */
567 break;
568 }
569 }
570
571 return buf.data;
572 }
573
574 /*
575 * Module load callback
576 */
577 void
578 _PG_init(void)
579 {
580 /*
581 * Unlike application_name GUC, don't set GUC_IS_NAME flag nor check_hook
582 * to allow postgres_fdw.application_name to be any string more than
583 * NAMEDATALEN characters and to include non-ASCII characters. Instead,
584 * remote server truncates application_name of remote connection to less
585 * than NAMEDATALEN and replaces any non-ASCII characters in it with a '?'
586 * character.
587 */
588 DefineCustomStringVariable("postgres_fdw.application_name",
589 "Sets the application name to be used on the remote server.",
590 NULL,
591 &pgfdw_application_name,
592 NULL,
593 PGC_USERSET,
594 0,
595 NULL,
596 NULL,
597 NULL);
598
599 MarkGUCPrefixReserved("postgres_fdw");
600 }