aclchk.c 137.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * aclchk.c
4
 *	  Routines to check access control permissions.
5
 *
B
Bruce Momjian 已提交
6
 * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
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 19
#include "postgres.h"

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/catalog.h"
26
#include "catalog/dependency.h"
B
Bruce Momjian 已提交
27
#include "catalog/indexing.h"
28
#include "catalog/objectaccess.h"
29
#include "catalog/pg_authid.h"
P
Peter Eisentraut 已提交
30
#include "catalog/pg_collation.h"
31
#include "catalog/pg_conversion.h"
32
#include "catalog/pg_database.h"
33
#include "catalog/pg_default_acl.h"
34
#include "catalog/pg_event_trigger.h"
35
#include "catalog/pg_extension.h"
36 37
#include "catalog/pg_foreign_data_wrapper.h"
#include "catalog/pg_foreign_server.h"
38
#include "catalog/pg_language.h"
39 40
#include "catalog/pg_largeobject.h"
#include "catalog/pg_largeobject_metadata.h"
41
#include "catalog/pg_namespace.h"
42
#include "catalog/pg_opclass.h"
B
Bruce Momjian 已提交
43
#include "catalog/pg_operator.h"
44
#include "catalog/pg_opfamily.h"
B
Bruce Momjian 已提交
45
#include "catalog/pg_proc.h"
46
#include "catalog/pg_tablespace.h"
B
Bruce Momjian 已提交
47
#include "catalog/pg_type.h"
48 49
#include "catalog/pg_ts_config.h"
#include "catalog/pg_ts_dict.h"
50
#include "commands/dbcommands.h"
51 52
#include "commands/proclang.h"
#include "commands/tablespace.h"
53
#include "foreign/foreign.h"
B
Bruce Momjian 已提交
54
#include "miscadmin.h"
55
#include "nodes/makefuncs.h"
56
#include "parser/parse_func.h"
57
#include "parser/parse_type.h"
B
Bruce Momjian 已提交
58
#include "utils/acl.h"
59
#include "utils/builtins.h"
60 61
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
62
#include "utils/rel.h"
63
#include "utils/syscache.h"
64
#include "utils/tqual.h"
65

66

67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
/*
 * The information about one Grant/Revoke statement, in internal format: object
 * and grantees names have been turned into Oids, the privilege list is an
 * AclMode bitmask.  If 'privileges' is ACL_NO_RIGHTS (the 0 value) and
 * all_privs is true, 'privileges' will be internally set to the right kind of
 * ACL_ALL_RIGHTS_*, depending on the object type (NB - this will modify the
 * InternalGrant struct!)
 *
 * Note: 'all_privs' and 'privileges' represent object-level privileges only.
 * There might also be column-level privilege specifications, which are
 * represented in col_privs (this is a list of untransformed AccessPriv nodes).
 * Column privileges are only valid for objtype ACL_OBJECT_RELATION.
 */
typedef struct
{
	bool		is_grant;
	GrantObjectType objtype;
	List	   *objects;
	bool		all_privs;
	AclMode		privileges;
	List	   *col_privs;
	List	   *grantees;
	bool		grant_option;
	DropBehavior behavior;
} InternalGrant;

/*
 * Internal format used by ALTER DEFAULT PRIVILEGES.
 */
typedef struct
{
B
Bruce Momjian 已提交
98 99
	Oid			roleid;			/* owning role */
	Oid			nspid;			/* namespace, or InvalidOid if none */
100 101 102 103 104 105 106 107 108 109 110 111
	/* remaining fields are same as in InternalGrant: */
	bool		is_grant;
	GrantObjectType objtype;
	bool		all_privs;
	AclMode		privileges;
	List	   *grantees;
	bool		grant_option;
	DropBehavior behavior;
} InternalDefaultACL;


static void ExecGrantStmt_oids(InternalGrant *istmt);
112 113
static void ExecGrant_Relation(InternalGrant *grantStmt);
static void ExecGrant_Database(InternalGrant *grantStmt);
114 115
static void ExecGrant_Fdw(InternalGrant *grantStmt);
static void ExecGrant_ForeignServer(InternalGrant *grantStmt);
116 117
static void ExecGrant_Function(InternalGrant *grantStmt);
static void ExecGrant_Language(InternalGrant *grantStmt);
118
static void ExecGrant_Largeobject(InternalGrant *grantStmt);
119 120
static void ExecGrant_Namespace(InternalGrant *grantStmt);
static void ExecGrant_Tablespace(InternalGrant *grantStmt);
121
static void ExecGrant_Type(InternalGrant *grantStmt);
122

123 124 125
static void SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames);
static void SetDefaultACL(InternalDefaultACL *iacls);

126
static List *objectNamesToOids(GrantObjectType objtype, List *objnames);
127 128
static List *objectsInSchemaToOids(GrantObjectType objtype, List *nspnames);
static List *getRelationsInNamespace(Oid namespaceId, char relkind);
129
static void expand_col_privileges(List *colnames, Oid table_oid,
130 131 132
					  AclMode this_privileges,
					  AclMode *col_privileges,
					  int num_col_privileges);
133
static void expand_all_col_privileges(Oid table_oid, Form_pg_class classForm,
134 135 136
						  AclMode this_privileges,
						  AclMode *col_privileges,
						  int num_col_privileges);
137
static AclMode string_to_privilege(const char *privname);
138
static const char *privilege_to_string(AclMode privilege);
139
static AclMode restrict_and_check_grant(bool is_grant, AclMode avail_goptions,
B
Bruce Momjian 已提交
140 141
						 bool all_privs, AclMode privileges,
						 Oid objectId, Oid grantorId,
142 143 144
						 AclObjectKind objkind, const char *objname,
						 AttrNumber att_number, const char *colname);
static AclMode pg_aclmask(AclObjectKind objkind, Oid table_oid, AttrNumber attnum,
145
		   Oid roleid, AclMode mask, AclMaskHow how);
146

147

148
#ifdef ACLDEBUG
149
static void
B
Bruce Momjian 已提交
150
dumpacl(Acl *acl)
151
{
152
	int			i;
153
	AclItem    *aip;
154

155
	elog(DEBUG2, "acl size = %d, # acls = %d",
156
		 ACL_SIZE(acl), ACL_NUM(acl));
157
	aip = ACL_DAT(acl);
158
	for (i = 0; i < ACL_NUM(acl); ++i)
159
		elog(DEBUG2, "	acl[%d]: %s", i,
160
			 DatumGetCString(DirectFunctionCall1(aclitemout,
B
Bruce Momjian 已提交
161
												 PointerGetDatum(aip + i))));
162
}
163
#endif   /* ACLDEBUG */
164

165

166 167 168 169
/*
 * If is_grant is true, adds the given privileges for the list of
 * grantees to the existing old_acl.  If is_grant is false, the
 * privileges for the given grantees are removed from old_acl.
170 171
 *
 * NB: the original old_acl is pfree'd.
172
 */
173 174
static Acl *
merge_acl_with_grant(Acl *old_acl, bool is_grant,
175
					 bool grant_option, DropBehavior behavior,
176
					 List *grantees, AclMode privileges,
177
					 Oid grantorId, Oid ownerId)
178
{
179
	unsigned	modechg;
180
	ListCell   *j;
181 182
	Acl		   *new_acl;

183 184
	modechg = is_grant ? ACL_MODECHG_ADD : ACL_MODECHG_DEL;

185 186 187 188 189 190 191
#ifdef ACLDEBUG
	dumpacl(old_acl);
#endif
	new_acl = old_acl;

	foreach(j, grantees)
	{
192
		AclItem		aclitem;
193
		Acl		   *newer_acl;
194

195
		aclitem.ai_grantee = lfirst_oid(j);
196

197
		/*
198 199 200 201
		 * Grant options can only be granted to individual roles, not PUBLIC.
		 * The reason is that if a user would re-grant a privilege that he
		 * held through PUBLIC, and later the user is removed, the situation
		 * is impossible to clean up.
202
		 */
203
		if (is_grant && grant_option && aclitem.ai_grantee == ACL_ID_PUBLIC)
204 205
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_GRANT_OPERATION),
206
					 errmsg("grant options can only be granted to roles")));
207

208
		aclitem.ai_grantor = grantorId;
209

210 211
		/*
		 * The asymmetry in the conditions here comes from the spec.  In
B
Bruce Momjian 已提交
212 213 214 215
		 * GRANT, the grant_option flag signals WITH GRANT OPTION, which means
		 * to grant both the basic privilege and its grant option. But in
		 * REVOKE, plain revoke revokes both the basic privilege and its grant
		 * option, while REVOKE GRANT OPTION revokes only the option.
216
		 */
217
		ACLITEM_SET_PRIVS_GOPTIONS(aclitem,
B
Bruce Momjian 已提交
218 219
					(is_grant || !grant_option) ? privileges : ACL_NO_RIGHTS,
				   (!is_grant || grant_option) ? privileges : ACL_NO_RIGHTS);
220

221
		newer_acl = aclupdate(new_acl, &aclitem, modechg, ownerId, behavior);
222 223 224 225

		/* avoid memory leak when there are many grantees */
		pfree(new_acl);
		new_acl = newer_acl;
226 227 228 229 230 231 232 233 234

#ifdef ACLDEBUG
		dumpacl(new_acl);
#endif
	}

	return new_acl;
}

235 236 237 238 239 240 241
/*
 * Restrict the privileges to what we can actually grant, and emit
 * the standards-mandated warning and error messages.
 */
static AclMode
restrict_and_check_grant(bool is_grant, AclMode avail_goptions, bool all_privs,
						 AclMode privileges, Oid objectId, Oid grantorId,
242 243
						 AclObjectKind objkind, const char *objname,
						 AttrNumber att_number, const char *colname)
244
{
B
Bruce Momjian 已提交
245 246
	AclMode		this_privileges;
	AclMode		whole_mask;
247 248 249

	switch (objkind)
	{
250 251 252
		case ACL_KIND_COLUMN:
			whole_mask = ACL_ALL_RIGHTS_COLUMN;
			break;
253 254 255
		case ACL_KIND_CLASS:
			whole_mask = ACL_ALL_RIGHTS_RELATION;
			break;
256 257 258
		case ACL_KIND_SEQUENCE:
			whole_mask = ACL_ALL_RIGHTS_SEQUENCE;
			break;
259 260 261 262 263 264 265 266 267
		case ACL_KIND_DATABASE:
			whole_mask = ACL_ALL_RIGHTS_DATABASE;
			break;
		case ACL_KIND_PROC:
			whole_mask = ACL_ALL_RIGHTS_FUNCTION;
			break;
		case ACL_KIND_LANGUAGE:
			whole_mask = ACL_ALL_RIGHTS_LANGUAGE;
			break;
268 269 270
		case ACL_KIND_LARGEOBJECT:
			whole_mask = ACL_ALL_RIGHTS_LARGEOBJECT;
			break;
271 272 273 274 275 276
		case ACL_KIND_NAMESPACE:
			whole_mask = ACL_ALL_RIGHTS_NAMESPACE;
			break;
		case ACL_KIND_TABLESPACE:
			whole_mask = ACL_ALL_RIGHTS_TABLESPACE;
			break;
277 278 279 280 281 282
		case ACL_KIND_FDW:
			whole_mask = ACL_ALL_RIGHTS_FDW;
			break;
		case ACL_KIND_FOREIGN_SERVER:
			whole_mask = ACL_ALL_RIGHTS_FOREIGN_SERVER;
			break;
283 284 285 286
		case ACL_KIND_EVENT_TRIGGER:
			elog(ERROR, "grantable rights not supported for event triggers");
			/* not reached, but keep compiler quiet */
			return ACL_NO_RIGHTS;
287 288 289
		case ACL_KIND_TYPE:
			whole_mask = ACL_ALL_RIGHTS_TYPE;
			break;
290 291 292 293 294 295 296
		default:
			elog(ERROR, "unrecognized object kind: %d", objkind);
			/* not reached, but keep compiler quiet */
			return ACL_NO_RIGHTS;
	}

	/*
B
Bruce Momjian 已提交
297 298 299
	 * If we found no grant options, consider whether to issue a hard error.
	 * Per spec, having any privilege at all on the object will get you by
	 * here.
300 301 302
	 */
	if (avail_goptions == ACL_NO_RIGHTS)
	{
303
		if (pg_aclmask(objkind, objectId, att_number, grantorId,
304 305
					   whole_mask | ACL_GRANT_OPTION_FOR(whole_mask),
					   ACLMASK_ANY) == ACL_NO_RIGHTS)
306 307 308 309 310 311
		{
			if (objkind == ACL_KIND_COLUMN && colname)
				aclcheck_error_col(ACLCHECK_NO_PRIV, objkind, objname, colname);
			else
				aclcheck_error(ACLCHECK_NO_PRIV, objkind, objname);
		}
312 313 314 315
	}

	/*
	 * Restrict the operation to what we can actually grant or revoke, and
B
Bruce Momjian 已提交
316 317 318 319
	 * issue a warning if appropriate.	(For REVOKE this isn't quite what the
	 * spec says to do: the spec seems to want a warning only if no privilege
	 * bits actually change in the ACL. In practice that behavior seems much
	 * too noisy, as well as inconsistent with the GRANT case.)
320 321 322 323 324
	 */
	this_privileges = privileges & ACL_OPTION_TO_PRIVS(avail_goptions);
	if (is_grant)
	{
		if (this_privileges == 0)
B
Bruce Momjian 已提交
325
		{
326 327 328 329 330 331 332 333 334 335 336
			if (objkind == ACL_KIND_COLUMN && colname)
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
						 errmsg("no privileges were granted for column \"%s\" of relation \"%s\"",
								colname, objname)));
			else
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
						 errmsg("no privileges were granted for \"%s\"",
								objname)));
		}
337
		else if (!all_privs && this_privileges != privileges)
338 339 340 341 342 343 344 345 346 347 348 349
		{
			if (objkind == ACL_KIND_COLUMN && colname)
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
						 errmsg("not all privileges were granted for column \"%s\" of relation \"%s\"",
								colname, objname)));
			else
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_GRANTED),
						 errmsg("not all privileges were granted for \"%s\"",
								objname)));
		}
350 351 352 353
	}
	else
	{
		if (this_privileges == 0)
354 355 356 357 358 359 360 361 362 363 364 365
		{
			if (objkind == ACL_KIND_COLUMN && colname)
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
						 errmsg("no privileges could be revoked for column \"%s\" of relation \"%s\"",
								colname, objname)));
			else
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
						 errmsg("no privileges could be revoked for \"%s\"",
								objname)));
		}
366
		else if (!all_privs && this_privileges != privileges)
367 368 369 370 371 372 373 374 375
		{
			if (objkind == ACL_KIND_COLUMN && colname)
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
						 errmsg("not all privileges could be revoked for column \"%s\" of relation \"%s\"",
								colname, objname)));
			else
				ereport(WARNING,
						(errcode(ERRCODE_WARNING_PRIVILEGE_NOT_REVOKED),
B
Bruce Momjian 已提交
376 377
					 errmsg("not all privileges could be revoked for \"%s\"",
							objname)));
378
		}
379 380 381 382
	}

	return this_privileges;
}
383

384
/*
385
 * Called to execute the utility commands GRANT and REVOKE
386 387
 */
void
388
ExecuteGrantStmt(GrantStmt *stmt)
389
{
390
	InternalGrant istmt;
391
	ListCell   *cell;
392
	const char *errormsg;
393 394 395 396 397 398 399
	AclMode		all_privileges;

	/*
	 * Turn the regular GrantStmt into the InternalGrant form.
	 */
	istmt.is_grant = stmt->is_grant;
	istmt.objtype = stmt->objtype;
400 401 402 403 404 405 406 407 408 409

	/* Collect the OIDs of the target objects */
	switch (stmt->targtype)
	{
		case ACL_TARGET_OBJECT:
			istmt.objects = objectNamesToOids(stmt->objtype, stmt->objects);
			break;
		case ACL_TARGET_ALL_IN_SCHEMA:
			istmt.objects = objectsInSchemaToOids(stmt->objtype, stmt->objects);
			break;
B
Bruce Momjian 已提交
410
			/* ACL_TARGET_DEFAULTS should not be seen here */
411 412 413 414 415
		default:
			elog(ERROR, "unrecognized GrantStmt.targtype: %d",
				 (int) stmt->targtype);
	}

416 417
	/* all_privs to be filled below */
	/* privileges to be filled below */
418 419
	istmt.col_privs = NIL;		/* may get filled below */
	istmt.grantees = NIL;		/* filled below */
420 421 422
	istmt.grant_option = stmt->grant_option;
	istmt.behavior = stmt->behavior;

423 424 425 426
	/*
	 * Convert the PrivGrantee list into an Oid list.  Note that at this point
	 * we insert an ACL_ID_PUBLIC into the list if an empty role name is
	 * detected (which is what the grammar uses if PUBLIC is found), so
427 428
	 * downstream there shouldn't be any additional work needed to support
	 * this case.
429 430 431 432 433 434
	 */
	foreach(cell, stmt->grantees)
	{
		PrivGrantee *grantee = (PrivGrantee *) lfirst(cell);

		if (grantee->rolname == NULL)
435
			istmt.grantees = lappend_oid(istmt.grantees, ACL_ID_PUBLIC);
436
		else
437 438
			istmt.grantees =
				lappend_oid(istmt.grantees,
439
							get_role_oid(grantee->rolname, false));
440 441 442
	}

	/*
443 444
	 * Convert stmt->privileges, a list of AccessPriv nodes, into an AclMode
	 * bitmask.  Note: objtype can't be ACL_OBJECT_COLUMN.
445
	 */
446
	switch (stmt->objtype)
447
	{
B
Bruce Momjian 已提交
448 449 450 451 452
			/*
			 * Because this might be a sequence, we test both relation and
			 * sequence bits, and later do a more limited test when we know
			 * the object type.
			 */
453
		case ACL_OBJECT_RELATION:
454
			all_privileges = ACL_ALL_RIGHTS_RELATION | ACL_ALL_RIGHTS_SEQUENCE;
455
			errormsg = gettext_noop("invalid privilege type %s for relation");
456 457 458
			break;
		case ACL_OBJECT_SEQUENCE:
			all_privileges = ACL_ALL_RIGHTS_SEQUENCE;
459
			errormsg = gettext_noop("invalid privilege type %s for sequence");
460 461
			break;
		case ACL_OBJECT_DATABASE:
462
			all_privileges = ACL_ALL_RIGHTS_DATABASE;
463
			errormsg = gettext_noop("invalid privilege type %s for database");
464
			break;
465 466 467 468
		case ACL_OBJECT_DOMAIN:
			all_privileges = ACL_ALL_RIGHTS_TYPE;
			errormsg = gettext_noop("invalid privilege type %s for domain");
			break;
469
		case ACL_OBJECT_FUNCTION:
470
			all_privileges = ACL_ALL_RIGHTS_FUNCTION;
471
			errormsg = gettext_noop("invalid privilege type %s for function");
472
			break;
473
		case ACL_OBJECT_LANGUAGE:
474
			all_privileges = ACL_ALL_RIGHTS_LANGUAGE;
475
			errormsg = gettext_noop("invalid privilege type %s for language");
476
			break;
477 478 479 480
		case ACL_OBJECT_LARGEOBJECT:
			all_privileges = ACL_ALL_RIGHTS_LARGEOBJECT;
			errormsg = gettext_noop("invalid privilege type %s for large object");
			break;
481
		case ACL_OBJECT_NAMESPACE:
482
			all_privileges = ACL_ALL_RIGHTS_NAMESPACE;
483
			errormsg = gettext_noop("invalid privilege type %s for schema");
484
			break;
485
		case ACL_OBJECT_TABLESPACE:
486
			all_privileges = ACL_ALL_RIGHTS_TABLESPACE;
487
			errormsg = gettext_noop("invalid privilege type %s for tablespace");
488
			break;
489 490 491 492
		case ACL_OBJECT_TYPE:
			all_privileges = ACL_ALL_RIGHTS_TYPE;
			errormsg = gettext_noop("invalid privilege type %s for type");
			break;
493 494 495 496 497 498 499 500
		case ACL_OBJECT_FDW:
			all_privileges = ACL_ALL_RIGHTS_FDW;
			errormsg = gettext_noop("invalid privilege type %s for foreign-data wrapper");
			break;
		case ACL_OBJECT_FOREIGN_SERVER:
			all_privileges = ACL_ALL_RIGHTS_FOREIGN_SERVER;
			errormsg = gettext_noop("invalid privilege type %s for foreign server");
			break;
501
		default:
502 503
			elog(ERROR, "unrecognized GrantStmt.objtype: %d",
				 (int) stmt->objtype);
504 505 506
			/* keep compiler quiet */
			all_privileges = ACL_NO_RIGHTS;
			errormsg = NULL;
507 508
	}

509
	if (stmt->privileges == NIL)
510
	{
511
		istmt.all_privs = true;
B
Bruce Momjian 已提交
512

513 514 515 516 517
		/*
		 * will be turned into ACL_ALL_RIGHTS_* by the internal routines
		 * depending on the object type
		 */
		istmt.privileges = ACL_NO_RIGHTS;
518
	}
519 520
	else
	{
521 522
		istmt.all_privs = false;
		istmt.privileges = ACL_NO_RIGHTS;
523

524
		foreach(cell, stmt->privileges)
525
		{
526 527 528 529
			AccessPriv *privnode = (AccessPriv *) lfirst(cell);
			AclMode		priv;

			/*
530 531
			 * If it's a column-level specification, we just set it aside in
			 * col_privs for the moment; but insist it's for a relation.
532 533 534 535 536 537 538 539 540 541 542
			 */
			if (privnode->cols)
			{
				if (stmt->objtype != ACL_OBJECT_RELATION)
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_GRANT_OPERATION),
							 errmsg("column privileges are only valid for relations")));
				istmt.col_privs = lappend(istmt.col_privs, privnode);
				continue;
			}

543
			if (privnode->priv_name == NULL)	/* parser mistake? */
544 545
				elog(ERROR, "AccessPriv node must specify privilege or columns");
			priv = string_to_privilege(privnode->priv_name);
546

547
			if (priv & ~((AclMode) all_privileges))
548 549
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_GRANT_OPERATION),
550
						 errmsg(errormsg, privilege_to_string(priv))));
551

552
			istmt.privileges |= priv;
553 554 555
		}
	}

556
	ExecGrantStmt_oids(&istmt);
557 558 559 560 561
}

/*
 * ExecGrantStmt_oids
 *
562
 * Internal entry point for granting and revoking privileges.
563
 */
564
static void
565
ExecGrantStmt_oids(InternalGrant *istmt)
566
{
567
	switch (istmt->objtype)
568
	{
569
		case ACL_OBJECT_RELATION:
570
		case ACL_OBJECT_SEQUENCE:
571
			ExecGrant_Relation(istmt);
572 573
			break;
		case ACL_OBJECT_DATABASE:
574
			ExecGrant_Database(istmt);
575
			break;
576 577 578 579
		case ACL_OBJECT_DOMAIN:
		case ACL_OBJECT_TYPE:
			ExecGrant_Type(istmt);
			break;
580 581 582 583 584 585
		case ACL_OBJECT_FDW:
			ExecGrant_Fdw(istmt);
			break;
		case ACL_OBJECT_FOREIGN_SERVER:
			ExecGrant_ForeignServer(istmt);
			break;
586
		case ACL_OBJECT_FUNCTION:
587
			ExecGrant_Function(istmt);
588 589
			break;
		case ACL_OBJECT_LANGUAGE:
590
			ExecGrant_Language(istmt);
591
			break;
592 593 594
		case ACL_OBJECT_LARGEOBJECT:
			ExecGrant_Largeobject(istmt);
			break;
595
		case ACL_OBJECT_NAMESPACE:
596
			ExecGrant_Namespace(istmt);
597 598
			break;
		case ACL_OBJECT_TABLESPACE:
599
			ExecGrant_Tablespace(istmt);
600 601 602
			break;
		default:
			elog(ERROR, "unrecognized GrantStmt.objtype: %d",
603
				 (int) istmt->objtype);
604 605 606 607 608 609 610
	}
}

/*
 * objectNamesToOids
 *
 * Turn a list of object names of a given type into an Oid list.
611 612 613 614 615
 *
 * XXX: This function doesn't take any sort of locks on the objects whose
 * names it looks up.  In the face of concurrent DDL, we might easily latch
 * onto an old version of an object, causing the GRANT or REVOKE statement
 * to fail.
616 617 618 619
 */
static List *
objectNamesToOids(GrantObjectType objtype, List *objnames)
{
620 621
	List	   *objects = NIL;
	ListCell   *cell;
622 623 624 625 626 627

	Assert(objnames != NIL);

	switch (objtype)
	{
		case ACL_OBJECT_RELATION:
628
		case ACL_OBJECT_SEQUENCE:
629 630 631
			foreach(cell, objnames)
			{
				RangeVar   *relvar = (RangeVar *) lfirst(cell);
632
				Oid			relOid;
633

634
				relOid = RangeVarGetRelid(relvar, NoLock, false);
635 636 637 638 639 640 641
				objects = lappend_oid(objects, relOid);
			}
			break;
		case ACL_OBJECT_DATABASE:
			foreach(cell, objnames)
			{
				char	   *dbname = strVal(lfirst(cell));
642
				Oid			dbid;
643

644
				dbid = get_database_oid(dbname, false);
645
				objects = lappend_oid(objects, dbid);
646 647
			}
			break;
648 649 650 651 652 653 654 655 656 657 658
		case ACL_OBJECT_DOMAIN:
		case ACL_OBJECT_TYPE:
			foreach(cell, objnames)
			{
				List	   *typname = (List *) lfirst(cell);
				Oid			oid;

				oid = typenameTypeId(NULL, makeTypeNameFromNameList(typname));
				objects = lappend_oid(objects, oid);
			}
			break;
659 660 661 662 663 664 665 666 667 668 669 670 671 672
		case ACL_OBJECT_FUNCTION:
			foreach(cell, objnames)
			{
				FuncWithArgs *func = (FuncWithArgs *) lfirst(cell);
				Oid			funcid;

				funcid = LookupFuncNameTypeNames(func->funcname,
												 func->funcargs, false);
				objects = lappend_oid(objects, funcid);
			}
			break;
		case ACL_OBJECT_LANGUAGE:
			foreach(cell, objnames)
			{
673
				char	   *langname = strVal(lfirst(cell));
674
				Oid			oid;
675

676 677
				oid = get_language_oid(langname, false);
				objects = lappend_oid(objects, oid);
678 679
			}
			break;
680 681 682
		case ACL_OBJECT_LARGEOBJECT:
			foreach(cell, objnames)
			{
683
				Oid			lobjOid = oidparse(lfirst(cell));
684 685 686 687 688 689 690 691 692 693

				if (!LargeObjectExists(lobjOid))
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_OBJECT),
							 errmsg("large object %u does not exist",
									lobjOid)));

				objects = lappend_oid(objects, lobjOid);
			}
			break;
694
		case ACL_OBJECT_NAMESPACE:
695
			foreach(cell, objnames)
696 697
			{
				char	   *nspname = strVal(lfirst(cell));
698
				Oid			oid;
699

700 701
				oid = get_namespace_oid(nspname, false);
				objects = lappend_oid(objects, oid);
702 703 704
			}
			break;
		case ACL_OBJECT_TABLESPACE:
705
			foreach(cell, objnames)
706
			{
707
				char	   *spcname = strVal(lfirst(cell));
708
				Oid			spcoid;
709

710 711
				spcoid = get_tablespace_oid(spcname, false);
				objects = lappend_oid(objects, spcoid);
712 713
			}
			break;
714 715 716
		case ACL_OBJECT_FDW:
			foreach(cell, objnames)
			{
717
				char	   *fdwname = strVal(lfirst(cell));
718
				Oid			fdwid = get_foreign_data_wrapper_oid(fdwname, false);
719 720 721 722 723 724 725

				objects = lappend_oid(objects, fdwid);
			}
			break;
		case ACL_OBJECT_FOREIGN_SERVER:
			foreach(cell, objnames)
			{
726
				char	   *srvname = strVal(lfirst(cell));
727
				Oid			srvid = get_foreign_server_oid(srvname, false);
728 729 730 731

				objects = lappend_oid(objects, srvid);
			}
			break;
732 733 734 735 736 737 738 739
		default:
			elog(ERROR, "unrecognized GrantStmt.objtype: %d",
				 (int) objtype);
	}

	return objects;
}

740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
/*
 * objectsInSchemaToOids
 *
 * Find all objects of a given type in specified schemas, and make a list
 * of their Oids.  We check USAGE privilege on the schemas, but there is
 * no privilege checking on the individual objects here.
 */
static List *
objectsInSchemaToOids(GrantObjectType objtype, List *nspnames)
{
	List	   *objects = NIL;
	ListCell   *cell;

	foreach(cell, nspnames)
	{
		char	   *nspname = strVal(lfirst(cell));
		Oid			namespaceId;
		List	   *objs;

759
		namespaceId = LookupExplicitNamespace(nspname, false);
760 761 762 763

		switch (objtype)
		{
			case ACL_OBJECT_RELATION:
R
Robert Haas 已提交
764
				/* Process regular tables, views and foreign tables */
765 766 767 768
				objs = getRelationsInNamespace(namespaceId, RELKIND_RELATION);
				objects = list_concat(objects, objs);
				objs = getRelationsInNamespace(namespaceId, RELKIND_VIEW);
				objects = list_concat(objects, objs);
769 770
				objs = getRelationsInNamespace(namespaceId, RELKIND_MATVIEW);
				objects = list_concat(objects, objs);
R
Robert Haas 已提交
771 772
				objs = getRelationsInNamespace(namespaceId, RELKIND_FOREIGN_TABLE);
				objects = list_concat(objects, objs);
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
				break;
			case ACL_OBJECT_SEQUENCE:
				objs = getRelationsInNamespace(namespaceId, RELKIND_SEQUENCE);
				objects = list_concat(objects, objs);
				break;
			case ACL_OBJECT_FUNCTION:
				{
					ScanKeyData key[1];
					Relation	rel;
					HeapScanDesc scan;
					HeapTuple	tuple;

					ScanKeyInit(&key[0],
								Anum_pg_proc_pronamespace,
								BTEqualStrategyNumber, F_OIDEQ,
								ObjectIdGetDatum(namespaceId));

					rel = heap_open(ProcedureRelationId, AccessShareLock);
					scan = heap_beginscan(rel, SnapshotNow, 1, key);

					while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
					{
						objects = lappend_oid(objects, HeapTupleGetOid(tuple));
					}

					heap_endscan(scan);
					heap_close(rel, AccessShareLock);
				}
				break;
			default:
				/* should not happen */
				elog(ERROR, "unrecognized GrantStmt.objtype: %d",
					 (int) objtype);
		}
	}

	return objects;
}

/*
 * getRelationsInNamespace
 *
 * Return Oid list of relations in given namespace filtered by relation kind
 */
static List *
getRelationsInNamespace(Oid namespaceId, char relkind)
{
	List	   *relations = NIL;
	ScanKeyData key[2];
	Relation	rel;
	HeapScanDesc scan;
	HeapTuple	tuple;

	ScanKeyInit(&key[0],
				Anum_pg_class_relnamespace,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(namespaceId));
	ScanKeyInit(&key[1],
				Anum_pg_class_relkind,
				BTEqualStrategyNumber, F_CHAREQ,
				CharGetDatum(relkind));

	rel = heap_open(RelationRelationId, AccessShareLock);
	scan = heap_beginscan(rel, SnapshotNow, 2, key);

	while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
	{
		relations = lappend_oid(relations, HeapTupleGetOid(tuple));
	}

	heap_endscan(scan);
	heap_close(rel, AccessShareLock);

	return relations;
}


850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
/*
 * ALTER DEFAULT PRIVILEGES statement
 */
void
ExecAlterDefaultPrivilegesStmt(AlterDefaultPrivilegesStmt *stmt)
{
	GrantStmt  *action = stmt->action;
	InternalDefaultACL iacls;
	ListCell   *cell;
	List	   *rolenames = NIL;
	List	   *nspnames = NIL;
	DefElem    *drolenames = NULL;
	DefElem    *dnspnames = NULL;
	AclMode		all_privileges;
	const char *errormsg;

	/* Deconstruct the "options" part of the statement */
	foreach(cell, stmt->options)
	{
		DefElem    *defel = (DefElem *) lfirst(cell);

		if (strcmp(defel->defname, "schemas") == 0)
		{
			if (dnspnames)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			dnspnames = defel;
		}
		else if (strcmp(defel->defname, "roles") == 0)
		{
			if (drolenames)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			drolenames = defel;
		}
		else
			elog(ERROR, "option \"%s\" not recognized", defel->defname);
	}

	if (dnspnames)
		nspnames = (List *) dnspnames->arg;
	if (drolenames)
		rolenames = (List *) drolenames->arg;

	/* Prepare the InternalDefaultACL representation of the statement */
	/* roleid to be filled below */
	/* nspid to be filled in SetDefaultACLsInSchemas */
	iacls.is_grant = action->is_grant;
	iacls.objtype = action->objtype;
	/* all_privs to be filled below */
	/* privileges to be filled below */
	iacls.grantees = NIL;		/* filled below */
	iacls.grant_option = action->grant_option;
	iacls.behavior = action->behavior;

	/*
	 * Convert the PrivGrantee list into an Oid list.  Note that at this point
	 * we insert an ACL_ID_PUBLIC into the list if an empty role name is
	 * detected (which is what the grammar uses if PUBLIC is found), so
	 * downstream there shouldn't be any additional work needed to support
	 * this case.
	 */
	foreach(cell, action->grantees)
	{
		PrivGrantee *grantee = (PrivGrantee *) lfirst(cell);

		if (grantee->rolname == NULL)
			iacls.grantees = lappend_oid(iacls.grantees, ACL_ID_PUBLIC);
		else
			iacls.grantees =
				lappend_oid(iacls.grantees,
923
							get_role_oid(grantee->rolname, false));
924 925 926
	}

	/*
B
Bruce Momjian 已提交
927 928
	 * Convert action->privileges, a list of privilege strings, into an
	 * AclMode bitmask.
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
	 */
	switch (action->objtype)
	{
		case ACL_OBJECT_RELATION:
			all_privileges = ACL_ALL_RIGHTS_RELATION;
			errormsg = gettext_noop("invalid privilege type %s for relation");
			break;
		case ACL_OBJECT_SEQUENCE:
			all_privileges = ACL_ALL_RIGHTS_SEQUENCE;
			errormsg = gettext_noop("invalid privilege type %s for sequence");
			break;
		case ACL_OBJECT_FUNCTION:
			all_privileges = ACL_ALL_RIGHTS_FUNCTION;
			errormsg = gettext_noop("invalid privilege type %s for function");
			break;
944 945 946 947
		case ACL_OBJECT_TYPE:
			all_privileges = ACL_ALL_RIGHTS_TYPE;
			errormsg = gettext_noop("invalid privilege type %s for type");
			break;
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
		default:
			elog(ERROR, "unrecognized GrantStmt.objtype: %d",
				 (int) action->objtype);
			/* keep compiler quiet */
			all_privileges = ACL_NO_RIGHTS;
			errormsg = NULL;
	}

	if (action->privileges == NIL)
	{
		iacls.all_privs = true;

		/*
		 * will be turned into ACL_ALL_RIGHTS_* by the internal routines
		 * depending on the object type
		 */
		iacls.privileges = ACL_NO_RIGHTS;
	}
	else
	{
		iacls.all_privs = false;
		iacls.privileges = ACL_NO_RIGHTS;

		foreach(cell, action->privileges)
		{
			AccessPriv *privnode = (AccessPriv *) lfirst(cell);
			AclMode		priv;

			if (privnode->cols)
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_GRANT_OPERATION),
B
Bruce Momjian 已提交
979
					errmsg("default privileges cannot be set for columns")));
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

			if (privnode->priv_name == NULL)	/* parser mistake? */
				elog(ERROR, "AccessPriv node must specify privilege");
			priv = string_to_privilege(privnode->priv_name);

			if (priv & ~((AclMode) all_privileges))
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_GRANT_OPERATION),
						 errmsg(errormsg, privilege_to_string(priv))));

			iacls.privileges |= priv;
		}
	}

	if (rolenames == NIL)
	{
		/* Set permissions for myself */
		iacls.roleid = GetUserId();

		SetDefaultACLsInSchemas(&iacls, nspnames);
	}
	else
	{
		/* Look up the role OIDs and do permissions checks */
		ListCell   *rolecell;

		foreach(rolecell, rolenames)
		{
			char	   *rolename = strVal(lfirst(rolecell));

1010
			iacls.roleid = get_role_oid(rolename, false);
1011 1012

			/*
B
Bruce Momjian 已提交
1013 1014 1015 1016
			 * We insist that calling user be a member of each target role. If
			 * he has that, he could become that role anyway via SET ROLE, so
			 * FOR ROLE is just a syntactic convenience and doesn't give any
			 * special privileges.
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
			 */
			check_is_member_of_role(GetUserId(), iacls.roleid);

			SetDefaultACLsInSchemas(&iacls, nspnames);
		}
	}
}

/*
 * Process ALTER DEFAULT PRIVILEGES for a list of target schemas
 *
 * All fields of *iacls except nspid were filled already
 */
static void
SetDefaultACLsInSchemas(InternalDefaultACL *iacls, List *nspnames)
{
	if (nspnames == NIL)
	{
		/* Set database-wide permissions if no schema was specified */
		iacls->nspid = InvalidOid;

		SetDefaultACL(iacls);
	}
	else
	{
1042
		/* Look up the schema OIDs and set permissions for each one */
1043 1044 1045 1046 1047 1048
		ListCell   *nspcell;

		foreach(nspcell, nspnames)
		{
			char	   *nspname = strVal(lfirst(nspcell));

1049
			iacls->nspid = get_namespace_oid(nspname, false);
1050

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
			/*
			 * We used to insist that the target role have CREATE privileges
			 * on the schema, since without that it wouldn't be able to create
			 * an object for which these default privileges would apply.
			 * However, this check proved to be more confusing than helpful,
			 * and it also caused certain database states to not be
			 * dumpable/restorable, since revoking CREATE doesn't cause
			 * default privileges for the schema to go away.  So now, we just
			 * allow the ALTER; if the user lacks CREATE he'll find out when
			 * he tries to create an object.
			 */
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

			SetDefaultACL(iacls);
		}
	}
}


/*
 * Create or update a pg_default_acl entry
 */
static void
SetDefaultACL(InternalDefaultACL *iacls)
{
	AclMode		this_privileges = iacls->privileges;
	char		objtype;
	Relation	rel;
	HeapTuple	tuple;
	bool		isNew;
1080
	Acl		   *def_acl;
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
	Acl		   *old_acl;
	Acl		   *new_acl;
	HeapTuple	newtuple;
	Datum		values[Natts_pg_default_acl];
	bool		nulls[Natts_pg_default_acl];
	bool		replaces[Natts_pg_default_acl];
	int			noldmembers;
	int			nnewmembers;
	Oid		   *oldmembers;
	Oid		   *newmembers;

	rel = heap_open(DefaultAclRelationId, RowExclusiveLock);

1094 1095
	/*
	 * The default for a global entry is the hard-wired default ACL for the
B
Bruce Momjian 已提交
1096
	 * particular object type.	The default for non-global entries is an empty
1097 1098 1099 1100 1101 1102 1103 1104
	 * ACL.  This must be so because global entries replace the hard-wired
	 * defaults, while others are added on.
	 */
	if (!OidIsValid(iacls->nspid))
		def_acl = acldefault(iacls->objtype, iacls->roleid);
	else
		def_acl = make_empty_acl();

1105
	/*
B
Bruce Momjian 已提交
1106 1107
	 * Convert ACL object type to pg_default_acl object type and handle
	 * all_privs option
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
	 */
	switch (iacls->objtype)
	{
		case ACL_OBJECT_RELATION:
			objtype = DEFACLOBJ_RELATION;
			if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
				this_privileges = ACL_ALL_RIGHTS_RELATION;
			break;

		case ACL_OBJECT_SEQUENCE:
			objtype = DEFACLOBJ_SEQUENCE;
			if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
				this_privileges = ACL_ALL_RIGHTS_SEQUENCE;
			break;

		case ACL_OBJECT_FUNCTION:
			objtype = DEFACLOBJ_FUNCTION;
			if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
				this_privileges = ACL_ALL_RIGHTS_FUNCTION;
			break;

1129 1130 1131 1132 1133 1134
		case ACL_OBJECT_TYPE:
			objtype = DEFACLOBJ_TYPE;
			if (iacls->all_privs && this_privileges == ACL_NO_RIGHTS)
				this_privileges = ACL_ALL_RIGHTS_TYPE;
			break;

1135 1136 1137 1138 1139 1140 1141 1142
		default:
			elog(ERROR, "unrecognized objtype: %d",
				 (int) iacls->objtype);
			objtype = 0;		/* keep compiler quiet */
			break;
	}

	/* Search for existing row for this object type in catalog */
1143 1144 1145
	tuple = SearchSysCache3(DEFACLROLENSPOBJ,
							ObjectIdGetDatum(iacls->roleid),
							ObjectIdGetDatum(iacls->nspid),
B
Bruce Momjian 已提交
1146
							CharGetDatum(objtype));
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

	if (HeapTupleIsValid(tuple))
	{
		Datum		aclDatum;
		bool		isNull;

		aclDatum = SysCacheGetAttr(DEFACLROLENSPOBJ, tuple,
								   Anum_pg_default_acl_defaclacl,
								   &isNull);
		if (!isNull)
			old_acl = DatumGetAclPCopy(aclDatum);
		else
1159
			old_acl = NULL;		/* this case shouldn't happen, probably */
1160 1161 1162 1163 1164 1165 1166 1167
		isNew = false;
	}
	else
	{
		old_acl = NULL;
		isNew = true;
	}

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
	if (old_acl != NULL)
	{
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.  Collect data before
		 * merge_acl_with_grant throws away old_acl.
		 */
		noldmembers = aclmembers(old_acl, &oldmembers);
	}
	else
1178
	{
1179 1180
		/* If no or null entry, start with the default ACL value */
		old_acl = aclcopy(def_acl);
1181 1182 1183 1184
		/* There are no old member roles according to the catalogs */
		noldmembers = 0;
		oldmembers = NULL;
	}
1185 1186

	/*
B
Bruce Momjian 已提交
1187 1188
	 * Generate new ACL.  Grantor of rights is always the same as the target
	 * role.
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
	 */
	new_acl = merge_acl_with_grant(old_acl,
								   iacls->is_grant,
								   iacls->grant_option,
								   iacls->behavior,
								   iacls->grantees,
								   this_privileges,
								   iacls->roleid,
								   iacls->roleid);

1199 1200
	/*
	 * If the result is the same as the default value, we do not need an
B
Bruce Momjian 已提交
1201 1202
	 * explicit pg_default_acl entry, and should in fact remove the entry if
	 * it exists.  Must sort both arrays to compare properly.
1203 1204 1205 1206
	 */
	aclitemsort(new_acl);
	aclitemsort(def_acl);
	if (aclequal(new_acl, def_acl))
1207
	{
1208 1209 1210 1211
		/* delete old entry, if indeed there is one */
		if (!isNew)
		{
			ObjectAddress myself;
1212

1213 1214 1215 1216 1217 1218 1219 1220 1221
			/*
			 * The dependency machinery will take care of removing all
			 * associated dependency entries.  We use DROP_RESTRICT since
			 * there shouldn't be anything depending on this entry.
			 */
			myself.classId = DefaultAclRelationId;
			myself.objectId = HeapTupleGetOid(tuple);
			myself.objectSubId = 0;

1222
			performDeletion(&myself, DROP_RESTRICT, 0);
1223
		}
1224 1225 1226
	}
	else
	{
1227 1228 1229 1230
		/* Prepare to insert or update pg_default_acl entry */
		MemSet(values, 0, sizeof(values));
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));
1231

1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
		if (isNew)
		{
			/* insert new entry */
			values[Anum_pg_default_acl_defaclrole - 1] = ObjectIdGetDatum(iacls->roleid);
			values[Anum_pg_default_acl_defaclnamespace - 1] = ObjectIdGetDatum(iacls->nspid);
			values[Anum_pg_default_acl_defaclobjtype - 1] = CharGetDatum(objtype);
			values[Anum_pg_default_acl_defaclacl - 1] = PointerGetDatum(new_acl);

			newtuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
			simple_heap_insert(rel, newtuple);
		}
		else
		{
			/* update existing entry */
			values[Anum_pg_default_acl_defaclacl - 1] = PointerGetDatum(new_acl);
			replaces[Anum_pg_default_acl_defaclacl - 1] = true;
1248

1249 1250 1251 1252
			newtuple = heap_modify_tuple(tuple, RelationGetDescr(rel),
										 values, nulls, replaces);
			simple_heap_update(rel, &newtuple->t_self, newtuple);
		}
1253

1254 1255
		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(rel, newtuple);
1256

1257 1258
		/* these dependencies don't change in an update */
		if (isNew)
1259
		{
1260 1261 1262 1263
			/* dependency on role */
			recordDependencyOnOwner(DefaultAclRelationId,
									HeapTupleGetOid(newtuple),
									iacls->roleid);
1264

1265 1266 1267 1268
			/* dependency on namespace */
			if (OidIsValid(iacls->nspid))
			{
				ObjectAddress myself,
B
Bruce Momjian 已提交
1269
							referenced;
1270

1271 1272 1273
				myself.classId = DefaultAclRelationId;
				myself.objectId = HeapTupleGetOid(newtuple);
				myself.objectSubId = 0;
1274

1275 1276 1277
				referenced.classId = NamespaceRelationId;
				referenced.objectId = iacls->nspid;
				referenced.objectSubId = 0;
1278

1279 1280 1281
				recordDependencyOn(&myself, &referenced, DEPENDENCY_AUTO);
			}
		}
1282

1283 1284 1285 1286
		/*
		 * Update the shared dependency ACL info
		 */
		nnewmembers = aclmembers(new_acl, &newmembers);
1287

1288 1289 1290 1291 1292
		updateAclDependencies(DefaultAclRelationId,
							  HeapTupleGetOid(newtuple), 0,
							  iacls->roleid,
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);
1293 1294 1295 1296 1297 1298 1299

		if (isNew)
			InvokeObjectPostCreateHook(DefaultAclRelationId,
									   HeapTupleGetOid(newtuple), 0);
		else
			InvokeObjectPostAlterHook(DefaultAclRelationId,
									  HeapTupleGetOid(newtuple), 0);
1300
	}
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351

	if (HeapTupleIsValid(tuple))
		ReleaseSysCache(tuple);

	heap_close(rel, RowExclusiveLock);
}


/*
 * RemoveRoleFromObjectACL
 *
 * Used by shdepDropOwned to remove mentions of a role in ACLs
 */
void
RemoveRoleFromObjectACL(Oid roleid, Oid classid, Oid objid)
{
	if (classid == DefaultAclRelationId)
	{
		InternalDefaultACL iacls;
		Form_pg_default_acl pg_default_acl_tuple;
		Relation	rel;
		ScanKeyData skey[1];
		SysScanDesc scan;
		HeapTuple	tuple;

		/* first fetch info needed by SetDefaultACL */
		rel = heap_open(DefaultAclRelationId, AccessShareLock);

		ScanKeyInit(&skey[0],
					ObjectIdAttributeNumber,
					BTEqualStrategyNumber, F_OIDEQ,
					ObjectIdGetDatum(objid));

		scan = systable_beginscan(rel, DefaultAclOidIndexId, true,
								  SnapshotNow, 1, skey);

		tuple = systable_getnext(scan);

		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "could not find tuple for default ACL %u", objid);

		pg_default_acl_tuple = (Form_pg_default_acl) GETSTRUCT(tuple);

		iacls.roleid = pg_default_acl_tuple->defaclrole;
		iacls.nspid = pg_default_acl_tuple->defaclnamespace;

		switch (pg_default_acl_tuple->defaclobjtype)
		{
			case DEFACLOBJ_RELATION:
				iacls.objtype = ACL_OBJECT_RELATION;
				break;
1352
			case DEFACLOBJ_SEQUENCE:
1353 1354 1355 1356 1357
				iacls.objtype = ACL_OBJECT_SEQUENCE;
				break;
			case DEFACLOBJ_FUNCTION:
				iacls.objtype = ACL_OBJECT_FUNCTION;
				break;
1358 1359 1360
			case DEFACLOBJ_TYPE:
				iacls.objtype = ACL_OBJECT_TYPE;
				break;
1361 1362
			default:
				/* Shouldn't get here */
1363 1364
				elog(ERROR, "unexpected default ACL type: %d",
					 (int) pg_default_acl_tuple->defaclobjtype);
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
				break;
		}

		systable_endscan(scan);
		heap_close(rel, AccessShareLock);

		iacls.is_grant = false;
		iacls.all_privs = true;
		iacls.privileges = ACL_NO_RIGHTS;
		iacls.grantees = list_make1_oid(roleid);
		iacls.grant_option = false;
		iacls.behavior = DROP_CASCADE;

		/* Do it */
		SetDefaultACL(&iacls);
	}
	else
	{
		InternalGrant istmt;

		switch (classid)
		{
			case RelationRelationId:
				/* it's OK to use RELATION for a sequence */
				istmt.objtype = ACL_OBJECT_RELATION;
				break;
			case DatabaseRelationId:
				istmt.objtype = ACL_OBJECT_DATABASE;
				break;
1394 1395 1396
			case TypeRelationId:
				istmt.objtype = ACL_OBJECT_TYPE;
				break;
1397 1398 1399 1400 1401 1402
			case ProcedureRelationId:
				istmt.objtype = ACL_OBJECT_FUNCTION;
				break;
			case LanguageRelationId:
				istmt.objtype = ACL_OBJECT_LANGUAGE;
				break;
1403 1404 1405
			case LargeObjectRelationId:
				istmt.objtype = ACL_OBJECT_LARGEOBJECT;
				break;
1406 1407 1408 1409 1410 1411
			case NamespaceRelationId:
				istmt.objtype = ACL_OBJECT_NAMESPACE;
				break;
			case TableSpaceRelationId:
				istmt.objtype = ACL_OBJECT_TABLESPACE;
				break;
1412 1413 1414 1415 1416 1417
			case ForeignServerRelationId:
				istmt.objtype = ACL_OBJECT_FOREIGN_SERVER;
				break;
			case ForeignDataWrapperRelationId:
				istmt.objtype = ACL_OBJECT_FDW;
				break;
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
			default:
				elog(ERROR, "unexpected object class %u", classid);
				break;
		}
		istmt.is_grant = false;
		istmt.objects = list_make1_oid(objid);
		istmt.all_privs = true;
		istmt.privileges = ACL_NO_RIGHTS;
		istmt.col_privs = NIL;
		istmt.grantees = list_make1_oid(roleid);
		istmt.grant_option = false;
		istmt.behavior = DROP_CASCADE;

		ExecGrantStmt_oids(&istmt);
	}
}


/*
 * Remove a pg_default_acl entry
 */
void
RemoveDefaultACLById(Oid defaclOid)
{
	Relation	rel;
	ScanKeyData skey[1];
	SysScanDesc scan;
	HeapTuple	tuple;

	rel = heap_open(DefaultAclRelationId, RowExclusiveLock);

	ScanKeyInit(&skey[0],
				ObjectIdAttributeNumber,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(defaclOid));

	scan = systable_beginscan(rel, DefaultAclOidIndexId, true,
							  SnapshotNow, 1, skey);

	tuple = systable_getnext(scan);

	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "could not find tuple for default ACL %u", defaclOid);

	simple_heap_delete(rel, &tuple->t_self);

	systable_endscan(scan);
	heap_close(rel, RowExclusiveLock);
}


1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
/*
 * expand_col_privileges
 *
 * OR the specified privilege(s) into per-column array entries for each
 * specified attribute.  The per-column array is indexed starting at
 * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
 */
static void
expand_col_privileges(List *colnames, Oid table_oid,
					  AclMode this_privileges,
					  AclMode *col_privileges,
					  int num_col_privileges)
{
	ListCell   *cell;

	foreach(cell, colnames)
	{
		char	   *colname = strVal(lfirst(cell));
		AttrNumber	attnum;

		attnum = get_attnum(table_oid, colname);
		if (attnum == InvalidAttrNumber)
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("column \"%s\" of relation \"%s\" does not exist",
							colname, get_rel_name(table_oid))));
		attnum -= FirstLowInvalidHeapAttributeNumber;
		if (attnum <= 0 || attnum >= num_col_privileges)
1497
			elog(ERROR, "column number out of range");	/* safety check */
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
		col_privileges[attnum] |= this_privileges;
	}
}

/*
 * expand_all_col_privileges
 *
 * OR the specified privilege(s) into per-column array entries for each valid
 * attribute of a relation.  The per-column array is indexed starting at
 * FirstLowInvalidHeapAttributeNumber, up to relation's last attribute.
 */
static void
expand_all_col_privileges(Oid table_oid, Form_pg_class classForm,
						  AclMode this_privileges,
						  AclMode *col_privileges,
						  int num_col_privileges)
{
	AttrNumber	curr_att;

	Assert(classForm->relnatts - FirstLowInvalidHeapAttributeNumber < num_col_privileges);
	for (curr_att = FirstLowInvalidHeapAttributeNumber + 1;
		 curr_att <= classForm->relnatts;
		 curr_att++)
	{
		HeapTuple	attTuple;
		bool		isdropped;

		if (curr_att == InvalidAttrNumber)
			continue;

		/* Skip OID column if it doesn't exist */
		if (curr_att == ObjectIdAttributeNumber && !classForm->relhasoids)
			continue;

		/* Views don't have any system columns at all */
		if (classForm->relkind == RELKIND_VIEW && curr_att < 0)
			continue;

1536 1537 1538
		attTuple = SearchSysCache2(ATTNUM,
								   ObjectIdGetDatum(table_oid),
								   Int16GetDatum(curr_att));
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
		if (!HeapTupleIsValid(attTuple))
			elog(ERROR, "cache lookup failed for attribute %d of relation %u",
				 curr_att, table_oid);

		isdropped = ((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped;

		ReleaseSysCache(attTuple);

		/* ignore dropped columns */
		if (isdropped)
			continue;

		col_privileges[curr_att - FirstLowInvalidHeapAttributeNumber] |= this_privileges;
	}
}

/*
 *	This processes attributes, but expects to be called from
 *	ExecGrant_Relation, not directly from ExecGrantStmt.
 */
static void
ExecGrant_Attribute(InternalGrant *istmt, Oid relOid, const char *relname,
					AttrNumber attnum, Oid ownerId, AclMode col_privileges,
					Relation attRelation, const Acl *old_rel_acl)
{
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
	HeapTuple	attr_tuple;
	Form_pg_attribute pg_attribute_tuple;
	Acl		   *old_acl;
	Acl		   *new_acl;
	Acl		   *merged_acl;
	Datum		aclDatum;
	bool		isNull;
	Oid			grantorId;
	AclMode		avail_goptions;
	bool		need_update;
	HeapTuple	newtuple;
	Datum		values[Natts_pg_attribute];
	bool		nulls[Natts_pg_attribute];
	bool		replaces[Natts_pg_attribute];
	int			noldmembers;
	int			nnewmembers;
	Oid		   *oldmembers;
	Oid		   *newmembers;
1582

1583 1584 1585
	attr_tuple = SearchSysCache2(ATTNUM,
								 ObjectIdGetDatum(relOid),
								 Int16GetDatum(attnum));
1586 1587 1588 1589 1590 1591
	if (!HeapTupleIsValid(attr_tuple))
		elog(ERROR, "cache lookup failed for attribute %d of relation %u",
			 attnum, relOid);
	pg_attribute_tuple = (Form_pg_attribute) GETSTRUCT(attr_tuple);

	/*
1592 1593
	 * Get working copy of existing ACL. If there's no ACL, substitute the
	 * proper default.
1594 1595 1596 1597
	 */
	aclDatum = SysCacheGetAttr(ATTNUM, attr_tuple, Anum_pg_attribute_attacl,
							   &isNull);
	if (isNull)
1598
	{
1599
		old_acl = acldefault(ACL_OBJECT_COLUMN, ownerId);
1600 1601 1602 1603
		/* There are no old member roles according to the catalogs */
		noldmembers = 0;
		oldmembers = NULL;
	}
1604
	else
1605
	{
1606
		old_acl = DatumGetAclPCopy(aclDatum);
1607 1608 1609
		/* Get the roles mentioned in the existing ACL */
		noldmembers = aclmembers(old_acl, &oldmembers);
	}
1610 1611 1612 1613

	/*
	 * In select_best_grantor we should consider existing table-level ACL bits
	 * as well as the per-column ACL.  Build a new ACL that is their
1614 1615
	 * concatenation.  (This is a bit cheap and dirty compared to merging them
	 * properly with no duplications, but it's all we need here.)
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
	 */
	merged_acl = aclconcat(old_rel_acl, old_acl);

	/* Determine ID to do the grant as, and available grant options */
	select_best_grantor(GetUserId(), col_privileges,
						merged_acl, ownerId,
						&grantorId, &avail_goptions);

	pfree(merged_acl);

	/*
1627 1628 1629 1630 1631 1632
	 * Restrict the privileges to what we can actually grant, and emit the
	 * standards-mandated warning and error messages.  Note: we don't track
	 * whether the user actually used the ALL PRIVILEGES(columns) syntax for
	 * each column; we just approximate it by whether all the possible
	 * privileges are specified now.  Since the all_privs flag only determines
	 * whether a warning is issued, this seems close enough.
1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
	 */
	col_privileges =
		restrict_and_check_grant(istmt->is_grant, avail_goptions,
								 (col_privileges == ACL_ALL_RIGHTS_COLUMN),
								 col_privileges,
								 relOid, grantorId, ACL_KIND_COLUMN,
								 relname, attnum,
								 NameStr(pg_attribute_tuple->attname));

	/*
	 * Generate new ACL.
	 */
	new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
								   istmt->grant_option,
								   istmt->behavior, istmt->grantees,
								   col_privileges, grantorId,
								   ownerId);

1651 1652 1653 1654
	/*
	 * We need the members of both old and new ACLs so we can correct the
	 * shared dependency information.
	 */
1655 1656 1657 1658 1659 1660 1661 1662
	nnewmembers = aclmembers(new_acl, &newmembers);

	/* finished building new ACL value, now insert it */
	MemSet(values, 0, sizeof(values));
	MemSet(nulls, false, sizeof(nulls));
	MemSet(replaces, false, sizeof(replaces));

	/*
1663 1664 1665 1666 1667
	 * If the updated ACL is empty, we can set attacl to null, and maybe even
	 * avoid an update of the pg_attribute row.  This is worth testing because
	 * we'll come through here multiple times for any relation-level REVOKE,
	 * even if there were never any column GRANTs.	Note we are assuming that
	 * the "default" ACL state for columns is empty.
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
	 */
	if (ACL_NUM(new_acl) > 0)
	{
		values[Anum_pg_attribute_attacl - 1] = PointerGetDatum(new_acl);
		need_update = true;
	}
	else
	{
		nulls[Anum_pg_attribute_attacl - 1] = true;
		need_update = !isNull;
	}
	replaces[Anum_pg_attribute_attacl - 1] = true;

	if (need_update)
	{
		newtuple = heap_modify_tuple(attr_tuple, RelationGetDescr(attRelation),
									 values, nulls, replaces);

		simple_heap_update(attRelation, &newtuple->t_self, newtuple);

		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(attRelation, newtuple);

		/* Update the shared dependency ACL info */
		updateAclDependencies(RelationRelationId, relOid, attnum,
1693
							  ownerId,
1694 1695 1696 1697 1698 1699 1700 1701 1702
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);
	}

	pfree(new_acl);

	ReleaseSysCache(attr_tuple);
}

1703 1704 1705
/*
 *	This processes both sequences and non-sequences.
 */
1706
static void
1707
ExecGrant_Relation(InternalGrant *istmt)
1708 1709
{
	Relation	relation;
1710
	Relation	attRelation;
1711 1712 1713
	ListCell   *cell;

	relation = heap_open(RelationRelationId, RowExclusiveLock);
1714
	attRelation = heap_open(AttributeRelationId, RowExclusiveLock);
1715

1716
	foreach(cell, istmt->objects)
1717 1718
	{
		Oid			relOid = lfirst_oid(cell);
1719
		Datum		aclDatum;
1720
		Form_pg_class pg_class_tuple;
1721
		bool		isNull;
1722
		AclMode		this_privileges;
1723
		AclMode    *col_privileges;
1724 1725
		int			num_col_privileges;
		bool		have_col_privileges;
1726
		Acl		   *old_acl;
1727
		Acl		   *old_rel_acl;
1728 1729
		int			noldmembers;
		Oid		   *oldmembers;
B
Bruce Momjian 已提交
1730
		Oid			ownerId;
1731
		HeapTuple	tuple;
1732
		ListCell   *cell_colprivs;
1733

1734
		tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relOid));
1735
		if (!HeapTupleIsValid(tuple))
1736
			elog(ERROR, "cache lookup failed for relation %u", relOid);
1737 1738
		pg_class_tuple = (Form_pg_class) GETSTRUCT(tuple);

1739
		/* Not sensible to grant on an index */
1740
		if (pg_class_tuple->relkind == RELKIND_INDEX)
1741 1742 1743
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("\"%s\" is an index",
1744
							NameStr(pg_class_tuple->relname))));
1745

1746 1747 1748 1749 1750
		/* Composite types aren't tables either */
		if (pg_class_tuple->relkind == RELKIND_COMPOSITE_TYPE)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("\"%s\" is a composite type",
1751
							NameStr(pg_class_tuple->relname))));
1752

1753 1754 1755 1756 1757 1758 1759 1760
		/* Used GRANT SEQUENCE on a non-sequence? */
		if (istmt->objtype == ACL_OBJECT_SEQUENCE &&
			pg_class_tuple->relkind != RELKIND_SEQUENCE)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("\"%s\" is not a sequence",
							NameStr(pg_class_tuple->relname))));

R
Robert Haas 已提交
1761
		/* Adjust the default permissions based on object type */
1762 1763 1764 1765 1766 1767 1768 1769 1770
		if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		{
			if (pg_class_tuple->relkind == RELKIND_SEQUENCE)
				this_privileges = ACL_ALL_RIGHTS_SEQUENCE;
			else
				this_privileges = ACL_ALL_RIGHTS_RELATION;
		}
		else
			this_privileges = istmt->privileges;
B
Bruce Momjian 已提交
1771

1772
		/*
B
Bruce Momjian 已提交
1773 1774 1775 1776
		 * The GRANT TABLE syntax can be used for sequences and non-sequences,
		 * so we have to look at the relkind to determine the supported
		 * permissions.  The OR of table and sequence permissions were already
		 * checked.
1777 1778 1779 1780 1781 1782
		 */
		if (istmt->objtype == ACL_OBJECT_RELATION)
		{
			if (pg_class_tuple->relkind == RELKIND_SEQUENCE)
			{
				/*
1783
				 * For backward compatibility, just throw a warning for
B
Bruce Momjian 已提交
1784
				 * invalid sequence permissions when using the non-sequence
1785
				 * GRANT syntax.
1786 1787 1788 1789
				 */
				if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_SEQUENCE))
				{
					/*
B
Bruce Momjian 已提交
1790 1791 1792
					 * Mention the object name because the user needs to know
					 * which operations succeeded.	This is required because
					 * WARNING allows the command to continue.
1793 1794 1795
					 */
					ereport(WARNING,
							(errcode(ERRCODE_INVALID_GRANT_OPERATION),
1796
							 errmsg("sequence \"%s\" only supports USAGE, SELECT, and UPDATE privileges",
1797 1798 1799 1800 1801 1802 1803
									NameStr(pg_class_tuple->relname))));
					this_privileges &= (AclMode) ACL_ALL_RIGHTS_SEQUENCE;
				}
			}
			else
			{
				if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_RELATION))
1804
				{
1805
					/*
B
Bruce Momjian 已提交
1806 1807 1808 1809
					 * USAGE is the only permission supported by sequences but
					 * not by non-sequences.  Don't mention the object name
					 * because we didn't in the combined TABLE | SEQUENCE
					 * check.
1810 1811 1812
					 */
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_GRANT_OPERATION),
B
Bruce Momjian 已提交
1813
						  errmsg("invalid privilege type USAGE for table")));
1814
				}
1815 1816 1817
			}
		}

1818 1819
		/*
		 * Set up array in which we'll accumulate any column privilege bits
1820
		 * that need modification.	The array is indexed such that entry [0]
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
		 * corresponds to FirstLowInvalidHeapAttributeNumber.
		 */
		num_col_privileges = pg_class_tuple->relnatts - FirstLowInvalidHeapAttributeNumber + 1;
		col_privileges = (AclMode *) palloc0(num_col_privileges * sizeof(AclMode));
		have_col_privileges = false;

		/*
		 * If we are revoking relation privileges that are also column
		 * privileges, we must implicitly revoke them from each column too,
		 * per SQL spec.  (We don't need to implicitly add column privileges
		 * during GRANT because the permissions-checking code always checks
		 * both relation and per-column privileges.)
		 */
		if (!istmt->is_grant &&
			(this_privileges & ACL_ALL_RIGHTS_COLUMN) != 0)
		{
			expand_all_col_privileges(relOid, pg_class_tuple,
									  this_privileges & ACL_ALL_RIGHTS_COLUMN,
									  col_privileges,
									  num_col_privileges);
			have_col_privileges = true;
		}

1844
		/*
B
Bruce Momjian 已提交
1845 1846
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
1847
		 */
1848
		ownerId = pg_class_tuple->relowner;
1849 1850 1851
		aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
								   &isNull);
		if (isNull)
1852
		{
R
Robert Haas 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861
			switch (pg_class_tuple->relkind)
			{
				case RELKIND_SEQUENCE:
					old_acl = acldefault(ACL_OBJECT_SEQUENCE, ownerId);
					break;
				default:
					old_acl = acldefault(ACL_OBJECT_RELATION, ownerId);
					break;
			}
1862 1863 1864 1865
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
1866
		else
1867
		{
1868
			old_acl = DatumGetAclPCopy(aclDatum);
1869 1870 1871
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
1872

1873 1874
		/* Need an extra copy of original rel ACL for column handling */
		old_rel_acl = aclcopy(old_acl);
1875 1876

		/*
1877
		 * Handle relation-level privileges, if any were specified
1878
		 */
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
		if (this_privileges != ACL_NO_RIGHTS)
		{
			AclMode		avail_goptions;
			Acl		   *new_acl;
			Oid			grantorId;
			HeapTuple	newtuple;
			Datum		values[Natts_pg_class];
			bool		nulls[Natts_pg_class];
			bool		replaces[Natts_pg_class];
			int			nnewmembers;
			Oid		   *newmembers;
R
Robert Haas 已提交
1890
			AclObjectKind aclkind;
1891 1892 1893 1894 1895 1896

			/* Determine ID to do the grant as, and available grant options */
			select_best_grantor(GetUserId(), this_privileges,
								old_acl, ownerId,
								&grantorId, &avail_goptions);

R
Robert Haas 已提交
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
			switch (pg_class_tuple->relkind)
			{
				case RELKIND_SEQUENCE:
					aclkind = ACL_KIND_SEQUENCE;
					break;
				default:
					aclkind = ACL_KIND_CLASS;
					break;
			}

1907 1908 1909 1910 1911 1912 1913
			/*
			 * Restrict the privileges to what we can actually grant, and emit
			 * the standards-mandated warning and error messages.
			 */
			this_privileges =
				restrict_and_check_grant(istmt->is_grant, avail_goptions,
										 istmt->all_privs, this_privileges,
R
Robert Haas 已提交
1914
										 relOid, grantorId, aclkind,
1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
										 NameStr(pg_class_tuple->relname),
										 0, NULL);

			/*
			 * Generate new ACL.
			 */
			new_acl = merge_acl_with_grant(old_acl,
										   istmt->is_grant,
										   istmt->grant_option,
										   istmt->behavior,
										   istmt->grantees,
										   this_privileges,
										   grantorId,
										   ownerId);

1930 1931 1932 1933
			/*
			 * We need the members of both old and new ACLs so we can correct
			 * the shared dependency information.
			 */
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
			nnewmembers = aclmembers(new_acl, &newmembers);

			/* finished building new ACL value, now insert it */
			MemSet(values, 0, sizeof(values));
			MemSet(nulls, false, sizeof(nulls));
			MemSet(replaces, false, sizeof(replaces));

			replaces[Anum_pg_class_relacl - 1] = true;
			values[Anum_pg_class_relacl - 1] = PointerGetDatum(new_acl);

			newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
										 values, nulls, replaces);

			simple_heap_update(relation, &newtuple->t_self, newtuple);

			/* keep the catalog indexes up to date */
			CatalogUpdateIndexes(relation, newtuple);

			/* Update the shared dependency ACL info */
			updateAclDependencies(RelationRelationId, relOid, 0,
1954
								  ownerId,
1955 1956 1957 1958 1959
								  noldmembers, oldmembers,
								  nnewmembers, newmembers);

			pfree(new_acl);
		}
1960

1961
		/*
1962 1963 1964
		 * Handle column-level privileges, if any were specified or implied.
		 * We first expand the user-specified column privileges into the
		 * array, and then iterate over all nonempty array entries.
1965
		 */
1966 1967
		foreach(cell_colprivs, istmt->col_privs)
		{
1968
			AccessPriv *col_privs = (AccessPriv *) lfirst(cell_colprivs);
1969

1970 1971 1972 1973
			if (col_privs->priv_name == NULL)
				this_privileges = ACL_ALL_RIGHTS_COLUMN;
			else
				this_privileges = string_to_privilege(col_privs->priv_name);
1974

1975 1976 1977 1978 1979
			if (this_privileges & ~((AclMode) ACL_ALL_RIGHTS_COLUMN))
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_GRANT_OPERATION),
						 errmsg("invalid privilege type %s for column",
								privilege_to_string(this_privileges))));
1980

1981 1982 1983 1984 1985
			if (pg_class_tuple->relkind == RELKIND_SEQUENCE &&
				this_privileges & ~((AclMode) ACL_SELECT))
			{
				/*
				 * The only column privilege allowed on sequences is SELECT.
1986 1987
				 * This is a warning not error because we do it that way for
				 * relation-level privileges.
1988 1989 1990 1991 1992
				 */
				ereport(WARNING,
						(errcode(ERRCODE_INVALID_GRANT_OPERATION),
						 errmsg("sequence \"%s\" only supports SELECT column privileges",
								NameStr(pg_class_tuple->relname))));
1993

1994 1995
				this_privileges &= (AclMode) ACL_SELECT;
			}
1996

1997 1998 1999 2000 2001 2002
			expand_col_privileges(col_privs->cols, relOid,
								  this_privileges,
								  col_privileges,
								  num_col_privileges);
			have_col_privileges = true;
		}
2003

2004 2005
		if (have_col_privileges)
		{
2006
			AttrNumber	i;
2007

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
			for (i = 0; i < num_col_privileges; i++)
			{
				if (col_privileges[i] == ACL_NO_RIGHTS)
					continue;
				ExecGrant_Attribute(istmt,
									relOid,
									NameStr(pg_class_tuple->relname),
									i + FirstLowInvalidHeapAttributeNumber,
									ownerId,
									col_privileges[i],
									attRelation,
									old_rel_acl);
			}
		}
2022

2023 2024
		pfree(old_rel_acl);
		pfree(col_privileges);
2025 2026 2027

		ReleaseSysCache(tuple);

2028 2029
		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
2030
	}
2031

2032
	heap_close(attRelation, RowExclusiveLock);
2033
	heap_close(relation, RowExclusiveLock);
2034 2035
}

2036
static void
2037
ExecGrant_Database(InternalGrant *istmt)
2038
{
2039 2040
	Relation	relation;
	ListCell   *cell;
2041

2042 2043
	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_DATABASE;
2044

2045
	relation = heap_open(DatabaseRelationId, RowExclusiveLock);
2046

2047
	foreach(cell, istmt->objects)
2048
	{
2049
		Oid			datId = lfirst_oid(cell);
2050 2051 2052
		Form_pg_database pg_database_tuple;
		Datum		aclDatum;
		bool		isNull;
2053
		AclMode		avail_goptions;
2054
		AclMode		this_privileges;
2055 2056
		Acl		   *old_acl;
		Acl		   *new_acl;
B
Bruce Momjian 已提交
2057 2058
		Oid			grantorId;
		Oid			ownerId;
2059 2060
		HeapTuple	newtuple;
		Datum		values[Natts_pg_database];
2061 2062
		bool		nulls[Natts_pg_database];
		bool		replaces[Natts_pg_database];
2063 2064 2065 2066
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
2067
		HeapTuple	tuple;
2068

2069
		tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(datId));
2070
		if (!HeapTupleIsValid(tuple))
2071
			elog(ERROR, "cache lookup failed for database %u", datId);
2072

2073 2074
		pg_database_tuple = (Form_pg_database) GETSTRUCT(tuple);

2075
		/*
B
Bruce Momjian 已提交
2076 2077
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
2078
		 */
2079
		ownerId = pg_database_tuple->datdba;
2080 2081 2082
		aclDatum = heap_getattr(tuple, Anum_pg_database_datacl,
								RelationGetDescr(relation), &isNull);
		if (isNull)
2083
		{
2084
			old_acl = acldefault(ACL_OBJECT_DATABASE, ownerId);
2085 2086 2087 2088
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2089
		else
2090
		{
2091
			old_acl = DatumGetAclPCopy(aclDatum);
2092 2093 2094
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2095 2096

		/* Determine ID to do the grant as, and available grant options */
2097
		select_best_grantor(GetUserId(), istmt->privileges,
2098 2099
							old_acl, ownerId,
							&grantorId, &avail_goptions);
2100

2101
		/*
B
Bruce Momjian 已提交
2102 2103
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
2104
		 */
2105 2106 2107 2108
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 datId, grantorId, ACL_KIND_DATABASE,
2109 2110
									 NameStr(pg_database_tuple->datname),
									 0, NULL);
2111 2112

		/*
2113
		 * Generate new ACL.
2114
		 */
2115 2116 2117
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
2118
									   grantorId, ownerId);
2119

2120 2121 2122 2123
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2124 2125
		nnewmembers = aclmembers(new_acl, &newmembers);

2126 2127
		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
2128 2129
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));
2130

2131
		replaces[Anum_pg_database_datacl - 1] = true;
2132 2133
		values[Anum_pg_database_datacl - 1] = PointerGetDatum(new_acl);

2134 2135
		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);
2136 2137 2138

		simple_heap_update(relation, &newtuple->t_self, newtuple);

2139 2140
		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);
2141

2142
		/* Update the shared dependency ACL info */
2143
		updateAclDependencies(DatabaseRelationId, HeapTupleGetOid(tuple), 0,
2144
							  ownerId,
2145 2146 2147
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

2148
		ReleaseSysCache(tuple);
2149

2150
		pfree(new_acl);
2151 2152 2153

		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
2154
	}
2155 2156

	heap_close(relation, RowExclusiveLock);
2157
}
2158

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191
static void
ExecGrant_Fdw(InternalGrant *istmt)
{
	Relation	relation;
	ListCell   *cell;

	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_FDW;

	relation = heap_open(ForeignDataWrapperRelationId, RowExclusiveLock);

	foreach(cell, istmt->objects)
	{
		Oid			fdwid = lfirst_oid(cell);
		Form_pg_foreign_data_wrapper pg_fdw_tuple;
		Datum		aclDatum;
		bool		isNull;
		AclMode		avail_goptions;
		AclMode		this_privileges;
		Acl		   *old_acl;
		Acl		   *new_acl;
		Oid			grantorId;
		Oid			ownerId;
		HeapTuple	tuple;
		HeapTuple	newtuple;
		Datum		values[Natts_pg_foreign_data_wrapper];
		bool		nulls[Natts_pg_foreign_data_wrapper];
		bool		replaces[Natts_pg_foreign_data_wrapper];
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;

2192
		tuple = SearchSysCache1(FOREIGNDATAWRAPPEROID,
B
Bruce Momjian 已提交
2193
								ObjectIdGetDatum(fdwid));
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "cache lookup failed for foreign-data wrapper %u", fdwid);

		pg_fdw_tuple = (Form_pg_foreign_data_wrapper) GETSTRUCT(tuple);

		/*
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
		 */
		ownerId = pg_fdw_tuple->fdwowner;
		aclDatum = SysCacheGetAttr(FOREIGNDATAWRAPPEROID, tuple,
								   Anum_pg_foreign_data_wrapper_fdwacl,
								   &isNull);
		if (isNull)
2208
		{
2209
			old_acl = acldefault(ACL_OBJECT_FDW, ownerId);
2210 2211 2212 2213
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2214
		else
2215
		{
2216
			old_acl = DatumGetAclPCopy(aclDatum);
2217 2218 2219
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233

		/* Determine ID to do the grant as, and available grant options */
		select_best_grantor(GetUserId(), istmt->privileges,
							old_acl, ownerId,
							&grantorId, &avail_goptions);

		/*
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
		 */
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 fdwid, grantorId, ACL_KIND_FDW,
2234 2235
									 NameStr(pg_fdw_tuple->fdwname),
									 0, NULL);
2236 2237 2238 2239 2240 2241 2242 2243 2244

		/*
		 * Generate new ACL.
		 */
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
									   grantorId, ownerId);

2245 2246 2247 2248
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267
		nnewmembers = aclmembers(new_acl, &newmembers);

		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));

		replaces[Anum_pg_foreign_data_wrapper_fdwacl - 1] = true;
		values[Anum_pg_foreign_data_wrapper_fdwacl - 1] = PointerGetDatum(new_acl);

		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);

		simple_heap_update(relation, &newtuple->t_self, newtuple);

		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);

		/* Update the shared dependency ACL info */
2268 2269
		updateAclDependencies(ForeignDataWrapperRelationId,
							  HeapTupleGetOid(tuple), 0,
2270
							  ownerId,
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		ReleaseSysCache(tuple);

		pfree(new_acl);

		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
	}

	heap_close(relation, RowExclusiveLock);
}

2285 2286
static void
ExecGrant_ForeignServer(InternalGrant *istmt)
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
{
	Relation	relation;
	ListCell   *cell;

	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_FOREIGN_SERVER;

	relation = heap_open(ForeignServerRelationId, RowExclusiveLock);

	foreach(cell, istmt->objects)
	{
		Oid			srvid = lfirst_oid(cell);
		Form_pg_foreign_server pg_server_tuple;
		Datum		aclDatum;
		bool		isNull;
		AclMode		avail_goptions;
		AclMode		this_privileges;
		Acl		   *old_acl;
		Acl		   *new_acl;
		Oid			grantorId;
		Oid			ownerId;
		HeapTuple	tuple;
		HeapTuple	newtuple;
		Datum		values[Natts_pg_foreign_server];
		bool		nulls[Natts_pg_foreign_server];
		bool		replaces[Natts_pg_foreign_server];
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;

2318
		tuple = SearchSysCache1(FOREIGNSERVEROID, ObjectIdGetDatum(srvid));
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "cache lookup failed for foreign server %u", srvid);

		pg_server_tuple = (Form_pg_foreign_server) GETSTRUCT(tuple);

		/*
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
		 */
		ownerId = pg_server_tuple->srvowner;
		aclDatum = SysCacheGetAttr(FOREIGNSERVEROID, tuple,
								   Anum_pg_foreign_server_srvacl,
								   &isNull);
		if (isNull)
2333
		{
2334
			old_acl = acldefault(ACL_OBJECT_FOREIGN_SERVER, ownerId);
2335 2336 2337 2338
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2339
		else
2340
		{
2341
			old_acl = DatumGetAclPCopy(aclDatum);
2342 2343 2344
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357

		/* Determine ID to do the grant as, and available grant options */
		select_best_grantor(GetUserId(), istmt->privileges,
							old_acl, ownerId,
							&grantorId, &avail_goptions);

		/*
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
		 */
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
2358
								   srvid, grantorId, ACL_KIND_FOREIGN_SERVER,
2359 2360
									 NameStr(pg_server_tuple->srvname),
									 0, NULL);
2361 2362 2363 2364 2365 2366 2367 2368 2369

		/*
		 * Generate new ACL.
		 */
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
									   grantorId, ownerId);

2370 2371 2372 2373
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
		nnewmembers = aclmembers(new_acl, &newmembers);

		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));

		replaces[Anum_pg_foreign_server_srvacl - 1] = true;
		values[Anum_pg_foreign_server_srvacl - 1] = PointerGetDatum(new_acl);

		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);

		simple_heap_update(relation, &newtuple->t_self, newtuple);

		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);

		/* Update the shared dependency ACL info */
2393 2394
		updateAclDependencies(ForeignServerRelationId,
							  HeapTupleGetOid(tuple), 0,
2395
							  ownerId,
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		ReleaseSysCache(tuple);

		pfree(new_acl);

		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
	}

	heap_close(relation, RowExclusiveLock);
}

2410
static void
2411
ExecGrant_Function(InternalGrant *istmt)
2412
{
2413 2414
	Relation	relation;
	ListCell   *cell;
2415

2416 2417
	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_FUNCTION;
2418

2419
	relation = heap_open(ProcedureRelationId, RowExclusiveLock);
2420

2421
	foreach(cell, istmt->objects)
2422
	{
2423
		Oid			funcId = lfirst_oid(cell);
2424 2425 2426
		Form_pg_proc pg_proc_tuple;
		Datum		aclDatum;
		bool		isNull;
2427
		AclMode		avail_goptions;
2428
		AclMode		this_privileges;
2429 2430
		Acl		   *old_acl;
		Acl		   *new_acl;
B
Bruce Momjian 已提交
2431 2432
		Oid			grantorId;
		Oid			ownerId;
2433
		HeapTuple	tuple;
2434 2435
		HeapTuple	newtuple;
		Datum		values[Natts_pg_proc];
2436 2437
		bool		nulls[Natts_pg_proc];
		bool		replaces[Natts_pg_proc];
2438 2439 2440 2441
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
2442

2443
		tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcId));
2444
		if (!HeapTupleIsValid(tuple))
2445 2446
			elog(ERROR, "cache lookup failed for function %u", funcId);

2447 2448
		pg_proc_tuple = (Form_pg_proc) GETSTRUCT(tuple);

2449
		/*
B
Bruce Momjian 已提交
2450 2451
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
2452
		 */
2453
		ownerId = pg_proc_tuple->proowner;
2454 2455 2456
		aclDatum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proacl,
								   &isNull);
		if (isNull)
2457
		{
2458
			old_acl = acldefault(ACL_OBJECT_FUNCTION, ownerId);
2459 2460 2461 2462
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2463
		else
2464
		{
2465
			old_acl = DatumGetAclPCopy(aclDatum);
2466 2467 2468
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2469 2470

		/* Determine ID to do the grant as, and available grant options */
2471
		select_best_grantor(GetUserId(), istmt->privileges,
2472 2473
							old_acl, ownerId,
							&grantorId, &avail_goptions);
2474

2475
		/*
B
Bruce Momjian 已提交
2476 2477
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
2478
		 */
2479 2480 2481 2482
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 funcId, grantorId, ACL_KIND_PROC,
2483 2484
									 NameStr(pg_proc_tuple->proname),
									 0, NULL);
2485 2486

		/*
2487
		 * Generate new ACL.
2488
		 */
2489 2490 2491
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
2492
									   grantorId, ownerId);
2493

2494 2495 2496 2497
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2498 2499
		nnewmembers = aclmembers(new_acl, &newmembers);

2500
		/* finished building new ACL value, now insert it */
2501
		MemSet(values, 0, sizeof(values));
2502 2503
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));
2504

2505
		replaces[Anum_pg_proc_proacl - 1] = true;
2506
		values[Anum_pg_proc_proacl - 1] = PointerGetDatum(new_acl);
2507

2508 2509
		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);
2510 2511 2512

		simple_heap_update(relation, &newtuple->t_self, newtuple);

2513 2514
		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);
2515

2516
		/* Update the shared dependency ACL info */
2517
		updateAclDependencies(ProcedureRelationId, funcId, 0,
2518
							  ownerId,
2519 2520 2521 2522 2523
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		ReleaseSysCache(tuple);

2524 2525
		pfree(new_acl);

2526 2527
		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
2528
	}
2529 2530

	heap_close(relation, RowExclusiveLock);
2531 2532 2533
}

static void
2534
ExecGrant_Language(InternalGrant *istmt)
2535
{
2536 2537
	Relation	relation;
	ListCell   *cell;
2538

2539 2540
	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_LANGUAGE;
2541

2542
	relation = heap_open(LanguageRelationId, RowExclusiveLock);
2543

2544
	foreach(cell, istmt->objects)
2545
	{
2546
		Oid			langId = lfirst_oid(cell);
2547 2548 2549
		Form_pg_language pg_language_tuple;
		Datum		aclDatum;
		bool		isNull;
2550
		AclMode		avail_goptions;
2551
		AclMode		this_privileges;
2552 2553
		Acl		   *old_acl;
		Acl		   *new_acl;
B
Bruce Momjian 已提交
2554 2555
		Oid			grantorId;
		Oid			ownerId;
2556
		HeapTuple	tuple;
2557 2558
		HeapTuple	newtuple;
		Datum		values[Natts_pg_language];
2559 2560
		bool		nulls[Natts_pg_language];
		bool		replaces[Natts_pg_language];
2561 2562 2563 2564
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
2565

2566
		tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(langId));
2567
		if (!HeapTupleIsValid(tuple))
2568
			elog(ERROR, "cache lookup failed for language %u", langId);
2569

2570 2571
		pg_language_tuple = (Form_pg_language) GETSTRUCT(tuple);

2572 2573 2574
		if (!pg_language_tuple->lanpltrusted)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
2575 2576
					 errmsg("language \"%s\" is not trusted",
							NameStr(pg_language_tuple->lanname)),
2577
				   errhint("Only superusers can use untrusted languages.")));
2578

2579
		/*
B
Bruce Momjian 已提交
2580 2581
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
2582
		 */
2583
		ownerId = pg_language_tuple->lanowner;
2584 2585 2586
		aclDatum = SysCacheGetAttr(LANGNAME, tuple, Anum_pg_language_lanacl,
								   &isNull);
		if (isNull)
2587
		{
2588
			old_acl = acldefault(ACL_OBJECT_LANGUAGE, ownerId);
2589 2590 2591 2592
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2593
		else
2594
		{
2595
			old_acl = DatumGetAclPCopy(aclDatum);
2596 2597 2598
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2599 2600

		/* Determine ID to do the grant as, and available grant options */
2601
		select_best_grantor(GetUserId(), istmt->privileges,
2602 2603
							old_acl, ownerId,
							&grantorId, &avail_goptions);
2604

2605
		/*
B
Bruce Momjian 已提交
2606 2607
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
2608
		 */
2609 2610 2611 2612
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 langId, grantorId, ACL_KIND_LANGUAGE,
2613 2614
									 NameStr(pg_language_tuple->lanname),
									 0, NULL);
2615

2616
		/*
2617
		 * Generate new ACL.
2618
		 */
2619 2620 2621
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
2622
									   grantorId, ownerId);
2623

2624 2625 2626 2627
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2628 2629
		nnewmembers = aclmembers(new_acl, &newmembers);

2630
		/* finished building new ACL value, now insert it */
2631
		MemSet(values, 0, sizeof(values));
2632 2633
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));
2634

2635
		replaces[Anum_pg_language_lanacl - 1] = true;
2636
		values[Anum_pg_language_lanacl - 1] = PointerGetDatum(new_acl);
2637

2638 2639
		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);
2640 2641 2642

		simple_heap_update(relation, &newtuple->t_self, newtuple);

2643 2644
		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);
2645

2646
		/* Update the shared dependency ACL info */
2647
		updateAclDependencies(LanguageRelationId, HeapTupleGetOid(tuple), 0,
2648
							  ownerId,
2649 2650 2651 2652 2653
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		ReleaseSysCache(tuple);

2654 2655
		pfree(new_acl);

2656 2657
		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
2658
	}
2659 2660

	heap_close(relation, RowExclusiveLock);
2661 2662
}

2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
static void
ExecGrant_Largeobject(InternalGrant *istmt)
{
	Relation	relation;
	ListCell   *cell;

	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_LARGEOBJECT;

	relation = heap_open(LargeObjectMetadataRelationId,
						 RowExclusiveLock);

	foreach(cell, istmt->objects)
	{
		Oid			loid = lfirst_oid(cell);
B
Bruce Momjian 已提交
2678
		Form_pg_largeobject_metadata form_lo_meta;
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
		char		loname[NAMEDATALEN];
		Datum		aclDatum;
		bool		isNull;
		AclMode		avail_goptions;
		AclMode		this_privileges;
		Acl		   *old_acl;
		Acl		   *new_acl;
		Oid			grantorId;
		Oid			ownerId;
		HeapTuple	newtuple;
		Datum		values[Natts_pg_largeobject_metadata];
		bool		nulls[Natts_pg_largeobject_metadata];
		bool		replaces[Natts_pg_largeobject_metadata];
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
B
Bruce Momjian 已提交
2696 2697
		ScanKeyData entry[1];
		SysScanDesc scan;
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
		HeapTuple	tuple;

		/* There's no syscache for pg_largeobject_metadata */
		ScanKeyInit(&entry[0],
					ObjectIdAttributeNumber,
					BTEqualStrategyNumber, F_OIDEQ,
					ObjectIdGetDatum(loid));

		scan = systable_beginscan(relation,
								  LargeObjectMetadataOidIndexId, true,
								  SnapshotNow, 1, entry);

		tuple = systable_getnext(scan);
		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "cache lookup failed for large object %u", loid);

		form_lo_meta = (Form_pg_largeobject_metadata) GETSTRUCT(tuple);

		/*
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
		 */
		ownerId = form_lo_meta->lomowner;
		aclDatum = heap_getattr(tuple,
								Anum_pg_largeobject_metadata_lomacl,
								RelationGetDescr(relation), &isNull);
		if (isNull)
2725
		{
2726
			old_acl = acldefault(ACL_OBJECT_LARGEOBJECT, ownerId);
2727 2728 2729 2730
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2731
		else
2732
		{
2733
			old_acl = DatumGetAclPCopy(aclDatum);
2734 2735 2736
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761

		/* Determine ID to do the grant as, and available grant options */
		select_best_grantor(GetUserId(), istmt->privileges,
							old_acl, ownerId,
							&grantorId, &avail_goptions);

		/*
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
		 */
		snprintf(loname, sizeof(loname), "large object %u", loid);
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 loid, grantorId, ACL_KIND_LARGEOBJECT,
									 loname, 0, NULL);

		/*
		 * Generate new ACL.
		 */
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
									   grantorId, ownerId);

2762 2763 2764 2765
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
		nnewmembers = aclmembers(new_acl, &newmembers);

		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));

		replaces[Anum_pg_largeobject_metadata_lomacl - 1] = true;
		values[Anum_pg_largeobject_metadata_lomacl - 1]
			= PointerGetDatum(new_acl);

		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation),
									 values, nulls, replaces);

		simple_heap_update(relation, &newtuple->t_self, newtuple);

		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);

		/* Update the shared dependency ACL info */
		updateAclDependencies(LargeObjectRelationId,
							  HeapTupleGetOid(tuple), 0,
2788
							  ownerId,
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		systable_endscan(scan);

		pfree(new_acl);

		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
	}

	heap_close(relation, RowExclusiveLock);
}

2803
static void
2804
ExecGrant_Namespace(InternalGrant *istmt)
2805
{
2806 2807
	Relation	relation;
	ListCell   *cell;
2808

2809 2810
	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_NAMESPACE;
2811

2812
	relation = heap_open(NamespaceRelationId, RowExclusiveLock);
2813

2814
	foreach(cell, istmt->objects)
2815
	{
2816
		Oid			nspid = lfirst_oid(cell);
2817 2818 2819
		Form_pg_namespace pg_namespace_tuple;
		Datum		aclDatum;
		bool		isNull;
2820
		AclMode		avail_goptions;
2821
		AclMode		this_privileges;
2822 2823
		Acl		   *old_acl;
		Acl		   *new_acl;
B
Bruce Momjian 已提交
2824 2825
		Oid			grantorId;
		Oid			ownerId;
2826
		HeapTuple	tuple;
2827 2828
		HeapTuple	newtuple;
		Datum		values[Natts_pg_namespace];
2829 2830
		bool		nulls[Natts_pg_namespace];
		bool		replaces[Natts_pg_namespace];
2831 2832 2833 2834
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
2835

2836
		tuple = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nspid));
2837
		if (!HeapTupleIsValid(tuple))
2838 2839
			elog(ERROR, "cache lookup failed for namespace %u", nspid);

2840 2841
		pg_namespace_tuple = (Form_pg_namespace) GETSTRUCT(tuple);

2842
		/*
B
Bruce Momjian 已提交
2843 2844
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
2845
		 */
2846
		ownerId = pg_namespace_tuple->nspowner;
2847 2848 2849 2850
		aclDatum = SysCacheGetAttr(NAMESPACENAME, tuple,
								   Anum_pg_namespace_nspacl,
								   &isNull);
		if (isNull)
2851
		{
2852
			old_acl = acldefault(ACL_OBJECT_NAMESPACE, ownerId);
2853 2854 2855 2856
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2857
		else
2858
		{
2859
			old_acl = DatumGetAclPCopy(aclDatum);
2860 2861 2862
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2863 2864

		/* Determine ID to do the grant as, and available grant options */
2865
		select_best_grantor(GetUserId(), istmt->privileges,
2866 2867
							old_acl, ownerId,
							&grantorId, &avail_goptions);
2868

2869
		/*
B
Bruce Momjian 已提交
2870 2871
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
2872
		 */
2873 2874 2875 2876
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 nspid, grantorId, ACL_KIND_NAMESPACE,
2877 2878
									 NameStr(pg_namespace_tuple->nspname),
									 0, NULL);
2879 2880

		/*
2881
		 * Generate new ACL.
2882
		 */
2883 2884 2885
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
2886
									   grantorId, ownerId);
2887

2888 2889 2890 2891
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
2892 2893
		nnewmembers = aclmembers(new_acl, &newmembers);

2894 2895
		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
2896 2897
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));
2898

2899
		replaces[Anum_pg_namespace_nspacl - 1] = true;
2900 2901
		values[Anum_pg_namespace_nspacl - 1] = PointerGetDatum(new_acl);

2902 2903
		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);
2904 2905 2906

		simple_heap_update(relation, &newtuple->t_self, newtuple);

2907 2908
		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);
2909

2910
		/* Update the shared dependency ACL info */
2911
		updateAclDependencies(NamespaceRelationId, HeapTupleGetOid(tuple), 0,
2912
							  ownerId,
2913 2914 2915 2916 2917
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		ReleaseSysCache(tuple);

2918 2919
		pfree(new_acl);

2920 2921
		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
2922
	}
2923 2924

	heap_close(relation, RowExclusiveLock);
2925 2926
}

2927
static void
2928
ExecGrant_Tablespace(InternalGrant *istmt)
2929
{
2930 2931
	Relation	relation;
	ListCell   *cell;
2932

2933 2934
	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_TABLESPACE;
2935

2936
	relation = heap_open(TableSpaceRelationId, RowExclusiveLock);
2937

2938
	foreach(cell, istmt->objects)
2939
	{
2940
		Oid			tblId = lfirst_oid(cell);
2941 2942 2943
		Form_pg_tablespace pg_tablespace_tuple;
		Datum		aclDatum;
		bool		isNull;
2944
		AclMode		avail_goptions;
2945 2946 2947
		AclMode		this_privileges;
		Acl		   *old_acl;
		Acl		   *new_acl;
B
Bruce Momjian 已提交
2948 2949
		Oid			grantorId;
		Oid			ownerId;
2950 2951
		HeapTuple	newtuple;
		Datum		values[Natts_pg_tablespace];
2952 2953
		bool		nulls[Natts_pg_tablespace];
		bool		replaces[Natts_pg_tablespace];
2954 2955 2956 2957
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
2958
		HeapTuple	tuple;
2959

2960
		/* Search syscache for pg_tablespace */
2961
		tuple = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(tblId));
2962
		if (!HeapTupleIsValid(tuple))
2963 2964
			elog(ERROR, "cache lookup failed for tablespace %u", tblId);

2965 2966
		pg_tablespace_tuple = (Form_pg_tablespace) GETSTRUCT(tuple);

2967
		/*
B
Bruce Momjian 已提交
2968 2969
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
2970
		 */
2971
		ownerId = pg_tablespace_tuple->spcowner;
2972 2973 2974
		aclDatum = heap_getattr(tuple, Anum_pg_tablespace_spcacl,
								RelationGetDescr(relation), &isNull);
		if (isNull)
2975
		{
2976
			old_acl = acldefault(ACL_OBJECT_TABLESPACE, ownerId);
2977 2978 2979 2980
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
2981
		else
2982
		{
2983
			old_acl = DatumGetAclPCopy(aclDatum);
2984 2985 2986
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}
2987 2988

		/* Determine ID to do the grant as, and available grant options */
2989
		select_best_grantor(GetUserId(), istmt->privileges,
2990 2991
							old_acl, ownerId,
							&grantorId, &avail_goptions);
2992 2993

		/*
B
Bruce Momjian 已提交
2994 2995
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
2996
		 */
2997 2998 2999 3000
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 tblId, grantorId, ACL_KIND_TABLESPACE,
3001 3002
									 NameStr(pg_tablespace_tuple->spcname),
									 0, NULL);
3003 3004

		/*
3005
		 * Generate new ACL.
3006
		 */
3007 3008 3009
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
3010 3011
									   grantorId, ownerId);

3012 3013 3014 3015
		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
3016 3017
		nnewmembers = aclmembers(new_acl, &newmembers);

3018 3019
		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
3020 3021
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));
3022

3023
		replaces[Anum_pg_tablespace_spcacl - 1] = true;
3024 3025
		values[Anum_pg_tablespace_spcacl - 1] = PointerGetDatum(new_acl);

3026 3027
		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);
3028 3029 3030 3031 3032 3033

		simple_heap_update(relation, &newtuple->t_self, newtuple);

		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);

3034
		/* Update the shared dependency ACL info */
3035
		updateAclDependencies(TableSpaceRelationId, tblId, 0,
3036
							  ownerId,
3037 3038 3039
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

3040
		ReleaseSysCache(tuple);
3041
		pfree(new_acl);
3042 3043 3044

		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
3045
	}
3046 3047

	heap_close(relation, RowExclusiveLock);
3048 3049
}

3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
static void
ExecGrant_Type(InternalGrant *istmt)
{
	Relation	relation;
	ListCell   *cell;

	if (istmt->all_privs && istmt->privileges == ACL_NO_RIGHTS)
		istmt->privileges = ACL_ALL_RIGHTS_TYPE;

	relation = heap_open(TypeRelationId, RowExclusiveLock);

	foreach(cell, istmt->objects)
	{
		Oid			typId = lfirst_oid(cell);
		Form_pg_type pg_type_tuple;
		Datum		aclDatum;
		bool		isNull;
		AclMode		avail_goptions;
		AclMode		this_privileges;
		Acl		   *old_acl;
		Acl		   *new_acl;
		Oid			grantorId;
		Oid			ownerId;
		HeapTuple	newtuple;
		Datum		values[Natts_pg_type];
		bool		nulls[Natts_pg_type];
		bool		replaces[Natts_pg_type];
		int			noldmembers;
		int			nnewmembers;
		Oid		   *oldmembers;
		Oid		   *newmembers;
		HeapTuple	tuple;

		/* Search syscache for pg_type */
		tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typId));
		if (!HeapTupleIsValid(tuple))
			elog(ERROR, "cache lookup failed for type %u", typId);

		pg_type_tuple = (Form_pg_type) GETSTRUCT(tuple);

		if (pg_type_tuple->typelem != 0 && pg_type_tuple->typlen == -1)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_GRANT_OPERATION),
					 errmsg("cannot set privileges of array types"),
3094
				errhint("Set the privileges of the element type instead.")));
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186

		/* Used GRANT DOMAIN on a non-domain? */
		if (istmt->objtype == ACL_OBJECT_DOMAIN &&
			pg_type_tuple->typtype != TYPTYPE_DOMAIN)
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("\"%s\" is not a domain",
							NameStr(pg_type_tuple->typname))));

		/*
		 * Get owner ID and working copy of existing ACL. If there's no ACL,
		 * substitute the proper default.
		 */
		ownerId = pg_type_tuple->typowner;
		aclDatum = heap_getattr(tuple, Anum_pg_type_typacl,
								RelationGetDescr(relation), &isNull);
		if (isNull)
		{
			old_acl = acldefault(istmt->objtype, ownerId);
			/* There are no old member roles according to the catalogs */
			noldmembers = 0;
			oldmembers = NULL;
		}
		else
		{
			old_acl = DatumGetAclPCopy(aclDatum);
			/* Get the roles mentioned in the existing ACL */
			noldmembers = aclmembers(old_acl, &oldmembers);
		}

		/* Determine ID to do the grant as, and available grant options */
		select_best_grantor(GetUserId(), istmt->privileges,
							old_acl, ownerId,
							&grantorId, &avail_goptions);

		/*
		 * Restrict the privileges to what we can actually grant, and emit the
		 * standards-mandated warning and error messages.
		 */
		this_privileges =
			restrict_and_check_grant(istmt->is_grant, avail_goptions,
									 istmt->all_privs, istmt->privileges,
									 typId, grantorId, ACL_KIND_TYPE,
									 NameStr(pg_type_tuple->typname),
									 0, NULL);

		/*
		 * Generate new ACL.
		 */
		new_acl = merge_acl_with_grant(old_acl, istmt->is_grant,
									   istmt->grant_option, istmt->behavior,
									   istmt->grantees, this_privileges,
									   grantorId, ownerId);

		/*
		 * We need the members of both old and new ACLs so we can correct the
		 * shared dependency information.
		 */
		nnewmembers = aclmembers(new_acl, &newmembers);

		/* finished building new ACL value, now insert it */
		MemSet(values, 0, sizeof(values));
		MemSet(nulls, false, sizeof(nulls));
		MemSet(replaces, false, sizeof(replaces));

		replaces[Anum_pg_type_typacl - 1] = true;
		values[Anum_pg_type_typacl - 1] = PointerGetDatum(new_acl);

		newtuple = heap_modify_tuple(tuple, RelationGetDescr(relation), values,
									 nulls, replaces);

		simple_heap_update(relation, &newtuple->t_self, newtuple);

		/* keep the catalog indexes up to date */
		CatalogUpdateIndexes(relation, newtuple);

		/* Update the shared dependency ACL info */
		updateAclDependencies(TypeRelationId, typId, 0,
							  ownerId,
							  noldmembers, oldmembers,
							  nnewmembers, newmembers);

		ReleaseSysCache(tuple);
		pfree(new_acl);

		/* prevent error when processing duplicate objects */
		CommandCounterIncrement();
	}

	heap_close(relation, RowExclusiveLock);
}

3187

3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198
static AclMode
string_to_privilege(const char *privname)
{
	if (strcmp(privname, "insert") == 0)
		return ACL_INSERT;
	if (strcmp(privname, "select") == 0)
		return ACL_SELECT;
	if (strcmp(privname, "update") == 0)
		return ACL_UPDATE;
	if (strcmp(privname, "delete") == 0)
		return ACL_DELETE;
3199 3200
	if (strcmp(privname, "truncate") == 0)
		return ACL_TRUNCATE;
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
	if (strcmp(privname, "references") == 0)
		return ACL_REFERENCES;
	if (strcmp(privname, "trigger") == 0)
		return ACL_TRIGGER;
	if (strcmp(privname, "execute") == 0)
		return ACL_EXECUTE;
	if (strcmp(privname, "usage") == 0)
		return ACL_USAGE;
	if (strcmp(privname, "create") == 0)
		return ACL_CREATE;
	if (strcmp(privname, "temporary") == 0)
		return ACL_CREATE_TEMP;
	if (strcmp(privname, "temp") == 0)
		return ACL_CREATE_TEMP;
3215
	if (strcmp(privname, "connect") == 0)
3216
		return ACL_CONNECT;
3217 3218
	if (strcmp(privname, "rule") == 0)
		return 0;				/* ignore old RULE privileges */
3219 3220 3221 3222 3223 3224
	ereport(ERROR,
			(errcode(ERRCODE_SYNTAX_ERROR),
			 errmsg("unrecognized privilege type \"%s\"", privname)));
	return 0;					/* appease compiler */
}

3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
static const char *
privilege_to_string(AclMode privilege)
{
	switch (privilege)
	{
		case ACL_INSERT:
			return "INSERT";
		case ACL_SELECT:
			return "SELECT";
		case ACL_UPDATE:
			return "UPDATE";
		case ACL_DELETE:
			return "DELETE";
3238 3239
		case ACL_TRUNCATE:
			return "TRUNCATE";
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
		case ACL_REFERENCES:
			return "REFERENCES";
		case ACL_TRIGGER:
			return "TRIGGER";
		case ACL_EXECUTE:
			return "EXECUTE";
		case ACL_USAGE:
			return "USAGE";
		case ACL_CREATE:
			return "CREATE";
		case ACL_CREATE_TEMP:
			return "TEMP";
3252
		case ACL_CONNECT:
3253
			return "CONNECT";
3254
		default:
3255
			elog(ERROR, "unrecognized privilege: %d", (int) privilege);
3256 3257 3258 3259
	}
	return NULL;				/* appease compiler */
}

3260 3261
/*
 * Standardized reporting of aclcheck permissions failures.
3262 3263 3264
 *
 * Note: we do not double-quote the %s's below, because many callers
 * supply strings that might be already quoted.
3265
 */
3266

B
Bruce Momjian 已提交
3267
static const char *const no_priv_msg[MAX_ACL_KIND] =
3268
{
3269 3270
	/* ACL_KIND_COLUMN */
	gettext_noop("permission denied for column %s"),
3271 3272
	/* ACL_KIND_CLASS */
	gettext_noop("permission denied for relation %s"),
3273 3274
	/* ACL_KIND_SEQUENCE */
	gettext_noop("permission denied for sequence %s"),
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284
	/* ACL_KIND_DATABASE */
	gettext_noop("permission denied for database %s"),
	/* ACL_KIND_PROC */
	gettext_noop("permission denied for function %s"),
	/* ACL_KIND_OPER */
	gettext_noop("permission denied for operator %s"),
	/* ACL_KIND_TYPE */
	gettext_noop("permission denied for type %s"),
	/* ACL_KIND_LANGUAGE */
	gettext_noop("permission denied for language %s"),
3285 3286
	/* ACL_KIND_LARGEOBJECT */
	gettext_noop("permission denied for large object %s"),
3287 3288 3289 3290
	/* ACL_KIND_NAMESPACE */
	gettext_noop("permission denied for schema %s"),
	/* ACL_KIND_OPCLASS */
	gettext_noop("permission denied for operator class %s"),
3291 3292
	/* ACL_KIND_OPFAMILY */
	gettext_noop("permission denied for operator family %s"),
P
Peter Eisentraut 已提交
3293 3294
	/* ACL_KIND_COLLATION */
	gettext_noop("permission denied for collation %s"),
3295
	/* ACL_KIND_CONVERSION */
3296 3297
	gettext_noop("permission denied for conversion %s"),
	/* ACL_KIND_TABLESPACE */
3298 3299 3300 3301
	gettext_noop("permission denied for tablespace %s"),
	/* ACL_KIND_TSDICTIONARY */
	gettext_noop("permission denied for text search dictionary %s"),
	/* ACL_KIND_TSCONFIGURATION */
3302 3303 3304 3305
	gettext_noop("permission denied for text search configuration %s"),
	/* ACL_KIND_FDW */
	gettext_noop("permission denied for foreign-data wrapper %s"),
	/* ACL_KIND_FOREIGN_SERVER */
R
Robert Haas 已提交
3306
	gettext_noop("permission denied for foreign server %s"),
3307 3308
	/* ACL_KIND_EVENT_TRIGGER */
	gettext_noop("permission denied for event trigger %s"),
3309 3310
	/* ACL_KIND_EXTENSION */
	gettext_noop("permission denied for extension %s"),
3311 3312
};

B
Bruce Momjian 已提交
3313
static const char *const not_owner_msg[MAX_ACL_KIND] =
3314
{
3315 3316
	/* ACL_KIND_COLUMN */
	gettext_noop("must be owner of relation %s"),
3317 3318
	/* ACL_KIND_CLASS */
	gettext_noop("must be owner of relation %s"),
3319 3320
	/* ACL_KIND_SEQUENCE */
	gettext_noop("must be owner of sequence %s"),
3321 3322 3323 3324 3325 3326 3327 3328 3329 3330
	/* ACL_KIND_DATABASE */
	gettext_noop("must be owner of database %s"),
	/* ACL_KIND_PROC */
	gettext_noop("must be owner of function %s"),
	/* ACL_KIND_OPER */
	gettext_noop("must be owner of operator %s"),
	/* ACL_KIND_TYPE */
	gettext_noop("must be owner of type %s"),
	/* ACL_KIND_LANGUAGE */
	gettext_noop("must be owner of language %s"),
3331 3332
	/* ACL_KIND_LARGEOBJECT */
	gettext_noop("must be owner of large object %s"),
3333 3334 3335 3336
	/* ACL_KIND_NAMESPACE */
	gettext_noop("must be owner of schema %s"),
	/* ACL_KIND_OPCLASS */
	gettext_noop("must be owner of operator class %s"),
3337 3338
	/* ACL_KIND_OPFAMILY */
	gettext_noop("must be owner of operator family %s"),
P
Peter Eisentraut 已提交
3339 3340
	/* ACL_KIND_COLLATION */
	gettext_noop("must be owner of collation %s"),
3341
	/* ACL_KIND_CONVERSION */
3342 3343
	gettext_noop("must be owner of conversion %s"),
	/* ACL_KIND_TABLESPACE */
3344 3345 3346 3347
	gettext_noop("must be owner of tablespace %s"),
	/* ACL_KIND_TSDICTIONARY */
	gettext_noop("must be owner of text search dictionary %s"),
	/* ACL_KIND_TSCONFIGURATION */
3348 3349 3350 3351
	gettext_noop("must be owner of text search configuration %s"),
	/* ACL_KIND_FDW */
	gettext_noop("must be owner of foreign-data wrapper %s"),
	/* ACL_KIND_FOREIGN_SERVER */
R
Robert Haas 已提交
3352
	gettext_noop("must be owner of foreign server %s"),
3353 3354
	/* ACL_KIND_EVENT_TRIGGER */
	gettext_noop("must be owner of event trigger %s"),
3355 3356
	/* ACL_KIND_EXTENSION */
	gettext_noop("must be owner of extension %s"),
3357 3358 3359
};


3360
void
3361 3362
aclcheck_error(AclResult aclerr, AclObjectKind objectkind,
			   const char *objectname)
3363
{
3364
	switch (aclerr)
3365 3366 3367 3368 3369
	{
		case ACLCHECK_OK:
			/* no error, so return to caller */
			break;
		case ACLCHECK_NO_PRIV:
3370 3371
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3372
					 errmsg(no_priv_msg[objectkind], objectname)));
3373 3374
			break;
		case ACLCHECK_NOT_OWNER:
3375 3376
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
3377
					 errmsg(not_owner_msg[objectkind], objectname)));
3378 3379
			break;
		default:
3380
			elog(ERROR, "unrecognized AclResult: %d", (int) aclerr);
3381 3382 3383 3384 3385
			break;
	}
}


3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
void
aclcheck_error_col(AclResult aclerr, AclObjectKind objectkind,
				   const char *objectname, const char *colname)
{
	switch (aclerr)
	{
		case ACLCHECK_OK:
			/* no error, so return to caller */
			break;
		case ACLCHECK_NO_PRIV:
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
B
Bruce Momjian 已提交
3398 3399
			 errmsg("permission denied for column \"%s\" of relation \"%s\"",
					colname, objectname)));
3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
			break;
		case ACLCHECK_NOT_OWNER:
			/* relation msg is OK since columns don't have separate owners */
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg(not_owner_msg[objectkind], objectname)));
			break;
		default:
			elog(ERROR, "unrecognized AclResult: %d", (int) aclerr);
			break;
	}
}


3414 3415 3416 3417 3418 3419 3420
/*
 * Special common handling for types: use element type instead of array type,
 * and format nicely
 */
void
aclcheck_error_type(AclResult aclerr, Oid typeOid)
{
B
Bruce Momjian 已提交
3421
	Oid			element_type = get_element_type(typeOid);
3422 3423 3424 3425 3426

	aclcheck_error(aclerr, ACL_KIND_TYPE, format_type_be(element_type ? element_type : typeOid));
}


3427
/* Check if given user has rolcatupdate privilege according to pg_authid */
3428
static bool
3429
has_rolcatupdate(Oid roleid)
3430
{
3431
	bool		rolcatupdate;
3432 3433
	HeapTuple	tuple;

3434
	tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
3435 3436 3437
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
3438
				 errmsg("role with OID %u does not exist", roleid)));
3439

3440
	rolcatupdate = ((Form_pg_authid) GETSTRUCT(tuple))->rolcatupdate;
3441 3442 3443

	ReleaseSysCache(tuple);

3444
	return rolcatupdate;
3445 3446
}

3447 3448 3449 3450
/*
 * Relay for the various pg_*_mask routines depending on object kind
 */
static AclMode
3451
pg_aclmask(AclObjectKind objkind, Oid table_oid, AttrNumber attnum, Oid roleid,
3452 3453 3454 3455
		   AclMode mask, AclMaskHow how)
{
	switch (objkind)
	{
3456 3457 3458 3459
		case ACL_KIND_COLUMN:
			return
				pg_class_aclmask(table_oid, roleid, mask, how) |
				pg_attribute_aclmask(table_oid, attnum, roleid, mask, how);
3460
		case ACL_KIND_CLASS:
3461
		case ACL_KIND_SEQUENCE:
3462 3463 3464 3465 3466 3467 3468
			return pg_class_aclmask(table_oid, roleid, mask, how);
		case ACL_KIND_DATABASE:
			return pg_database_aclmask(table_oid, roleid, mask, how);
		case ACL_KIND_PROC:
			return pg_proc_aclmask(table_oid, roleid, mask, how);
		case ACL_KIND_LANGUAGE:
			return pg_language_aclmask(table_oid, roleid, mask, how);
3469 3470 3471
		case ACL_KIND_LARGEOBJECT:
			return pg_largeobject_aclmask_snapshot(table_oid, roleid,
												   mask, how, SnapshotNow);
3472 3473 3474 3475
		case ACL_KIND_NAMESPACE:
			return pg_namespace_aclmask(table_oid, roleid, mask, how);
		case ACL_KIND_TABLESPACE:
			return pg_tablespace_aclmask(table_oid, roleid, mask, how);
3476 3477 3478 3479
		case ACL_KIND_FDW:
			return pg_foreign_data_wrapper_aclmask(table_oid, roleid, mask, how);
		case ACL_KIND_FOREIGN_SERVER:
			return pg_foreign_server_aclmask(table_oid, roleid, mask, how);
3480 3481 3482 3483
		case ACL_KIND_EVENT_TRIGGER:
			elog(ERROR, "grantable rights not supported for event triggers");
			/* not reached, but keep compiler quiet */
			return ACL_NO_RIGHTS;
3484 3485
		case ACL_KIND_TYPE:
			return pg_type_aclmask(table_oid, roleid, mask, how);
3486 3487 3488 3489 3490 3491 3492
		default:
			elog(ERROR, "unrecognized objkind: %d",
				 (int) objkind);
			/* not reached, but keep compiler quiet */
			return ACL_NO_RIGHTS;
	}
}
3493

3494 3495 3496

/* ****************************************************************
 * Exported routines for examining a user's privileges for various objects
3497
 *
3498
 * See aclmask() for a description of the common API for these functions.
3499 3500
 *
 * Note: we give lookup failure the full ereport treatment because the
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510
 * has_xxx_privilege() family of functions allow users to pass any random
 * OID to these functions.
 * ****************************************************************
 */

/*
 * Exported routine for examining a user's privileges for a column
 *
 * Note: this considers only privileges granted specifically on the column.
 * It is caller's responsibility to take relation-level privileges into account
3511
 * as appropriate.	(For the same reason, we have no special case for
3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
 * superuser-ness here.)
 */
AclMode
pg_attribute_aclmask(Oid table_oid, AttrNumber attnum, Oid roleid,
					 AclMode mask, AclMaskHow how)
{
	AclMode		result;
	HeapTuple	classTuple;
	HeapTuple	attTuple;
	Form_pg_class classForm;
	Form_pg_attribute attributeForm;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
	Oid			ownerId;

	/*
3529
	 * First, get the column's ACL from its pg_attribute entry
3530
	 */
3531 3532 3533
	attTuple = SearchSysCache2(ATTNUM,
							   ObjectIdGetDatum(table_oid),
							   Int16GetDatum(attnum));
3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550
	if (!HeapTupleIsValid(attTuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_COLUMN),
				 errmsg("attribute %d of relation with OID %u does not exist",
						attnum, table_oid)));
	attributeForm = (Form_pg_attribute) GETSTRUCT(attTuple);

	/* Throw error on dropped columns, too */
	if (attributeForm->attisdropped)
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_COLUMN),
				 errmsg("attribute %d of relation with OID %u does not exist",
						attnum, table_oid)));

	aclDatum = SysCacheGetAttr(ATTNUM, attTuple, Anum_pg_attribute_attacl,
							   &isNull);

3551
	/*
3552 3553 3554
	 * Here we hard-wire knowledge that the default ACL for a column grants no
	 * privileges, so that we can fall out quickly in the very common case
	 * where attacl is null.
3555
	 */
3556 3557
	if (isNull)
	{
3558 3559
		ReleaseSysCache(attTuple);
		return 0;
3560
	}
3561 3562 3563

	/*
	 * Must get the relation's ownerId from pg_class.  Since we already found
3564 3565 3566 3567 3568
	 * a pg_attribute entry, the only likely reason for this to fail is that a
	 * concurrent DROP of the relation committed since then (which could only
	 * happen if we don't have lock on the relation).  We prefer to report "no
	 * privileges" rather than failing in such a case, so as to avoid unwanted
	 * failures in has_column_privilege() tests.
3569
	 */
3570
	classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3571
	if (!HeapTupleIsValid(classTuple))
3572
	{
3573 3574
		ReleaseSysCache(attTuple);
		return 0;
3575
	}
3576 3577 3578 3579 3580 3581 3582 3583
	classForm = (Form_pg_class) GETSTRUCT(classTuple);

	ownerId = classForm->relowner;

	ReleaseSysCache(classTuple);

	/* detoast column's ACL if necessary */
	acl = DatumGetAclP(aclDatum);
3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597

	result = aclmask(acl, roleid, ownerId, mask, how);

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(attTuple);

	return result;
}

/*
 * Exported routine for examining a user's privileges for a table
3598
 */
3599
AclMode
3600
pg_class_aclmask(Oid table_oid, Oid roleid,
3601
				 AclMode mask, AclMaskHow how)
3602
{
3603
	AclMode		result;
3604
	HeapTuple	tuple;
3605
	Form_pg_class classForm;
3606 3607 3608
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
B
Bruce Momjian 已提交
3609
	Oid			ownerId;
3610

3611
	/*
3612
	 * Must get the relation's tuple from pg_class
3613
	 */
3614
	tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
3615
	if (!HeapTupleIsValid(tuple))
3616 3617
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_TABLE),
3618 3619
				 errmsg("relation with OID %u does not exist",
						table_oid)));
3620
	classForm = (Form_pg_class) GETSTRUCT(tuple);
3621 3622 3623

	/*
	 * Deny anyone permission to update a system catalog unless
3624
	 * pg_authid.rolcatupdate is set.	(This is to let superusers protect
B
Bruce Momjian 已提交
3625
	 * themselves from themselves.)  Also allow it if allowSystemTableMods.
3626
	 *
B
Bruce Momjian 已提交
3627 3628
	 * As of 7.4 we have some updatable system views; those shouldn't be
	 * protected in this way.  Assume the view rules can take care of
B
Bruce Momjian 已提交
3629
	 * themselves.	ACL_USAGE is if we ever have system sequences.
3630
	 */
3631
	if ((mask & (ACL_INSERT | ACL_UPDATE | ACL_DELETE | ACL_TRUNCATE | ACL_USAGE)) &&
3632 3633
		IsSystemClass(classForm) &&
		classForm->relkind != RELKIND_VIEW &&
3634
		!has_rolcatupdate(roleid) &&
3635
		!allowSystemTableMods)
3636
	{
3637
#ifdef ACLDEBUG
3638
		elog(DEBUG2, "permission denied for system catalog update");
3639
#endif
3640
		mask &= ~(ACL_INSERT | ACL_UPDATE | ACL_DELETE | ACL_TRUNCATE | ACL_USAGE);
3641 3642 3643 3644 3645
	}

	/*
	 * Otherwise, superusers bypass all permission-checking.
	 */
3646
	if (superuser_arg(roleid))
3647
	{
3648
#ifdef ACLDEBUG
3649
		elog(DEBUG2, "OID %u is superuser, home free", roleid);
3650
#endif
3651
		ReleaseSysCache(tuple);
3652
		return mask;
3653
	}
3654

3655 3656 3657
	/*
	 * Normal case: get the relation's ACL from pg_class
	 */
3658 3659
	ownerId = classForm->relowner;

3660
	aclDatum = SysCacheGetAttr(RELOID, tuple, Anum_pg_class_relacl,
3661 3662 3663
							   &isNull);
	if (isNull)
	{
3664
		/* No ACL, so build default ACL */
R
Robert Haas 已提交
3665 3666 3667 3668 3669 3670 3671 3672 3673
		switch (classForm->relkind)
		{
			case RELKIND_SEQUENCE:
				acl = acldefault(ACL_OBJECT_SEQUENCE, ownerId);
				break;
			default:
				acl = acldefault(ACL_OBJECT_RELATION, ownerId);
				break;
		}
3674
		aclDatum = (Datum) 0;
3675
	}
3676
	else
3677
	{
3678 3679
		/* detoast rel's ACL if necessary */
		acl = DatumGetAclP(aclDatum);
3680
	}
3681

3682
	result = aclmask(acl, roleid, ownerId, mask, how);
3683

3684 3685
	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
3686
		pfree(acl);
3687

3688 3689
	ReleaseSysCache(tuple);

3690
	return result;
3691 3692
}

3693
/*
3694
 * Exported routine for examining a user's privileges for a database
3695
 */
3696
AclMode
3697
pg_database_aclmask(Oid db_oid, Oid roleid,
3698
					AclMode mask, AclMaskHow how)
3699
{
3700
	AclMode		result;
3701
	HeapTuple	tuple;
3702 3703 3704 3705
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
	Oid			ownerId;
3706 3707

	/* Superusers bypass all permission checking. */
3708
	if (superuser_arg(roleid))
3709
		return mask;
3710 3711 3712 3713

	/*
	 * Get the database's ACL from pg_database
	 */
3714
	tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(db_oid));
3715
	if (!HeapTupleIsValid(tuple))
3716 3717 3718
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_DATABASE),
				 errmsg("database with OID %u does not exist", db_oid)));
3719

3720
	ownerId = ((Form_pg_database) GETSTRUCT(tuple))->datdba;
3721

3722 3723
	aclDatum = SysCacheGetAttr(DATABASEOID, tuple, Anum_pg_database_datacl,
							   &isNull);
3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735
	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_DATABASE, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

3736
	result = aclmask(acl, roleid, ownerId, mask, how);
3737 3738 3739 3740 3741

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

3742 3743
	ReleaseSysCache(tuple);

3744 3745 3746
	return result;
}

3747
/*
3748
 * Exported routine for examining a user's privileges for a function
3749
 */
3750
AclMode
3751
pg_proc_aclmask(Oid proc_oid, Oid roleid,
3752
				AclMode mask, AclMaskHow how)
3753
{
3754
	AclMode		result;
3755 3756 3757 3758
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
B
Bruce Momjian 已提交
3759
	Oid			ownerId;
3760

3761
	/* Superusers bypass all permission checking. */
3762
	if (superuser_arg(roleid))
3763
		return mask;
3764 3765

	/*
3766
	 * Get the function's ACL from pg_proc
3767
	 */
3768
	tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(proc_oid));
3769
	if (!HeapTupleIsValid(tuple))
3770 3771
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_FUNCTION),
B
Bruce Momjian 已提交
3772
				 errmsg("function with OID %u does not exist", proc_oid)));
3773

3774 3775
	ownerId = ((Form_pg_proc) GETSTRUCT(tuple))->proowner;

3776 3777 3778 3779 3780
	aclDatum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proacl,
							   &isNull);
	if (isNull)
	{
		/* No ACL, so build default ACL */
3781
		acl = acldefault(ACL_OBJECT_FUNCTION, ownerId);
3782 3783 3784 3785 3786 3787 3788 3789
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

3790
	result = aclmask(acl, roleid, ownerId, mask, how);
3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(tuple);

	return result;
}

/*
3802
 * Exported routine for examining a user's privileges for a language
3803
 */
3804
AclMode
3805
pg_language_aclmask(Oid lang_oid, Oid roleid,
3806
					AclMode mask, AclMaskHow how)
3807
{
3808
	AclMode		result;
3809 3810 3811 3812
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
B
Bruce Momjian 已提交
3813
	Oid			ownerId;
3814

3815
	/* Superusers bypass all permission checking. */
3816
	if (superuser_arg(roleid))
3817
		return mask;
3818 3819

	/*
3820
	 * Get the language's ACL from pg_language
3821
	 */
3822
	tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(lang_oid));
3823
	if (!HeapTupleIsValid(tuple))
3824 3825
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
3826
				 errmsg("language with OID %u does not exist", lang_oid)));
3827

3828
	ownerId = ((Form_pg_language) GETSTRUCT(tuple))->lanowner;
3829

3830 3831 3832 3833 3834
	aclDatum = SysCacheGetAttr(LANGOID, tuple, Anum_pg_language_lanacl,
							   &isNull);
	if (isNull)
	{
		/* No ACL, so build default ACL */
3835
		acl = acldefault(ACL_OBJECT_LANGUAGE, ownerId);
3836 3837 3838 3839 3840 3841 3842 3843
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

3844
	result = aclmask(acl, roleid, ownerId, mask, how);
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(tuple);

	return result;
}

3855 3856 3857
/*
 * Exported routine for examining a user's privileges for a largeobject
 *
3858 3859 3860 3861 3862
 * When a large object is opened for reading, it is opened relative to the
 * caller's snapshot, but when it is opened for writing, it is always relative
 * to SnapshotNow, as documented in doc/src/sgml/lobj.sgml.  This function
 * takes a snapshot argument so that the permissions check can be made relative
 * to the same snapshot that will be used to read the underlying data.
3863 3864 3865 3866 3867 3868 3869 3870
 */
AclMode
pg_largeobject_aclmask_snapshot(Oid lobj_oid, Oid roleid,
								AclMode mask, AclMaskHow how,
								Snapshot snapshot)
{
	AclMode		result;
	Relation	pg_lo_meta;
B
Bruce Momjian 已提交
3871 3872
	ScanKeyData entry[1];
	SysScanDesc scan;
3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return mask;

	/*
	 * Get the largeobject's ACL from pg_language_metadata
	 */
	pg_lo_meta = heap_open(LargeObjectMetadataRelationId,
						   AccessShareLock);

	ScanKeyInit(&entry[0],
				ObjectIdAttributeNumber,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(lobj_oid));

	scan = systable_beginscan(pg_lo_meta,
							  LargeObjectMetadataOidIndexId, true,
							  snapshot, 1, entry);

	tuple = systable_getnext(scan);
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("large object %u does not exist", lobj_oid)));

	ownerId = ((Form_pg_largeobject_metadata) GETSTRUCT(tuple))->lomowner;

	aclDatum = heap_getattr(tuple, Anum_pg_largeobject_metadata_lomacl,
							RelationGetDescr(pg_lo_meta), &isNull);

	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_LARGEOBJECT, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

	result = aclmask(acl, roleid, ownerId, mask, how);

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	systable_endscan(scan);

	heap_close(pg_lo_meta, AccessShareLock);

	return result;
}

3934
/*
3935
 * Exported routine for examining a user's privileges for a namespace
3936
 */
3937
AclMode
3938
pg_namespace_aclmask(Oid nsp_oid, Oid roleid,
3939
					 AclMode mask, AclMaskHow how)
3940
{
3941
	AclMode		result;
3942 3943 3944 3945
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
B
Bruce Momjian 已提交
3946
	Oid			ownerId;
3947 3948

	/* Superusers bypass all permission checking. */
3949
	if (superuser_arg(roleid))
3950
		return mask;
3951

3952
	/*
B
Bruce Momjian 已提交
3953 3954 3955 3956 3957
	 * If we have been assigned this namespace as a temp namespace, check to
	 * make sure we have CREATE TEMP permission on the database, and if so act
	 * as though we have all standard (but not GRANT OPTION) permissions on
	 * the namespace.  If we don't have CREATE TEMP, act as though we have
	 * only USAGE (and not CREATE) rights.
3958
	 *
3959 3960
	 * This may seem redundant given the check in InitTempTableNamespace, but
	 * it really isn't since current user ID may have changed since then. The
B
Bruce Momjian 已提交
3961 3962 3963 3964
	 * upshot of this behavior is that a SECURITY DEFINER function can create
	 * temp tables that can then be accessed (if permission is granted) by
	 * code in the same session that doesn't have permissions to create temp
	 * tables.
3965 3966 3967
	 *
	 * XXX Would it be safe to ereport a special error message as
	 * InitTempTableNamespace does?  Returning zero here means we'll get a
B
Bruce Momjian 已提交
3968 3969
	 * generic "permission denied for schema pg_temp_N" message, which is not
	 * remarkably user-friendly.
3970
	 */
3971 3972
	if (isTempNamespace(nsp_oid))
	{
3973
		if (pg_database_aclcheck(MyDatabaseId, roleid,
3974 3975 3976 3977
								 ACL_CREATE_TEMP) == ACLCHECK_OK)
			return mask & ACL_ALL_RIGHTS_NAMESPACE;
		else
			return mask & ACL_USAGE;
3978 3979
	}

3980
	/*
3981
	 * Get the schema's ACL from pg_namespace
3982
	 */
3983
	tuple = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nsp_oid));
3984
	if (!HeapTupleIsValid(tuple))
3985 3986 3987
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_SCHEMA),
				 errmsg("schema with OID %u does not exist", nsp_oid)));
3988

3989 3990
	ownerId = ((Form_pg_namespace) GETSTRUCT(tuple))->nspowner;

3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
	aclDatum = SysCacheGetAttr(NAMESPACEOID, tuple, Anum_pg_namespace_nspacl,
							   &isNull);
	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_NAMESPACE, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

4005
	result = aclmask(acl, roleid, ownerId, mask, how);
4006 4007 4008 4009 4010 4011 4012 4013 4014

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(tuple);

	return result;
}
4015

4016 4017 4018 4019
/*
 * Exported routine for examining a user's privileges for a tablespace
 */
AclMode
4020
pg_tablespace_aclmask(Oid spc_oid, Oid roleid,
4021 4022 4023 4024 4025 4026 4027
					  AclMode mask, AclMaskHow how)
{
	AclMode		result;
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
B
Bruce Momjian 已提交
4028
	Oid			ownerId;
4029

4030
	/* Superusers bypass all permission checking. */
4031
	if (superuser_arg(roleid))
4032 4033 4034 4035 4036
		return mask;

	/*
	 * Get the tablespace's ACL from pg_tablespace
	 */
4037
	tuple = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(spc_oid));
4038 4039 4040
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
4041
				 errmsg("tablespace with OID %u does not exist", spc_oid)));
4042 4043 4044

	ownerId = ((Form_pg_tablespace) GETSTRUCT(tuple))->spcowner;

4045
	aclDatum = SysCacheGetAttr(TABLESPACEOID, tuple,
B
Bruce Momjian 已提交
4046 4047
							   Anum_pg_tablespace_spcacl,
							   &isNull);
4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060

	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_TABLESPACE, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

4061
	result = aclmask(acl, roleid, ownerId, mask, how);
4062 4063 4064 4065 4066

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

4067
	ReleaseSysCache(tuple);
4068 4069 4070 4071

	return result;
}

4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
/*
 * Exported routine for examining a user's privileges for a foreign
 * data wrapper
 */
AclMode
pg_foreign_data_wrapper_aclmask(Oid fdw_oid, Oid roleid,
								AclMode mask, AclMaskHow how)
{
	AclMode		result;
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
	Oid			ownerId;

	Form_pg_foreign_data_wrapper fdwForm;

	/* Bypass permission checks for superusers */
	if (superuser_arg(roleid))
		return mask;

	/*
	 * Must get the FDW's tuple from pg_foreign_data_wrapper
	 */
4096
	tuple = SearchSysCache1(FOREIGNDATAWRAPPEROID, ObjectIdGetDatum(fdw_oid));
4097 4098
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
4099
				(errmsg("foreign-data wrapper with OID %u does not exist",
4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138
						fdw_oid)));
	fdwForm = (Form_pg_foreign_data_wrapper) GETSTRUCT(tuple);

	/*
	 * Normal case: get the FDW's ACL from pg_foreign_data_wrapper
	 */
	ownerId = fdwForm->fdwowner;

	aclDatum = SysCacheGetAttr(FOREIGNDATAWRAPPEROID, tuple,
							   Anum_pg_foreign_data_wrapper_fdwacl, &isNull);
	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_FDW, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast rel's ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

	result = aclmask(acl, roleid, ownerId, mask, how);

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(tuple);

	return result;
}

/*
 * Exported routine for examining a user's privileges for a foreign
 * server.
 */
AclMode
pg_foreign_server_aclmask(Oid srv_oid, Oid roleid,
4139
						  AclMode mask, AclMaskHow how)
4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
{
	AclMode		result;
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
	Oid			ownerId;

	Form_pg_foreign_server srvForm;

	/* Bypass permission checks for superusers */
	if (superuser_arg(roleid))
		return mask;

	/*
	 * Must get the FDW's tuple from pg_foreign_data_wrapper
	 */
4157
	tuple = SearchSysCache1(FOREIGNSERVEROID, ObjectIdGetDatum(srv_oid));
4158 4159
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
4160
				(errmsg("foreign server with OID %u does not exist",
4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192
						srv_oid)));
	srvForm = (Form_pg_foreign_server) GETSTRUCT(tuple);

	/*
	 * Normal case: get the foreign server's ACL from pg_foreign_server
	 */
	ownerId = srvForm->srvowner;

	aclDatum = SysCacheGetAttr(FOREIGNSERVEROID, tuple,
							   Anum_pg_foreign_server_srvacl, &isNull);
	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_FOREIGN_SERVER, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast rel's ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

	result = aclmask(acl, roleid, ownerId, mask, how);

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(tuple);

	return result;
}
4193

4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225
/*
 * Exported routine for examining a user's privileges for a type.
 */
AclMode
pg_type_aclmask(Oid type_oid, Oid roleid, AclMode mask, AclMaskHow how)
{
	AclMode		result;
	HeapTuple	tuple;
	Datum		aclDatum;
	bool		isNull;
	Acl		   *acl;
	Oid			ownerId;

	Form_pg_type typeForm;

	/* Bypass permission checks for superusers */
	if (superuser_arg(roleid))
		return mask;

	/*
	 * Must get the type's tuple from pg_type
	 */
	tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errmsg("type with OID %u does not exist",
						type_oid)));
	typeForm = (Form_pg_type) GETSTRUCT(tuple);

	/* "True" array types don't manage permissions of their own */
	if (typeForm->typelem != 0 && typeForm->typlen == -1)
	{
4226
		Oid			elttype_oid = typeForm->typelem;
4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267

		ReleaseSysCache(tuple);

		tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(elttype_oid));
		if (!HeapTupleIsValid(tuple))
			ereport(ERROR,
					(errmsg("type with OID %u does not exist",
							type_oid)));
		typeForm = (Form_pg_type) GETSTRUCT(tuple);
	}

	/*
	 * Normal case: get the type's ACL from pg_type
	 */
	ownerId = typeForm->typowner;

	aclDatum = SysCacheGetAttr(TYPEOID, tuple,
							   Anum_pg_type_typacl, &isNull);
	if (isNull)
	{
		/* No ACL, so build default ACL */
		acl = acldefault(ACL_OBJECT_TYPE, ownerId);
		aclDatum = (Datum) 0;
	}
	else
	{
		/* detoast rel's ACL if necessary */
		acl = DatumGetAclP(aclDatum);
	}

	result = aclmask(acl, roleid, ownerId, mask, how);

	/* if we have a detoasted copy, free it */
	if (acl && (Pointer) acl != DatumGetPointer(aclDatum))
		pfree(acl);

	ReleaseSysCache(tuple);

	return result;
}

4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296
/*
 * Exported routine for checking a user's access privileges to a column
 *
 * Returns ACLCHECK_OK if the user has any of the privileges identified by
 * 'mode'; otherwise returns a suitable error code (in practice, always
 * ACLCHECK_NO_PRIV).
 *
 * As with pg_attribute_aclmask, only privileges granted directly on the
 * column are considered here.
 */
AclResult
pg_attribute_aclcheck(Oid table_oid, AttrNumber attnum,
					  Oid roleid, AclMode mode)
{
	if (pg_attribute_aclmask(table_oid, attnum, roleid, mode, ACLMASK_ANY) != 0)
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

/*
 * Exported routine for checking a user's access privileges to any/all columns
 *
 * If 'how' is ACLMASK_ANY, then returns ACLCHECK_OK if user has any of the
 * privileges identified by 'mode' on any non-dropped column in the relation;
 * otherwise returns a suitable error code (in practice, always
 * ACLCHECK_NO_PRIV).
 *
 * If 'how' is ACLMASK_ALL, then returns ACLCHECK_OK if user has any of the
4297
 * privileges identified by 'mode' on each non-dropped column in the relation
4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
 * (and there must be at least one such column); otherwise returns a suitable
 * error code (in practice, always ACLCHECK_NO_PRIV).
 *
 * As with pg_attribute_aclmask, only privileges granted directly on the
 * column(s) are considered here.
 *
 * Note: system columns are not considered here; there are cases where that
 * might be appropriate but there are also cases where it wouldn't.
 */
AclResult
pg_attribute_aclcheck_all(Oid table_oid, Oid roleid, AclMode mode,
						  AclMaskHow how)
{
4311 4312 4313 4314 4315
	AclResult	result;
	HeapTuple	classTuple;
	Form_pg_class classForm;
	AttrNumber	nattrs;
	AttrNumber	curr_att;
4316

4317 4318
	/*
	 * Must fetch pg_class row to check number of attributes.  As in
4319 4320
	 * pg_attribute_aclmask, we prefer to return "no privileges" instead of
	 * throwing an error if we get any unexpected lookup errors.
4321
	 */
4322
	classTuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
4323
	if (!HeapTupleIsValid(classTuple))
4324
		return ACLCHECK_NO_PRIV;
4325 4326 4327 4328 4329 4330 4331
	classForm = (Form_pg_class) GETSTRUCT(classTuple);

	nattrs = classForm->relnatts;

	ReleaseSysCache(classTuple);

	/*
4332 4333
	 * Initialize result in case there are no non-dropped columns.	We want to
	 * report failure in such cases for either value of 'how'.
4334 4335 4336 4337 4338 4339
	 */
	result = ACLCHECK_NO_PRIV;

	for (curr_att = 1; curr_att <= nattrs; curr_att++)
	{
		HeapTuple	attTuple;
4340
		AclMode		attmask;
4341

4342 4343 4344
		attTuple = SearchSysCache2(ATTNUM,
								   ObjectIdGetDatum(table_oid),
								   Int16GetDatum(curr_att));
4345
		if (!HeapTupleIsValid(attTuple))
4346
			continue;
4347 4348

		/* ignore dropped columns */
4349 4350 4351
		if (((Form_pg_attribute) GETSTRUCT(attTuple))->attisdropped)
		{
			ReleaseSysCache(attTuple);
4352
			continue;
4353 4354 4355 4356
		}

		/*
		 * Here we hard-wire knowledge that the default ACL for a column
4357 4358
		 * grants no privileges, so that we can fall out quickly in the very
		 * common case where attacl is null.
4359 4360 4361 4362 4363 4364 4365 4366
		 */
		if (heap_attisnull(attTuple, Anum_pg_attribute_attacl))
			attmask = 0;
		else
			attmask = pg_attribute_aclmask(table_oid, curr_att, roleid,
										   mode, ACLMASK_ANY);

		ReleaseSysCache(attTuple);
4367

4368
		if (attmask != 0)
4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
		{
			result = ACLCHECK_OK;
			if (how == ACLMASK_ANY)
				break;			/* succeed on any success */
		}
		else
		{
			result = ACLCHECK_NO_PRIV;
			if (how == ACLMASK_ALL)
				break;			/* fail on any failure */
		}
	}

	return result;
}

4385 4386 4387 4388 4389 4390 4391 4392
/*
 * Exported routine for checking a user's access privileges to a table
 *
 * Returns ACLCHECK_OK if the user has any of the privileges identified by
 * 'mode'; otherwise returns a suitable error code (in practice, always
 * ACLCHECK_NO_PRIV).
 */
AclResult
4393
pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
4394
{
4395
	if (pg_class_aclmask(table_oid, roleid, mode, ACLMASK_ANY) != 0)
4396 4397 4398 4399 4400 4401 4402 4403 4404
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

/*
 * Exported routine for checking a user's access privileges to a database
 */
AclResult
4405
pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
4406
{
4407
	if (pg_database_aclmask(db_oid, roleid, mode, ACLMASK_ANY) != 0)
4408 4409 4410 4411 4412 4413 4414 4415 4416
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

/*
 * Exported routine for checking a user's access privileges to a function
 */
AclResult
4417
pg_proc_aclcheck(Oid proc_oid, Oid roleid, AclMode mode)
4418
{
4419
	if (pg_proc_aclmask(proc_oid, roleid, mode, ACLMASK_ANY) != 0)
4420 4421 4422 4423 4424 4425 4426 4427 4428
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

/*
 * Exported routine for checking a user's access privileges to a language
 */
AclResult
4429
pg_language_aclcheck(Oid lang_oid, Oid roleid, AclMode mode)
4430
{
4431
	if (pg_language_aclmask(lang_oid, roleid, mode, ACLMASK_ANY) != 0)
4432 4433 4434 4435 4436
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450
/*
 * Exported routine for checking a user's access privileges to a largeobject
 */
AclResult
pg_largeobject_aclcheck_snapshot(Oid lobj_oid, Oid roleid, AclMode mode,
								 Snapshot snapshot)
{
	if (pg_largeobject_aclmask_snapshot(lobj_oid, roleid, mode,
										ACLMASK_ANY, snapshot) != 0)
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

4451 4452 4453 4454
/*
 * Exported routine for checking a user's access privileges to a namespace
 */
AclResult
4455
pg_namespace_aclcheck(Oid nsp_oid, Oid roleid, AclMode mode)
4456
{
4457
	if (pg_namespace_aclmask(nsp_oid, roleid, mode, ACLMASK_ANY) != 0)
4458 4459 4460 4461 4462
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

4463 4464 4465 4466
/*
 * Exported routine for checking a user's access privileges to a tablespace
 */
AclResult
4467
pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
4468
{
4469
	if (pg_tablespace_aclmask(spc_oid, roleid, mode, ACLMASK_ANY) != 0)
4470 4471 4472 4473 4474
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499
/*
 * Exported routine for checking a user's access privileges to a foreign
 * data wrapper
 */
AclResult
pg_foreign_data_wrapper_aclcheck(Oid fdw_oid, Oid roleid, AclMode mode)
{
	if (pg_foreign_data_wrapper_aclmask(fdw_oid, roleid, mode, ACLMASK_ANY) != 0)
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

/*
 * Exported routine for checking a user's access privileges to a foreign
 * server
 */
AclResult
pg_foreign_server_aclcheck(Oid srv_oid, Oid roleid, AclMode mode)
{
	if (pg_foreign_server_aclmask(srv_oid, roleid, mode, ACLMASK_ANY) != 0)
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}
4500

4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512
/*
 * Exported routine for checking a user's access privileges to a type
 */
AclResult
pg_type_aclcheck(Oid type_oid, Oid roleid, AclMode mode)
{
	if (pg_type_aclmask(type_oid, roleid, mode, ACLMASK_ANY) != 0)
		return ACLCHECK_OK;
	else
		return ACLCHECK_NO_PRIV;
}

4513 4514 4515 4516
/*
 * Ownership check for a relation (specified by OID).
 */
bool
4517
pg_class_ownercheck(Oid class_oid, Oid roleid)
4518 4519
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4520
	Oid			ownerId;
4521 4522

	/* Superusers bypass all permission checking. */
4523
	if (superuser_arg(roleid))
4524 4525
		return true;

4526
	tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(class_oid));
4527
	if (!HeapTupleIsValid(tuple))
4528 4529
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_TABLE),
B
Bruce Momjian 已提交
4530
				 errmsg("relation with OID %u does not exist", class_oid)));
4531

4532
	ownerId = ((Form_pg_class) GETSTRUCT(tuple))->relowner;
4533 4534 4535

	ReleaseSysCache(tuple);

4536
	return has_privs_of_role(roleid, ownerId);
4537 4538 4539 4540 4541 4542
}

/*
 * Ownership check for a type (specified by OID).
 */
bool
4543
pg_type_ownercheck(Oid type_oid, Oid roleid)
4544 4545
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4546
	Oid			ownerId;
4547 4548

	/* Superusers bypass all permission checking. */
4549
	if (superuser_arg(roleid))
4550 4551
		return true;

4552
	tuple = SearchSysCache1(TYPEOID, ObjectIdGetDatum(type_oid));
4553
	if (!HeapTupleIsValid(tuple))
4554 4555 4556
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("type with OID %u does not exist", type_oid)));
4557

4558
	ownerId = ((Form_pg_type) GETSTRUCT(tuple))->typowner;
4559 4560 4561

	ReleaseSysCache(tuple);

4562
	return has_privs_of_role(roleid, ownerId);
4563 4564 4565 4566 4567 4568
}

/*
 * Ownership check for an operator (specified by OID).
 */
bool
4569
pg_oper_ownercheck(Oid oper_oid, Oid roleid)
4570 4571
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4572
	Oid			ownerId;
4573 4574

	/* Superusers bypass all permission checking. */
4575
	if (superuser_arg(roleid))
4576 4577
		return true;

4578
	tuple = SearchSysCache1(OPEROID, ObjectIdGetDatum(oper_oid));
4579
	if (!HeapTupleIsValid(tuple))
4580 4581
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_FUNCTION),
B
Bruce Momjian 已提交
4582
				 errmsg("operator with OID %u does not exist", oper_oid)));
4583

4584
	ownerId = ((Form_pg_operator) GETSTRUCT(tuple))->oprowner;
4585 4586 4587

	ReleaseSysCache(tuple);

4588
	return has_privs_of_role(roleid, ownerId);
4589 4590 4591 4592 4593 4594
}

/*
 * Ownership check for a function (specified by OID).
 */
bool
4595
pg_proc_ownercheck(Oid proc_oid, Oid roleid)
4596 4597
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4598
	Oid			ownerId;
4599 4600

	/* Superusers bypass all permission checking. */
4601
	if (superuser_arg(roleid))
4602 4603
		return true;

4604
	tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(proc_oid));
4605
	if (!HeapTupleIsValid(tuple))
4606 4607
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_FUNCTION),
B
Bruce Momjian 已提交
4608
				 errmsg("function with OID %u does not exist", proc_oid)));
4609

4610
	ownerId = ((Form_pg_proc) GETSTRUCT(tuple))->proowner;
4611 4612 4613

	ReleaseSysCache(tuple);

4614
	return has_privs_of_role(roleid, ownerId);
4615
}
4616

4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629
/*
 * Ownership check for a procedural language (specified by OID)
 */
bool
pg_language_ownercheck(Oid lan_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

4630
	tuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(lan_oid));
4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_FUNCTION),
				 errmsg("language with OID %u does not exist", lan_oid)));

	ownerId = ((Form_pg_language) GETSTRUCT(tuple))->lanowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

4643 4644 4645
/*
 * Ownership check for a largeobject (specified by OID)
 *
4646 4647
 * This is only used for operations like ALTER LARGE OBJECT that are always
 * relative to SnapshotNow.
4648 4649 4650 4651 4652
 */
bool
pg_largeobject_ownercheck(Oid lobj_oid, Oid roleid)
{
	Relation	pg_lo_meta;
B
Bruce Momjian 已提交
4653 4654
	ScanKeyData entry[1];
	SysScanDesc scan;
4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

	/* There's no syscache for pg_largeobject_metadata */
	pg_lo_meta = heap_open(LargeObjectMetadataRelationId,
						   AccessShareLock);

	ScanKeyInit(&entry[0],
				ObjectIdAttributeNumber,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(lobj_oid));

	scan = systable_beginscan(pg_lo_meta,
							  LargeObjectMetadataOidIndexId, true,
							  SnapshotNow, 1, entry);

	tuple = systable_getnext(scan);
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("large object %u does not exist", lobj_oid)));

	ownerId = ((Form_pg_largeobject_metadata) GETSTRUCT(tuple))->lomowner;

	systable_endscan(scan);
	heap_close(pg_lo_meta, AccessShareLock);

	return has_privs_of_role(roleid, ownerId);
}

4689 4690 4691 4692
/*
 * Ownership check for a namespace (specified by OID).
 */
bool
4693
pg_namespace_ownercheck(Oid nsp_oid, Oid roleid)
4694 4695
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4696
	Oid			ownerId;
4697 4698

	/* Superusers bypass all permission checking. */
4699
	if (superuser_arg(roleid))
4700 4701
		return true;

4702
	tuple = SearchSysCache1(NAMESPACEOID, ObjectIdGetDatum(nsp_oid));
4703
	if (!HeapTupleIsValid(tuple))
4704 4705 4706
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_SCHEMA),
				 errmsg("schema with OID %u does not exist", nsp_oid)));
4707

4708
	ownerId = ((Form_pg_namespace) GETSTRUCT(tuple))->nspowner;
4709 4710 4711

	ReleaseSysCache(tuple);

4712
	return has_privs_of_role(roleid, ownerId);
4713
}
4714

4715 4716 4717 4718
/*
 * Ownership check for a tablespace (specified by OID).
 */
bool
4719
pg_tablespace_ownercheck(Oid spc_oid, Oid roleid)
4720 4721
{
	HeapTuple	spctuple;
B
Bruce Momjian 已提交
4722
	Oid			spcowner;
4723 4724

	/* Superusers bypass all permission checking. */
4725
	if (superuser_arg(roleid))
4726 4727
		return true;

4728
	/* Search syscache for pg_tablespace */
4729
	spctuple = SearchSysCache1(TABLESPACEOID, ObjectIdGetDatum(spc_oid));
4730 4731 4732
	if (!HeapTupleIsValid(spctuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
4733
				 errmsg("tablespace with OID %u does not exist", spc_oid)));
4734 4735 4736

	spcowner = ((Form_pg_tablespace) GETSTRUCT(spctuple))->spcowner;

4737
	ReleaseSysCache(spctuple);
4738

4739
	return has_privs_of_role(roleid, spcowner);
4740 4741
}

4742 4743 4744 4745
/*
 * Ownership check for an operator class (specified by OID).
 */
bool
4746
pg_opclass_ownercheck(Oid opc_oid, Oid roleid)
4747 4748
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4749
	Oid			ownerId;
4750 4751

	/* Superusers bypass all permission checking. */
4752
	if (superuser_arg(roleid))
4753 4754
		return true;

4755
	tuple = SearchSysCache1(CLAOID, ObjectIdGetDatum(opc_oid));
4756
	if (!HeapTupleIsValid(tuple))
4757 4758 4759 4760
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("operator class with OID %u does not exist",
						opc_oid)));
4761

4762
	ownerId = ((Form_pg_opclass) GETSTRUCT(tuple))->opcowner;
4763 4764 4765

	ReleaseSysCache(tuple);

4766
	return has_privs_of_role(roleid, ownerId);
4767
}
4768

4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781
/*
 * Ownership check for an operator family (specified by OID).
 */
bool
pg_opfamily_ownercheck(Oid opf_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

4782
	tuple = SearchSysCache1(OPFAMILYOID, ObjectIdGetDatum(opf_oid));
4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("operator family with OID %u does not exist",
						opf_oid)));

	ownerId = ((Form_pg_opfamily) GETSTRUCT(tuple))->opfowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808
/*
 * Ownership check for a text search dictionary (specified by OID).
 */
bool
pg_ts_dict_ownercheck(Oid dict_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

4809
	tuple = SearchSysCache1(TSDICTOID, ObjectIdGetDatum(dict_oid));
4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("text search dictionary with OID %u does not exist",
						dict_oid)));

	ownerId = ((Form_pg_ts_dict) GETSTRUCT(tuple))->dictowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

/*
 * Ownership check for a text search configuration (specified by OID).
 */
bool
pg_ts_config_ownercheck(Oid cfg_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

4836
	tuple = SearchSysCache1(TSCONFIGOID, ObjectIdGetDatum(cfg_oid));
4837 4838 4839
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
4840 4841
			   errmsg("text search configuration with OID %u does not exist",
					  cfg_oid)));
4842 4843 4844 4845 4846 4847 4848 4849

	ownerId = ((Form_pg_ts_config) GETSTRUCT(tuple))->cfgowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876
/*
 * Ownership check for a foreign-data wrapper (specified by OID).
 */
bool
pg_foreign_data_wrapper_ownercheck(Oid srv_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

	tuple = SearchSysCache1(FOREIGNDATAWRAPPEROID, ObjectIdGetDatum(srv_oid));
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("foreign-data wrapper with OID %u does not exist",
						srv_oid)));

	ownerId = ((Form_pg_foreign_data_wrapper) GETSTRUCT(tuple))->fdwowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889
/*
 * Ownership check for a foreign server (specified by OID).
 */
bool
pg_foreign_server_ownercheck(Oid srv_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

4890
	tuple = SearchSysCache1(FOREIGNSERVEROID, ObjectIdGetDatum(srv_oid));
4891 4892 4893
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
4894 4895
				 errmsg("foreign server with OID %u does not exist",
						srv_oid)));
4896 4897 4898 4899 4900 4901 4902

	ownerId = ((Form_pg_foreign_server) GETSTRUCT(tuple))->srvowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}
4903

4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930
/*
 * Ownership check for an event trigger (specified by OID).
 */
bool
pg_event_trigger_ownercheck(Oid et_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

	tuple = SearchSysCache1(EVENTTRIGGEROID, ObjectIdGetDatum(et_oid));
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("event trigger with OID %u does not exist",
						et_oid)));

	ownerId = ((Form_pg_event_trigger) GETSTRUCT(tuple))->evtowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

4931
/*
4932
 * Ownership check for a database (specified by OID).
4933 4934
 */
bool
4935
pg_database_ownercheck(Oid db_oid, Oid roleid)
4936
{
4937
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4938
	Oid			dba;
4939 4940

	/* Superusers bypass all permission checking. */
4941
	if (superuser_arg(roleid))
4942 4943
		return true;

4944
	tuple = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(db_oid));
4945
	if (!HeapTupleIsValid(tuple))
4946 4947 4948
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_DATABASE),
				 errmsg("database with OID %u does not exist", db_oid)));
4949

4950
	dba = ((Form_pg_database) GETSTRUCT(tuple))->datdba;
4951

4952
	ReleaseSysCache(tuple);
4953

4954
	return has_privs_of_role(roleid, dba);
4955
}
4956

P
Peter Eisentraut 已提交
4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982
/*
 * Ownership check for a collation (specified by OID).
 */
bool
pg_collation_ownercheck(Oid coll_oid, Oid roleid)
{
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

	tuple = SearchSysCache1(COLLOID, ObjectIdGetDatum(coll_oid));
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("collation with OID %u does not exist", coll_oid)));

	ownerId = ((Form_pg_collation) GETSTRUCT(tuple))->collowner;

	ReleaseSysCache(tuple);

	return has_privs_of_role(roleid, ownerId);
}

4983 4984 4985 4986
/*
 * Ownership check for a conversion (specified by OID).
 */
bool
4987
pg_conversion_ownercheck(Oid conv_oid, Oid roleid)
4988 4989
{
	HeapTuple	tuple;
B
Bruce Momjian 已提交
4990
	Oid			ownerId;
4991 4992

	/* Superusers bypass all permission checking. */
4993
	if (superuser_arg(roleid))
4994 4995
		return true;

4996
	tuple = SearchSysCache1(CONVOID, ObjectIdGetDatum(conv_oid));
4997 4998 4999
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
B
Bruce Momjian 已提交
5000
				 errmsg("conversion with OID %u does not exist", conv_oid)));
5001

5002
	ownerId = ((Form_pg_conversion) GETSTRUCT(tuple))->conowner;
5003 5004 5005

	ReleaseSysCache(tuple);

5006
	return has_privs_of_role(roleid, ownerId);
5007
}
5008

5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050
/*
 * Ownership check for an extension (specified by OID).
 */
bool
pg_extension_ownercheck(Oid ext_oid, Oid roleid)
{
	Relation	pg_extension;
	ScanKeyData entry[1];
	SysScanDesc scan;
	HeapTuple	tuple;
	Oid			ownerId;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

	/* There's no syscache for pg_extension, so do it the hard way */
	pg_extension = heap_open(ExtensionRelationId, AccessShareLock);

	ScanKeyInit(&entry[0],
				ObjectIdAttributeNumber,
				BTEqualStrategyNumber, F_OIDEQ,
				ObjectIdGetDatum(ext_oid));

	scan = systable_beginscan(pg_extension,
							  ExtensionOidIndexId, true,
							  SnapshotNow, 1, entry);

	tuple = systable_getnext(scan);
	if (!HeapTupleIsValid(tuple))
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_OBJECT),
				 errmsg("extension with OID %u does not exist", ext_oid)));

	ownerId = ((Form_pg_extension) GETSTRUCT(tuple))->extowner;

	systable_endscan(scan);
	heap_close(pg_extension, AccessShareLock);

	return has_privs_of_role(roleid, ownerId);
}

5051 5052 5053 5054 5055 5056
/*
 * Check whether specified role has CREATEROLE privilege (or is a superuser)
 *
 * Note: roles do not have owners per se; instead we use this test in
 * places where an ownership-like permissions test is needed for a role.
 * Be sure to apply it to the role trying to do the operation, not the
5057
 * role being operated on!	Also note that this generally should not be
5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080
 * considered enough privilege if the target role is a superuser.
 * (We don't handle that consideration here because we want to give a
 * separate error message for such cases, so the caller has to deal with it.)
 */
bool
has_createrole_privilege(Oid roleid)
{
	bool		result = false;
	HeapTuple	utup;

	/* Superusers bypass all permission checking. */
	if (superuser_arg(roleid))
		return true;

	utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
	if (HeapTupleIsValid(utup))
	{
		result = ((Form_pg_authid) GETSTRUCT(utup))->rolcreaterole;
		ReleaseSysCache(utup);
	}
	return result;
}

5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091
/*
 * Fetch pg_default_acl entry for given role, namespace and object type
 * (object type must be given in pg_default_acl's encoding).
 * Returns NULL if no such entry.
 */
static Acl *
get_default_acl_internal(Oid roleId, Oid nsp_oid, char objtype)
{
	Acl		   *result = NULL;
	HeapTuple	tuple;

5092 5093 5094 5095
	tuple = SearchSysCache3(DEFACLROLENSPOBJ,
							ObjectIdGetDatum(roleId),
							ObjectIdGetDatum(nsp_oid),
							CharGetDatum(objtype));
5096 5097 5098

	if (HeapTupleIsValid(tuple))
	{
B
Bruce Momjian 已提交
5099 5100
		Datum		aclDatum;
		bool		isNull;
5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148

		aclDatum = SysCacheGetAttr(DEFACLROLENSPOBJ, tuple,
								   Anum_pg_default_acl_defaclacl,
								   &isNull);
		if (!isNull)
			result = DatumGetAclPCopy(aclDatum);
		ReleaseSysCache(tuple);
	}

	return result;
}

/*
 * Get default permissions for newly created object within given schema
 *
 * Returns NULL if built-in system defaults should be used
 */
Acl *
get_user_default_acl(GrantObjectType objtype, Oid ownerId, Oid nsp_oid)
{
	Acl		   *result;
	Acl		   *glob_acl;
	Acl		   *schema_acl;
	Acl		   *def_acl;
	char		defaclobjtype;

	/*
	 * Use NULL during bootstrap, since pg_default_acl probably isn't there
	 * yet.
	 */
	if (IsBootstrapProcessingMode())
		return NULL;

	/* Check if object type is supported in pg_default_acl */
	switch (objtype)
	{
		case ACL_OBJECT_RELATION:
			defaclobjtype = DEFACLOBJ_RELATION;
			break;

		case ACL_OBJECT_SEQUENCE:
			defaclobjtype = DEFACLOBJ_SEQUENCE;
			break;

		case ACL_OBJECT_FUNCTION:
			defaclobjtype = DEFACLOBJ_FUNCTION;
			break;

5149 5150 5151 5152
		case ACL_OBJECT_TYPE:
			defaclobjtype = DEFACLOBJ_TYPE;
			break;

5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185
		default:
			return NULL;
	}

	/* Look up the relevant pg_default_acl entries */
	glob_acl = get_default_acl_internal(ownerId, InvalidOid, defaclobjtype);
	schema_acl = get_default_acl_internal(ownerId, nsp_oid, defaclobjtype);

	/* Quick out if neither entry exists */
	if (glob_acl == NULL && schema_acl == NULL)
		return NULL;

	/* We need to know the hard-wired default value, too */
	def_acl = acldefault(objtype, ownerId);

	/* If there's no global entry, substitute the hard-wired default */
	if (glob_acl == NULL)
		glob_acl = def_acl;

	/* Merge in any per-schema privileges */
	result = aclmerge(glob_acl, schema_acl, ownerId);

	/*
	 * For efficiency, we want to return NULL if the result equals default.
	 * This requires sorting both arrays to get an accurate comparison.
	 */
	aclitemsort(result);
	aclitemsort(def_acl);
	if (aclequal(result, def_acl))
		result = NULL;

	return result;
}