PostgreSQL Source Code  git master
option.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * option.c
4  * FDW and GUC option handling for postgres_fdw
5  *
6  * Portions Copyright (c) 2012-2021, 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"
19 #include "commands/defrem.h"
20 #include "commands/extension.h"
21 #include "postgres_fdw.h"
22 #include "utils/builtins.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  */
41 
42 /*
43  * Valid options for libpq.
44  * Allocated and filled in InitPgFdwOptions.
45  */
47 
48 /*
49  * GUC parameters
50  */
52 
53 void _PG_init(void);
54 
55 /*
56  * Helper functions
57  */
58 static void InitPgFdwOptions(void);
59 static bool is_valid_option(const char *keyword, Oid context);
60 static bool is_libpq_option(const char *keyword);
61 
62 #include "miscadmin.h"
63 
64 /*
65  * Validate the generic options given to a FOREIGN DATA WRAPPER, SERVER,
66  * USER MAPPING or FOREIGN TABLE that uses postgres_fdw.
67  *
68  * Raise an ERROR if the option or its value is considered invalid.
69  */
71 
72 Datum
74 {
75  List *options_list = untransformRelOptions(PG_GETARG_DATUM(0));
76  Oid catalog = PG_GETARG_OID(1);
77  ListCell *cell;
78 
79  /* Build our options lists if we didn't yet. */
81 
82  /*
83  * Check that only options supported by postgres_fdw, and allowed for the
84  * current object type, are given.
85  */
86  foreach(cell, options_list)
87  {
88  DefElem *def = (DefElem *) lfirst(cell);
89 
90  if (!is_valid_option(def->defname, catalog))
91  {
92  /*
93  * Unknown option specified, complain about it. Provide a hint
94  * with list of valid options for the object.
95  */
96  PgFdwOption *opt;
98 
99  initStringInfo(&buf);
100  for (opt = postgres_fdw_options; opt->keyword; opt++)
101  {
102  if (catalog == opt->optcontext)
103  appendStringInfo(&buf, "%s%s", (buf.len > 0) ? ", " : "",
104  opt->keyword);
105  }
106 
107  ereport(ERROR,
108  (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
109  errmsg("invalid option \"%s\"", def->defname),
110  errhint("Valid options in this context are: %s",
111  buf.data)));
112  }
113 
114  /*
115  * Validate option value, when we can do so without any context.
116  */
117  if (strcmp(def->defname, "use_remote_estimate") == 0 ||
118  strcmp(def->defname, "updatable") == 0 ||
119  strcmp(def->defname, "truncatable") == 0 ||
120  strcmp(def->defname, "async_capable") == 0 ||
121  strcmp(def->defname, "keep_connections") == 0)
122  {
123  /* these accept only boolean values */
124  (void) defGetBoolean(def);
125  }
126  else if (strcmp(def->defname, "fdw_startup_cost") == 0 ||
127  strcmp(def->defname, "fdw_tuple_cost") == 0)
128  {
129  /*
130  * These must have a floating point value greater than or equal to
131  * zero.
132  */
133  char *value;
134  double real_val;
135  bool is_parsed;
136 
137  value = defGetString(def);
138  is_parsed = parse_real(value, &real_val, 0, NULL);
139 
140  if (!is_parsed)
141  ereport(ERROR,
142  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
143  errmsg("invalid value for floating point option \"%s\": %s",
144  def->defname, value)));
145 
146  if (real_val < 0)
147  ereport(ERROR,
148  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
149  errmsg("\"%s\" must be a floating point value greater than or equal to zero",
150  def->defname)));
151  }
152  else if (strcmp(def->defname, "extensions") == 0)
153  {
154  /* check list syntax, warn about uninstalled extensions */
155  (void) ExtractExtensionList(defGetString(def), true);
156  }
157  else if (strcmp(def->defname, "fetch_size") == 0 ||
158  strcmp(def->defname, "batch_size") == 0)
159  {
160  char *value;
161  int int_val;
162  bool is_parsed;
163 
164  value = defGetString(def);
165  is_parsed = parse_int(value, &int_val, 0, NULL);
166 
167  if (!is_parsed)
168  ereport(ERROR,
169  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
170  errmsg("invalid value for integer option \"%s\": %s",
171  def->defname, value)));
172 
173  if (int_val <= 0)
174  ereport(ERROR,
175  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
176  errmsg("\"%s\" must be an integer value greater than zero",
177  def->defname)));
178  }
179  else if (strcmp(def->defname, "password_required") == 0)
180  {
181  bool pw_required = defGetBoolean(def);
182 
183  /*
184  * Only the superuser may set this option on a user mapping, or
185  * alter a user mapping on which this option is set. We allow a
186  * user to clear this option if it's set - in fact, we don't have
187  * a choice since we can't see the old mapping when validating an
188  * alter.
189  */
190  if (!superuser() && !pw_required)
191  ereport(ERROR,
192  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
193  errmsg("password_required=false is superuser-only"),
194  errhint("User mappings with the password_required option set to false may only be created or modified by the superuser")));
195  }
196  else if (strcmp(def->defname, "sslcert") == 0 ||
197  strcmp(def->defname, "sslkey") == 0)
198  {
199  /* similarly for sslcert / sslkey on user mapping */
200  if (catalog == UserMappingRelationId && !superuser())
201  ereport(ERROR,
202  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
203  errmsg("sslcert and sslkey are superuser-only"),
204  errhint("User mappings with the sslcert or sslkey options set may only be created or modified by the superuser")));
205  }
206  }
207 
208  PG_RETURN_VOID();
209 }
210 
211 /*
212  * Initialize option lists.
213  */
214 static void
216 {
217  int num_libpq_opts;
218  PQconninfoOption *lopt;
219  PgFdwOption *popt;
220 
221  /* non-libpq FDW-specific FDW options */
222  static const PgFdwOption non_libpq_options[] = {
223  {"schema_name", ForeignTableRelationId, false},
224  {"table_name", ForeignTableRelationId, false},
225  {"column_name", AttributeRelationId, false},
226  /* use_remote_estimate is available on both server and table */
227  {"use_remote_estimate", ForeignServerRelationId, false},
228  {"use_remote_estimate", ForeignTableRelationId, false},
229  /* cost factors */
230  {"fdw_startup_cost", ForeignServerRelationId, false},
231  {"fdw_tuple_cost", ForeignServerRelationId, false},
232  /* shippable extensions */
233  {"extensions", ForeignServerRelationId, false},
234  /* updatable is available on both server and table */
235  {"updatable", ForeignServerRelationId, false},
236  {"updatable", ForeignTableRelationId, false},
237  /* truncatable is available on both server and table */
238  {"truncatable", ForeignServerRelationId, false},
239  {"truncatable", ForeignTableRelationId, false},
240  /* fetch_size is available on both server and table */
241  {"fetch_size", ForeignServerRelationId, false},
242  {"fetch_size", ForeignTableRelationId, false},
243  /* batch_size is available on both server and table */
244  {"batch_size", ForeignServerRelationId, false},
245  {"batch_size", ForeignTableRelationId, false},
246  /* async_capable is available on both server and table */
247  {"async_capable", ForeignServerRelationId, false},
248  {"async_capable", ForeignTableRelationId, false},
249  {"keep_connections", ForeignServerRelationId, false},
250  {"password_required", UserMappingRelationId, false},
251 
252  /*
253  * sslcert and sslkey are in fact libpq options, but we repeat them
254  * here to allow them to appear in both foreign server context (when
255  * we generate libpq options) and user mapping context (from here).
256  */
257  {"sslcert", UserMappingRelationId, true},
258  {"sslkey", UserMappingRelationId, true},
259 
260  {NULL, InvalidOid, false}
261  };
262 
263  /* Prevent redundant initialization. */
264  if (postgres_fdw_options)
265  return;
266 
267  /*
268  * Get list of valid libpq options.
269  *
270  * To avoid unnecessary work, we get the list once and use it throughout
271  * the lifetime of this backend process. We don't need to care about
272  * memory context issues, because PQconndefaults allocates with malloc.
273  */
274  libpq_options = PQconndefaults();
275  if (!libpq_options) /* assume reason for failure is OOM */
276  ereport(ERROR,
277  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
278  errmsg("out of memory"),
279  errdetail("Could not get libpq's default connection options.")));
280 
281  /* Count how many libpq options are available. */
282  num_libpq_opts = 0;
283  for (lopt = libpq_options; lopt->keyword; lopt++)
284  num_libpq_opts++;
285 
286  /*
287  * Construct an array which consists of all valid options for
288  * postgres_fdw, by appending FDW-specific options to libpq options.
289  *
290  * We use plain malloc here to allocate postgres_fdw_options because it
291  * lives as long as the backend process does. Besides, keeping
292  * libpq_options in memory allows us to avoid copying every keyword
293  * string.
294  */
295  postgres_fdw_options = (PgFdwOption *)
296  malloc(sizeof(PgFdwOption) * num_libpq_opts +
297  sizeof(non_libpq_options));
298  if (postgres_fdw_options == NULL)
299  ereport(ERROR,
300  (errcode(ERRCODE_FDW_OUT_OF_MEMORY),
301  errmsg("out of memory")));
302 
303  popt = postgres_fdw_options;
304  for (lopt = libpq_options; lopt->keyword; lopt++)
305  {
306  /* Hide debug options, as well as settings we override internally. */
307  if (strchr(lopt->dispchar, 'D') ||
308  strcmp(lopt->keyword, "fallback_application_name") == 0 ||
309  strcmp(lopt->keyword, "client_encoding") == 0)
310  continue;
311 
312  /* We don't have to copy keyword string, as described above. */
313  popt->keyword = lopt->keyword;
314 
315  /*
316  * "user" and any secret options are allowed only on user mappings.
317  * Everything else is a server option.
318  */
319  if (strcmp(lopt->keyword, "user") == 0 || strchr(lopt->dispchar, '*'))
320  popt->optcontext = UserMappingRelationId;
321  else
322  popt->optcontext = ForeignServerRelationId;
323  popt->is_libpq_opt = true;
324 
325  popt++;
326  }
327 
328  /* Append FDW-specific options and dummy terminator. */
329  memcpy(popt, non_libpq_options, sizeof(non_libpq_options));
330 }
331 
332 /*
333  * Check whether the given option is one of the valid postgres_fdw options.
334  * context is the Oid of the catalog holding the object the option is for.
335  */
336 static bool
337 is_valid_option(const char *keyword, Oid context)
338 {
339  PgFdwOption *opt;
340 
341  Assert(postgres_fdw_options); /* must be initialized already */
342 
343  for (opt = postgres_fdw_options; opt->keyword; opt++)
344  {
345  if (context == opt->optcontext && strcmp(opt->keyword, keyword) == 0)
346  return true;
347  }
348 
349  return false;
350 }
351 
352 /*
353  * Check whether the given option is one of the valid libpq options.
354  */
355 static bool
357 {
358  PgFdwOption *opt;
359 
360  Assert(postgres_fdw_options); /* must be initialized already */
361 
362  for (opt = postgres_fdw_options; opt->keyword; opt++)
363  {
364  if (opt->is_libpq_opt && strcmp(opt->keyword, keyword) == 0)
365  return true;
366  }
367 
368  return false;
369 }
370 
371 /*
372  * Generate key-value arrays which include only libpq options from the
373  * given list (which can contain any kind of options). Caller must have
374  * allocated large-enough arrays. Returns number of options found.
375  */
376 int
377 ExtractConnectionOptions(List *defelems, const char **keywords,
378  const char **values)
379 {
380  ListCell *lc;
381  int i;
382 
383  /* Build our options lists if we didn't yet. */
385 
386  i = 0;
387  foreach(lc, defelems)
388  {
389  DefElem *d = (DefElem *) lfirst(lc);
390 
391  if (is_libpq_option(d->defname))
392  {
393  keywords[i] = d->defname;
394  values[i] = defGetString(d);
395  i++;
396  }
397  }
398  return i;
399 }
400 
401 /*
402  * Parse a comma-separated string and return a List of the OIDs of the
403  * extensions named in the string. If any names in the list cannot be
404  * found, report a warning if warnOnMissing is true, else just silently
405  * ignore them.
406  */
407 List *
408 ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
409 {
410  List *extensionOids = NIL;
411  List *extlist;
412  ListCell *lc;
413 
414  /* SplitIdentifierString scribbles on its input, so pstrdup first */
415  if (!SplitIdentifierString(pstrdup(extensionsString), ',', &extlist))
416  {
417  /* syntax error in name list */
418  ereport(ERROR,
419  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
420  errmsg("parameter \"%s\" must be a list of extension names",
421  "extensions")));
422  }
423 
424  foreach(lc, extlist)
425  {
426  const char *extension_name = (const char *) lfirst(lc);
427  Oid extension_oid = get_extension_oid(extension_name, true);
428 
429  if (OidIsValid(extension_oid))
430  {
431  extensionOids = lappend_oid(extensionOids, extension_oid);
432  }
433  else if (warnOnMissing)
434  {
436  (errcode(ERRCODE_UNDEFINED_OBJECT),
437  errmsg("extension \"%s\" is not installed",
438  extension_name)));
439  }
440  }
441 
442  list_free(extlist);
443  return extensionOids;
444 }
445 
446 /*
447  * Module load callback
448  */
449 void
450 _PG_init(void)
451 {
452  /*
453  * Unlike application_name GUC, don't set GUC_IS_NAME flag nor check_hook
454  * to allow postgres_fdw.application_name to be any string more than
455  * NAMEDATALEN characters and to include non-ASCII characters. Instead,
456  * remote server truncates application_name of remote connection to less
457  * than NAMEDATALEN and replaces any non-ASCII characters in it with a '?'
458  * character.
459  */
460  DefineCustomStringVariable("postgres_fdw.application_name",
461  "Sets the application name to be used on the remote server.",
462  NULL,
464  NULL,
465  PGC_USERSET,
466  0,
467  NULL,
468  NULL,
469  NULL);
470 }
#define NIL
Definition: pg_list.h:65
PG_FUNCTION_INFO_V1(postgres_fdw_validator)
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
char * pstrdup(const char *in)
Definition: mcxt.c:1299
const char * keyword
Definition: option.c:31
static bool is_valid_option(const char *keyword, Oid context)
Definition: option.c:337
bool is_libpq_opt
Definition: option.c:33
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
bool parse_real(const char *value, double *result, int flags, const char **hintmsg)
Definition: guc.c:6937
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
static PgFdwOption * postgres_fdw_options
Definition: option.c:40
#define malloc(a)
Definition: header.h:50
struct PgFdwOption PgFdwOption
bool defGetBoolean(DefElem *def)
Definition: define.c:106
int ExtractConnectionOptions(List *defelems, const char **keywords, const char **values)
Definition: option.c:377
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
char * defGetString(DefElem *def)
Definition: define.c:49
List * ExtractExtensionList(const char *extensionsString, bool warnOnMissing)
Definition: option.c:408
static char * buf
Definition: pg_test_fsync.c:68
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3746
int errdetail(const char *fmt,...)
Definition: elog.c:1042
Oid optcontext
Definition: option.c:32
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define WARNING
Definition: elog.h:40
void _PG_init(void)
Definition: option.c:450
char * pgfdw_application_name
Definition: option.c:51
void DefineCustomStringVariable(const char *name, const char *short_desc, const char *long_desc, char **valueAddr, const char *bootValue, GucContext context, int flags, GucStringCheckHook check_hook, GucStringAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:9248
uintptr_t Datum
Definition: postgres.h:411
bool parse_int(const char *value, int *result, int flags, const char **hintmsg)
Definition: guc.c:6847
List * untransformRelOptions(Datum options)
Definition: reloptions.c:1325
Datum postgres_fdw_validator(PG_FUNCTION_ARGS)
Definition: option.c:73
#define InvalidOid
Definition: postgres_ext.h:36
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:157
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1472
static Datum values[MAXATTR]
Definition: bootstrap.c:156
Oid get_extension_oid(const char *extname, bool missing_ok)
Definition: extension.c:140
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
int i
static bool is_libpq_option(const char *keyword)
Definition: option.c:356
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
char * defname
Definition: parsenodes.h:758
static PQconninfoOption * libpq_options
Definition: option.c:46
Definition: pg_list.h:50
static void InitPgFdwOptions(void)
Definition: option.c:215