PostgreSQL Source Code  git master
aclchk.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * aclchk.c
4  * Routines to check access control permissions.
5  *
6  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/catalog/aclchk.c
12  *
13  * NOTES
14  * See acl.h.
15  *
16  *-------------------------------------------------------------------------
17  */
18 #include "postgres.h"
19 
20 #include "access/genam.h"
21 #include "access/heapam.h"
22 #include "access/htup_details.h"
23 #include "access/sysattr.h"
24 #include "access/xact.h"
25 #include "catalog/binary_upgrade.h"
26 #include "catalog/catalog.h"
27 #include "catalog/dependency.h"
28 #include "catalog/indexing.h"
29 #include "catalog/objectaccess.h"
30 #include "catalog/pg_aggregate.h"
31 #include "catalog/pg_am.h"
32 #include "catalog/pg_authid.h"
33 #include "catalog/pg_cast.h"
34 #include "catalog/pg_collation.h"
35 #include "catalog/pg_conversion.h"
36 #include "catalog/pg_database.h"
37 #include "catalog/pg_default_acl.h"
39 #include "catalog/pg_extension.h"
42 #include "catalog/pg_init_privs.h"
43 #include "catalog/pg_language.h"
44 #include "catalog/pg_largeobject.h"
46 #include "catalog/pg_namespace.h"
47 #include "catalog/pg_opclass.h"
48 #include "catalog/pg_operator.h"
49 #include "catalog/pg_opfamily.h"
50 #include "catalog/pg_proc.h"
53 #include "catalog/pg_tablespace.h"
54 #include "catalog/pg_type.h"
55 #include "catalog/pg_ts_config.h"
56 #include "catalog/pg_ts_dict.h"
57 #include "catalog/pg_ts_parser.h"
58 #include "catalog/pg_ts_template.h"
59 #include "catalog/pg_transform.h"
60 #include "commands/dbcommands.h"
61 #include "commands/event_trigger.h"
62 #include "commands/extension.h"
63 #include "commands/proclang.h"
64 #include "commands/tablespace.h"
65 #include "foreign/foreign.h"
66 #include "miscadmin.h"
67 #include "nodes/makefuncs.h"
68 #include "parser/parse_func.h"
69 #include "parser/parse_type.h"
70 #include "utils/acl.h"
71 #include "utils/aclchk_internal.h"
72 #include "utils/builtins.h"
73 #include "utils/fmgroids.h"
74 #include "utils/lsyscache.h"
75 #include "utils/rel.h"
76 #include "utils/syscache.h"
77 #include "utils/tqual.h"
78 
79 
80 /*
81  * Internal format used by ALTER DEFAULT PRIVILEGES.
82  */
83 typedef struct
84 {
85  Oid roleid; /* owning role */
86  Oid nspid; /* namespace, or InvalidOid if none */
87  /* remaining fields are same as in InternalGrant: */
88  bool is_grant;
90  bool all_privs;
96 
97 /*
98  * When performing a binary-upgrade, pg_dump will call a function to set
99  * this variable to let us know that we need to populate the pg_init_privs
100  * table for the GRANT/REVOKE commands while this variable is set to true.
101  */
103 
104 static void ExecGrantStmt_oids(InternalGrant *istmt);
105 static void ExecGrant_Relation(InternalGrant *grantStmt);
106 static void ExecGrant_Database(InternalGrant *grantStmt);
107 static void ExecGrant_Fdw(InternalGrant *grantStmt);
108 static void ExecGrant_ForeignServer(InternalGrant *grantStmt);
109 static void ExecGrant_Function(InternalGrant *grantStmt);
110 static void ExecGrant_Language(InternalGrant *grantStmt);
111 static void ExecGrant_Largeobject(InternalGrant *grantStmt);
112 static void ExecGrant_Namespace(InternalGrant *grantStmt);
113 static void ExecGrant_Tablespace(InternalGrant *grantStmt);
114 static void ExecGrant_Type(InternalGrant *grantStmt);
115 
116 static void SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames);
117 static void SetDefaultACL(InternalDefaultACL *iacls);
118 
119 static List *objectNamesToOids(ObjectType objtype, List *objnames);
120 static List *objectsInSchemaToOids(ObjectType objtype, List *nspnames);
121 static List *getRelationsInNamespace(Oid namespaceId, char relkind);
122 static void expand_col_privileges(List *colnames, Oid table_oid,
123  AclMode this_privileges,
124  AclMode *col_privileges,
125  int num_col_privileges);
126 static void expand_all_col_privileges(Oid table_oid, Form_pg_class classForm,
127  AclMode this_privileges,
128  AclMode *col_privileges,
129  int num_col_privileges);
130 static AclMode string_to_privilege(const char *privname);
131 static const char *privilege_to_string(AclMode privilege);
132 static AclMode restrict_and_check_grant(bool is_grant, AclMode avail_goptions,
133  bool all_privs, AclMode privileges,
134  Oid objectId, Oid grantorId,
135  ObjectType objtype, const char *objname,
136  AttrNumber att_number, const char *colname);
137 static AclMode pg_aclmask(ObjectType objtype, Oid table_oid, AttrNumber attnum,
138  Oid roleid, AclMode mask, AclMaskHow how);
139 static void recordExtensionInitPriv(Oid objoid, Oid classoid, int objsubid,
140  Acl *new_acl);
141 static void recordExtensionInitPrivWorker(Oid objoid, Oid classoid, int objsubid,
142  Acl *new_acl);
143 
144 
145 #ifdef ACLDEBUG
146 static void
147 dumpacl(Acl *acl)
148 {
149  int i;
150  AclItem *aip;
151 
152  elog(DEBUG2, "acl size = %d, # acls = %d",
153  ACL_SIZE(acl), ACL_NUM(acl));
154  aip = ACL_DAT(acl);
155  for (i = 0; i < ACL_NUM(acl); ++i)
156  elog(DEBUG2, " acl[%d]: %s", i,
158  PointerGetDatum(aip + i))));
159 }
160 #endif /* ACLDEBUG */
161 
162 
163 /*
164  * If is_grant is true, adds the given privileges for the list of
165  * grantees to the existing old_acl. If is_grant is false, the
166  * privileges for the given grantees are removed from old_acl.
167  *
168  * NB: the original old_acl is pfree'd.
169  */
170 static Acl *
171 merge_acl_with_grant(Acl *old_acl, bool is_grant,
172  bool grant_option, DropBehavior behavior,
173  List *grantees, AclMode privileges,
174  Oid grantorId, Oid ownerId)
175 {
176  unsigned modechg;
177  ListCell *j;
178  Acl *new_acl;
179 
180  modechg = is_grant ? ACL_MODECHG_ADD : ACL_MODECHG_DEL;
181 
182 #ifdef ACLDEBUG
183  dumpacl(old_acl);
184 #endif
185  new_acl = old_acl;
186 
187  foreach(j, grantees)
188  {
189  AclItem aclitem;
190  Acl *newer_acl;
191 
192  aclitem.ai_grantee = lfirst_oid(j);
193 
194  /*
195  * Grant options can only be granted to individual roles, not PUBLIC.
196  * The reason is that if a user would re-grant a privilege that he
197  * held through PUBLIC, and later the user is removed, the situation
198  * is impossible to clean up.
199  */
200  if (is_grant && grant_option && aclitem.ai_grantee == ACL_ID_PUBLIC)
201  ereport(ERROR,
202  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
203  errmsg("grant options can only be granted to roles")));
204 
205  aclitem.ai_grantor = grantorId;
206 
207  /*
208  * The asymmetry in the conditions here comes from the spec. In
209  * GRANT, the grant_option flag signals WITH GRANT OPTION, which means
210  * to grant both the basic privilege and its grant option. But in
211  * REVOKE, plain revoke revokes both the basic privilege and its grant
212  * option, while REVOKE GRANT OPTION revokes only the option.
213  */
215  (is_grant || !grant_option) ? privileges : ACL_NO_RIGHTS,
216  (!is_grant || grant_option) ? privileges : ACL_NO_RIGHTS);
217 
218  newer_acl = aclupdate(new_acl, &aclitem, modechg, ownerId, behavior);
219 
220  /* avoid memory leak when there are many grantees */
221  pfree(new_acl);
222  new_acl = newer_acl;
223 
224 #ifdef ACLDEBUG
225  dumpacl(new_acl);
226 #endif
227  }
228 
229  return new_acl;
230 }
231 
232 /*
233  * Restrict the privileges to what we can actually grant, and emit
234  * the standards-mandated warning and error messages.
235  */
236 static AclMode
237 restrict_and_check_grant(bool is_grant, AclMode avail_goptions, bool all_privs,
238  AclMode privileges, Oid objectId, Oid grantorId,
239  ObjectType objtype, const char *objname,
240  AttrNumber att_number, const char *colname)
241 {
242  AclMode this_privileges;
243  AclMode whole_mask;
244 
245  switch (objtype)
246  {
247  case OBJECT_COLUMN:
248  whole_mask = ACL_ALL_RIGHTS_COLUMN;
249  break;
250  case OBJECT_TABLE:
251  whole_mask = ACL_ALL_RIGHTS_RELATION;
252  break;
253  case OBJECT_SEQUENCE:
254  whole_mask = ACL_ALL_RIGHTS_SEQUENCE;
255  break;
256  case OBJECT_DATABASE:
257  whole_mask = ACL_ALL_RIGHTS_DATABASE;
258  break;
259  case OBJECT_FUNCTION:
260  whole_mask = ACL_ALL_RIGHTS_FUNCTION;
261  break;
262  case OBJECT_LANGUAGE:
263  whole_mask = ACL_ALL_RIGHTS_LANGUAGE;
264  break;
265  case OBJECT_LARGEOBJECT:
266  whole_mask = ACL_ALL_RIGHTS_LARGEOBJECT;
267  break;
268  case OBJECT_SCHEMA:
269  whole_mask = ACL_ALL_RIGHTS_SCHEMA;
270  break;
271  case OBJECT_TABLESPACE:
272  whole_mask = ACL_ALL_RIGHTS_TABLESPACE;
273  break;
274  case OBJECT_FDW:
275  whole_mask = ACL_ALL_RIGHTS_FDW;
276  break;
278  whole_mask = ACL_ALL_RIGHTS_FOREIGN_SERVER;
279  break;
281  elog(ERROR, "grantable rights not supported for event triggers");
282  /* not reached, but keep compiler quiet */
283  return ACL_NO_RIGHTS;
284  case OBJECT_TYPE:
285  whole_mask = ACL_ALL_RIGHTS_TYPE;
286  break;
287  default:
288  elog(ERROR, "unrecognized object type: %d", objtype);
289  /* not reached, but keep compiler quiet */
290  return ACL_NO_RIGHTS;
291  }
292 
293  /*
294  * If we found no grant options, consider whether to issue a hard error.
295  * Per spec, having any privilege at all on the object will get you by
296  * here.
297  */
298  if (avail_goptions == ACL_NO_RIGHTS)
299  {
300  if (pg_aclmask(objtype, objectId, att_number, grantorId,
301  whole_mask | ACL_GRANT_OPTION_FOR(whole_mask),
303  {
304  if (objtype == OBJECT_COLUMN && colname)
305  aclcheck_error_col(ACLCHECK_NO_PRIV, objtype, objname, colname);
306  else
307  aclcheck_error(ACLCHECK_NO_PRIV, objtype, objname);
308  }
309  }
310 
311  /*
312  * Restrict the operation to what we can actually grant or revoke, and
313  * issue a warning if appropriate. (For REVOKE this isn't quite what the
314  * spec says to do: the spec seems to want a warning only if no privilege
315  * bits actually change in the ACL. In practice that behavior seems much
316  * too noisy, as well as inconsistent with the GRANT case.)
317  */
318  this_privileges = privileges & ACL_OPTION_TO_PRIVS(avail_goptions);
319  if (is_grant)
320  {
321  if (this_privileges == 0)
322  {
323  if (objtype == OBJECT_COLUMN && colname)
325  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
326  errmsg("no privileges were granted for column \"%s\" of relation \"%s\"",
327  colname, objname)));
328  else
330  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
331  errmsg("no privileges were granted for \"%s\"",
332  objname)));
333  }
334  else if (!all_privs && this_privileges != privileges)
335  {
336  if (objtype == OBJECT_COLUMN && colname)
338  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
339  errmsg("not all privileges were granted for column \"%s\" of relation \"%s\"",
340  colname, objname)));
341  else
343  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
344  errmsg("not all privileges were granted for \"%s\"",
345  objname)));
346  }
347  }
348  else
349  {
350  if (this_privileges == 0)
351  {
352  if (objtype == OBJECT_COLUMN && colname)
354  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
355  errmsg("no privileges could be revoked for column \"%s\" of relation \"%s\"",
356  colname, objname)));
357  else
359  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
360  errmsg("no privileges could be revoked for \"%s\"",
361  objname)));
362  }
363  else if (!all_privs && this_privileges != privileges)
364  {
365  if (objtype == OBJECT_COLUMN && colname)
367  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
368  errmsg("not all privileges could be revoked for column \"%s\" of relation \"%s\"",
369  colname, objname)));
370  else
372  (errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
373  errmsg("not all privileges could be revoked for \"%s\"",
374  objname)));
375  }
376  }
377 
378  return this_privileges;
379 }
380 
381 /*
382  * Called to execute the utility commands GRANT and REVOKE
383  */
384 void
386 {
387  InternalGrant istmt;
388  ListCell *cell;
389  const char *errormsg;
390  AclMode all_privileges;
391 
392  /*
393  * Turn the regular GrantStmt into the InternalGrant form.
394  */
395  istmt.is_grant = stmt->is_grant;
396  istmt.objtype = stmt->objtype;
397 
398  /* Collect the OIDs of the target objects */
399  switch (stmt->targtype)
400  {
401  case ACL_TARGET_OBJECT:
402  istmt.objects = objectNamesToOids(stmt->objtype, stmt->objects);
403  break;
405  istmt.objects = objectsInSchemaToOids(stmt->objtype, stmt->objects);
406  break;
407  /* ACL_TARGET_DEFAULTS should not be seen here */
408  default:
409  elog(ERROR, "unrecognized GrantStmt.targtype: %d",
410  (int) stmt->targtype);
411  }
412 
413  /* all_privs to be filled below */
414  /* privileges to be filled below */
415  istmt.col_privs = NIL; /* may get filled below */
416  istmt.grantees = NIL; /* filled below */
417  istmt.grant_option = stmt->grant_option;
418  istmt.behavior = stmt->behavior;
419 
420  /*
421  * Convert the RoleSpec list into an Oid list. Note that at this point we
422  * insert an ACL_ID_PUBLIC into the list if appropriate, so downstream
423  * there shouldn't be any additional work needed to support this case.
424  */
425  foreach(cell, stmt->grantees)
426  {
427  RoleSpec *grantee = (RoleSpec *) lfirst(cell);
428  Oid grantee_uid;
429 
430  switch (grantee->roletype)
431  {
432  case ROLESPEC_PUBLIC:
433  grantee_uid = ACL_ID_PUBLIC;
434  break;
435  default:
436  grantee_uid = get_rolespec_oid(grantee, false);
437  break;
438  }
439  istmt.grantees = lappend_oid(istmt.grantees, grantee_uid);
440  }
441 
442  /*
443  * Convert stmt->privileges, a list of AccessPriv nodes, into an AclMode
444  * bitmask. Note: objtype can't be OBJECT_COLUMN.
445  */
446  switch (stmt->objtype)
447  {
448  case OBJECT_TABLE:
449  /*
450  * Because this might be a sequence, we test both relation and
451  * sequence bits, and later do a more limited test when we know
452  * the object type.
453  */
455  errormsg = gettext_noop("invalid privilege type %s for relation");
456  break;
457  case OBJECT_SEQUENCE:
458  all_privileges = ACL_ALL_RIGHTS_SEQUENCE;
459  errormsg = gettext_noop("invalid privilege type %s for sequence");
460  break;
461  case OBJECT_DATABASE:
462  all_privileges = ACL_ALL_RIGHTS_DATABASE;
463  errormsg = gettext_noop("invalid privilege type %s for database");
464  break;
465  case OBJECT_DOMAIN:
466  all_privileges = ACL_ALL_RIGHTS_TYPE;
467  errormsg = gettext_noop("invalid privilege type %s for domain");
468  break;
469  case OBJECT_FUNCTION:
470  all_privileges = ACL_ALL_RIGHTS_FUNCTION;
471  errormsg = gettext_noop("invalid privilege type %s for function");
472  break;
473  case OBJECT_LANGUAGE:
474  all_privileges = ACL_ALL_RIGHTS_LANGUAGE;
475  errormsg = gettext_noop("invalid privilege type %s for language");
476  break;
477  case OBJECT_LARGEOBJECT:
478  all_privileges = ACL_ALL_RIGHTS_LARGEOBJECT;
479  errormsg = gettext_noop("invalid privilege type %s for large object");
480  break;
481  case OBJECT_SCHEMA:
482  all_privileges = ACL_ALL_RIGHTS_SCHEMA;
483  errormsg = gettext_noop("invalid privilege type %s for schema");
484  break;
485  case OBJECT_PROCEDURE:
486  all_privileges = ACL_ALL_RIGHTS_FUNCTION;
487  errormsg = gettext_noop("invalid privilege type %s for procedure");
488  break;
489  case OBJECT_ROUTINE:
490  all_privileges = ACL_ALL_RIGHTS_FUNCTION;
491  errormsg = gettext_noop("invalid privilege type %s for routine");
492  break;
493  case OBJECT_TABLESPACE:
494  all_privileges = ACL_ALL_RIGHTS_TABLESPACE;
495  errormsg = gettext_noop("invalid privilege type %s for tablespace");
496  break;
497  case OBJECT_TYPE:
498  all_privileges = ACL_ALL_RIGHTS_TYPE;
499  errormsg = gettext_noop("invalid privilege type %s for type");
500  break;
501  case OBJECT_FDW:
502  all_privileges = ACL_ALL_RIGHTS_FDW;
503  errormsg = gettext_noop("invalid privilege type %s for foreign-data wrapper");
504  break;
506  all_privileges = ACL_ALL_RIGHTS_FOREIGN_SERVER;
507  errormsg = gettext_noop("invalid privilege type %s for foreign server");
508  break;
509  default:
510  elog(ERROR, "unrecognized GrantStmt.objtype: %d",
511  (int) stmt->objtype);
512  /* keep compiler quiet */
513  all_privileges = ACL_NO_RIGHTS;
514  errormsg = NULL;
515  }
516 
517  if (stmt->privileges == NIL)
518  {
519  istmt.all_privs = true;
520 
521  /*
522  * will be turned into ACL_ALL_RIGHTS_* by the internal routines
523  * depending on the object type
524  */
525  istmt.privileges = ACL_NO_RIGHTS;
526  }
527  else
528  {
529  istmt.all_privs = false;
530  istmt.privileges = ACL_NO_RIGHTS;
531 
532  foreach(cell, stmt->privileges)
533  {
534  AccessPriv *privnode = (AccessPriv *) lfirst(cell);
535  AclMode priv;
536 
537  /*
538  * If it's a column-level specification, we just set it aside in
539  * col_privs for the moment; but insist it's for a relation.
540  */
541  if (privnode->cols)
542  {
543  if (stmt->objtype != OBJECT_TABLE)
544  ereport(ERROR,
545  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
546  errmsg("column privileges are only valid for relations")));
547  istmt.col_privs = lappend(istmt.col_privs, privnode);
548  continue;
549  }
550 
551  if (privnode->priv_name == NULL) /* parser mistake? */
552  elog(ERROR, "AccessPriv node must specify privilege or columns");
553  priv = string_to_privilege(privnode->priv_name);
554 
555  if (priv & ~((AclMode) all_privileges))
556  ereport(ERROR,
557  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
558  errmsg(errormsg, privilege_to_string(priv))));
559 
560  istmt.privileges |= priv;
561  }
562  }
563 
564  ExecGrantStmt_oids(&istmt);
565 }
566 
567 /*
568  * ExecGrantStmt_oids
569  *
570  * Internal entry point for granting and revoking privileges.
571  */
572 static void
574 {
575  switch (istmt->objtype)
576  {
577  case OBJECT_TABLE:
578  case OBJECT_SEQUENCE:
579  ExecGrant_Relation(istmt);
580  break;
581  case OBJECT_DATABASE:
582  ExecGrant_Database(istmt);
583  break;
584  case OBJECT_DOMAIN:
585  case OBJECT_TYPE:
586  ExecGrant_Type(istmt);
587  break;
588  case OBJECT_FDW:
589  ExecGrant_Fdw(istmt);
590  break;
593  break;
594  case OBJECT_FUNCTION:
595  case OBJECT_PROCEDURE:
596  case OBJECT_ROUTINE:
597  ExecGrant_Function(istmt);
598  break;
599  case OBJECT_LANGUAGE:
600  ExecGrant_Language(istmt);
601  break;
602  case OBJECT_LARGEOBJECT:
603  ExecGrant_Largeobject(istmt);
604  break;
605  case OBJECT_SCHEMA:
606  ExecGrant_Namespace(istmt);
607  break;
608  case OBJECT_TABLESPACE:
609  ExecGrant_Tablespace(istmt);
610  break;
611  default:
612  elog(ERROR, "unrecognized GrantStmt.objtype: %d",
613  (int) istmt->objtype);
614  }
615 
616  /*
617  * Pass the info to event triggers about the just-executed GRANT. Note
618  * that we prefer to do it after actually executing it, because that gives
619  * the functions a chance to adjust the istmt with privileges actually
620  * granted.
621  */
624 }
625 
626 /*
627  * objectNamesToOids
628  *
629  * Turn a list of object names of a given type into an Oid list.
630  *
631  * XXX: This function doesn't take any sort of locks on the objects whose
632  * names it looks up. In the face of concurrent DDL, we might easily latch
633  * onto an old version of an object, causing the GRANT or REVOKE statement
634  * to fail.
635  */
636 static List *
637 objectNamesToOids(ObjectType objtype, List *objnames)
638 {
639  List *objects = NIL;
640  ListCell *cell;
641 
642  Assert(objnames != NIL);
643 
644  switch (objtype)
645  {
646  case OBJECT_TABLE:
647  case OBJECT_SEQUENCE:
648  foreach(cell, objnames)
649  {
650  RangeVar *relvar = (RangeVar *) lfirst(cell);
651  Oid relOid;
652 
653  relOid = RangeVarGetRelid(relvar, NoLock, false);
654  objects = lappend_oid(objects, relOid);
655  }
656  break;
657  case OBJECT_DATABASE:
658  foreach(cell, objnames)
659  {
660  char *dbname = strVal(lfirst(cell));
661  Oid dbid;
662 
663  dbid = get_database_oid(dbname, false);
664  objects = lappend_oid(objects, dbid);
665  }
666  break;
667  case OBJECT_DOMAIN:
668  case OBJECT_TYPE:
669  foreach(cell, objnames)
670  {
671  List *typname = (List *) lfirst(cell);
672  Oid oid;
673 
674  oid = typenameTypeId(NULL, makeTypeNameFromNameList(typname));
675  objects = lappend_oid(objects, oid);
676  }
677  break;
678  case OBJECT_FUNCTION:
679  foreach(cell, objnames)
680  {
681  ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
682  Oid funcid;
683 
684  funcid = LookupFuncWithArgs(OBJECT_FUNCTION, func, false);
685  objects = lappend_oid(objects, funcid);
686  }
687  break;
688  case OBJECT_LANGUAGE:
689  foreach(cell, objnames)
690  {
691  char *langname = strVal(lfirst(cell));
692  Oid oid;
693 
694  oid = get_language_oid(langname, false);
695  objects = lappend_oid(objects, oid);
696  }
697  break;
698  case OBJECT_LARGEOBJECT:
699  foreach(cell, objnames)
700  {
701  Oid lobjOid = oidparse(lfirst(cell));
702 
703  if (!LargeObjectExists(lobjOid))
704  ereport(ERROR,
705  (errcode(ERRCODE_UNDEFINED_OBJECT),
706  errmsg("large object %u does not exist",
707  lobjOid)));
708 
709  objects = lappend_oid(objects, lobjOid);
710  }
711  break;
712  case OBJECT_SCHEMA:
713  foreach(cell, objnames)
714  {
715  char *nspname = strVal(lfirst(cell));
716  Oid oid;
717 
718  oid = get_namespace_oid(nspname, false);
719  objects = lappend_oid(objects, oid);
720  }
721  break;
722  case OBJECT_PROCEDURE:
723  foreach(cell, objnames)
724  {
725  ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
726  Oid procid;
727 
728  procid = LookupFuncWithArgs(OBJECT_PROCEDURE, func, false);
729  objects = lappend_oid(objects, procid);
730  }
731  break;
732  case OBJECT_ROUTINE:
733  foreach(cell, objnames)
734  {
735  ObjectWithArgs *func = (ObjectWithArgs *) lfirst(cell);
736  Oid routid;
737 
738  routid = LookupFuncWithArgs(OBJECT_ROUTINE, func, false);
739  objects = lappend_oid(objects, routid);
740  }
741  break;
742  case OBJECT_TABLESPACE:
743  foreach(cell, objnames)
744  {
745  char *spcname = strVal(lfirst(cell));
746  Oid spcoid;
747 
748  spcoid = get_tablespace_oid(spcname, false);
749  objects = lappend_oid(objects, spcoid);
750  }
751  break;
752  case OBJECT_FDW:
753  foreach(cell, objnames)
754  {
755  char *fdwname = strVal(lfirst(cell));
756  Oid fdwid = get_foreign_data_wrapper_oid(fdwname, false);
757 
758  objects = lappend_oid(objects, fdwid);
759  }
760  break;
762  foreach(cell, objnames)
763  {
764  char *srvname = strVal(lfirst(cell));
765  Oid srvid = get_foreign_server_oid(srvname, false);
766 
767  objects = lappend_oid(objects, srvid);
768  }
769  break;
770  default:
771  elog(ERROR, "unrecognized GrantStmt.objtype: %d",
772  (int) objtype);
773  }
774 
775  return objects;
776 }
777 
778 /*
779  * objectsInSchemaToOids
780  *
781  * Find all objects of a given type in specified schemas, and make a list
782  * of their Oids. We check USAGE privilege on the schemas, but there is
783  * no privilege checking on the individual objects here.
784  */
785 static List *
787 {
788  List *objects = NIL;
789  ListCell *cell;
790 
791  foreach(cell, nspnames)
792  {
793  char *nspname = strVal(lfirst(cell));
794  Oid namespaceId;
795  List *objs;
796 
797  namespaceId = LookupExplicitNamespace(nspname, false);
798 
799  switch (objtype)
800  {
801  case OBJECT_TABLE:
802  objs = getRelationsInNamespace(namespaceId, RELKIND_RELATION);
803  objects = list_concat(objects, objs);
804  objs = getRelationsInNamespace(namespaceId, RELKIND_VIEW);
805  objects = list_concat(objects, objs);
806  objs = getRelationsInNamespace(namespaceId, RELKIND_MATVIEW);
807  objects = list_concat(objects, objs);
808  objs = getRelationsInNamespace(namespaceId, RELKIND_FOREIGN_TABLE);
809  objects = list_concat(objects, objs);
811  objects = list_concat(objects, objs);
812  break;
813  case OBJECT_SEQUENCE:
814  objs = getRelationsInNamespace(namespaceId, RELKIND_SEQUENCE);
815  objects = list_concat(objects, objs);
816  break;
817  case OBJECT_FUNCTION:
818  case OBJECT_PROCEDURE:
819  case OBJECT_ROUTINE:
820  {
821  ScanKeyData key[2];
822  int keycount;
823  Relation rel;
824  HeapScanDesc scan;
825  HeapTuple tuple;
826 
827  keycount = 0;
828  ScanKeyInit(&key[keycount++],
830  BTEqualStrategyNumber, F_OIDEQ,
831  ObjectIdGetDatum(namespaceId));
832 
833  /*
834  * When looking for functions, check for return type <>0.
835  * When looking for procedures, check for return type ==0.
836  * When looking for routines, don't check the return type.
837  */
838  if (objtype == OBJECT_FUNCTION)
839  ScanKeyInit(&key[keycount++],
841  BTEqualStrategyNumber, F_OIDNE,
842  InvalidOid);
843  else if (objtype == OBJECT_PROCEDURE)
844  ScanKeyInit(&key[keycount++],
846  BTEqualStrategyNumber, F_OIDEQ,
847  InvalidOid);
848 
850  scan = heap_beginscan_catalog(rel, keycount, key);
851 
852  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
853  {
854  objects = lappend_oid(objects, HeapTupleGetOid(tuple));
855  }
856 
857  heap_endscan(scan);
859  }
860  break;
861  default:
862  /* should not happen */
863  elog(ERROR, "unrecognized GrantStmt.objtype: %d",
864  (int) objtype);
865  }
866  }
867 
868  return objects;
869 }
870 
871 /*
872  * getRelationsInNamespace
873  *
874  * Return Oid list of relations in given namespace filtered by relation kind
875  */
876 static List *
877 getRelationsInNamespace(Oid namespaceId, char relkind)
878 {
879  List *relations = NIL;
880  ScanKeyData key[2];
881  Relation rel;
882  HeapScanDesc scan;
883  HeapTuple tuple;
884 
885  ScanKeyInit(&key[0],
887  BTEqualStrategyNumber, F_OIDEQ,
888  ObjectIdGetDatum(namespaceId));
889  ScanKeyInit(&key[1],
891  BTEqualStrategyNumber, F_CHAREQ,
892  CharGetDatum(relkind));
893 
895  scan = heap_beginscan_catalog(rel, 2, key);
896 
897  while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
898  {
899  relations = lappend_oid(relations, HeapTupleGetOid(tuple));
900  }
901 
902  heap_endscan(scan);
904 
905  return relations;
906 }
907 
908 
909 /*
910  * ALTER DEFAULT PRIVILEGES statement
911  */
912 void
914 {
915  GrantStmt *action = stmt->action;
916  InternalDefaultACL iacls;
917  ListCell *cell;
918  List *rolespecs = NIL;
919  List *nspnames = NIL;
920  DefElem *drolespecs = NULL;
921  DefElem *dnspnames = NULL;
922  AclMode all_privileges;
923  const char *errormsg;
924 
925  /* Deconstruct the "options" part of the statement */
926  foreach(cell, stmt->options)
927  {
928  DefElem *defel = (DefElem *) lfirst(cell);
929 
930  if (strcmp(defel->defname, "schemas") == 0)
931  {
932  if (dnspnames)
933  ereport(ERROR,
934  (errcode(ERRCODE_SYNTAX_ERROR),
935  errmsg("conflicting or redundant options"),
936  parser_errposition(pstate, defel->location)));
937  dnspnames = defel;
938  }
939  else if (strcmp(defel->defname, "roles") == 0)
940  {
941  if (drolespecs)
942  ereport(ERROR,
943  (errcode(ERRCODE_SYNTAX_ERROR),
944  errmsg("conflicting or redundant options"),
945  parser_errposition(pstate, defel->location)));
946  drolespecs = defel;
947  }
948  else
949  elog(ERROR, "option \"%s\" not recognized", defel->defname);
950  }
951 
952  if (dnspnames)
953  nspnames = (List *) dnspnames->arg;
954  if (drolespecs)
955  rolespecs = (List *) drolespecs->arg;
956 
957  /* Prepare the InternalDefaultACL representation of the statement */
958  /* roleid to be filled below */
959  /* nspid to be filled in SetDefaultACLsInSchemas */
960  iacls.is_grant = action->is_grant;
961  iacls.objtype = action->objtype;
962  /* all_privs to be filled below */
963  /* privileges to be filled below */
964  iacls.grantees = NIL; /* filled below */
965  iacls.grant_option = action->grant_option;
966  iacls.behavior = action->behavior;
967 
968  /*
969  * Convert the RoleSpec list into an Oid list. Note that at this point we
970  * insert an ACL_ID_PUBLIC into the list if appropriate, so downstream
971  * there shouldn't be any additional work needed to support this case.
972  */
973  foreach(cell, action->grantees)
974  {
975  RoleSpec *grantee = (RoleSpec *) lfirst(cell);
976  Oid grantee_uid;
977 
978  switch (grantee->roletype)
979  {
980  case ROLESPEC_PUBLIC:
981  grantee_uid = ACL_ID_PUBLIC;
982  break;
983  default:
984  grantee_uid = get_rolespec_oid(grantee, false);
985  break;
986  }
987  iacls.grantees = lappend_oid(iacls.grantees, grantee_uid);
988  }
989 
990  /*
991  * Convert action->privileges, a list of privilege strings, into an
992  * AclMode bitmask.
993  */
994  switch (action->objtype)
995  {
996  case OBJECT_TABLE:
997  all_privileges = ACL_ALL_RIGHTS_RELATION;
998  errormsg = gettext_noop("invalid privilege type %s for relation");
999  break;
1000  case OBJECT_SEQUENCE:
1001  all_privileges = ACL_ALL_RIGHTS_SEQUENCE;
1002  errormsg = gettext_noop("invalid privilege type %s for sequence");
1003  break;
1004  case OBJECT_FUNCTION:
1005  all_privileges = ACL_ALL_RIGHTS_FUNCTION;
1006  errormsg = gettext_noop("invalid privilege type %s for function");
1007  break;
1008  case OBJECT_PROCEDURE:
1009  all_privileges = ACL_ALL_RIGHTS_FUNCTION;
1010  errormsg = gettext_noop("invalid privilege type %s for procedure");
1011  break;
1012  case OBJECT_ROUTINE:
1013  all_privileges = ACL_ALL_RIGHTS_FUNCTION;
1014  errormsg = gettext_noop("invalid privilege type %s for routine");
1015  break;
1016  case OBJECT_TYPE:
1017  all_privileges = ACL_ALL_RIGHTS_TYPE;
1018  errormsg = gettext_noop("invalid privilege type %s for type");
1019  break;
1020  case OBJECT_SCHEMA:
1021  all_privileges = ACL_ALL_RIGHTS_SCHEMA;
1022  errormsg = gettext_noop("invalid privilege type %s for schema");
1023  break;
1024  default:
1025  elog(ERROR, "unrecognized GrantStmt.objtype: %d",
1026  (int) action->objtype);
1027  /* keep compiler quiet */
1028  all_privileges = ACL_NO_RIGHTS;
1029  errormsg = NULL;
1030  }
1031 
1032  if (action->privileges == NIL)
1033  {
1034  iacls.all_privs = true;
1035 
1036  /*
1037  * will be turned into ACL_ALL_RIGHTS_* by the internal routines
1038  * depending on the object type
1039  */
1040  iacls.privileges = ACL_NO_RIGHTS;
1041  }
1042  else
1043  {
1044  iacls.all_privs = false;
1045  iacls.privileges = ACL_NO_RIGHTS;
1046 
1047  foreach(cell, action->privileges)
1048  {
1049  AccessPriv *privnode = (AccessPriv *) lfirst(cell);
1050  AclMode priv;
1051 
1052  if (privnode->cols)
1053  ereport(ERROR,
1054  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1055  errmsg("default privileges cannot be set for columns")));
1056 
1057  if (privnode->priv_name == NULL) /* parser mistake? */
1058  elog(ERROR, "AccessPriv node must specify privilege");
1059  priv = string_to_privilege(privnode->priv_name);
1060 
1061  if (priv & ~((AclMode) all_privileges))
1062  ereport(ERROR,
1063  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1064  errmsg(errormsg, privilege_to_string(priv))));
1065 
1066  iacls.privileges |= priv;
1067  }
1068  }
1069 
1070  if (rolespecs == NIL)
1071  {
1072  /* Set permissions for myself */
1073  iacls.roleid = GetUserId();
1074 
1075  SetDefaultACLsInSchemas(&iacls, nspnames);
1076  }
1077  else
1078  {
1079  /* Look up the role OIDs and do permissions checks */
1080  ListCell *rolecell;
1081 
1082  foreach(rolecell, rolespecs)
1083  {
1084  RoleSpec *rolespec = lfirst(rolecell);
1085 
1086  iacls.roleid = get_rolespec_oid(rolespec, false);
1087 
1088  /*
1089  * We insist that calling user be a member of each target role. If
1090  * he has that, he could become that role anyway via SET ROLE, so
1091  * FOR ROLE is just a syntactic convenience and doesn't give any
1092  * special privileges.
1093  */
1095 
1096  SetDefaultACLsInSchemas(&iacls, nspnames);
1097  }
1098  }
1099 }
1100 
1101 /*
1102  * Process ALTER DEFAULT PRIVILEGES for a list of target schemas
1103  *
1104  * All fields of *iacls except nspid were filled already
1105  */
1106 static void
1108 {
1109  if (nspnames == NIL)
1110  {
1111  /* Set database-wide permissions if no schema was specified */
1112  iacls->nspid = InvalidOid;
1113 
1114  SetDefaultACL(iacls);
1115  }
1116  else
1117  {
1118  /* Look up the schema OIDs and set permissions for each one */
1119  ListCell *nspcell;
1120 
1121  foreach(nspcell, nspnames)
1122  {
1123  char *nspname = strVal(lfirst(nspcell));
1124 
1125  iacls->nspid = get_namespace_oid(nspname, false);
1126 
1127  /*
1128  * We used to insist that the target role have CREATE privileges
1129  * on the schema, since without that it wouldn't be able to create
1130  * an object for which these default privileges would apply.
1131  * However, this check proved to be more confusing than helpful,
1132  * and it also caused certain database states to not be
1133  * dumpable/restorable, since revoking CREATE doesn't cause
1134  * default privileges for the schema to go away. So now, we just
1135  * allow the ALTER; if the user lacks CREATE he'll find out when
1136  * he tries to create an object.
1137  */
1138 
1139  SetDefaultACL(iacls);
1140  }
1141  }
1142 }
1143 
1144 
1145 /*
1146  * Create or update a pg_default_acl entry
1147  */
1148 static void
1150 {
1151  AclMode this_privileges = iacls->privileges;
1152  char objtype;
1153  Relation rel;
1154  HeapTuple tuple;
1155  bool isNew;
1156  Acl *def_acl;
1157  Acl *old_acl;
1158  Acl *new_acl;
1159  HeapTuple newtuple;
1161  bool nulls[Natts_pg_default_acl];
1162  bool replaces[Natts_pg_default_acl];
1163  int noldmembers;
1164  int nnewmembers;
1165  Oid *oldmembers;
1166  Oid *newmembers;
1167 
1169 
1170  /*
1171  * The default for a global entry is the hard-wired default ACL for the
1172  * particular object type. The default for non-global entries is an empty
1173  * ACL. This must be so because global entries replace the hard-wired
1174  * defaults, while others are added on.
1175  */
1176  if (!OidIsValid(iacls->nspid))
1177  def_acl = acldefault(iacls->objtype, iacls->roleid);
1178  else
1179  def_acl = make_empty_acl();
1180 
1181  /*
1182  * Convert ACL object type to pg_default_acl object type and handle
1183  * all_privs option
1184  */
1185  switch (iacls->objtype)
1186  {
1187  case OBJECT_TABLE:
1188  objtype = DEFACLOBJ_RELATION;
1189  if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1190  this_privileges = ACL_ALL_RIGHTS_RELATION;
1191  break;
1192 
1193  case OBJECT_SEQUENCE:
1194  objtype = DEFACLOBJ_SEQUENCE;
1195  if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1196  this_privileges = ACL_ALL_RIGHTS_SEQUENCE;
1197  break;
1198 
1199  case OBJECT_FUNCTION:
1200  objtype = DEFACLOBJ_FUNCTION;
1201  if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1202  this_privileges = ACL_ALL_RIGHTS_FUNCTION;
1203  break;
1204 
1205  case OBJECT_TYPE:
1206  objtype = DEFACLOBJ_TYPE;
1207  if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1208  this_privileges = ACL_ALL_RIGHTS_TYPE;
1209  break;
1210 
1211  case OBJECT_SCHEMA:
1212  if (OidIsValid(iacls->nspid))
1213  ereport(ERROR,
1214  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1215  errmsg("cannot use IN SCHEMA clause when using GRANT/REVOKE ON SCHEMAS")));
1216  objtype = DEFACLOBJ_NAMESPACE;
1217  if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
1218  this_privileges = ACL_ALL_RIGHTS_SCHEMA;
1219  break;
1220 
1221  default:
1222  elog(ERROR, "unrecognized objtype: %d",
1223  (int) iacls->objtype);
1224  objtype = 0; /* keep compiler quiet */
1225  break;
1226  }
1227 
1228  /* Search for existing row for this object type in catalog */
1230  ObjectIdGetDatum(iacls->roleid),
1231  ObjectIdGetDatum(iacls->nspid),
1232  CharGetDatum(objtype));
1233 
1234  if (HeapTupleIsValid(tuple))
1235  {
1236  Datum aclDatum;
1237  bool isNull;
1238 
1239  aclDatum = SysCacheGetAttr(DEFACLROLENSPOBJ, tuple,
1241  &isNull);
1242  if (!isNull)
1243  old_acl = DatumGetAclPCopy(aclDatum);
1244  else
1245  old_acl = NULL; /* this case shouldn't happen, probably */
1246  isNew = false;
1247  }
1248  else
1249  {
1250  old_acl = NULL;
1251  isNew = true;
1252  }
1253 
1254  if (old_acl != NULL)
1255  {
1256  /*
1257  * We need the members of both old and new ACLs so we can correct the
1258  * shared dependency information. Collect data before
1259  * merge_acl_with_grant throws away old_acl.
1260  */
1261  noldmembers = aclmembers(old_acl, &oldmembers);
1262  }
1263  else
1264  {
1265  /* If no or null entry, start with the default ACL value */
1266  old_acl = aclcopy(def_acl);
1267  /* There are no old member roles according to the catalogs */
1268  noldmembers = 0;
1269  oldmembers = NULL;
1270  }
1271 
1272  /*
1273  * Generate new ACL. Grantor of rights is always the same as the target
1274  * role.
1275  */
1276  new_acl = merge_acl_with_grant(old_acl,
1277  iacls->is_grant,
1278  iacls->grant_option,
1279  iacls->behavior,
1280  iacls->grantees,
1281  this_privileges,
1282  iacls->roleid,
1283  iacls->roleid);
1284 
1285  /*
1286  * If the result is the same as the default value, we do not need an
1287  * explicit pg_default_acl entry, and should in fact remove the entry if
1288  * it exists. Must sort both arrays to compare properly.
1289  */
1290  aclitemsort(new_acl);
1291  aclitemsort(def_acl);
1292  if (aclequal(new_acl, def_acl))
1293  {
1294  /* delete old entry, if indeed there is one */
1295  if (!isNew)
1296  {
1297  ObjectAddress myself;
1298 
1299  /*
1300  * The dependency machinery will take care of removing all
1301  * associated dependency entries. We use DROP_RESTRICT since
1302  * there shouldn't be anything depending on this entry.
1303  */
1304  myself.classId = DefaultAclRelationId;
1305  myself.objectId = HeapTupleGetOid(tuple);
1306  myself.objectSubId = 0;
1307 
1308  performDeletion(&myself, DROP_RESTRICT, 0);
1309  }
1310  }
1311  else
1312  {
1313  /* Prepare to insert or update pg_default_acl entry */
1314  MemSet(values, 0, sizeof(values));
1315  MemSet(nulls, false, sizeof(nulls));
1316  MemSet(replaces, false, sizeof(replaces));
1317 
1318  if (isNew)
1319  {
1320  /* insert new entry */
1323  values[Anum_pg_default_acl_defaclobjtype - 1] = CharGetDatum(objtype);
1324  values[Anum_pg_default_acl_defaclacl - 1] = PointerGetDatum(new_acl);
1325 
1326  newtuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
1327  CatalogTupleInsert(rel, newtuple);
1328  }
1329  else
1330  {
1331  /* update existing entry */
1332  values[Anum_pg_default_acl_defaclacl - 1] = PointerGetDatum(new_acl);
1333  replaces[Anum_pg_default_acl_defaclacl - 1] = true;
1334 
1335  newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
1336  values, nulls, replaces);
1337  CatalogTupleUpdate(rel, &newtuple->t_self, newtuple);
1338  }
1339 
1340  /* these dependencies don't change in an update */
1341  if (isNew)
1342  {
1343  /* dependency on role */
1345  HeapTupleGetOid(newtuple),
1346  iacls->roleid);
1347 
1348  /* dependency on namespace */
1349  if (OidIsValid(iacls->nspid))
1350  {
1351  ObjectAddress myself,
1352  referenced;
1353 
1354  myself.classId = DefaultAclRelationId;
1355  myself.objectId = HeapTupleGetOid(newtuple);
1356  myself.objectSubId = 0;
1357 
1358  referenced.classId = NamespaceRelationId;
1359  referenced.objectId = iacls->nspid;
1360  referenced.objectSubId = 0;
1361 
1362  recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
1363  }
1364  }
1365 
1366  /*
1367  * Update the shared dependency ACL info
1368  */
1369  nnewmembers = aclmembers(new_acl, &newmembers);
1370 
1372  HeapTupleGetOid(newtuple), 0,
1373  iacls->roleid,
1374  noldmembers, oldmembers,
1375  nnewmembers, newmembers);
1376 
1377  if (isNew)
1379  HeapTupleGetOid(newtuple), 0);
1380  else
1382  HeapTupleGetOid(newtuple), 0);
1383  }
1384 
1385  if (HeapTupleIsValid(tuple))
1386  ReleaseSysCache(tuple);
1387 
1389 }
1390 
1391 
1392 /*
1393  * RemoveRoleFromObjectACL
1394  *
1395  * Used by shdepDropOwned to remove mentions of a role in ACLs
1396  */
1397 void
1398 RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
1399 {
1400  if (classid == DefaultAclRelationId)
1401  {
1402  InternalDefaultACL iacls;
1403  Form_pg_default_acl pg_default_acl_tuple;
1404  Relation rel;
1405  ScanKeyData skey[1];
1406  SysScanDesc scan;
1407  HeapTuple tuple;
1408 
1409  /* first fetch info needed by SetDefaultACL */
1411 
1412  ScanKeyInit(&skey[0],
1414  BTEqualStrategyNumber, F_OIDEQ,
1415  ObjectIdGetDatum(objid));
1416 
1417  scan = systable_beginscan(rel, DefaultAclOidIndexId, true,
1418  NULL, 1, skey);
1419 
1420  tuple = systable_getnext(scan);
1421 
1422  if (!HeapTupleIsValid(tuple))
1423  elog(ERROR, "could not find tuple for default ACL %u", objid);
1424 
1425  pg_default_acl_tuple = (Form_pg_default_acl) GETSTRUCT(tuple);
1426 
1427  iacls.roleid = pg_default_acl_tuple->defaclrole;
1428  iacls.nspid = pg_default_acl_tuple->defaclnamespace;
1429 
1430  switch (pg_default_acl_tuple->defaclobjtype)
1431  {
1432  case DEFACLOBJ_RELATION:
1433  iacls.objtype = OBJECT_TABLE;
1434  break;
1435  case DEFACLOBJ_SEQUENCE:
1436  iacls.objtype = OBJECT_SEQUENCE;
1437  break;
1438  case DEFACLOBJ_FUNCTION:
1439  iacls.objtype = OBJECT_FUNCTION;
1440  break;
1441  case DEFACLOBJ_TYPE:
1442  iacls.objtype = OBJECT_TYPE;
1443  break;
1444  case DEFACLOBJ_NAMESPACE:
1445  iacls.objtype = OBJECT_SCHEMA;
1446  break;
1447  default:
1448  /* Shouldn't get here */
1449  elog(ERROR, "unexpected default ACL type: %d",
1450  (int) pg_default_acl_tuple->defaclobjtype);
1451  break;
1452  }
1453 
1454  systable_endscan(scan);
1456 
1457  iacls.is_grant = false;
1458  iacls.all_privs = true;
1459  iacls.privileges = ACL_NO_RIGHTS;
1460  iacls.grantees = list_make1_oid(roleid);
1461  iacls.grant_option = false;
1462  iacls.behavior = DROP_CASCADE;
1463 
1464  /* Do it */
1465  SetDefaultACL(&iacls);
1466  }
1467  else
1468  {
1469  InternalGrant istmt;
1470 
1471  switch (classid)
1472  {
1473  case RelationRelationId:
1474  /* it's OK to use TABLE for a sequence */
1475  istmt.objtype = OBJECT_TABLE;
1476  break;
1477  case DatabaseRelationId:
1478  istmt.objtype = OBJECT_DATABASE;
1479  break;
1480  case TypeRelationId:
1481  istmt.objtype = OBJECT_TYPE;
1482  break;
1483  case ProcedureRelationId:
1484  istmt.objtype = OBJECT_ROUTINE;
1485  break;
1486  case LanguageRelationId:
1487  istmt.objtype = OBJECT_LANGUAGE;
1488  break;
1489  case LargeObjectRelationId:
1490  istmt.objtype = OBJECT_LARGEOBJECT;
1491  break;
1492  case NamespaceRelationId:
1493  istmt.objtype = OBJECT_SCHEMA;
1494  break;
1495  case TableSpaceRelationId:
1496  istmt.objtype = OBJECT_TABLESPACE;
1497  break;
1500  break;
1502  istmt.objtype = OBJECT_FDW;
1503  break;
1504  default:
1505  elog(ERROR, "unexpected object class %u", classid);
1506  break;
1507  }
1508  istmt.is_grant = false;
1509  istmt.objects = list_make1_oid(objid);
1510  istmt.all_privs = true;
1511  istmt.privileges = ACL_NO_RIGHTS;
1512  istmt.col_privs = NIL;
1513  istmt.grantees = list_make1_oid(roleid);
1514  istmt.grant_option = false;
1515  istmt.behavior = DROP_CASCADE;
1516 
1517  ExecGrantStmt_oids(&istmt);
1518  }
1519 }
1520 
1521 
1522 /*
1523  * Remove a pg_default_acl entry
1524  */
1525 void
1527 {
1528  Relation rel;
1529  ScanKeyData skey[1];
1530  SysScanDesc scan;
1531  HeapTuple tuple;
1532 
1534 
1535  ScanKeyInit(&skey[0],
1537  BTEqualStrategyNumber, F_OIDEQ,
1538  ObjectIdGetDatum(defaclOid));
1539 
1540  scan = systable_beginscan(rel, DefaultAclOidIndexId, true,
1541  NULL, 1, skey);
1542 
1543  tuple = systable_getnext(scan);
1544 
1545  if (!HeapTupleIsValid(tuple))
1546  elog(ERROR, "could not find tuple for default ACL %u", defaclOid);
1547 
1548  CatalogTupleDelete(rel, &tuple->t_self);
1549 
1550  systable_endscan(scan);
1552 }
1553 
1554 
1555 /*
1556  * expand_col_privileges
1557  *
1558  * OR the specified privilege(s) into per-column array entries for each
1559  * specified attribute. The per-column array is indexed starting at
1560  * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
1561  */
1562 static void
1563 expand_col_privileges(List *colnames, Oid table_oid,
1564  AclMode this_privileges,
1565  AclMode *col_privileges,
1566  int num_col_privileges)
1567 {
1568  ListCell *cell;
1569 
1570  foreach(cell, colnames)
1571  {
1572  char *colname = strVal(lfirst(cell));
1573  AttrNumber attnum;
1574 
1575  attnum = get_attnum(table_oid, colname);
1576  if (attnum == InvalidAttrNumber)
1577  ereport(ERROR,
1578  (errcode(ERRCODE_UNDEFINED_COLUMN),
1579  errmsg("column \"%s\" of relation \"%s\" does not exist",
1580  colname, get_rel_name(table_oid))));
1582  if (attnum <= 0 || attnum >= num_col_privileges)
1583  elog(ERROR, "column number out of range"); /* safety check */
1584  col_privileges[attnum] |= this_privileges;
1585  }
1586 }
1587 
1588 /*
1589  * expand_all_col_privileges
1590  *
1591  * OR the specified privilege(s) into per-column array entries for each valid
1592  * attribute of a relation. The per-column array is indexed starting at
1593  * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
1594  */
1595 static void
1597  AclMode this_privileges,
1598  AclMode *col_privileges,
1599  int num_col_privileges)
1600 {
1601  AttrNumber curr_att;
1602 
1603  Assert(classForm->relnatts - FirstLowInvalidHeapAttributeNumber < num_col_privileges);
1604  for (curr_att = FirstLowInvalidHeapAttributeNumber + 1;
1605  curr_att <= classForm->relnatts;
1606  curr_att++)
1607  {
1608  HeapTuple attTuple;
1609  bool isdropped;
1610 
1611  if (curr_att == InvalidAttrNumber)
1612  continue;
1613 
1614  /* Skip OID column if it doesn't exist */
1615  if (curr_att == ObjectIdAttributeNumber && !classForm->relhasoids)
1616  continue;
1617 
1618  /* Views don't have any system columns at all */
1619  if (classForm->relkind == RELKIND_VIEW && curr_att < 0)
1620  continue;
1621 
1622  attTuple = SearchSysCache2(ATTNUM,
1623  ObjectIdGetDatum(table_oid),
1624  Int16GetDatum(curr_att));
1625  if (!HeapTupleIsValid(attTuple))
1626  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1627  curr_att, table_oid);
1628 
1629  isdropped = ((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped;
1630 
1631  ReleaseSysCache(attTuple);
1632 
1633  /* ignore dropped columns */
1634  if (isdropped)
1635  continue;
1636 
1637  col_privileges[curr_att - FirstLowInvalidHeapAttributeNumber] |= this_privileges;
1638  }
1639 }
1640 
1641 /*
1642  * This processes attributes, but expects to be called from
1643  * ExecGrant_Relation, not directly from ExecGrantStmt.
1644  */
1645 static void
1646 ExecGrant_Attribute(InternalGrant *istmt, Oid relOid, const char *relname,
1647  AttrNumber attnum, Oid ownerId, AclMode col_privileges,
1648  Relation attRelation, const Acl *old_rel_acl)
1649 {
1650  HeapTuple attr_tuple;
1651  Form_pg_attribute pg_attribute_tuple;
1652  Acl *old_acl;
1653  Acl *new_acl;
1654  Acl *merged_acl;
1655  Datum aclDatum;
1656  bool isNull;
1657  Oid grantorId;
1658  AclMode avail_goptions;
1659  bool need_update;
1660  HeapTuple newtuple;
1662  bool nulls[Natts_pg_attribute];
1663  bool replaces[Natts_pg_attribute];
1664  int noldmembers;
1665  int nnewmembers;
1666  Oid *oldmembers;
1667  Oid *newmembers;
1668 
1669  attr_tuple = SearchSysCache2(ATTNUM,
1670  ObjectIdGetDatum(relOid),
1671  Int16GetDatum(attnum));
1672  if (!HeapTupleIsValid(attr_tuple))
1673  elog(ERROR, "cache lookup failed for attribute %d of relation %u",
1674  attnum, relOid);
1675  pg_attribute_tuple = (Form_pg_attribute) GETSTRUCT(attr_tuple);
1676 
1677  /*
1678  * Get working copy of existing ACL. If there's no ACL, substitute the
1679  * proper default.
1680  */
1681  aclDatum = SysCacheGetAttr(ATTNUM, attr_tuple, Anum_pg_attribute_attacl,
1682  &isNull);
1683  if (isNull)
1684  {
1685  old_acl = acldefault(OBJECT_COLUMN, ownerId);
1686  /* There are no old member roles according to the catalogs */
1687  noldmembers = 0;
1688  oldmembers = NULL;
1689  }
1690  else
1691  {
1692  old_acl = DatumGetAclPCopy(aclDatum);
1693  /* Get the roles mentioned in the existing ACL */
1694  noldmembers = aclmembers(old_acl, &oldmembers);
1695  }
1696 
1697  /*
1698  * In select_best_grantor we should consider existing table-level ACL bits
1699  * as well as the per-column ACL. Build a new ACL that is their
1700  * concatenation. (This is a bit cheap and dirty compared to merging them
1701  * properly with no duplications, but it's all we need here.)
1702  */
1703  merged_acl = aclconcat(old_rel_acl, old_acl);
1704 
1705  /* Determine ID to do the grant as, and available grant options */
1706  select_best_grantor(GetUserId(), col_privileges,
1707  merged_acl, ownerId,
1708  &grantorId, &avail_goptions);
1709 
1710  pfree(merged_acl);
1711 
1712  /*
1713  * Restrict the privileges to what we can actually grant, and emit the
1714  * standards-mandated warning and error messages. Note: we don't track
1715  * whether the user actually used the ALL PRIVILEGES(columns) syntax for
1716  * each column; we just approximate it by whether all the possible
1717  * privileges are specified now. Since the all_privs flag only determines
1718  * whether a warning is issued, this seems close enough.
1719  */
1720  col_privileges =
1721  restrict_and_check_grant(istmt->is_grant, avail_goptions,
1722  (col_privileges == ACL_ALL_RIGHTS_COLUMN),
1723  col_privileges,
1724  relOid, grantorId, OBJECT_COLUMN,
1725  relname, attnum,
1726  NameStr(pg_attribute_tuple->attname));
1727 
1728  /*
1729  * Generate new ACL.
1730  */
1731  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
1732  istmt->grant_option,
1733  istmt->behavior, istmt->grantees,
1734  col_privileges, grantorId,
1735  ownerId);
1736 
1737  /*
1738  * We need the members of both old and new ACLs so we can correct the
1739  * shared dependency information.
1740  */
1741  nnewmembers = aclmembers(new_acl, &newmembers);
1742 
1743  /* finished building new ACL value, now insert it */
1744  MemSet(values, 0, sizeof(values));
1745  MemSet(nulls, false, sizeof(nulls));
1746  MemSet(replaces, false, sizeof(replaces));
1747 
1748  /*
1749  * If the updated ACL is empty, we can set attacl to null, and maybe even
1750  * avoid an update of the pg_attribute row. This is worth testing because
1751  * we'll come through here multiple times for any relation-level REVOKE,
1752  * even if there were never any column GRANTs. Note we are assuming that
1753  * the "default" ACL state for columns is empty.
1754  */
1755  if (ACL_NUM(new_acl) > 0)
1756  {
1757  values[Anum_pg_attribute_attacl - 1] = PointerGetDatum(new_acl);
1758  need_update = true;
1759  }
1760  else
1761  {
1762  nulls[Anum_pg_attribute_attacl - 1] = true;
1763  need_update = !isNull;
1764  }
1765  replaces[Anum_pg_attribute_attacl - 1] = true;
1766 
1767  if (need_update)
1768  {
1769  newtuple = heap_modify_tuple(attr_tuple, RelationGetDescr(attRelation),
1770  values, nulls, replaces);
1771 
1772  CatalogTupleUpdate(attRelation, &newtuple->t_self, newtuple);
1773 
1774  /* Update initial privileges for extensions */
1776  ACL_NUM(new_acl) > 0 ? new_acl : NULL);
1777 
1778  /* Update the shared dependency ACL info */
1779  updateAclDependencies(RelationRelationId, relOid, attnum,
1780  ownerId,
1781  noldmembers, oldmembers,
1782  nnewmembers, newmembers);
1783  }
1784 
1785  pfree(new_acl);
1786 
1787  ReleaseSysCache(attr_tuple);
1788 }
1789 
1790 /*
1791  * This processes both sequences and non-sequences.
1792  */
1793 static void
1795 {
1796  Relation relation;
1797  Relation attRelation;
1798  ListCell *cell;
1799 
1802 
1803  foreach(cell, istmt->objects)
1804  {
1805  Oid relOid = lfirst_oid(cell);
1806  Datum aclDatum;
1807  Form_pg_class pg_class_tuple;
1808  bool isNull;
1809  AclMode this_privileges;
1810  AclMode *col_privileges;
1811  int num_col_privileges;
1812  bool have_col_privileges;
1813  Acl *old_acl;
1814  Acl *old_rel_acl;
1815  int noldmembers;
1816  Oid *oldmembers;
1817  Oid ownerId;
1818  HeapTuple tuple;
1819  ListCell *cell_colprivs;
1820 
1821  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1822  if (!HeapTupleIsValid(tuple))
1823  elog(ERROR, "cache lookup failed for relation %u", relOid);
1824  pg_class_tuple = (Form_pg_class) GETSTRUCT(tuple);
1825 
1826  /* Not sensible to grant on an index */
1827  if (pg_class_tuple->relkind == RELKIND_INDEX ||
1828  pg_class_tuple->relkind == RELKIND_PARTITIONED_INDEX)
1829  ereport(ERROR,
1830  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1831  errmsg("\"%s\" is an index",
1832  NameStr(pg_class_tuple->relname))));
1833 
1834  /* Composite types aren't tables either */
1835  if (pg_class_tuple->relkind == RELKIND_COMPOSITE_TYPE)
1836  ereport(ERROR,
1837  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1838  errmsg("\"%s\" is a composite type",
1839  NameStr(pg_class_tuple->relname))));
1840 
1841  /* Used GRANT SEQUENCE on a non-sequence? */
1842  if (istmt->objtype == OBJECT_SEQUENCE &&
1843  pg_class_tuple->relkind != RELKIND_SEQUENCE)
1844  ereport(ERROR,
1845  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1846  errmsg("\"%s\" is not a sequence",
1847  NameStr(pg_class_tuple->relname))));
1848 
1849  /* Adjust the default permissions based on object type */
1850  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
1851  {
1852  if (pg_class_tuple->relkind == RELKIND_SEQUENCE)
1853  this_privileges = ACL_ALL_RIGHTS_SEQUENCE;
1854  else
1855  this_privileges = ACL_ALL_RIGHTS_RELATION;
1856  }
1857  else
1858  this_privileges = istmt->privileges;
1859 
1860  /*
1861  * The GRANT TABLE syntax can be used for sequences and non-sequences,
1862  * so we have to look at the relkind to determine the supported
1863  * permissions. The OR of table and sequence permissions were already
1864  * checked.
1865  */
1866  if (istmt->objtype == OBJECT_TABLE)
1867  {
1868  if (pg_class_tuple->relkind == RELKIND_SEQUENCE)
1869  {
1870  /*
1871  * For backward compatibility, just throw a warning for
1872  * invalid sequence permissions when using the non-sequence
1873  * GRANT syntax.
1874  */
1875  if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_SEQUENCE))
1876  {
1877  /*
1878  * Mention the object name because the user needs to know
1879  * which operations succeeded. This is required because
1880  * WARNING allows the command to continue.
1881  */
1882  ereport(WARNING,
1883  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1884  errmsg("sequence \"%s\" only supports USAGE, SELECT, and UPDATE privileges",
1885  NameStr(pg_class_tuple->relname))));
1886  this_privileges &= (AclMode) ACL_ALL_RIGHTS_SEQUENCE;
1887  }
1888  }
1889  else
1890  {
1891  if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_RELATION))
1892  {
1893  /*
1894  * USAGE is the only permission supported by sequences but
1895  * not by non-sequences. Don't mention the object name
1896  * because we didn't in the combined TABLE | SEQUENCE
1897  * check.
1898  */
1899  ereport(ERROR,
1900  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
1901  errmsg("invalid privilege type %s for table",
1902  "USAGE")));
1903  }
1904  }
1905  }
1906 
1907  /*
1908  * Set up array in which we'll accumulate any column privilege bits
1909  * that need modification. The array is indexed such that entry [0]
1910  * corresponds to FirstLowInvalidHeapAttributeNumber.
1911  */
1912  num_col_privileges = pg_class_tuple->relnatts - FirstLowInvalidHeapAttributeNumber + 1;
1913  col_privileges = (AclMode *) palloc0(num_col_privileges * sizeof(AclMode));
1914  have_col_privileges = false;
1915 
1916  /*
1917  * If we are revoking relation privileges that are also column
1918  * privileges, we must implicitly revoke them from each column too,
1919  * per SQL spec. (We don't need to implicitly add column privileges
1920  * during GRANT because the permissions-checking code always checks
1921  * both relation and per-column privileges.)
1922  */
1923  if (!istmt->is_grant &&
1924  (this_privileges & ACL_ALL_RIGHTS_COLUMN) != 0)
1925  {
1926  expand_all_col_privileges(relOid, pg_class_tuple,
1927  this_privileges & ACL_ALL_RIGHTS_COLUMN,
1928  col_privileges,
1929  num_col_privileges);
1930  have_col_privileges = true;
1931  }
1932 
1933  /*
1934  * Get owner ID and working copy of existing ACL. If there's no ACL,
1935  * substitute the proper default.
1936  */
1937  ownerId = pg_class_tuple->relowner;
1938  aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
1939  &isNull);
1940  if (isNull)
1941  {
1942  switch (pg_class_tuple->relkind)
1943  {
1944  case RELKIND_SEQUENCE:
1945  old_acl = acldefault(OBJECT_SEQUENCE, ownerId);
1946  break;
1947  default:
1948  old_acl = acldefault(OBJECT_TABLE, ownerId);
1949  break;
1950  }
1951  /* There are no old member roles according to the catalogs */
1952  noldmembers = 0;
1953  oldmembers = NULL;
1954  }
1955  else
1956  {
1957  old_acl = DatumGetAclPCopy(aclDatum);
1958  /* Get the roles mentioned in the existing ACL */
1959  noldmembers = aclmembers(old_acl, &oldmembers);
1960  }
1961 
1962  /* Need an extra copy of original rel ACL for column handling */
1963  old_rel_acl = aclcopy(old_acl);
1964 
1965  /*
1966  * Handle relation-level privileges, if any were specified
1967  */
1968  if (this_privileges != ACL_NO_RIGHTS)
1969  {
1970  AclMode avail_goptions;
1971  Acl *new_acl;
1972  Oid grantorId;
1973  HeapTuple newtuple;
1975  bool nulls[Natts_pg_class];
1976  bool replaces[Natts_pg_class];
1977  int nnewmembers;
1978  Oid *newmembers;
1979  ObjectType objtype;
1980 
1981  /* Determine ID to do the grant as, and available grant options */
1982  select_best_grantor(GetUserId(), this_privileges,
1983  old_acl, ownerId,
1984  &grantorId, &avail_goptions);
1985 
1986  switch (pg_class_tuple->relkind)
1987  {
1988  case RELKIND_SEQUENCE:
1989  objtype = OBJECT_SEQUENCE;
1990  break;
1991  default:
1992  objtype = OBJECT_TABLE;
1993  break;
1994  }
1995 
1996  /*
1997  * Restrict the privileges to what we can actually grant, and emit
1998  * the standards-mandated warning and error messages.
1999  */
2000  this_privileges =
2001  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2002  istmt->all_privs, this_privileges,
2003  relOid, grantorId, objtype,
2004  NameStr(pg_class_tuple->relname),
2005  0, NULL);
2006 
2007  /*
2008  * Generate new ACL.
2009  */
2010  new_acl = merge_acl_with_grant(old_acl,
2011  istmt->is_grant,
2012  istmt->grant_option,
2013  istmt->behavior,
2014  istmt->grantees,
2015  this_privileges,
2016  grantorId,
2017  ownerId);
2018 
2019  /*
2020  * We need the members of both old and new ACLs so we can correct
2021  * the shared dependency information.
2022  */
2023  nnewmembers = aclmembers(new_acl, &newmembers);
2024 
2025  /* finished building new ACL value, now insert it */
2026  MemSet(values, 0, sizeof(values));
2027  MemSet(nulls, false, sizeof(nulls));
2028  MemSet(replaces, false, sizeof(replaces));
2029 
2030  replaces[Anum_pg_class_relacl - 1] = true;
2031  values[Anum_pg_class_relacl - 1] = PointerGetDatum(new_acl);
2032 
2033  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
2034  values, nulls, replaces);
2035 
2036  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2037 
2038  /* Update initial privileges for extensions */
2039  recordExtensionInitPriv(relOid, RelationRelationId, 0, new_acl);
2040 
2041  /* Update the shared dependency ACL info */
2043  ownerId,
2044  noldmembers, oldmembers,
2045  nnewmembers, newmembers);
2046 
2047  pfree(new_acl);
2048  }
2049 
2050  /*
2051  * Handle column-level privileges, if any were specified or implied.
2052  * We first expand the user-specified column privileges into the
2053  * array, and then iterate over all nonempty array entries.
2054  */
2055  foreach(cell_colprivs, istmt->col_privs)
2056  {
2057  AccessPriv *col_privs = (AccessPriv *) lfirst(cell_colprivs);
2058 
2059  if (col_privs->priv_name == NULL)
2060  this_privileges = ACL_ALL_RIGHTS_COLUMN;
2061  else
2062  this_privileges = string_to_privilege(col_privs->priv_name);
2063 
2064  if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_COLUMN))
2065  ereport(ERROR,
2066  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
2067  errmsg("invalid privilege type %s for column",
2068  privilege_to_string(this_privileges))));
2069 
2070  if (pg_class_tuple->relkind == RELKIND_SEQUENCE &&
2071  this_privileges & ~((AclMode) ACL_SELECT))
2072  {
2073  /*
2074  * The only column privilege allowed on sequences is SELECT.
2075  * This is a warning not error because we do it that way for
2076  * relation-level privileges.
2077  */
2078  ereport(WARNING,
2079  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
2080  errmsg("sequence \"%s\" only supports SELECT column privileges",
2081  NameStr(pg_class_tuple->relname))));
2082 
2083  this_privileges &= (AclMode) ACL_SELECT;
2084  }
2085 
2086  expand_col_privileges(col_privs->cols, relOid,
2087  this_privileges,
2088  col_privileges,
2089  num_col_privileges);
2090  have_col_privileges = true;
2091  }
2092 
2093  if (have_col_privileges)
2094  {
2095  AttrNumber i;
2096 
2097  for (i = 0; i < num_col_privileges; i++)
2098  {
2099  if (col_privileges[i] == ACL_NO_RIGHTS)
2100  continue;
2101  ExecGrant_Attribute(istmt,
2102  relOid,
2103  NameStr(pg_class_tuple->relname),
2105  ownerId,
2106  col_privileges[i],
2107  attRelation,
2108  old_rel_acl);
2109  }
2110  }
2111 
2112  pfree(old_rel_acl);
2113  pfree(col_privileges);
2114 
2115  ReleaseSysCache(tuple);
2116 
2117  /* prevent error when processing duplicate objects */
2119  }
2120 
2121  heap_close(attRelation, RowExclusiveLock);
2122  heap_close(relation, RowExclusiveLock);
2123 }
2124 
2125 static void
2127 {
2128  Relation relation;
2129  ListCell *cell;
2130 
2131  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2133 
2135 
2136  foreach(cell, istmt->objects)
2137  {
2138  Oid datId = lfirst_oid(cell);
2139  Form_pg_database pg_database_tuple;
2140  Datum aclDatum;
2141  bool isNull;
2142  AclMode avail_goptions;
2143  AclMode this_privileges;
2144  Acl *old_acl;
2145  Acl *new_acl;
2146  Oid grantorId;
2147  Oid ownerId;
2148  HeapTuple newtuple;
2150  bool nulls[Natts_pg_database];
2151  bool replaces[Natts_pg_database];
2152  int noldmembers;
2153  int nnewmembers;
2154  Oid *oldmembers;
2155  Oid *newmembers;
2156  HeapTuple tuple;
2157 
2158  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(datId));
2159  if (!HeapTupleIsValid(tuple))
2160  elog(ERROR, "cache lookup failed for database %u", datId);
2161 
2162  pg_database_tuple = (Form_pg_database) GETSTRUCT(tuple);
2163 
2164  /*
2165  * Get owner ID and working copy of existing ACL. If there's no ACL,
2166  * substitute the proper default.
2167  */
2168  ownerId = pg_database_tuple->datdba;
2169  aclDatum = heap_getattr(tuple, Anum_pg_database_datacl,
2170  RelationGetDescr(relation), &isNull);
2171  if (isNull)
2172  {
2173  old_acl = acldefault(OBJECT_DATABASE, ownerId);
2174  /* There are no old member roles according to the catalogs */
2175  noldmembers = 0;
2176  oldmembers = NULL;
2177  }
2178  else
2179  {
2180  old_acl = DatumGetAclPCopy(aclDatum);
2181  /* Get the roles mentioned in the existing ACL */
2182  noldmembers = aclmembers(old_acl, &oldmembers);
2183  }
2184 
2185  /* Determine ID to do the grant as, and available grant options */
2187  old_acl, ownerId,
2188  &grantorId, &avail_goptions);
2189 
2190  /*
2191  * Restrict the privileges to what we can actually grant, and emit the
2192  * standards-mandated warning and error messages.
2193  */
2194  this_privileges =
2195  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2196  istmt->all_privs, istmt->privileges,
2197  datId, grantorId, OBJECT_DATABASE,
2198  NameStr(pg_database_tuple->datname),
2199  0, NULL);
2200 
2201  /*
2202  * Generate new ACL.
2203  */
2204  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2205  istmt->grant_option, istmt->behavior,
2206  istmt->grantees, this_privileges,
2207  grantorId, ownerId);
2208 
2209  /*
2210  * We need the members of both old and new ACLs so we can correct the
2211  * shared dependency information.
2212  */
2213  nnewmembers = aclmembers(new_acl, &newmembers);
2214 
2215  /* finished building new ACL value, now insert it */
2216  MemSet(values, 0, sizeof(values));
2217  MemSet(nulls, false, sizeof(nulls));
2218  MemSet(replaces, false, sizeof(replaces));
2219 
2220  replaces[Anum_pg_database_datacl - 1] = true;
2221  values[Anum_pg_database_datacl - 1] = PointerGetDatum(new_acl);
2222 
2223  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2224  nulls, replaces);
2225 
2226  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2227 
2228  /* Update the shared dependency ACL info */
2230  ownerId,
2231  noldmembers, oldmembers,
2232  nnewmembers, newmembers);
2233 
2234  ReleaseSysCache(tuple);
2235 
2236  pfree(new_acl);
2237 
2238  /* prevent error when processing duplicate objects */
2240  }
2241 
2242  heap_close(relation, RowExclusiveLock);
2243 }
2244 
2245 static void
2247 {
2248  Relation relation;
2249  ListCell *cell;
2250 
2251  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2252  istmt->privileges = ACL_ALL_RIGHTS_FDW;
2253 
2255 
2256  foreach(cell, istmt->objects)
2257  {
2258  Oid fdwid = lfirst_oid(cell);
2259  Form_pg_foreign_data_wrapper pg_fdw_tuple;
2260  Datum aclDatum;
2261  bool isNull;
2262  AclMode avail_goptions;
2263  AclMode this_privileges;
2264  Acl *old_acl;
2265  Acl *new_acl;
2266  Oid grantorId;
2267  Oid ownerId;
2268  HeapTuple tuple;
2269  HeapTuple newtuple;
2271  bool nulls[Natts_pg_foreign_data_wrapper];
2272  bool replaces[Natts_pg_foreign_data_wrapper];
2273  int noldmembers;
2274  int nnewmembers;
2275  Oid *oldmembers;
2276  Oid *newmembers;
2277 
2279  ObjectIdGetDatum(fdwid));
2280  if (!HeapTupleIsValid(tuple))
2281  elog(ERROR, "cache lookup failed for foreign-data wrapper %u", fdwid);
2282 
2283  pg_fdw_tuple = (Form_pg_foreign_data_wrapper) GETSTRUCT(tuple);
2284 
2285  /*
2286  * Get owner ID and working copy of existing ACL. If there's no ACL,
2287  * substitute the proper default.
2288  */
2289  ownerId = pg_fdw_tuple->fdwowner;
2290  aclDatum = SysCacheGetAttr(FOREIGNDATAWRAPPEROID, tuple,
2292  &isNull);
2293  if (isNull)
2294  {
2295  old_acl = acldefault(OBJECT_FDW, ownerId);
2296  /* There are no old member roles according to the catalogs */
2297  noldmembers = 0;
2298  oldmembers = NULL;
2299  }
2300  else
2301  {
2302  old_acl = DatumGetAclPCopy(aclDatum);
2303  /* Get the roles mentioned in the existing ACL */
2304  noldmembers = aclmembers(old_acl, &oldmembers);
2305  }
2306 
2307  /* Determine ID to do the grant as, and available grant options */
2309  old_acl, ownerId,
2310  &grantorId, &avail_goptions);
2311 
2312  /*
2313  * Restrict the privileges to what we can actually grant, and emit the
2314  * standards-mandated warning and error messages.
2315  */
2316  this_privileges =
2317  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2318  istmt->all_privs, istmt->privileges,
2319  fdwid, grantorId, OBJECT_FDW,
2320  NameStr(pg_fdw_tuple->fdwname),
2321  0, NULL);
2322 
2323  /*
2324  * Generate new ACL.
2325  */
2326  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2327  istmt->grant_option, istmt->behavior,
2328  istmt->grantees, this_privileges,
2329  grantorId, ownerId);
2330 
2331  /*
2332  * We need the members of both old and new ACLs so we can correct the
2333  * shared dependency information.
2334  */
2335  nnewmembers = aclmembers(new_acl, &newmembers);
2336 
2337  /* finished building new ACL value, now insert it */
2338  MemSet(values, 0, sizeof(values));
2339  MemSet(nulls, false, sizeof(nulls));
2340  MemSet(replaces, false, sizeof(replaces));
2341 
2342  replaces[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
2344 
2345  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2346  nulls, replaces);
2347 
2348  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2349 
2350  /* Update initial privileges for extensions */
2352  new_acl);
2353 
2354  /* Update the shared dependency ACL info */
2356  HeapTupleGetOid(tuple), 0,
2357  ownerId,
2358  noldmembers, oldmembers,
2359  nnewmembers, newmembers);
2360 
2361  ReleaseSysCache(tuple);
2362 
2363  pfree(new_acl);
2364 
2365  /* prevent error when processing duplicate objects */
2367  }
2368 
2369  heap_close(relation, RowExclusiveLock);
2370 }
2371 
2372 static void
2374 {
2375  Relation relation;
2376  ListCell *cell;
2377 
2378  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2380 
2382 
2383  foreach(cell, istmt->objects)
2384  {
2385  Oid srvid = lfirst_oid(cell);
2386  Form_pg_foreign_server pg_server_tuple;
2387  Datum aclDatum;
2388  bool isNull;
2389  AclMode avail_goptions;
2390  AclMode this_privileges;
2391  Acl *old_acl;
2392  Acl *new_acl;
2393  Oid grantorId;
2394  Oid ownerId;
2395  HeapTuple tuple;
2396  HeapTuple newtuple;
2398  bool nulls[Natts_pg_foreign_server];
2399  bool replaces[Natts_pg_foreign_server];
2400  int noldmembers;
2401  int nnewmembers;
2402  Oid *oldmembers;
2403  Oid *newmembers;
2404 
2406  if (!HeapTupleIsValid(tuple))
2407  elog(ERROR, "cache lookup failed for foreign server %u", srvid);
2408 
2409  pg_server_tuple = (Form_pg_foreign_server) GETSTRUCT(tuple);
2410 
2411  /*
2412  * Get owner ID and working copy of existing ACL. If there's no ACL,
2413  * substitute the proper default.
2414  */
2415  ownerId = pg_server_tuple->srvowner;
2416  aclDatum = SysCacheGetAttr(FOREIGNSERVEROID, tuple,
2418  &isNull);
2419  if (isNull)
2420  {
2421  old_acl = acldefault(OBJECT_FOREIGN_SERVER, ownerId);
2422  /* There are no old member roles according to the catalogs */
2423  noldmembers = 0;
2424  oldmembers = NULL;
2425  }
2426  else
2427  {
2428  old_acl = DatumGetAclPCopy(aclDatum);
2429  /* Get the roles mentioned in the existing ACL */
2430  noldmembers = aclmembers(old_acl, &oldmembers);
2431  }
2432 
2433  /* Determine ID to do the grant as, and available grant options */
2435  old_acl, ownerId,
2436  &grantorId, &avail_goptions);
2437 
2438  /*
2439  * Restrict the privileges to what we can actually grant, and emit the
2440  * standards-mandated warning and error messages.
2441  */
2442  this_privileges =
2443  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2444  istmt->all_privs, istmt->privileges,
2445  srvid, grantorId, OBJECT_FOREIGN_SERVER,
2446  NameStr(pg_server_tuple->srvname),
2447  0, NULL);
2448 
2449  /*
2450  * Generate new ACL.
2451  */
2452  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2453  istmt->grant_option, istmt->behavior,
2454  istmt->grantees, this_privileges,
2455  grantorId, ownerId);
2456 
2457  /*
2458  * We need the members of both old and new ACLs so we can correct the
2459  * shared dependency information.
2460  */
2461  nnewmembers = aclmembers(new_acl, &newmembers);
2462 
2463  /* finished building new ACL value, now insert it */
2464  MemSet(values, 0, sizeof(values));
2465  MemSet(nulls, false, sizeof(nulls));
2466  MemSet(replaces, false, sizeof(replaces));
2467 
2468  replaces[Anum_pg_foreign_server_srvacl - 1] = true;
2469  values[Anum_pg_foreign_server_srvacl - 1] = PointerGetDatum(new_acl);
2470 
2471  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2472  nulls, replaces);
2473 
2474  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2475 
2476  /* Update initial privileges for extensions */
2478 
2479  /* Update the shared dependency ACL info */
2481  HeapTupleGetOid(tuple), 0,
2482  ownerId,
2483  noldmembers, oldmembers,
2484  nnewmembers, newmembers);
2485 
2486  ReleaseSysCache(tuple);
2487 
2488  pfree(new_acl);
2489 
2490  /* prevent error when processing duplicate objects */
2492  }
2493 
2494  heap_close(relation, RowExclusiveLock);
2495 }
2496 
2497 static void
2499 {
2500  Relation relation;
2501  ListCell *cell;
2502 
2503  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2505 
2507 
2508  foreach(cell, istmt->objects)
2509  {
2510  Oid funcId = lfirst_oid(cell);
2511  Form_pg_proc pg_proc_tuple;
2512  Datum aclDatum;
2513  bool isNull;
2514  AclMode avail_goptions;
2515  AclMode this_privileges;
2516  Acl *old_acl;
2517  Acl *new_acl;
2518  Oid grantorId;
2519  Oid ownerId;
2520  HeapTuple tuple;
2521  HeapTuple newtuple;
2523  bool nulls[Natts_pg_proc];
2524  bool replaces[Natts_pg_proc];
2525  int noldmembers;
2526  int nnewmembers;
2527  Oid *oldmembers;
2528  Oid *newmembers;
2529 
2530  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
2531  if (!HeapTupleIsValid(tuple))
2532  elog(ERROR, "cache lookup failed for function %u", funcId);
2533 
2534  pg_proc_tuple = (Form_pg_proc) GETSTRUCT(tuple);
2535 
2536  /*
2537  * Get owner ID and working copy of existing ACL. If there's no ACL,
2538  * substitute the proper default.
2539  */
2540  ownerId = pg_proc_tuple->proowner;
2541  aclDatum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proacl,
2542  &isNull);
2543  if (isNull)
2544  {
2545  old_acl = acldefault(OBJECT_FUNCTION, ownerId);
2546  /* There are no old member roles according to the catalogs */
2547  noldmembers = 0;
2548  oldmembers = NULL;
2549  }
2550  else
2551  {
2552  old_acl = DatumGetAclPCopy(aclDatum);
2553  /* Get the roles mentioned in the existing ACL */
2554  noldmembers = aclmembers(old_acl, &oldmembers);
2555  }
2556 
2557  /* Determine ID to do the grant as, and available grant options */
2559  old_acl, ownerId,
2560  &grantorId, &avail_goptions);
2561 
2562  /*
2563  * Restrict the privileges to what we can actually grant, and emit the
2564  * standards-mandated warning and error messages.
2565  */
2566  this_privileges =
2567  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2568  istmt->all_privs, istmt->privileges,
2569  funcId, grantorId, OBJECT_FUNCTION,
2570  NameStr(pg_proc_tuple->proname),
2571  0, NULL);
2572 
2573  /*
2574  * Generate new ACL.
2575  */
2576  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2577  istmt->grant_option, istmt->behavior,
2578  istmt->grantees, this_privileges,
2579  grantorId, ownerId);
2580 
2581  /*
2582  * We need the members of both old and new ACLs so we can correct the
2583  * shared dependency information.
2584  */
2585  nnewmembers = aclmembers(new_acl, &newmembers);
2586 
2587  /* finished building new ACL value, now insert it */
2588  MemSet(values, 0, sizeof(values));
2589  MemSet(nulls, false, sizeof(nulls));
2590  MemSet(replaces, false, sizeof(replaces));
2591 
2592  replaces[Anum_pg_proc_proacl - 1] = true;
2593  values[Anum_pg_proc_proacl - 1] = PointerGetDatum(new_acl);
2594 
2595  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2596  nulls, replaces);
2597 
2598  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2599 
2600  /* Update initial privileges for extensions */
2601  recordExtensionInitPriv(funcId, ProcedureRelationId, 0, new_acl);
2602 
2603  /* Update the shared dependency ACL info */
2605  ownerId,
2606  noldmembers, oldmembers,
2607  nnewmembers, newmembers);
2608 
2609  ReleaseSysCache(tuple);
2610 
2611  pfree(new_acl);
2612 
2613  /* prevent error when processing duplicate objects */
2615  }
2616 
2617  heap_close(relation, RowExclusiveLock);
2618 }
2619 
2620 static void
2622 {
2623  Relation relation;
2624  ListCell *cell;
2625 
2626  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2628 
2630 
2631  foreach(cell, istmt->objects)
2632  {
2633  Oid langId = lfirst_oid(cell);
2634  Form_pg_language pg_language_tuple;
2635  Datum aclDatum;
2636  bool isNull;
2637  AclMode avail_goptions;
2638  AclMode this_privileges;
2639  Acl *old_acl;
2640  Acl *new_acl;
2641  Oid grantorId;
2642  Oid ownerId;
2643  HeapTuple tuple;
2644  HeapTuple newtuple;
2646  bool nulls[Natts_pg_language];
2647  bool replaces[Natts_pg_language];
2648  int noldmembers;
2649  int nnewmembers;
2650  Oid *oldmembers;
2651  Oid *newmembers;
2652 
2653  tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(langId));
2654  if (!HeapTupleIsValid(tuple))
2655  elog(ERROR, "cache lookup failed for language %u", langId);
2656 
2657  pg_language_tuple = (Form_pg_language) GETSTRUCT(tuple);
2658 
2659  if (!pg_language_tuple->lanpltrusted)
2660  ereport(ERROR,
2661  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2662  errmsg("language \"%s\" is not trusted",
2663  NameStr(pg_language_tuple->lanname)),
2664  errdetail("GRANT and REVOKE are not allowed on untrusted languages, "
2665  "because only superusers can use untrusted languages.")));
2666 
2667  /*
2668  * Get owner ID and working copy of existing ACL. If there's no ACL,
2669  * substitute the proper default.
2670  */
2671  ownerId = pg_language_tuple->lanowner;
2673  &isNull);
2674  if (isNull)
2675  {
2676  old_acl = acldefault(OBJECT_LANGUAGE, ownerId);
2677  /* There are no old member roles according to the catalogs */
2678  noldmembers = 0;
2679  oldmembers = NULL;
2680  }
2681  else
2682  {
2683  old_acl = DatumGetAclPCopy(aclDatum);
2684  /* Get the roles mentioned in the existing ACL */
2685  noldmembers = aclmembers(old_acl, &oldmembers);
2686  }
2687 
2688  /* Determine ID to do the grant as, and available grant options */
2690  old_acl, ownerId,
2691  &grantorId, &avail_goptions);
2692 
2693  /*
2694  * Restrict the privileges to what we can actually grant, and emit the
2695  * standards-mandated warning and error messages.
2696  */
2697  this_privileges =
2698  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2699  istmt->all_privs, istmt->privileges,
2700  langId, grantorId, OBJECT_LANGUAGE,
2701  NameStr(pg_language_tuple->lanname),
2702  0, NULL);
2703 
2704  /*
2705  * Generate new ACL.
2706  */
2707  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2708  istmt->grant_option, istmt->behavior,
2709  istmt->grantees, this_privileges,
2710  grantorId, ownerId);
2711 
2712  /*
2713  * We need the members of both old and new ACLs so we can correct the
2714  * shared dependency information.
2715  */
2716  nnewmembers = aclmembers(new_acl, &newmembers);
2717 
2718  /* finished building new ACL value, now insert it */
2719  MemSet(values, 0, sizeof(values));
2720  MemSet(nulls, false, sizeof(nulls));
2721  MemSet(replaces, false, sizeof(replaces));
2722 
2723  replaces[Anum_pg_language_lanacl - 1] = true;
2724  values[Anum_pg_language_lanacl - 1] = PointerGetDatum(new_acl);
2725 
2726  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2727  nulls, replaces);
2728 
2729  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2730 
2731  /* Update initial privileges for extensions */
2732  recordExtensionInitPriv(langId, LanguageRelationId, 0, new_acl);
2733 
2734  /* Update the shared dependency ACL info */
2736  ownerId,
2737  noldmembers, oldmembers,
2738  nnewmembers, newmembers);
2739 
2740  ReleaseSysCache(tuple);
2741 
2742  pfree(new_acl);
2743 
2744  /* prevent error when processing duplicate objects */
2746  }
2747 
2748  heap_close(relation, RowExclusiveLock);
2749 }
2750 
2751 static void
2753 {
2754  Relation relation;
2755  ListCell *cell;
2756 
2757  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2759 
2762 
2763  foreach(cell, istmt->objects)
2764  {
2765  Oid loid = lfirst_oid(cell);
2766  Form_pg_largeobject_metadata form_lo_meta;
2767  char loname[NAMEDATALEN];
2768  Datum aclDatum;
2769  bool isNull;
2770  AclMode avail_goptions;
2771  AclMode this_privileges;
2772  Acl *old_acl;
2773  Acl *new_acl;
2774  Oid grantorId;
2775  Oid ownerId;
2776  HeapTuple newtuple;
2778  bool nulls[Natts_pg_largeobject_metadata];
2779  bool replaces[Natts_pg_largeobject_metadata];
2780  int noldmembers;
2781  int nnewmembers;
2782  Oid *oldmembers;
2783  Oid *newmembers;
2784  ScanKeyData entry[1];
2785  SysScanDesc scan;
2786  HeapTuple tuple;
2787 
2788  /* There's no syscache for pg_largeobject_metadata */
2789  ScanKeyInit(&entry[0],
2791  BTEqualStrategyNumber, F_OIDEQ,
2792  ObjectIdGetDatum(loid));
2793 
2794  scan = systable_beginscan(relation,
2796  NULL, 1, entry);
2797 
2798  tuple = systable_getnext(scan);
2799  if (!HeapTupleIsValid(tuple))
2800  elog(ERROR, "could not find tuple for large object %u", loid);
2801 
2802  form_lo_meta = (Form_pg_largeobject_metadata) GETSTRUCT(tuple);
2803 
2804  /*
2805  * Get owner ID and working copy of existing ACL. If there's no ACL,
2806  * substitute the proper default.
2807  */
2808  ownerId = form_lo_meta->lomowner;
2809  aclDatum = heap_getattr(tuple,
2811  RelationGetDescr(relation), &isNull);
2812  if (isNull)
2813  {
2814  old_acl = acldefault(OBJECT_LARGEOBJECT, ownerId);
2815  /* There are no old member roles according to the catalogs */
2816  noldmembers = 0;
2817  oldmembers = NULL;
2818  }
2819  else
2820  {
2821  old_acl = DatumGetAclPCopy(aclDatum);
2822  /* Get the roles mentioned in the existing ACL */
2823  noldmembers = aclmembers(old_acl, &oldmembers);
2824  }
2825 
2826  /* Determine ID to do the grant as, and available grant options */
2828  old_acl, ownerId,
2829  &grantorId, &avail_goptions);
2830 
2831  /*
2832  * Restrict the privileges to what we can actually grant, and emit the
2833  * standards-mandated warning and error messages.
2834  */
2835  snprintf(loname, sizeof(loname), "large object %u", loid);
2836  this_privileges =
2837  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2838  istmt->all_privs, istmt->privileges,
2839  loid, grantorId, OBJECT_LARGEOBJECT,
2840  loname, 0, NULL);
2841 
2842  /*
2843  * Generate new ACL.
2844  */
2845  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2846  istmt->grant_option, istmt->behavior,
2847  istmt->grantees, this_privileges,
2848  grantorId, ownerId);
2849 
2850  /*
2851  * We need the members of both old and new ACLs so we can correct the
2852  * shared dependency information.
2853  */
2854  nnewmembers = aclmembers(new_acl, &newmembers);
2855 
2856  /* finished building new ACL value, now insert it */
2857  MemSet(values, 0, sizeof(values));
2858  MemSet(nulls, false, sizeof(nulls));
2859  MemSet(replaces, false, sizeof(replaces));
2860 
2861  replaces[Anum_pg_largeobject_metadata_lomacl - 1] = true;
2863  = PointerGetDatum(new_acl);
2864 
2865  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
2866  values, nulls, replaces);
2867 
2868  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2869 
2870  /* Update initial privileges for extensions */
2872 
2873  /* Update the shared dependency ACL info */
2875  HeapTupleGetOid(tuple), 0,
2876  ownerId,
2877  noldmembers, oldmembers,
2878  nnewmembers, newmembers);
2879 
2880  systable_endscan(scan);
2881 
2882  pfree(new_acl);
2883 
2884  /* prevent error when processing duplicate objects */
2886  }
2887 
2888  heap_close(relation, RowExclusiveLock);
2889 }
2890 
2891 static void
2893 {
2894  Relation relation;
2895  ListCell *cell;
2896 
2897  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
2899 
2901 
2902  foreach(cell, istmt->objects)
2903  {
2904  Oid nspid = lfirst_oid(cell);
2905  Form_pg_namespace pg_namespace_tuple;
2906  Datum aclDatum;
2907  bool isNull;
2908  AclMode avail_goptions;
2909  AclMode this_privileges;
2910  Acl *old_acl;
2911  Acl *new_acl;
2912  Oid grantorId;
2913  Oid ownerId;
2914  HeapTuple tuple;
2915  HeapTuple newtuple;
2917  bool nulls[Natts_pg_namespace];
2918  bool replaces[Natts_pg_namespace];
2919  int noldmembers;
2920  int nnewmembers;
2921  Oid *oldmembers;
2922  Oid *newmembers;
2923 
2925  if (!HeapTupleIsValid(tuple))
2926  elog(ERROR, "cache lookup failed for namespace %u", nspid);
2927 
2928  pg_namespace_tuple = (Form_pg_namespace) GETSTRUCT(tuple);
2929 
2930  /*
2931  * Get owner ID and working copy of existing ACL. If there's no ACL,
2932  * substitute the proper default.
2933  */
2934  ownerId = pg_namespace_tuple->nspowner;
2935  aclDatum = SysCacheGetAttr(NAMESPACENAME, tuple,
2937  &isNull);
2938  if (isNull)
2939  {
2940  old_acl = acldefault(OBJECT_SCHEMA, ownerId);
2941  /* There are no old member roles according to the catalogs */
2942  noldmembers = 0;
2943  oldmembers = NULL;
2944  }
2945  else
2946  {
2947  old_acl = DatumGetAclPCopy(aclDatum);
2948  /* Get the roles mentioned in the existing ACL */
2949  noldmembers = aclmembers(old_acl, &oldmembers);
2950  }
2951 
2952  /* Determine ID to do the grant as, and available grant options */
2954  old_acl, ownerId,
2955  &grantorId, &avail_goptions);
2956 
2957  /*
2958  * Restrict the privileges to what we can actually grant, and emit the
2959  * standards-mandated warning and error messages.
2960  */
2961  this_privileges =
2962  restrict_and_check_grant(istmt->is_grant, avail_goptions,
2963  istmt->all_privs, istmt->privileges,
2964  nspid, grantorId, OBJECT_SCHEMA,
2965  NameStr(pg_namespace_tuple->nspname),
2966  0, NULL);
2967 
2968  /*
2969  * Generate new ACL.
2970  */
2971  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
2972  istmt->grant_option, istmt->behavior,
2973  istmt->grantees, this_privileges,
2974  grantorId, ownerId);
2975 
2976  /*
2977  * We need the members of both old and new ACLs so we can correct the
2978  * shared dependency information.
2979  */
2980  nnewmembers = aclmembers(new_acl, &newmembers);
2981 
2982  /* finished building new ACL value, now insert it */
2983  MemSet(values, 0, sizeof(values));
2984  MemSet(nulls, false, sizeof(nulls));
2985  MemSet(replaces, false, sizeof(replaces));
2986 
2987  replaces[Anum_pg_namespace_nspacl - 1] = true;
2988  values[Anum_pg_namespace_nspacl - 1] = PointerGetDatum(new_acl);
2989 
2990  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
2991  nulls, replaces);
2992 
2993  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
2994 
2995  /* Update initial privileges for extensions */
2996  recordExtensionInitPriv(nspid, NamespaceRelationId, 0, new_acl);
2997 
2998  /* Update the shared dependency ACL info */
3000  ownerId,
3001  noldmembers, oldmembers,
3002  nnewmembers, newmembers);
3003 
3004  ReleaseSysCache(tuple);
3005 
3006  pfree(new_acl);
3007 
3008  /* prevent error when processing duplicate objects */
3010  }
3011 
3012  heap_close(relation, RowExclusiveLock);
3013 }
3014 
3015 static void
3017 {
3018  Relation relation;
3019  ListCell *cell;
3020 
3021  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
3023 
3025 
3026  foreach(cell, istmt->objects)
3027  {
3028  Oid tblId = lfirst_oid(cell);
3029  Form_pg_tablespace pg_tablespace_tuple;
3030  Datum aclDatum;
3031  bool isNull;
3032  AclMode avail_goptions;
3033  AclMode this_privileges;
3034  Acl *old_acl;
3035  Acl *new_acl;
3036  Oid grantorId;
3037  Oid ownerId;
3038  HeapTuple newtuple;
3040  bool nulls[Natts_pg_tablespace];
3041  bool replaces[Natts_pg_tablespace];
3042  int noldmembers;
3043  int nnewmembers;
3044  Oid *oldmembers;
3045  Oid *newmembers;
3046  HeapTuple tuple;
3047 
3048  /* Search syscache for pg_tablespace */
3050  if (!HeapTupleIsValid(tuple))
3051  elog(ERROR, "cache lookup failed for tablespace %u", tblId);
3052 
3053  pg_tablespace_tuple = (Form_pg_tablespace) GETSTRUCT(tuple);
3054 
3055  /*
3056  * Get owner ID and working copy of existing ACL. If there's no ACL,
3057  * substitute the proper default.
3058  */
3059  ownerId = pg_tablespace_tuple->spcowner;
3060  aclDatum = heap_getattr(tuple, Anum_pg_tablespace_spcacl,
3061  RelationGetDescr(relation), &isNull);
3062  if (isNull)
3063  {
3064  old_acl = acldefault(OBJECT_TABLESPACE, ownerId);
3065  /* There are no old member roles according to the catalogs */
3066  noldmembers = 0;
3067  oldmembers = NULL;
3068  }
3069  else
3070  {
3071  old_acl = DatumGetAclPCopy(aclDatum);
3072  /* Get the roles mentioned in the existing ACL */
3073  noldmembers = aclmembers(old_acl, &oldmembers);
3074  }
3075 
3076  /* Determine ID to do the grant as, and available grant options */
3078  old_acl, ownerId,
3079  &grantorId, &avail_goptions);
3080 
3081  /*
3082  * Restrict the privileges to what we can actually grant, and emit the
3083  * standards-mandated warning and error messages.
3084  */
3085  this_privileges =
3086  restrict_and_check_grant(istmt->is_grant, avail_goptions,
3087  istmt->all_privs, istmt->privileges,
3088  tblId, grantorId, OBJECT_TABLESPACE,
3089  NameStr(pg_tablespace_tuple->spcname),
3090  0, NULL);
3091 
3092  /*
3093  * Generate new ACL.
3094  */
3095  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
3096  istmt->grant_option, istmt->behavior,
3097  istmt->grantees, this_privileges,
3098  grantorId, ownerId);
3099 
3100  /*
3101  * We need the members of both old and new ACLs so we can correct the
3102  * shared dependency information.
3103  */
3104  nnewmembers = aclmembers(new_acl, &newmembers);
3105 
3106  /* finished building new ACL value, now insert it */
3107  MemSet(values, 0, sizeof(values));
3108  MemSet(nulls, false, sizeof(nulls));
3109  MemSet(replaces, false, sizeof(replaces));
3110 
3111  replaces[Anum_pg_tablespace_spcacl - 1] = true;
3112  values[Anum_pg_tablespace_spcacl - 1] = PointerGetDatum(new_acl);
3113 
3114  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
3115  nulls, replaces);
3116 
3117  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
3118 
3119  /* Update the shared dependency ACL info */
3121  ownerId,
3122  noldmembers, oldmembers,
3123  nnewmembers, newmembers);
3124 
3125  ReleaseSysCache(tuple);
3126  pfree(new_acl);
3127 
3128  /* prevent error when processing duplicate objects */
3130  }
3131 
3132  heap_close(relation, RowExclusiveLock);
3133 }
3134 
3135 static void
3137 {
3138  Relation relation;
3139  ListCell *cell;
3140 
3141  if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
3143 
3145 
3146  foreach(cell, istmt->objects)
3147  {
3148  Oid typId = lfirst_oid(cell);
3149  Form_pg_type pg_type_tuple;
3150  Datum aclDatum;
3151  bool isNull;
3152  AclMode avail_goptions;
3153  AclMode this_privileges;
3154  Acl *old_acl;
3155  Acl *new_acl;
3156  Oid grantorId;
3157  Oid ownerId;
3158  HeapTuple newtuple;
3160  bool nulls[Natts_pg_type];
3161  bool replaces[Natts_pg_type];
3162  int noldmembers;
3163  int nnewmembers;
3164  Oid *oldmembers;
3165  Oid *newmembers;
3166  HeapTuple tuple;
3167 
3168  /* Search syscache for pg_type */
3169  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typId));
3170  if (!HeapTupleIsValid(tuple))
3171  elog(ERROR, "cache lookup failed for type %u", typId);
3172 
3173  pg_type_tuple = (Form_pg_type) GETSTRUCT(tuple);
3174 
3175  if (pg_type_tuple->typelem != 0 && pg_type_tuple->typlen == -1)
3176  ereport(ERROR,
3177  (errcode(ERRCODE_INVALID_GRANT_OPERATION),
3178  errmsg("cannot set privileges of array types"),
3179  errhint("Set the privileges of the element type instead.")));
3180 
3181  /* Used GRANT DOMAIN on a non-domain? */
3182  if (istmt->objtype == OBJECT_DOMAIN &&
3183  pg_type_tuple->typtype != TYPTYPE_DOMAIN)
3184  ereport(ERROR,
3185  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3186  errmsg("\"%s\" is not a domain",
3187  NameStr(pg_type_tuple->typname))));
3188 
3189  /*
3190  * Get owner ID and working copy of existing ACL. If there's no ACL,
3191  * substitute the proper default.
3192  */
3193  ownerId = pg_type_tuple->typowner;
3194  aclDatum = heap_getattr(tuple, Anum_pg_type_typacl,
3195  RelationGetDescr(relation), &isNull);
3196  if (isNull)
3197  {
3198  old_acl = acldefault(istmt->objtype, ownerId);
3199  /* There are no old member roles according to the catalogs */
3200  noldmembers = 0;
3201  oldmembers = NULL;
3202  }
3203  else
3204  {
3205  old_acl = DatumGetAclPCopy(aclDatum);
3206  /* Get the roles mentioned in the existing ACL */
3207  noldmembers = aclmembers(old_acl, &oldmembers);
3208  }
3209 
3210  /* Determine ID to do the grant as, and available grant options */
3212  old_acl, ownerId,
3213  &grantorId, &avail_goptions);
3214 
3215  /*
3216  * Restrict the privileges to what we can actually grant, and emit the
3217  * standards-mandated warning and error messages.
3218  */
3219  this_privileges =
3220  restrict_and_check_grant(istmt->is_grant, avail_goptions,
3221  istmt->all_privs, istmt->privileges,
3222  typId, grantorId, OBJECT_TYPE,
3223  NameStr(pg_type_tuple->typname),
3224  0, NULL);
3225 
3226  /*
3227  * Generate new ACL.
3228  */
3229  new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
3230  istmt->grant_option, istmt->behavior,
3231  istmt->grantees, this_privileges,
3232  grantorId, ownerId);
3233 
3234  /*
3235  * We need the members of both old and new ACLs so we can correct the
3236  * shared dependency information.
3237  */
3238  nnewmembers = aclmembers(new_acl, &newmembers);
3239 
3240  /* finished building new ACL value, now insert it */
3241  MemSet(values, 0, sizeof(values));
3242  MemSet(nulls, false, sizeof(nulls));
3243  MemSet(replaces, false, sizeof(replaces));
3244 
3245  replaces[Anum_pg_type_typacl - 1] = true;
3246  values[Anum_pg_type_typacl - 1] = PointerGetDatum(new_acl);
3247 
3248  newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
3249  nulls, replaces);
3250 
3251  CatalogTupleUpdate(relation, &newtuple->t_self, newtuple);
3252 
3253  /* Update initial privileges for extensions */
3254  recordExtensionInitPriv(typId, TypeRelationId, 0, new_acl);
3255 
3256  /* Update the shared dependency ACL info */
3258  ownerId,
3259  noldmembers, oldmembers,
3260  nnewmembers, newmembers);
3261 
3262  ReleaseSysCache(tuple);
3263  pfree(new_acl);
3264 
3265  /* prevent error when processing duplicate objects */
3267  }
3268 
3269  heap_close(relation, RowExclusiveLock);
3270 }
3271 
3272 
3273 static AclMode
3274 string_to_privilege(const char *privname)
3275 {
3276  if (strcmp(privname, "insert") == 0)
3277  return ACL_INSERT;
3278  if (strcmp(privname, "select") == 0)
3279  return ACL_SELECT;
3280  if (strcmp(privname, "update") == 0)
3281  return ACL_UPDATE;
3282  if (strcmp(privname, "delete") == 0)
3283  return ACL_DELETE;
3284  if (strcmp(privname, "truncate") == 0)
3285  return ACL_TRUNCATE;
3286  if (strcmp(privname, "references") == 0)
3287  return ACL_REFERENCES;
3288  if (strcmp(privname, "trigger") == 0)
3289  return ACL_TRIGGER;
3290  if (strcmp(privname, "execute") == 0)
3291  return ACL_EXECUTE;
3292  if (strcmp(privname, "usage") == 0)
3293  return ACL_USAGE;
3294  if (strcmp(privname, "create") == 0)
3295  return ACL_CREATE;
3296  if (strcmp(privname, "temporary") == 0)
3297  return ACL_CREATE_TEMP;
3298  if (strcmp(privname, "temp") == 0)
3299  return ACL_CREATE_TEMP;
3300  if (strcmp(privname, "connect") == 0)
3301  return ACL_CONNECT;
3302  if (strcmp(privname, "rule") == 0)
3303  return 0; /* ignore old RULE privileges */
3304  ereport(ERROR,
3305  (errcode(ERRCODE_SYNTAX_ERROR),
3306  errmsg("unrecognized privilege type \"%s\"", privname)));
3307  return 0; /* appease compiler */
3308 }
3309 
3310 static const char *
3312 {
3313  switch (privilege)
3314  {
3315  case ACL_INSERT:
3316  return "INSERT";
3317  case ACL_SELECT:
3318  return "SELECT";
3319  case ACL_UPDATE:
3320  return "UPDATE";
3321  case ACL_DELETE:
3322  return "DELETE";
3323  case ACL_TRUNCATE:
3324  return "TRUNCATE";
3325  case ACL_REFERENCES:
3326  return "REFERENCES";
3327  case ACL_TRIGGER:
3328  return "TRIGGER";
3329  case ACL_EXECUTE:
3330  return "EXECUTE";
3331  case ACL_USAGE:
3332  return "USAGE";
3333  case ACL_CREATE:
3334  return "CREATE";
3335  case ACL_CREATE_TEMP:
3336  return "TEMP";
3337  case ACL_CONNECT:
3338  return "CONNECT";
3339  default:
3340  elog(ERROR, "unrecognized privilege: %d", (int) privilege);
3341  }
3342  return NULL; /* appease compiler */
3343 }
3344 
3345 /*
3346  * Standardized reporting of aclcheck permissions failures.
3347  *
3348  * Note: we do not double-quote the %s's below, because many callers
3349  * supply strings that might be already quoted.
3350  */
3351 void
3353  const char *objectname)
3354 {
3355  switch (aclerr)
3356  {
3357  case ACLCHECK_OK:
3358  /* no error, so return to caller */
3359  break;
3360  case ACLCHECK_NO_PRIV:
3361  {
3362  const char *msg = "???";
3363 
3364  switch (objtype)
3365  {
3366  case OBJECT_AGGREGATE:
3367  msg = gettext_noop("permission denied for aggregate %s");
3368  break;
3369  case OBJECT_COLLATION:
3370  msg = gettext_noop("permission denied for collation %s");
3371  break;
3372  case OBJECT_COLUMN:
3373  msg = gettext_noop("permission denied for column %s");
3374  break;
3375  case OBJECT_CONVERSION:
3376  msg = gettext_noop("permission denied for conversion %s");
3377  break;
3378  case OBJECT_DATABASE:
3379  msg = gettext_noop("permission denied for database %s");
3380  break;
3381  case OBJECT_DOMAIN:
3382  msg = gettext_noop("permission denied for domain %s");
3383  break;
3384  case OBJECT_EVENT_TRIGGER:
3385  msg = gettext_noop("permission denied for event trigger %s");
3386  break;
3387  case OBJECT_EXTENSION:
3388  msg = gettext_noop("permission denied for extension %s");
3389  break;
3390  case OBJECT_FDW:
3391  msg = gettext_noop("permission denied for foreign-data wrapper %s");
3392  break;
3393  case OBJECT_FOREIGN_SERVER:
3394  msg = gettext_noop("permission denied for foreign server %s");
3395  break;
3396  case OBJECT_FOREIGN_TABLE:
3397  msg = gettext_noop("permission denied for foreign table %s");
3398  break;
3399  case OBJECT_FUNCTION:
3400  msg = gettext_noop("permission denied for function %s");
3401  break;
3402  case OBJECT_INDEX:
3403  msg = gettext_noop("permission denied for index %s");
3404  break;
3405  case OBJECT_LANGUAGE:
3406  msg = gettext_noop("permission denied for language %s");
3407  break;
3408  case OBJECT_LARGEOBJECT:
3409  msg = gettext_noop("permission denied for large object %s");
3410  break;
3411  case OBJECT_MATVIEW:
3412  msg = gettext_noop("permission denied for materialized view %s");
3413  break;
3414  case OBJECT_OPCLASS:
3415  msg = gettext_noop("permission denied for operator class %s");
3416  break;
3417  case OBJECT_OPERATOR:
3418  msg = gettext_noop("permission denied for operator %s");
3419  break;
3420  case OBJECT_OPFAMILY:
3421  msg = gettext_noop("permission denied for operator family %s");
3422  break;
3423  case OBJECT_POLICY:
3424  msg = gettext_noop("permission denied for policy %s");
3425  break;
3426  case OBJECT_PROCEDURE:
3427  msg = gettext_noop("permission denied for procedure %s");
3428  break;
3429  case OBJECT_PUBLICATION:
3430  msg = gettext_noop("permission denied for publication %s");
3431  break;
3432  case OBJECT_ROUTINE:
3433  msg = gettext_noop("permission denied for routine %s");
3434  break;
3435  case OBJECT_SCHEMA:
3436  msg = gettext_noop("permission denied for schema %s");
3437  break;
3438  case OBJECT_SEQUENCE:
3439  msg = gettext_noop("permission denied for sequence %s");
3440  break;
3441  case OBJECT_STATISTIC_EXT:
3442  msg = gettext_noop("permission denied for statistics object %s");
3443  break;
3444  case OBJECT_SUBSCRIPTION:
3445  msg = gettext_noop("permission denied for subscription %s");
3446  break;
3447  case OBJECT_TABLE:
3448  msg = gettext_noop("permission denied for table %s");
3449  break;
3450  case OBJECT_TABLESPACE:
3451  msg = gettext_noop("permission denied for tablespace %s");
3452  break;
3454  msg = gettext_noop("permission denied for text search configuration %s");
3455  break;
3456  case OBJECT_TSDICTIONARY:
3457  msg = gettext_noop("permission denied for text search dictionary %s");
3458  break;
3459  case OBJECT_TYPE:
3460  msg = gettext_noop("permission denied for type %s");
3461  break;
3462  case OBJECT_VIEW:
3463  msg = gettext_noop("permission denied for view %s");
3464  break;
3465  /* these currently aren't used */
3466  case OBJECT_ACCESS_METHOD:
3467  case OBJECT_AMOP:
3468  case OBJECT_AMPROC:
3469  case OBJECT_ATTRIBUTE:
3470  case OBJECT_CAST:
3471  case OBJECT_DEFAULT:
3472  case OBJECT_DEFACL:
3473  case OBJECT_DOMCONSTRAINT:
3475  case OBJECT_ROLE:
3476  case OBJECT_RULE:
3477  case OBJECT_TABCONSTRAINT:
3478  case OBJECT_TRANSFORM:
3479  case OBJECT_TRIGGER:
3480  case OBJECT_TSPARSER:
3481  case OBJECT_TSTEMPLATE:
3482  case OBJECT_USER_MAPPING:
3483  elog(ERROR, "unsupported object type %d", objtype);
3484  }
3485 
3486  ereport(ERROR,
3487  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3488  errmsg(msg, objectname)));
3489  break;
3490  }
3491  case ACLCHECK_NOT_OWNER:
3492  {
3493  const char *msg = "???";
3494 
3495  switch (objtype)
3496  {
3497  case OBJECT_AGGREGATE:
3498  msg = gettext_noop("must be owner of aggregate %s");
3499  break;
3500  case OBJECT_COLLATION:
3501  msg = gettext_noop("must be owner of collation %s");
3502  break;
3503  case OBJECT_CONVERSION:
3504  msg = gettext_noop("must be owner of conversion %s");
3505  break;
3506  case OBJECT_DATABASE:
3507  msg = gettext_noop("must be owner of database %s");
3508  break;
3509  case OBJECT_DOMAIN:
3510  msg = gettext_noop("must be owner of domain %s");
3511  break;
3512  case OBJECT_EVENT_TRIGGER:
3513  msg = gettext_noop("must be owner of event trigger %s");
3514  break;
3515  case OBJECT_EXTENSION:
3516  msg = gettext_noop("must be owner of extension %s");
3517  break;
3518  case OBJECT_FDW:
3519  msg = gettext_noop("must be owner of foreign-data wrapper %s");
3520  break;
3521  case OBJECT_FOREIGN_SERVER:
3522  msg = gettext_noop("must be owner of foreign server %s");
3523  break;
3524  case OBJECT_FOREIGN_TABLE:
3525  msg = gettext_noop("must be owner of foreign table %s");
3526  break;
3527  case OBJECT_FUNCTION:
3528  msg = gettext_noop("must be owner of function %s");
3529  break;
3530  case OBJECT_INDEX:
3531  msg = gettext_noop("must be owner of index %s");
3532  break;
3533  case OBJECT_LANGUAGE:
3534  msg = gettext_noop("must be owner of language %s");
3535  break;
3536  case OBJECT_LARGEOBJECT:
3537  msg = gettext_noop("must be owner of large object %s");
3538  break;
3539  case OBJECT_MATVIEW:
3540  msg = gettext_noop("must be owner of materialized view %s");
3541  break;
3542  case OBJECT_OPCLASS:
3543  msg = gettext_noop("must be owner of operator class %s");
3544  break;
3545  case OBJECT_OPERATOR:
3546  msg = gettext_noop("must be owner of operator %s");
3547  break;
3548  case OBJECT_OPFAMILY:
3549  msg = gettext_noop("must be owner of operator family %s");
3550  break;
3551  case OBJECT_PROCEDURE:
3552  msg = gettext_noop("must be owner of procedure %s");
3553  break;
3554  case OBJECT_PUBLICATION:
3555  msg = gettext_noop("must be owner of publication %s");
3556  break;
3557  case OBJECT_ROUTINE:
3558  msg = gettext_noop("must be owner of routine %s");
3559  break;
3560  case OBJECT_SEQUENCE:
3561  msg = gettext_noop("must be owner of sequence %s");
3562  break;
3563  case OBJECT_SUBSCRIPTION:
3564  msg = gettext_noop("must be owner of subscription %s");
3565  break;
3566  case OBJECT_TABLE:
3567  msg = gettext_noop("must be owner of table %s");
3568  break;
3569  case OBJECT_TYPE:
3570  msg = gettext_noop("must be owner of type %s");
3571  break;
3572  case OBJECT_VIEW:
3573  msg = gettext_noop("must be owner of view %s");
3574  break;
3575  case OBJECT_SCHEMA:
3576  msg = gettext_noop("must be owner of schema %s");
3577  break;
3578  case OBJECT_STATISTIC_EXT:
3579  msg = gettext_noop("must be owner of statistics object %s");
3580  break;
3581  case OBJECT_TABLESPACE:
3582  msg = gettext_noop("must be owner of tablespace %s");
3583  break;
3585  msg = gettext_noop("must be owner of text search configuration %s");
3586  break;
3587  case OBJECT_TSDICTIONARY:
3588  msg = gettext_noop("must be owner of text search dictionary %s");
3589  break;
3590  /*
3591  * Special cases: For these, the error message talks about
3592  * "relation", because that's where the ownership is
3593  * attached. See also check_object_ownership().
3594  */
3595  case OBJECT_COLUMN:
3596  case OBJECT_POLICY:
3597  case OBJECT_RULE:
3598  case OBJECT_TABCONSTRAINT:
3599  case OBJECT_TRIGGER:
3600  msg = gettext_noop("must be owner of relation %s");
3601  break;
3602  /* these currently aren't used */
3603  case OBJECT_ACCESS_METHOD:
3604  case OBJECT_AMOP:
3605  case OBJECT_AMPROC:
3606  case OBJECT_ATTRIBUTE:
3607  case OBJECT_CAST:
3608  case OBJECT_DEFAULT:
3609  case OBJECT_DEFACL:
3610  case OBJECT_DOMCONSTRAINT:
3612  case OBJECT_ROLE:
3613  case OBJECT_TRANSFORM:
3614  case OBJECT_TSPARSER:
3615  case OBJECT_TSTEMPLATE:
3616  case OBJECT_USER_MAPPING:
3617  elog(ERROR, "unsupported object type %d", objtype);
3618  }
3619 
3620  ereport(ERROR,
3621  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3622  errmsg(msg, objectname)));
3623  break;
3624  }
3625  default:
3626  elog(ERROR, "unrecognized AclResult: %d", (int) aclerr);
3627  break;
3628  }
3629 }
3630 
3631 
3632 void
3634  const char *objectname, const char *colname)
3635 {
3636  switch (aclerr)
3637  {
3638  case ACLCHECK_OK:
3639  /* no error, so return to caller */
3640  break;
3641  case ACLCHECK_NO_PRIV:
3642  ereport(ERROR,
3643  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3644  errmsg("permission denied for column \"%s\" of relation \"%s\"",
3645  colname, objectname)));
3646  break;
3647  case ACLCHECK_NOT_OWNER:
3648  /* relation msg is OK since columns don't have separate owners */
3649  aclcheck_error(aclerr, objtype, objectname);
3650  break;
3651  default:
3652  elog(ERROR, "unrecognized AclResult: %d", (int) aclerr);
3653  break;
3654  }
3655 }
3656 
3657 
3658 /*
3659  * Special common handling for types: use element type instead of array type,
3660  * and format nicely
3661  */
3662 void
3664 {
3665  Oid element_type = get_element_type(typeOid);
3666 
3667  aclcheck_error(aclerr, OBJECT_TYPE, format_type_be(element_type ? element_type : typeOid));
3668 }
3669 
3670 
3671 /*
3672  * Relay for the various pg_*_mask routines depending on object kind
3673  */
3674 static AclMode
3675 pg_aclmask(ObjectType objtype, Oid table_oid, AttrNumber attnum, Oid roleid,
3676  AclMode mask, AclMaskHow how)
3677 {
3678  switch (objtype)
3679  {
3680  case OBJECT_COLUMN:
3681  return
3682  pg_class_aclmask(table_oid, roleid, mask, how) |
3683  pg_attribute_aclmask(table_oid, attnum, roleid, mask, how);
3684  case OBJECT_TABLE:
3685  case OBJECT_SEQUENCE:
3686  return pg_class_aclmask(table_oid, roleid, mask, how);
3687  case OBJECT_DATABASE:
3688  return pg_database_aclmask(table_oid, roleid, mask, how);
3689  case OBJECT_FUNCTION:
3690  return pg_proc_aclmask(table_oid, roleid, mask, how);
3691  case OBJECT_LANGUAGE:
3692  return pg_language_aclmask(table_oid, roleid, mask, how);
3693  case OBJECT_LARGEOBJECT:
3694  return pg_largeobject_aclmask_snapshot(table_oid, roleid,
3695  mask, how, NULL);
3696  case OBJECT_SCHEMA:
3697  return pg_namespace_aclmask(table_oid, roleid, mask, how);
3698  case OBJECT_STATISTIC_EXT:
3699  elog(ERROR, "grantable rights not supported for statistics objects");
3700  /* not reached, but keep compiler quiet */
3701  return ACL_NO_RIGHTS;
3702  case OBJECT_TABLESPACE:
3703  return pg_tablespace_aclmask(table_oid, roleid, mask, how);
3704  case OBJECT_FDW:
3705  return pg_foreign_data_wrapper_aclmask(table_oid, roleid, mask, how);
3706  case OBJECT_FOREIGN_SERVER:
3707  return pg_foreign_server_aclmask(table_oid, roleid, mask, how);
3708  case OBJECT_EVENT_TRIGGER:
3709  elog(ERROR, "grantable rights not supported for event triggers");
3710  /* not reached, but keep compiler quiet */
3711  return ACL_NO_RIGHTS;
3712  case OBJECT_TYPE:
3713  return pg_type_aclmask(table_oid, roleid, mask, how);
3714  default:
3715  elog(ERROR, "unrecognized objtype: %d",
3716  (int) objtype);
3717  /* not reached, but keep compiler quiet */
3718  return ACL_NO_RIGHTS;
3719  }
3720 }
3721 
3722 
3723 /* ****************************************************************
3724  * Exported routines for examining a user's privileges for various objects
3725  *
3726  * See aclmask() for a description of the common API for these functions.
3727  *
3728  * Note: we give lookup failure the full ereport treatment because the
3729  * has_xxx_privilege() family of functions allow users to pass any random
3730  * OID to these functions.
3731  * ****************************************************************
3732  */
3733 
3734 /*
3735  * Exported routine for examining a user's privileges for a column
3736  *
3737  * Note: this considers only privileges granted specifically on the column.
3738  * It is caller's responsibility to take relation-level privileges into account
3739  * as appropriate. (For the same reason, we have no special case for
3740  * superuser-ness here.)
3741  */
3742 AclMode
3743 pg_attribute_aclmask(Oid table_oid, AttrNumber attnum, Oid roleid,
3744  AclMode mask, AclMaskHow how)
3745 {
3746  AclMode result;
3747  HeapTuple classTuple;
3748  HeapTuple attTuple;
3749  Form_pg_class classForm;
3750  Form_pg_attribute attributeForm;
3751  Datum aclDatum;
3752  bool isNull;
3753  Acl *acl;
3754  Oid ownerId;
3755 
3756  /*
3757  * First, get the column's ACL from its pg_attribute entry
3758  */
3759  attTuple = SearchSysCache2(ATTNUM,
3760  ObjectIdGetDatum(table_oid),
3761  Int16GetDatum(attnum));
3762  if (!HeapTupleIsValid(attTuple))
3763  ereport(ERROR,
3764  (errcode(ERRCODE_UNDEFINED_COLUMN),
3765  errmsg("attribute %d of relation with OID %u does not exist",
3766  attnum, table_oid)));
3767  attributeForm = (Form_pg_attribute) GETSTRUCT(attTuple);
3768 
3769  /* Throw error on dropped columns, too */
3770  if (attributeForm->attisdropped)
3771  ereport(ERROR,
3772  (errcode(ERRCODE_UNDEFINED_COLUMN),
3773  errmsg("attribute %d of relation with OID %u does not exist",
3774  attnum, table_oid)));
3775 
3776  aclDatum = SysCacheGetAttr(ATTNUM, attTuple, Anum_pg_attribute_attacl,
3777  &isNull);
3778 
3779  /*
3780  * Here we hard-wire knowledge that the default ACL for a column grants no
3781  * privileges, so that we can fall out quickly in the very common case
3782  * where attacl is null.
3783  */
3784  if (isNull)
3785  {
3786  ReleaseSysCache(attTuple);
3787  return 0;
3788  }
3789 
3790  /*
3791  * Must get the relation's ownerId from pg_class. Since we already found
3792  * a pg_attribute entry, the only likely reason for this to fail is that a
3793  * concurrent DROP of the relation committed since then (which could only
3794  * happen if we don't have lock on the relation). We prefer to report "no
3795  * privileges" rather than failing in such a case, so as to avoid unwanted
3796  * failures in has_column_privilege() tests.
3797  */
3798  classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3799  if (!HeapTupleIsValid(classTuple))
3800  {
3801  ReleaseSysCache(attTuple);
3802  return 0;
3803  }
3804  classForm = (Form_pg_class) GETSTRUCT(classTuple);
3805 
3806  ownerId = classForm->relowner;
3807 
3808  ReleaseSysCache(classTuple);
3809 
3810  /* detoast column's ACL if necessary */
3811  acl = DatumGetAclP(aclDatum);
3812 
3813  result = aclmask(acl, roleid, ownerId, mask, how);
3814 
3815  /* if we have a detoasted copy, free it */
3816  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3817  pfree(acl);
3818 
3819  ReleaseSysCache(attTuple);
3820 
3821  return result;
3822 }
3823 
3824 /*
3825  * Exported routine for examining a user's privileges for a table
3826  */
3827 AclMode
3828 pg_class_aclmask(Oid table_oid, Oid roleid,
3829  AclMode mask, AclMaskHow how)
3830 {
3831  AclMode result;
3832  HeapTuple tuple;
3833  Form_pg_class classForm;
3834  Datum aclDatum;
3835  bool isNull;
3836  Acl *acl;
3837  Oid ownerId;
3838 
3839  /*
3840  * Must get the relation's tuple from pg_class
3841  */
3842  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3843  if (!HeapTupleIsValid(tuple))
3844  ereport(ERROR,
3846  errmsg("relation with OID %u does not exist",
3847  table_oid)));
3848  classForm = (Form_pg_class) GETSTRUCT(tuple);
3849 
3850  /*
3851  * Deny anyone permission to update a system catalog unless
3852  * pg_authid.rolsuper is set. Also allow it if allowSystemTableMods.
3853  *
3854  * As of 7.4 we have some updatable system views; those shouldn't be
3855  * protected in this way. Assume the view rules can take care of
3856  * themselves. ACL_USAGE is if we ever have system sequences.
3857  */
3858  if ((mask & (ACL_INSERT | ACL_UPDATE | ACL_DELETE | ACL_TRUNCATE | ACL_USAGE)) &&
3859  IsSystemClass(table_oid, classForm) &&
3860  classForm->relkind != RELKIND_VIEW &&
3861  !superuser_arg(roleid) &&
3863  {
3864 #ifdef ACLDEBUG
3865  elog(DEBUG2, "permission denied for system catalog update");
3866 #endif
3868  }
3869 
3870  /*
3871  * Otherwise, superusers bypass all permission-checking.
3872  */
3873  if (superuser_arg(roleid))
3874  {
3875 #ifdef ACLDEBUG
3876  elog(DEBUG2, "OID %u is superuser, home free", roleid);
3877 #endif
3878  ReleaseSysCache(tuple);
3879  return mask;
3880  }
3881 
3882  /*
3883  * Normal case: get the relation's ACL from pg_class
3884  */
3885  ownerId = classForm->relowner;
3886 
3887  aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
3888  &isNull);
3889  if (isNull)
3890  {
3891  /* No ACL, so build default ACL */
3892  switch (classForm->relkind)
3893  {
3894  case RELKIND_SEQUENCE:
3895  acl = acldefault(OBJECT_SEQUENCE, ownerId);
3896  break;
3897  default:
3898  acl = acldefault(OBJECT_TABLE, ownerId);
3899  break;
3900  }
3901  aclDatum = (Datum) 0;
3902  }
3903  else
3904  {
3905  /* detoast rel's ACL if necessary */
3906  acl = DatumGetAclP(aclDatum);
3907  }
3908 
3909  result = aclmask(acl, roleid, ownerId, mask, how);
3910 
3911  /* if we have a detoasted copy, free it */
3912  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3913  pfree(acl);
3914 
3915  ReleaseSysCache(tuple);
3916 
3917  return result;
3918 }
3919 
3920 /*
3921  * Exported routine for examining a user's privileges for a database
3922  */
3923 AclMode
3924 pg_database_aclmask(Oid db_oid, Oid roleid,
3925  AclMode mask, AclMaskHow how)
3926 {
3927  AclMode result;
3928  HeapTuple tuple;
3929  Datum aclDatum;
3930  bool isNull;
3931  Acl *acl;
3932  Oid ownerId;
3933 
3934  /* Superusers bypass all permission checking. */
3935  if (superuser_arg(roleid))
3936  return mask;
3937 
3938  /*
3939  * Get the database's ACL from pg_database
3940  */
3941  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(db_oid));
3942  if (!HeapTupleIsValid(tuple))
3943  ereport(ERROR,
3944  (errcode(ERRCODE_UNDEFINED_DATABASE),
3945  errmsg("database with OID %u does not exist", db_oid)));
3946 
3947  ownerId = ((Form_pg_database) GETSTRUCT(tuple))->datdba;
3948 
3950  &isNull);
3951  if (isNull)
3952  {
3953  /* No ACL, so build default ACL */
3954  acl = acldefault(OBJECT_DATABASE, ownerId);
3955  aclDatum = (Datum) 0;
3956  }
3957  else
3958  {
3959  /* detoast ACL if necessary */
3960  acl = DatumGetAclP(aclDatum);
3961  }
3962 
3963  result = aclmask(acl, roleid, ownerId, mask, how);
3964 
3965  /* if we have a detoasted copy, free it */
3966  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3967  pfree(acl);
3968 
3969  ReleaseSysCache(tuple);
3970 
3971  return result;
3972 }
3973 
3974 /*
3975  * Exported routine for examining a user's privileges for a function
3976  */
3977 AclMode
3978 pg_proc_aclmask(Oid proc_oid, Oid roleid,
3979  AclMode mask, AclMaskHow how)
3980 {
3981  AclMode result;
3982  HeapTuple tuple;
3983  Datum aclDatum;
3984  bool isNull;
3985  Acl *acl;
3986  Oid ownerId;
3987 
3988  /* Superusers bypass all permission checking. */
3989  if (superuser_arg(roleid))
3990  return mask;
3991 
3992  /*
3993  * Get the function's ACL from pg_proc
3994  */
3995  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(proc_oid));
3996  if (!HeapTupleIsValid(tuple))
3997  ereport(ERROR,
3998  (errcode(ERRCODE_UNDEFINED_FUNCTION),
3999  errmsg("function with OID %u does not exist", proc_oid)));
4000 
4001  ownerId = ((Form_pg_proc) GETSTRUCT(tuple))->proowner;
4002 
4003  aclDatum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proacl,
4004  &isNull);
4005  if (isNull)
4006  {
4007  /* No ACL, so build default ACL */
4008  acl = acldefault(OBJECT_FUNCTION, ownerId);
4009  aclDatum = (Datum) 0;
4010  }
4011  else
4012  {
4013  /* detoast ACL if necessary */
4014  acl = DatumGetAclP(aclDatum);
4015  }
4016 
4017  result = aclmask(acl, roleid, ownerId, mask, how);
4018 
4019  /* if we have a detoasted copy, free it */
4020  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4021  pfree(acl);
4022 
4023  ReleaseSysCache(tuple);
4024 
4025  return result;
4026 }
4027 
4028 /*
4029  * Exported routine for examining a user's privileges for a language
4030  */
4031 AclMode
4032 pg_language_aclmask(Oid lang_oid, Oid roleid,
4033  AclMode mask, AclMaskHow how)
4034 {
4035  AclMode result;
4036  HeapTuple tuple;
4037  Datum aclDatum;
4038  bool isNull;
4039  Acl *acl;
4040  Oid ownerId;
4041 
4042  /* Superusers bypass all permission checking. */
4043  if (superuser_arg(roleid))
4044  return mask;
4045 
4046  /*
4047  * Get the language's ACL from pg_language
4048  */
4049  tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(lang_oid));
4050  if (!HeapTupleIsValid(tuple))
4051  ereport(ERROR,
4052  (errcode(ERRCODE_UNDEFINED_OBJECT),
4053  errmsg("language with OID %u does not exist", lang_oid)));
4054 
4055  ownerId = ((Form_pg_language) GETSTRUCT(tuple))->lanowner;
4056 
4057  aclDatum = SysCacheGetAttr(LANGOID, tuple, Anum_pg_language_lanacl,
4058  &isNull);
4059  if (isNull)
4060  {
4061  /* No ACL, so build default ACL */
4062  acl = acldefault(OBJECT_LANGUAGE, ownerId);
4063  aclDatum = (Datum) 0;
4064  }
4065  else
4066  {
4067  /* detoast ACL if necessary */
4068  acl = DatumGetAclP(aclDatum);
4069  }
4070 
4071  result = aclmask(acl, roleid, ownerId, mask, how);
4072 
4073  /* if we have a detoasted copy, free it */
4074  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4075  pfree(acl);
4076 
4077  ReleaseSysCache(tuple);
4078 
4079  return result;
4080 }
4081 
4082 /*
4083  * Exported routine for examining a user's privileges for a largeobject
4084  *
4085  * When a large object is opened for reading, it is opened relative to the
4086  * caller's snapshot, but when it is opened for writing, a current
4087  * MVCC snapshot will be used. See doc/src/sgml/lobj.sgml. This function
4088  * takes a snapshot argument so that the permissions check can be made
4089  * relative to the same snapshot that will be used to read the underlying
4090  * data. The caller will actually pass NULL for an instantaneous MVCC
4091  * snapshot, since all we do with the snapshot argument is pass it through
4092  * to systable_beginscan().
4093  */
4094 AclMode
4096  AclMode mask, AclMaskHow how,
4097  Snapshot snapshot)
4098 {
4099  AclMode result;
4100  Relation pg_lo_meta;
4101  ScanKeyData entry[1];
4102  SysScanDesc scan;
4103  HeapTuple tuple;
4104  Datum aclDatum;
4105  bool isNull;
4106  Acl *acl;
4107  Oid ownerId;
4108 
4109  /* Superusers bypass all permission checking. */
4110  if (superuser_arg(roleid))
4111  return mask;
4112 
4113  /*
4114  * Get the largeobject's ACL from pg_language_metadata
4115  */
4117  AccessShareLock);
4118 
4119  ScanKeyInit(&entry[0],
4121  BTEqualStrategyNumber, F_OIDEQ,
4122  ObjectIdGetDatum(lobj_oid));
4123 
4124  scan = systable_beginscan(pg_lo_meta,
4126  snapshot, 1, entry);
4127 
4128  tuple = systable_getnext(scan);
4129  if (!HeapTupleIsValid(tuple))
4130  ereport(ERROR,
4131  (errcode(ERRCODE_UNDEFINED_OBJECT),
4132  errmsg("large object %u does not exist", lobj_oid)));
4133 
4134  ownerId = ((Form_pg_largeobject_metadata) GETSTRUCT(tuple))->lomowner;
4135 
4137  RelationGetDescr(pg_lo_meta), &isNull);
4138 
4139  if (isNull)
4140  {
4141  /* No ACL, so build default ACL */
4142  acl = acldefault(OBJECT_LARGEOBJECT, ownerId);
4143  aclDatum = (Datum) 0;
4144  }
4145  else
4146  {
4147  /* detoast ACL if necessary */
4148  acl = DatumGetAclP(aclDatum);
4149  }
4150 
4151  result = aclmask(acl, roleid, ownerId, mask, how);
4152 
4153  /* if we have a detoasted copy, free it */
4154  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4155  pfree(acl);
4156 
4157  systable_endscan(scan);
4158 
4159  heap_close(pg_lo_meta, AccessShareLock);
4160 
4161  return result;
4162 }
4163 
4164 /*
4165  * Exported routine for examining a user's privileges for a namespace
4166  */
4167 AclMode
4168 pg_namespace_aclmask(Oid nsp_oid, Oid roleid,
4169  AclMode mask, AclMaskHow how)
4170 {
4171  AclMode result;
4172  HeapTuple tuple;
4173  Datum aclDatum;
4174  bool isNull;
4175  Acl *acl;
4176  Oid ownerId;
4177 
4178  /* Superusers bypass all permission checking. */
4179  if (superuser_arg(roleid))
4180  return mask;
4181 
4182  /*
4183  * If we have been assigned this namespace as a temp namespace, check to
4184  * make sure we have CREATE TEMP permission on the database, and if so act
4185  * as though we have all standard (but not GRANT OPTION) permissions on
4186  * the namespace. If we don't have CREATE TEMP, act as though we have
4187  * only USAGE (and not CREATE) rights.
4188  *
4189  * This may seem redundant given the check in InitTempTableNamespace, but
4190  * it really isn't since current user ID may have changed since then. The
4191  * upshot of this behavior is that a SECURITY DEFINER function can create
4192  * temp tables that can then be accessed (if permission is granted) by
4193  * code in the same session that doesn't have permissions to create temp
4194  * tables.
4195  *
4196  * XXX Would it be safe to ereport a special error message as
4197  * InitTempTableNamespace does? Returning zero here means we'll get a
4198  * generic "permission denied for schema pg_temp_N" message, which is not
4199  * remarkably user-friendly.
4200  */
4201  if (isTempNamespace(nsp_oid))
4202  {
4203  if (pg_database_aclcheck(MyDatabaseId, roleid,
4205  return mask & ACL_ALL_RIGHTS_SCHEMA;
4206  else
4207  return mask & ACL_USAGE;
4208  }
4209 
4210  /*
4211  * Get the schema's ACL from pg_namespace
4212  */
4213  tuple = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nsp_oid));
4214  if (!HeapTupleIsValid(tuple))
4215  ereport(ERROR,
4216  (errcode(ERRCODE_UNDEFINED_SCHEMA),
4217  errmsg("schema with OID %u does not exist", nsp_oid)));
4218 
4219  ownerId = ((Form_pg_namespace) GETSTRUCT(tuple))->nspowner;
4220 
4222  &isNull);
4223  if (isNull)
4224  {
4225  /* No ACL, so build default ACL */
4226  acl = acldefault(OBJECT_SCHEMA, ownerId);
4227  aclDatum = (Datum) 0;
4228  }
4229  else
4230  {
4231  /* detoast ACL if necessary */
4232  acl = DatumGetAclP(aclDatum);
4233  }
4234 
4235  result = aclmask(acl, roleid, ownerId, mask, how);
4236 
4237  /* if we have a detoasted copy, free it */
4238  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4239  pfree(acl);
4240 
4241  ReleaseSysCache(tuple);
4242 
4243  return result;
4244 }
4245 
4246 /*
4247  * Exported routine for examining a user's privileges for a tablespace
4248  */
4249 AclMode
4251  AclMode mask, AclMaskHow how)
4252 {
4253  AclMode result;
4254  HeapTuple tuple;
4255  Datum aclDatum;
4256  bool isNull;
4257  Acl *acl;
4258  Oid ownerId;
4259 
4260  /* Superusers bypass all permission checking. */
4261  if (superuser_arg(roleid))
4262  return mask;
4263 
4264  /*
4265  * Get the tablespace's ACL from pg_tablespace
4266  */
4267  tuple = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(spc_oid));
4268  if (!HeapTupleIsValid(tuple))
4269  ereport(ERROR,
4270  (errcode(ERRCODE_UNDEFINED_OBJECT),
4271  errmsg("tablespace with OID %u does not exist", spc_oid)));
4272 
4273  ownerId = ((Form_pg_tablespace) GETSTRUCT(tuple))->spcowner;
4274 
4275  aclDatum = SysCacheGetAttr(TABLESPACEOID, tuple,
4277  &isNull);
4278 
4279  if (isNull)
4280  {
4281  /* No ACL, so build default ACL */
4282  acl = acldefault(OBJECT_TABLESPACE, ownerId);
4283  aclDatum = (Datum) 0;
4284  }
4285  else
4286  {
4287  /* detoast ACL if necessary */
4288  acl = DatumGetAclP(aclDatum);
4289  }
4290 
4291  result = aclmask(acl, roleid, ownerId, mask, how);
4292 
4293  /* if we have a detoasted copy, free it */
4294  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4295  pfree(acl);
4296 
4297  ReleaseSysCache(tuple);
4298 
4299  return result;
4300 }
4301 
4302 /*
4303  * Exported routine for examining a user's privileges for a foreign
4304  * data wrapper
4305  */
4306 AclMode
4308  AclMode mask, AclMaskHow how)
4309 {
4310  AclMode result;
4311  HeapTuple tuple;
4312  Datum aclDatum;
4313  bool isNull;
4314  Acl *acl;
4315  Oid ownerId;
4316 
4318 
4319  /* Bypass permission checks for superusers */
4320  if (superuser_arg(roleid))
4321  return mask;
4322 
4323  /*
4324  * Must get the FDW's tuple from pg_foreign_data_wrapper
4325  */
4327  if (!HeapTupleIsValid(tuple))
4328  ereport(ERROR,
4329  (errcode(ERRCODE_UNDEFINED_OBJECT),
4330  errmsg("foreign-data wrapper with OID %u does not exist",
4331  fdw_oid)));
4332  fdwForm = (Form_pg_foreign_data_wrapper) GETSTRUCT(tuple);
4333 
4334  /*
4335  * Normal case: get the FDW's ACL from pg_foreign_data_wrapper
4336  */
4337  ownerId = fdwForm->fdwowner;
4338 
4339  aclDatum = SysCacheGetAttr(FOREIGNDATAWRAPPEROID, tuple,
4341  if (isNull)
4342  {
4343  /* No ACL, so build default ACL */
4344  acl = acldefault(OBJECT_FDW, ownerId);
4345  aclDatum = (Datum) 0;
4346  }
4347  else
4348  {
4349  /* detoast rel's ACL if necessary */
4350  acl = DatumGetAclP(aclDatum);
4351  }
4352 
4353  result = aclmask(acl, roleid, ownerId, mask, how);
4354 
4355  /* if we have a detoasted copy, free it */
4356  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4357  pfree(acl);
4358 
4359  ReleaseSysCache(tuple);
4360 
4361  return result;
4362 }
4363 
4364 /*
4365  * Exported routine for examining a user's privileges for a foreign
4366  * server.
4367  */
4368 AclMode
4370  AclMode mask, AclMaskHow how)
4371 {
4372  AclMode result;
4373  HeapTuple tuple;
4374  Datum aclDatum;
4375  bool isNull;
4376  Acl *acl;
4377  Oid ownerId;
4378 
4379  Form_pg_foreign_server srvForm;
4380 
4381  /* Bypass permission checks for superusers */
4382  if (superuser_arg(roleid))
4383  return mask;
4384 
4385  /*
4386  * Must get the FDW's tuple from pg_foreign_data_wrapper
4387  */
4389  if (!HeapTupleIsValid(tuple))
4390  ereport(ERROR,
4391  (errcode(ERRCODE_UNDEFINED_OBJECT),
4392  errmsg("foreign server with OID %u does not exist",
4393  srv_oid)));
4394  srvForm = (Form_pg_foreign_server) GETSTRUCT(tuple);
4395 
4396  /*
4397  * Normal case: get the foreign server's ACL from pg_foreign_server
4398  */
4399  ownerId = srvForm->srvowner;
4400 
4401  aclDatum = SysCacheGetAttr(FOREIGNSERVEROID, tuple,
4403  if (isNull)
4404  {
4405  /* No ACL, so build default ACL */
4406  acl = acldefault(OBJECT_FOREIGN_SERVER, ownerId);
4407  aclDatum = (Datum) 0;
4408  }
4409  else
4410  {
4411  /* detoast rel's ACL if necessary */
4412  acl = DatumGetAclP(aclDatum);
4413  }
4414 
4415  result = aclmask(acl, roleid, ownerId, mask, how);
4416 
4417  /* if we have a detoasted copy, free it */
4418  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4419  pfree(acl);
4420 
4421  ReleaseSysCache(tuple);
4422 
4423  return result;
4424 }
4425 
4426 /*
4427  * Exported routine for examining a user's privileges for a type.
4428  */
4429 AclMode
4430 pg_type_aclmask(Oid type_oid, Oid roleid, AclMode mask, AclMaskHow how)
4431 {
4432  AclMode result;
4433  HeapTuple tuple;
4434  Datum aclDatum;
4435  bool isNull;
4436  Acl *acl;
4437  Oid ownerId;
4438 
4439  Form_pg_type typeForm;
4440 
4441  /* Bypass permission checks for superusers */
4442  if (superuser_arg(roleid))
4443  return mask;
4444 
4445  /*
4446  * Must get the type's tuple from pg_type
4447  */
4448  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
4449  if (!HeapTupleIsValid(tuple))
4450  ereport(ERROR,
4451  (errcode(ERRCODE_UNDEFINED_OBJECT),
4452  errmsg("type with OID %u does not exist",
4453  type_oid)));
4454  typeForm = (Form_pg_type) GETSTRUCT(tuple);
4455 
4456  /*
4457  * "True" array types don't manage permissions of their own; consult the
4458  * element type instead.
4459  */
4460  if (OidIsValid(typeForm->typelem) && typeForm->typlen == -1)
4461  {
4462  Oid elttype_oid = typeForm->typelem;
4463 
4464  ReleaseSysCache(tuple);
4465 
4466  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(elttype_oid));
4467  /* this case is not a user-facing error, so elog not ereport */
4468  if (!HeapTupleIsValid(tuple))
4469  elog(ERROR, "cache lookup failed for type %u", elttype_oid);
4470  typeForm = (Form_pg_type) GETSTRUCT(tuple);
4471  }
4472 
4473  /*
4474  * Now get the type's owner and ACL from the tuple
4475  */
4476  ownerId = typeForm->typowner;
4477 
4478  aclDatum = SysCacheGetAttr(TYPEOID, tuple,
4479  Anum_pg_type_typacl, &isNull);
4480  if (isNull)
4481  {
4482  /* No ACL, so build default ACL */
4483  acl = acldefault(OBJECT_TYPE, ownerId);
4484  aclDatum = (Datum) 0;
4485  }
4486  else
4487  {
4488  /* detoast rel's ACL if necessary */
4489  acl = DatumGetAclP(aclDatum);
4490  }
4491 
4492  result = aclmask(acl, roleid, ownerId, mask, how);
4493 
4494  /* if we have a detoasted copy, free it */
4495  if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
4496  pfree(acl);
4497 
4498  ReleaseSysCache(tuple);
4499 
4500  return result;
4501 }
4502 
4503 /*
4504  * Exported routine for checking a user's access privileges to a column
4505  *
4506  * Returns ACLCHECK_OK if the user has any of the privileges identified by
4507  * 'mode'; otherwise returns a suitable error code (in practice, always
4508  * ACLCHECK_NO_PRIV).
4509  *
4510  * As with pg_attribute_aclmask, only privileges granted directly on the
4511  * column are considered here.
4512  */
4513 AclResult
4515  Oid roleid, AclMode mode)
4516 {
4517  if (pg_attribute_aclmask(table_oid, attnum, roleid, mode, ACLMASK_ANY) != 0)
4518  return ACLCHECK_OK;
4519  else
4520  return ACLCHECK_NO_PRIV;
4521 }
4522 
4523 /*
4524  * Exported routine for checking a user's access privileges to any/all columns
4525  *
4526  * If 'how' is ACLMASK_ANY, then returns ACLCHECK_OK if user has any of the
4527  * privileges identified by 'mode' on any non-dropped column in the relation;
4528  * otherwise returns a suitable error code (in practice, always
4529  * ACLCHECK_NO_PRIV).
4530  *
4531  * If 'how' is ACLMASK_ALL, then returns ACLCHECK_OK if user has any of the
4532  * privileges identified by 'mode' on each non-dropped column in the relation
4533  * (and there must be at least one such column); otherwise returns a suitable
4534  * error code (in practice, always ACLCHECK_NO_PRIV).
4535  *
4536  * As with pg_attribute_aclmask, only privileges granted directly on the
4537  * column(s) are considered here.
4538  *
4539  * Note: system columns are not considered here; there are cases where that
4540  * might be appropriate but there are also cases where it wouldn't.
4541  */
4542 AclResult
4543 pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode,
4544  AclMaskHow how)
4545 {
4546  AclResult result;
4547  HeapTuple classTuple;
4548  Form_pg_class classForm;
4549  AttrNumber nattrs;
4550  AttrNumber curr_att;
4551 
4552  /*
4553  * Must fetch pg_class row to check number of attributes. As in
4554  * pg_attribute_aclmask, we prefer to return "no privileges" instead of
4555  * throwing an error if we get any unexpected lookup errors.
4556  */
4557  classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
4558  if (!HeapTupleIsValid(classTuple))
4559  return ACLCHECK_NO_PRIV;
4560  classForm = (Form_pg_class) GETSTRUCT(classTuple);
4561 
4562  nattrs = classForm->relnatts;
4563 
4564  ReleaseSysCache(classTuple);
4565 
4566  /*
4567  * Initialize result in case there are no non-dropped columns. We want to
4568  * report failure in such cases for either value of 'how'.
4569  */
4570  result = ACLCHECK_NO_PRIV;
4571 
4572  for (curr_att = 1; curr_att <= nattrs; curr_att++)
4573  {
4574  HeapTuple attTuple;
4575  AclMode attmask;
4576 
4577  attTuple = SearchSysCache2(ATTNUM,
4578  ObjectIdGetDatum(table_oid),
4579  Int16GetDatum(curr_att));
4580  if (!HeapTupleIsValid(attTuple))
4581  continue;
4582 
4583  /* ignore dropped columns */
4584  if (((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped)
4585  {
4586  ReleaseSysCache(attTuple);
4587  continue;
4588  }
4589 
4590  /*
4591  * Here we hard-wire knowledge that the default ACL for a column
4592  * grants no privileges, so that we can fall out quickly in the very
4593  * common case where attacl is null.
4594  */
4596  attmask = 0;
4597  else
4598  attmask = pg_attribute_aclmask(table_oid, curr_att, roleid,
4599  mode, ACLMASK_ANY);
4600 
4601  ReleaseSysCache(attTuple);
4602 
4603  if (attmask != 0)
4604  {
4605  result = ACLCHECK_OK;
4606  if (how == ACLMASK_ANY)
4607  break; /* succeed on any success */
4608  }
4609  else
4610  {
4611  result = ACLCHECK_NO_PRIV;
4612  if (how == ACLMASK_ALL)
4613  break; /* fail on any failure */
4614  }
4615  }
4616 
4617  return result;
4618 }
4619 
4620 /*
4621  * Exported routine for checking a user's access privileges to a table
4622  *
4623  * Returns ACLCHECK_OK if the user has any of the privileges identified by
4624  * 'mode'; otherwise returns a suitable error code (in practice, always
4625  * ACLCHECK_NO_PRIV).
4626  */
4627 AclResult
4628 pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
4629 {
4630  if (pg_class_aclmask(table_oid, roleid, mode, ACLMASK_ANY) != 0)
4631  return ACLCHECK_OK;
4632  else
4633  return ACLCHECK_NO_PRIV;
4634 }
4635 
4636 /*
4637  * Exported routine for checking a user's access privileges to a database
4638  */
4639 AclResult
4640 pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
4641 {
4642  if (pg_database_aclmask(db_oid, roleid, mode, ACLMASK_ANY) != 0)
4643  return ACLCHECK_OK;
4644  else
4645  return ACLCHECK_NO_PRIV;
4646 }
4647 
4648 /*
4649  * Exported routine for checking a user's access privileges to a function
4650  */
4651 AclResult
4652 pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
4653 {
4654  if (pg_proc_aclmask(proc_oid, roleid, mode, ACLMASK_ANY) != 0)
4655  return ACLCHECK_OK;
4656  else
4657  return ACLCHECK_NO_PRIV;
4658 }
4659 
4660 /*
4661  * Exported routine for checking a user's access privileges to a language
4662  */
4663 AclResult
4664 pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
4665 {
4666  if (pg_language_aclmask(lang_oid, roleid, mode, ACLMASK_ANY) != 0)
4667  return ACLCHECK_OK;
4668  else
4669  return ACLCHECK_NO_PRIV;
4670 }
4671 
4672 /*
4673  * Exported routine for checking a user's access privileges to a largeobject
4674  */
4675 AclResult
4677  Snapshot snapshot)
4678 {
4679  if (pg_largeobject_aclmask_snapshot(lobj_oid, roleid, mode,
4680  ACLMASK_ANY, snapshot) != 0)
4681  return ACLCHECK_OK;
4682  else
4683  return ACLCHECK_NO_PRIV;
4684 }
4685 
4686 /*
4687  * Exported routine for checking a user's access privileges to a namespace
4688  */
4689 AclResult
4690 pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
4691 {
4692  if (pg_namespace_aclmask(nsp_oid, roleid, mode, ACLMASK_ANY) != 0)
4693  return ACLCHECK_OK;
4694  else
4695  return ACLCHECK_NO_PRIV;
4696 }
4697 
4698 /*
4699  * Exported routine for checking a user's access privileges to a tablespace
4700  */
4701 AclResult
4702 pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
4703 {
4704  if (pg_tablespace_aclmask(spc_oid, roleid, mode, ACLMASK_ANY) != 0)
4705  return ACLCHECK_OK;
4706  else
4707  return ACLCHECK_NO_PRIV;
4708 }
4709 
4710 /*
4711  * Exported routine for checking a user's access privileges to a foreign
4712  * data wrapper
4713  */
4714 AclResult
4716 {
4717  if (pg_foreign_data_wrapper_aclmask(fdw_oid, roleid, mode, ACLMASK_ANY) != 0)
4718  return ACLCHECK_OK;
4719  else
4720  return ACLCHECK_NO_PRIV;
4721 }
4722 
4723 /*
4724  * Exported routine for checking a user's access privileges to a foreign
4725  * server
4726  */
4727 AclResult
4729 {
4730  if (pg_foreign_server_aclmask(srv_oid, roleid, mode, ACLMASK_ANY) != 0)
4731  return ACLCHECK_OK;
4732  else
4733  return ACLCHECK_NO_PRIV;
4734 }
4735 
4736 /*
4737  * Exported routine for checking a user's access privileges to a type
4738  */
4739 AclResult
4740 pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
4741 {
4742  if (pg_type_aclmask(type_oid, roleid, mode, ACLMASK_ANY) != 0)
4743  return ACLCHECK_OK;
4744  else
4745  return ACLCHECK_NO_PRIV;
4746 }
4747 
4748 /*
4749  * Ownership check for a relation (specified by OID).
4750  */
4751 bool
4752 pg_class_ownercheck(Oid class_oid, Oid roleid)
4753 {
4754  HeapTuple tuple;
4755  Oid ownerId;
4756 
4757  /* Superusers bypass all permission checking. */
4758  if (superuser_arg(roleid))
4759  return true;
4760 
4761  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(class_oid));
4762  if (!HeapTupleIsValid(tuple))
4763  ereport(ERROR,
4765  errmsg("relation with OID %u does not exist", class_oid)));
4766 
4767  ownerId = ((Form_pg_class) GETSTRUCT(tuple))->relowner;
4768 
4769  ReleaseSysCache(tuple);
4770 
4771  return has_privs_of_role(roleid, ownerId);
4772 }
4773 
4774 /*
4775  * Ownership check for a type (specified by OID).
4776  */
4777 bool
4778 pg_type_ownercheck(Oid type_oid, Oid roleid)
4779 {
4780  HeapTuple tuple;
4781  Oid ownerId;
4782 
4783  /* Superusers bypass all permission checking. */
4784  if (superuser_arg(roleid))
4785  return true;
4786 
4787  tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
4788  if (!HeapTupleIsValid(tuple))
4789  ereport(ERROR,
4790  (errcode(ERRCODE_UNDEFINED_OBJECT),
4791  errmsg("type with OID %u does not exist", type_oid)));
4792 
4793  ownerId = ((Form_pg_type) GETSTRUCT(tuple))->typowner;
4794 
4795  ReleaseSysCache(tuple);
4796 
4797  return has_privs_of_role(roleid, ownerId);
4798 }
4799 
4800 /*
4801  * Ownership check for an operator (specified by OID).
4802  */
4803 bool
4804 pg_oper_ownercheck(Oid oper_oid, Oid roleid)
4805 {
4806  HeapTuple tuple;
4807  Oid ownerId;
4808 
4809  /* Superusers bypass all permission checking. */
4810  if (superuser_arg(roleid))
4811  return true;
4812 
4813  tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(oper_oid));
4814  if (!HeapTupleIsValid(tuple))
4815  ereport(ERROR,
4816  (errcode(ERRCODE_UNDEFINED_FUNCTION),
4817  errmsg("operator with OID %u does not exist", oper_oid)));
4818 
4819  ownerId = ((Form_pg_operator) GETSTRUCT(tuple))->oprowner;
4820 
4821  ReleaseSysCache(tuple);
4822 
4823  return has_privs_of_role(roleid, ownerId);
4824 }
4825 
4826 /*
4827  * Ownership check for a function (specified by OID).
4828  */
4829 bool
4830 pg_proc_ownercheck(Oid proc_oid, Oid roleid)
4831 {
4832  HeapTuple tuple;
4833  Oid ownerId;
4834 
4835  /* Superusers bypass all permission checking. */
4836  if (superuser_arg(roleid))
4837  return true;
4838 
4839  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(proc_oid));
4840  if (!HeapTupleIsValid(tuple))
4841  ereport(ERROR,
4842  (errcode(ERRCODE_UNDEFINED_FUNCTION),
4843  errmsg("function with OID %u does not exist", proc_oid)));
4844 
4845  ownerId = ((Form_pg_proc) GETSTRUCT(tuple))->proowner;
4846 
4847  ReleaseSysCache(tuple);
4848 
4849  return has_privs_of_role(roleid, ownerId);
4850 }
4851 
4852 /*
4853  * Ownership check for a procedural language (specified by OID)
4854  */
4855 bool
4857 {
4858  HeapTuple tuple;
4859  Oid ownerId;
4860 
4861  /* Superusers bypass all permission checking. */
4862  if (superuser_arg(roleid))
4863  return true;
4864 
4865  tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(lan_oid));
4866  if (!HeapTupleIsValid(tuple))
4867  ereport(ERROR,
4868  (errcode(ERRCODE_UNDEFINED_FUNCTION),
4869  errmsg("language with OID %u does not exist", lan_oid)));
4870 
4871  ownerId = ((Form_pg_language) GETSTRUCT(tuple))->lanowner;
4872 
4873  ReleaseSysCache(tuple);
4874 
4875  return has_privs_of_role(roleid, ownerId);
4876 }
4877 
4878 /*
4879  * Ownership check for a largeobject (specified by OID)
4880  *
4881  * This is only used for operations like ALTER LARGE OBJECT that are always
4882  * relative to an up-to-date snapshot.
4883  */
4884 bool
4886 {
4887  Relation pg_lo_meta;
4888  ScanKeyData entry[1];
4889  SysScanDesc scan;
4890  HeapTuple tuple;
4891  Oid ownerId;
4892 
4893  /* Superusers bypass all permission checking. */
4894  if (superuser_arg(roleid))
4895  return true;
4896 
4897  /* There's no syscache for pg_largeobject_metadata */
4899  AccessShareLock);
4900 
4901  ScanKeyInit(&entry[0],
4903  BTEqualStrategyNumber, F_OIDEQ,
4904  ObjectIdGetDatum(lobj_oid));
4905 
4906  scan = systable_beginscan(pg_lo_meta,
4908  NULL, 1, entry);
4909 
4910  tuple = systable_getnext(scan);
4911  if (!HeapTupleIsValid(tuple))
4912  ereport(ERROR,
4913  (errcode(ERRCODE_UNDEFINED_OBJECT),
4914  errmsg("large object %u does not exist", lobj_oid)));
4915 
4916  ownerId = ((Form_pg_largeobject_metadata) GETSTRUCT(tuple))->lomowner;
4917 
4918  systable_endscan(scan);
4919  heap_close(pg_lo_meta, AccessShareLock);
4920 
4921  return has_privs_of_role(roleid, ownerId);
4922 }
4923 
4924 /*
4925  * Ownership check for a namespace (specified by OID).
4926  */
4927 bool
4929 {
4930  HeapTuple tuple;
4931  Oid ownerId;
4932 
4933  /* Superusers bypass all permission checking. */
4934  if (superuser_arg(roleid))
4935  return true;
4936 
4937  tuple = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nsp_oid));
4938  if (!HeapTupleIsValid(tuple))
4939  ereport(ERROR,
4940  (errcode(ERRCODE_UNDEFINED_SCHEMA),
4941  errmsg("schema with OID %u does not exist", nsp_oid)));
4942 
4943  ownerId = ((Form_pg_namespace) GETSTRUCT(tuple))->nspowner;
4944 
4945  ReleaseSysCache(tuple);
4946 
4947  return has_privs_of_role(roleid, ownerId);
4948 }
4949 
4950 /*
4951  * Ownership check for a tablespace (specified by OID).
4952  */
4953 bool
4955 {
4956  HeapTuple spctuple;
4957  Oid spcowner;
4958 
4959  /* Superusers bypass all permission checking. */
4960  if (superuser_arg(roleid))
4961  return true;
4962 
4963  /* Search syscache for pg_tablespace */
4964  spctuple = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(spc_oid));
4965  if (!HeapTupleIsValid(spctuple))
4966  ereport(ERROR,
4967  (errcode(ERRCODE_UNDEFINED_OBJECT),
4968  errmsg("tablespace with OID %u does not exist", spc_oid)));
4969 
4970  spcowner = ((Form_pg_tablespace) GETSTRUCT(spctuple))->spcowner;
4971 
4972  ReleaseSysCache(spctuple);
4973 
4974  return has_privs_of_role(roleid, spcowner);
4975 }
4976 
4977 /*
4978  * Ownership check for an operator class (specified by OID).
4979  */
4980 bool
4982 {
4983  HeapTuple tuple;
4984  Oid ownerId;
4985 
4986  /* Superusers bypass all permission checking. */
4987  if (superuser_arg(roleid))
4988  return true;
4989 
4990  tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opc_oid));
4991  if (!HeapTupleIsValid(tuple))
4992  ereport(ERROR,
4993  (errcode(ERRCODE_UNDEFINED_OBJECT),
4994  errmsg("operator class with OID %u does not exist",
4995  opc_oid)));
4996 
4997  ownerId = ((Form_pg_opclass) GETSTRUCT(tuple))->opcowner;
4998 
4999  ReleaseSysCache(tuple);
5000 
5001  return has_privs_of_role(roleid, ownerId);
5002 }
5003 
5004 /*
5005  * Ownership check for an operator family (specified by OID).
5006  */
5007 bool
5009 {
5010  HeapTuple tuple;
5011  Oid ownerId;
5012 
5013  /* Superusers bypass all permission checking. */
5014  if (superuser_arg(roleid))
5015  return true;
5016 
5017  tuple = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opf_oid));
5018  if (!HeapTupleIsValid(tuple))
5019  ereport(ERROR,
5020  (errcode(ERRCODE_UNDEFINED_OBJECT),
5021  errmsg("operator family with OID %u does not exist",
5022  opf_oid)));
5023 
5024  ownerId = ((Form_pg_opfamily) GETSTRUCT(tuple))->opfowner;
5025 
5026  ReleaseSysCache(tuple);
5027 
5028  return has_privs_of_role(roleid, ownerId);
5029 }
5030 
5031 /*
5032  * Ownership check for a text search dictionary (specified by OID).
5033  */
5034 bool
5035 pg_ts_dict_ownercheck(Oid dict_oid, Oid roleid)
5036 {
5037  HeapTuple tuple;
5038  Oid ownerId;
5039 
5040  /* Superusers bypass all permission checking. */
5041  if (superuser_arg(roleid))
5042  return true;
5043 
5044  tuple = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dict_oid));
5045  if (!HeapTupleIsValid(tuple))
5046  ereport(ERROR,
5047  (errcode(ERRCODE_UNDEFINED_OBJECT),
5048  errmsg("text search dictionary with OID %u does not exist",
5049  dict_oid)));
5050 
5051  ownerId = ((Form_pg_ts_dict) GETSTRUCT(tuple))->dictowner;
5052 
5053  ReleaseSysCache(tuple);
5054 
5055  return has_privs_of_role(roleid, ownerId);
5056 }
5057 
5058 /*
5059  * Ownership check for a text search configuration (specified by OID).
5060  */
5061 bool
5063 {
5064  HeapTuple tuple;
5065  Oid ownerId;
5066 
5067  /* Superusers bypass all permission checking. */
5068  if (superuser_arg(roleid))
5069  return true;
5070 
5071  tuple = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfg_oid));
5072  if (!HeapTupleIsValid(tuple))
5073  ereport(ERROR,
5074  (errcode(ERRCODE_UNDEFINED_OBJECT),
5075  errmsg("text search configuration with OID %u does not exist",
5076  cfg_oid)));
5077 
5078  ownerId = ((Form_pg_ts_config) GETSTRUCT(tuple))->cfgowner;
5079 
5080  ReleaseSysCache(tuple);
5081 
5082  return has_privs_of_role(roleid, ownerId);
5083 }
5084 
5085 /*
5086  * Ownership check for a foreign-data wrapper (specified by OID).
5087  */
5088 bool
5090 {
5091  HeapTuple tuple;
5092  Oid ownerId;
5093 
5094  /* Superusers bypass all permission checking. */
5095  if (superuser_arg(roleid))
5096  return true;
5097 
5099  if (!HeapTupleIsValid(tuple))
5100  ereport(ERROR,
5101  (errcode(ERRCODE_UNDEFINED_OBJECT),
5102  errmsg("foreign-data wrapper with OID %u does not exist",
5103  srv_oid)));
5104 
5105  ownerId = ((Form_pg_foreign_data_wrapper) GETSTRUCT(tuple))->fdwowner;
5106 
5107  ReleaseSysCache(tuple);
5108 
5109  return has_privs_of_role(roleid, ownerId);
5110 }
5111 
5112 /*
5113  * Ownership check for a foreign server (specified by OID).
5114  */
5115 bool
5117 {
5118  HeapTuple tuple;
5119  Oid ownerId;
5120 
5121  /* Superusers bypass all permission checking. */
5122  if (superuser_arg(roleid))
5123  return true;
5124 
5126  if (!HeapTupleIsValid(tuple))
5127  ereport(ERROR,
5128  (errcode(ERRCODE_UNDEFINED_OBJECT),
5129  errmsg("foreign server with OID %u does not exist",
5130  srv_oid)));
5131 
5132  ownerId = ((Form_pg_foreign_server) GETSTRUCT(tuple))->srvowner;
5133 
5134  ReleaseSysCache(tuple);
5135 
5136  return has_privs_of_role(roleid, ownerId);
5137 }
5138 
5139 /*
5140  * Ownership check for an event trigger (specified by OID).
5141  */
5142 bool
5144 {
5145  HeapTuple tuple;
5146  Oid ownerId;
5147 
5148  /* Superusers bypass all permission checking. */
5149  if (superuser_arg(roleid))
5150  return true;
5151 
5153  if (!HeapTupleIsValid(tuple))
5154  ereport(ERROR,
5155  (errcode(ERRCODE_UNDEFINED_OBJECT),
5156  errmsg("event trigger with OID %u does not exist",
5157  et_oid)));
5158 
5159  ownerId = ((Form_pg_event_trigger) GETSTRUCT(tuple))->evtowner;
5160 
5161  ReleaseSysCache(tuple);
5162 
5163  return has_privs_of_role(roleid, ownerId);
5164 }
5165 
5166 /*
5167  * Ownership check for a database (specified by OID).
5168  */
5169 bool
5171 {
5172  HeapTuple tuple;
5173  Oid dba;
5174 
5175  /* Superusers bypass all permission checking. */
5176  if (superuser_arg(roleid))
5177  return true;
5178 
5179  tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(db_oid));
5180  if (!HeapTupleIsValid(tuple))
5181  ereport(ERROR,
5182  (errcode(ERRCODE_UNDEFINED_DATABASE),
5183  errmsg("database with OID %u does not exist", db_oid)));
5184 
5185  dba = ((Form_pg_database) GETSTRUCT(tuple))->datdba;
5186 
5187  ReleaseSysCache(tuple);
5188 
5189  return has_privs_of_role(roleid, dba);
5190 }
5191 
5192 /*
5193  * Ownership check for a collation (specified by OID).
5194  */
5195 bool
5197 {
5198  HeapTuple tuple;
5199  Oid ownerId;
5200 
5201  /* Superusers bypass all permission checking. */
5202  if (superuser_arg(roleid))
5203  return true;
5204 
5205  tuple = SearchSysCache1(COLLOID, ObjectIdGetDatum(coll_oid));
5206  if (!HeapTupleIsValid(tuple))
5207  ereport(ERROR,
5208  (errcode(ERRCODE_UNDEFINED_OBJECT),
5209  errmsg("collation with OID %u does not exist", coll_oid)));
5210 
5211  ownerId = ((Form_pg_collation) GETSTRUCT(tuple))->collowner;
5212 
5213  ReleaseSysCache(tuple);
5214 
5215  return has_privs_of_role(roleid, ownerId);
5216 }
5217 
5218 /*
5219  * Ownership check for a conversion (specified by OID).
5220  */
5221 bool
5223 {
5224  HeapTuple tuple;
5225  Oid ownerId;
5226 
5227  /* Superusers bypass all permission checking. */
5228  if (superuser_arg(roleid))
5229  return true;
5230 
5231  tuple = SearchSysCache1(CONVOID, ObjectIdGetDatum(conv_oid));
5232  if (!HeapTupleIsValid(tuple))
5233  ereport(ERROR,
5234  (errcode(ERRCODE_UNDEFINED_OBJECT),
5235  errmsg("conversion with OID %u does not exist", conv_oid)));
5236 
5237  ownerId = ((Form_pg_conversion) GETSTRUCT(tuple))->conowner;
5238 
5239  ReleaseSysCache(tuple);
5240 
5241  return has_privs_of_role(roleid, ownerId);
5242 }
5243 
5244 /*
5245  * Ownership check for an extension (specified by OID).
5246  */
5247 bool
5249 {
5250  Relation pg_extension;
5251  ScanKeyData entry[1];
5252  SysScanDesc scan;
5253  HeapTuple tuple;
5254  Oid ownerId;
5255 
5256  /* Superusers bypass all permission checking. */
5257  if (superuser_arg(roleid))
5258  return true;
5259 
5260  /* There's no syscache for pg_extension, so do it the hard way */
5262 
5263  ScanKeyInit(&entry[0],
5265  BTEqualStrategyNumber, F_OIDEQ,
5266  ObjectIdGetDatum(ext_oid));
5267 
5268  scan = systable_beginscan(pg_extension,
5269  ExtensionOidIndexId, true,
5270  NULL, 1, entry);
5271 
5272  tuple = systable_getnext(scan);
5273  if (!HeapTupleIsValid(tuple))
5274  ereport(ERROR,
5275  (errcode(ERRCODE_UNDEFINED_OBJECT),
5276  errmsg("extension with OID %u does not exist", ext_oid)));
5277 
5278  ownerId = ((Form_pg_extension) GETSTRUCT(tuple))->extowner;
5279 
5280  systable_endscan(scan);
5281  heap_close(pg_extension, AccessShareLock);
5282 
5283  return has_privs_of_role(roleid, ownerId);
5284 }
5285 
5286 /*
5287  * Ownership check for an publication (specified by OID).
5288  */
5289 bool
5291 {
5292  HeapTuple tuple;
5293  Oid ownerId;
5294 
5295  /* Superusers bypass all permission checking. */
5296  if (superuser_arg(roleid))
5297  return true;
5298 
5299  tuple = SearchSysCache1(PUBLICATIONOID, ObjectIdGetDatum(pub_oid));
5300  if (!HeapTupleIsValid(tuple))
5301  ereport(ERROR,
5302  (errcode(ERRCODE_UNDEFINED_OBJECT),
5303  errmsg("publication with OID %u does not exist", pub_oid)));
5304 
5305  ownerId = ((Form_pg_publication) GETSTRUCT(tuple))->pubowner;
5306 
5307  ReleaseSysCache(tuple);
5308 
5309  return has_privs_of_role(roleid, ownerId);
5310 }
5311 
5312 /*
5313  * Ownership check for a subscription (specified by OID).
5314  */
5315 bool
5317 {
5318  HeapTuple tuple;
5319  Oid ownerId;
5320 
5321  /* Superusers bypass all permission checking. */
5322  if (superuser_arg(roleid))
5323  return true;
5324 
5326  if (!HeapTupleIsValid(tuple))
5327  ereport(ERROR,
5328  (errcode(ERRCODE_UNDEFINED_OBJECT),
5329  errmsg("subscription with OID %u does not exist", sub_oid)));
5330 
5331  ownerId = ((Form_pg_subscription) GETSTRUCT(tuple))->subowner;
5332 
5333  ReleaseSysCache(tuple);
5334 
5335  return has_privs_of_role(roleid, ownerId);
5336 }
5337 
5338 /*
5339  * Ownership check for a statistics object (specified by OID).
5340  */
5341 bool
5343 {
5344  HeapTuple tuple;
5345  Oid ownerId;
5346 
5347  /* Superusers bypass all permission checking. */
5348  if (superuser_arg(roleid))
5349  return true;
5350 
5351  tuple = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stat_oid));
5352  if (!HeapTupleIsValid(tuple))
5353  ereport(ERROR,
5354  (errcode(ERRCODE_UNDEFINED_OBJECT),
5355  errmsg("statistics object with OID %u does not exist",
5356  stat_oid)));
5357 
5358  ownerId = ((Form_pg_statistic_ext) GETSTRUCT(tuple))->stxowner;
5359 
5360  ReleaseSysCache(tuple);
5361 
5362  return has_privs_of_role(roleid, ownerId);
5363 }
5364 
5365 /*
5366  * Check whether specified role has CREATEROLE privilege (or is a superuser)
5367  *
5368  * Note: roles do not have owners per se; instead we use this test in
5369  * places where an ownership-like permissions test is needed for a role.
5370  * Be sure to apply it to the role trying to do the operation, not the
5371  * role being operated on! Also note that this generally should not be
5372  * considered enough privilege if the target role is a superuser.
5373  * (We don't handle that consideration here because we want to give a
5374  * separate error message for such cases, so the caller has to deal with it.)
5375  */
5376 bool
5378 {
5379  bool result = false;
5380  HeapTuple utup;
5381 
5382  /* Superusers bypass all permission checking. */
5383  if (superuser_arg(roleid))
5384  return true;
5385 
5386  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
5387  if (HeapTupleIsValid(utup))
5388  {
5389  result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreaterole;
5390  ReleaseSysCache(utup);
5391  }
5392  return result;
5393 }
5394 
5395 bool
5397 {
5398  bool result = false;
5399  HeapTuple utup;
5400 
5401  /* Superusers bypass all permission checking. */
5402  if (superuser_arg(roleid))
5403  return true;
5404 
5405  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
5406  if (HeapTupleIsValid(utup))
5407  {
5408  result = ((Form_pg_authid) GETSTRUCT(utup))->rolbypassrls;
5409  ReleaseSysCache(utup);
5410  }
5411  return result;
5412 }
5413 
5414 /*
5415  * Fetch pg_default_acl entry for given role, namespace and object type
5416  * (object type must be given in pg_default_acl's encoding).
5417  * Returns NULL if no such entry.
5418  */
5419 static Acl *
5420 get_default_acl_internal(Oid roleId, Oid nsp_oid, char objtype)
5421 {
5422  Acl *result = NULL;
5423  HeapTuple tuple;
5424 
5426  ObjectIdGetDatum(roleId),
5427  ObjectIdGetDatum(nsp_oid),
5428  CharGetDatum(objtype));
5429 
5430  if (HeapTupleIsValid(tuple))
5431  {
5432  Datum aclDatum;
5433  bool isNull;
5434 
5435  aclDatum = SysCacheGetAttr(DEFACLROLENSPOBJ, tuple,
5437  &isNull);
5438  if (!isNull)
5439  result = DatumGetAclPCopy(aclDatum);
5440  ReleaseSysCache(tuple);
5441  }
5442 
5443  return result;
5444 }
5445 
5446 /*
5447  * Get default permissions for newly created object within given schema
5448  *
5449  * Returns NULL if built-in system defaults should be used
5450  */
5451 Acl *
5452 get_user_default_acl(ObjectType objtype, Oid ownerId, Oid nsp_oid)
5453 {
5454  Acl *result;
5455  Acl *glob_acl;
5456  Acl *schema_acl;
5457  Acl *def_acl;
5458  char defaclobjtype;
5459 
5460  /*
5461  * Use NULL during bootstrap, since pg_default_acl probably isn't there
5462  * yet.
5463  */
5465  return NULL;
5466 
5467  /* Check if object type is supported in pg_default_acl */
5468  switch (objtype)
5469  {
5470  case OBJECT_TABLE:
5471  defaclobjtype = DEFACLOBJ_RELATION;
5472  break;
5473 
5474  case OBJECT_SEQUENCE:
5475  defaclobjtype = DEFACLOBJ_SEQUENCE;
5476  break;
5477 
5478  case OBJECT_FUNCTION:
5479  defaclobjtype = DEFACLOBJ_FUNCTION;
5480  break;
5481 
5482  case OBJECT_TYPE:
5483  defaclobjtype = DEFACLOBJ_TYPE;
5484  break;
5485 
5486  case OBJECT_SCHEMA:
5487  defaclobjtype = DEFACLOBJ_NAMESPACE;
5488  break;
5489 
5490  default:
5491  return NULL;
5492  }
5493 
5494  /* Look up the relevant pg_default_acl entries */
5495  glob_acl = get_default_acl_internal(ownerId, InvalidOid, defaclobjtype);
5496  schema_acl = get_default_acl_internal(ownerId, nsp_oid, defaclobjtype);
5497 
5498  /* Quick out if neither entry exists */
5499  if (glob_acl == NULL && schema_acl == NULL)
5500  return NULL;
5501 
5502  /* We need to know the hard-wired default value, too */
5503  def_acl = acldefault(objtype, ownerId);
5504 
5505  /* If there's no global entry, substitute the hard-wired default */
5506  if (glob_acl == NULL)
5507  glob_acl = def_acl;
5508 
5509  /* Merge in any per-schema privileges */
5510  result = aclmerge(glob_acl, schema_acl, ownerId);
5511 
5512  /*
5513  * For efficiency, we want to return NULL if the result equals default.
5514  * This requires sorting both arrays to get an accurate comparison.
5515  */
5516  aclitemsort(result);
5517  aclitemsort(def_acl);
5518  if (aclequal(result, def_acl))
5519  result = NULL;
5520 
5521  return result;
5522 }
5523 
5524 /*
5525  * Record initial privileges for the top-level object passed in.
5526  *
5527  * For the object passed in, this will record its ACL (if any) and the ACLs of
5528  * any sub-objects (eg: columns) into pg_init_privs.
5529  *
5530  * Any new kinds of objects which have ACLs associated with them and can be
5531  * added to an extension should be added to the if-else tree below.
5532  */
5533 void
5534 recordExtObjInitPriv(Oid objoid, Oid classoid)
5535 {
5536  /*
5537  * pg_class / pg_attribute
5538  *
5539  * If this is a relation then we need to see if there are any sub-objects
5540  * (eg: columns) for it and, if so, be sure to call
5541  * recordExtensionInitPrivWorker() for each one.
5542  */
5543  if (classoid == RelationRelationId)
5544  {
5545  Form_pg_class pg_class_tuple;
5546  Datum aclDatum;
5547  bool isNull;
5548  HeapTuple tuple;
5549 
5550  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(objoid));
5551  if (!HeapTupleIsValid(tuple))
5552  elog(ERROR, "cache lookup failed for relation %u", objoid);
5553  pg_class_tuple = (Form_pg_class) GETSTRUCT(tuple);
5554 
5555  /* Indexes don't have permissions */
5556  if (pg_class_tuple->relkind == RELKIND_INDEX ||
5557  pg_class_tuple->relkind == RELKIND_PARTITIONED_INDEX)
5558  return;
5559 
5560  /* Composite types don't have permissions either */
5561  if (pg_class_tuple->relkind == RELKIND_COMPOSITE_TYPE)
5562  return;
5563 
5564  /*
5565  * If this isn't a sequence, index, or composite type then it's
5566  * possibly going to have columns associated with it that might have
5567  * ACLs.
5568  */
5569  if (pg_class_tuple->relkind != RELKIND_SEQUENCE)
5570  {
5571  AttrNumber curr_att;
5572  AttrNumber nattrs = pg_class_tuple->relnatts;
5573 
5574  for (curr_att = 1; curr_att <= nattrs; curr_att++)
5575  {
5576  HeapTuple attTuple;
5577  Datum attaclDatum;
5578 
5579  attTuple = SearchSysCache2(ATTNUM,
5580  ObjectIdGetDatum(objoid),
5581  Int16GetDatum(curr_att));
5582 
5583  if (!HeapTupleIsValid(attTuple))
5584  continue;
5585 
5586  /* ignore dropped columns */
5587  if (((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped)
5588  {
5589  ReleaseSysCache(attTuple);
5590  continue;
5591  }
5592 
5593  attaclDatum = SysCacheGetAttr(ATTNUM, attTuple,
5595  &isNull);
5596 
5597  /* no need to do anything for a NULL ACL */
5598  if (isNull)
5599  {
5600  ReleaseSysCache(attTuple);
5601  continue;
5602  }
5603 
5604  recordExtensionInitPrivWorker(objoid, classoid, curr_att,
5605  DatumGetAclP(attaclDatum));
5606 
5607  ReleaseSysCache(attTuple);
5608  }
5609  }
5610 
5611  aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
5612  &isNull);
5613 
5614  /* Add the record, if any, for the top-level object */
5615  if (!isNull)
5616  recordExtensionInitPrivWorker(objoid, classoid, 0,
5617  DatumGetAclP(aclDatum));
5618 
5619  ReleaseSysCache(tuple);
5620  }
5621  /* pg_foreign_data_wrapper */
5622  else if (classoid == ForeignDataWrapperRelationId)
5623  {
5624  Datum aclDatum;
5625  bool isNull;
5626  HeapTuple tuple;
5627 
5629  ObjectIdGetDatum(objoid));
5630  if (!HeapTupleIsValid(tuple))
5631  elog(ERROR, "cache lookup failed for foreign data wrapper %u",
5632  objoid);
5633 
5634  aclDatum = SysCacheGetAttr(FOREIGNDATAWRAPPEROID, tuple,
5636  &isNull);
5637 
5638  /* Add the record, if any, for the top-level object */
5639  if (!isNull)
5640  recordExtensionInitPrivWorker(objoid, classoid, 0,
5641  DatumGetAclP(aclDatum));
5642 
5643  ReleaseSysCache(tuple);
5644  }
5645  /* pg_foreign_server */
5646  else if (classoid == ForeignServerRelationId)
5647  {
5648  Datum aclDatum;
5649  bool isNull;
5650  HeapTuple tuple;
5651 
5653  if (!HeapTupleIsValid(tuple))
5654  elog(ERROR, "cache lookup failed for foreign data wrapper %u",
5655  objoid);
5656 
5657  aclDatum = SysCacheGetAttr(FOREIGNSERVEROID, tuple,
5659  &isNull);
5660 
5661  /* Add the record, if any, for the top-level object */
5662  if (!isNull)
5663  recordExtensionInitPrivWorker(objoid, classoid, 0,
5664  DatumGetAclP(aclDatum));
5665 
5666  ReleaseSysCache(tuple);
5667  }
5668  /* pg_language */
5669  else if (classoid == LanguageRelationId)
5670  {
5671  Datum aclDatum;
5672  bool isNull;
5673  HeapTuple tuple;
5674 
5675  tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(objoid));
5676  if (!HeapTupleIsValid(tuple))
5677  elog(ERROR, "cache lookup failed for language %u", objoid);
5678 
5679  aclDatum = SysCacheGetAttr(LANGOID, tuple, Anum_pg_language_lanacl,
5680  &isNull);
5681 
5682  /* Add the record, if any, for the top-level object */
5683  if (!isNull)
5684  recordExtensionInitPrivWorker(objoid, classoid, 0,
5685