* miscinit.c
* miscellaneous initialization support stuff
*
- * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
- * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.145 2005/07/04 04:51:50 tgl Exp $
+ * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.158 2006/08/16 04:32:48 tgl Exp $
*
*-------------------------------------------------------------------------
*/
#endif
#include "catalog/pg_authid.h"
-#include "libpq/libpq-be.h"
#include "miscadmin.h"
+#include "postmaster/autovacuum.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/pg_shmem.h"
+#include "storage/proc.h"
+#include "storage/procarray.h"
#include "utils/builtins.h"
#include "utils/guc.h"
-#include "utils/lsyscache.h"
#include "utils/syscache.h"
* ----------------------------------------------------------------
*/
-static bool isIgnoringSystemIndexes = false;
-
-/*
- * IsIgnoringSystemIndexes
- * True if ignoring system indexes.
- */
-bool
-IsIgnoringSystemIndexes(void)
-{
- return isIgnoringSystemIndexes;
-}
-
-/*
- * IgnoreSystemIndexes
- * Set true or false whether PostgreSQL ignores system indexes.
- */
-void
-IgnoreSystemIndexes(bool mode)
-{
- isIgnoringSystemIndexes = mode;
-}
+bool IgnoreSystemIndexes = false;
/* ----------------------------------------------------------------
* system index reindexing support
/* ----------------------------------------------------------------
- * Role ID things
+ * User ID state
+ *
+ * We have to track several different values associated with the concept
+ * of "user ID".
+ *
+ * AuthenticatedUserId is determined at connection start and never changes.
+ *
+ * SessionUserId is initially the same as AuthenticatedUserId, but can be
+ * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
+ * This is the ID reported by the SESSION_USER SQL function.
*
- * The authenticated user is determined at connection start and never
- * changes. The session user can be changed only by SET SESSION
- * AUTHORIZATION. The current user may change when "setuid" functions
- * are implemented. Conceptually there is a stack, whose bottom
- * is the session user. You are yourself responsible to save and
- * restore the current user id if you need to change it.
+ * OuterUserId is the current user ID in effect at the "outer level" (outside
+ * any transaction or function). This is initially the same as SessionUserId,
+ * but can be changed by SET ROLE to any role that SessionUserId is a
+ * member of. We store this mainly so that AtAbort_UserId knows what to
+ * reset CurrentUserId to.
+ *
+ * CurrentUserId is the current effective user ID; this is the one to use
+ * for all normal permissions-checking purposes. At outer level this will
+ * be the same as OuterUserId, but it changes during calls to SECURITY
+ * DEFINER functions, as well as locally in some specialized commands.
* ----------------------------------------------------------------
*/
-static Oid AuthenticatedUserId = InvalidOid;
-static Oid SessionUserId = InvalidOid;
-static Oid CurrentUserId = InvalidOid;
+static Oid AuthenticatedUserId = InvalidOid;
+static Oid SessionUserId = InvalidOid;
+static Oid OuterUserId = InvalidOid;
+static Oid CurrentUserId = InvalidOid;
+/* We also have to remember the superuser state of some of these levels */
static bool AuthenticatedUserIsSuperuser = false;
+static bool SessionUserIsSuperuser = false;
+
+/* We also remember if a SET ROLE is currently active */
+static bool SetRoleIsActive = false;
+
/*
- * This function is relevant for all privilege checks.
+ * GetUserId/SetUserId - get/set the current effective user ID.
*/
Oid
GetUserId(void)
void
-SetUserId(Oid roleid)
+SetUserId(Oid userid)
+{
+ AssertArg(OidIsValid(userid));
+ CurrentUserId = userid;
+}
+
+
+/*
+ * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
+ */
+Oid
+GetOuterUserId(void)
+{
+ AssertState(OidIsValid(OuterUserId));
+ return OuterUserId;
+}
+
+
+static void
+SetOuterUserId(Oid userid)
{
- AssertArg(OidIsValid(roleid));
- CurrentUserId = roleid;
+ AssertArg(OidIsValid(userid));
+ OuterUserId = userid;
+
+ /* We force the effective user ID to match, too */
+ CurrentUserId = userid;
}
/*
- * This value is only relevant for informational purposes.
+ * GetSessionUserId/SetSessionUserId - get/set the session user ID.
*/
Oid
GetSessionUserId(void)
}
-void
-SetSessionUserId(Oid roleid)
+static void
+SetSessionUserId(Oid userid, bool is_superuser)
{
- AssertArg(OidIsValid(roleid));
- SessionUserId = roleid;
- /* Current user defaults to session user. */
- if (!OidIsValid(CurrentUserId))
- CurrentUserId = roleid;
+ AssertArg(OidIsValid(userid));
+ SessionUserId = userid;
+ SessionUserIsSuperuser = is_superuser;
+ SetRoleIsActive = false;
+
+ /* We force the effective user IDs to match, too */
+ OuterUserId = userid;
+ CurrentUserId = userid;
}
+/*
+ * Initialize user identity during normal backend startup
+ */
void
InitializeSessionUserId(const char *rolename)
{
rform = (Form_pg_authid) GETSTRUCT(roleTup);
roleid = HeapTupleGetOid(roleTup);
- if (!rform->rolcanlogin)
- ereport(FATAL,
- (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
- errmsg("role \"%s\" is not permitted to log in", rolename)));
-
AuthenticatedUserId = roleid;
AuthenticatedUserIsSuperuser = rform->rolsuper;
- SetSessionUserId(roleid); /* sets CurrentUserId too */
+ /* This sets OuterUserId/CurrentUserId too */
+ SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
+
+ /* Also mark our PGPROC entry with the authenticated user id */
+ /* (We assume this is an atomic store so no lock is needed) */
+ MyProc->roleId = roleid;
+
+ /*
+ * These next checks are not enforced when in standalone mode, so that
+ * there is a way to recover from sillinesses like "UPDATE pg_authid SET
+ * rolcanlogin = false;".
+ *
+ * We do not enforce them for the autovacuum process either.
+ */
+ if (IsUnderPostmaster && !IsAutoVacuumProcess())
+ {
+ /*
+ * Is role allowed to login at all?
+ */
+ if (!rform->rolcanlogin)
+ ereport(FATAL,
+ (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
+ errmsg("role \"%s\" is not permitted to log in",
+ rolename)));
+
+ /*
+ * Check connection limit for this role.
+ *
+ * There is a race condition here --- we create our PGPROC before
+ * checking for other PGPROCs. If two backends did this at about the
+ * same time, they might both think they were over the limit, while
+ * ideally one should succeed and one fail. Getting that to work
+ * exactly seems more trouble than it is worth, however; instead we
+ * just document that the connection limit is approximate.
+ */
+ if (rform->rolconnlimit >= 0 &&
+ !AuthenticatedUserIsSuperuser &&
+ CountUserBackends(roleid) > rform->rolconnlimit)
+ ereport(FATAL,
+ (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
+ errmsg("too many connections for role \"%s\"",
+ rolename)));
+ }
/* Record username and superuser status as GUC settings too */
SetConfigOption("session_authorization", rolename,
PGC_INTERNAL, PGC_S_OVERRIDE);
/*
- * Set up user-specific configuration variables. This is a good place
- * to do it so we don't have to read pg_authid twice during session
- * startup.
+ * Set up user-specific configuration variables. This is a good place to
+ * do it so we don't have to read pg_authid twice during session startup.
*/
datum = SysCacheGetAttr(AUTHNAME, roleTup,
Anum_pg_authid_rolconfig, &isnull);
}
+/*
+ * Initialize user identity during special backend startup
+ */
void
InitializeSessionUserIdStandalone(void)
{
/* This function should only be called in a single-user backend. */
- AssertState(!IsUnderPostmaster);
+ AssertState(!IsUnderPostmaster || IsAutoVacuumProcess());
/* call only once */
AssertState(!OidIsValid(AuthenticatedUserId));
AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
AuthenticatedUserIsSuperuser = true;
- SetSessionUserId(BOOTSTRAP_SUPERUSERID);
+ SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
+}
+
+
+/*
+ * Reset effective userid during AbortTransaction
+ *
+ * This is essentially SetUserId(GetOuterUserId()), but without the Asserts.
+ * The reason is that if a backend's InitPostgres transaction fails (eg,
+ * because an invalid user name was given), we have to be able to get through
+ * AbortTransaction without asserting.
+ */
+void
+AtAbort_UserId(void)
+{
+ CurrentUserId = OuterUserId;
}
* that in case of multiple SETs in a single session, the original userid's
* superuserness is what matters. But we set the GUC variable is_superuser
* to indicate whether the *current* session userid is a superuser.
+ *
+ * Note: this is not an especially clean place to do the permission check.
+ * It's OK because the check does not require catalog access and can't
+ * fail during an end-of-transaction GUC reversion, but we may someday
+ * have to push it up into assign_session_authorization.
*/
void
-SetSessionAuthorization(Oid roleid, bool is_superuser)
+SetSessionAuthorization(Oid userid, bool is_superuser)
{
/* Must have authenticated already, else can't make permission check */
AssertState(OidIsValid(AuthenticatedUserId));
- if (roleid != AuthenticatedUserId &&
+ if (userid != AuthenticatedUserId &&
!AuthenticatedUserIsSuperuser)
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
- errmsg("permission denied to set session authorization")));
+ errmsg("permission denied to set session authorization")));
+
+ SetSessionUserId(userid, is_superuser);
+
+ SetConfigOption("is_superuser",
+ is_superuser ? "on" : "off",
+ PGC_INTERNAL, PGC_S_OVERRIDE);
+}
+
+/*
+ * Report current role id
+ * This follows the semantics of SET ROLE, ie return the outer-level ID
+ * not the current effective ID, and return InvalidOid when the setting
+ * is logically SET ROLE NONE.
+ */
+Oid
+GetCurrentRoleId(void)
+{
+ if (SetRoleIsActive)
+ return OuterUserId;
+ else
+ return InvalidOid;
+}
+
+/*
+ * Change Role ID while running (SET ROLE)
+ *
+ * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
+ * session user authorization. In this case the is_superuser argument
+ * is ignored.
+ *
+ * When roleid is not InvalidOid, the caller must have checked whether
+ * the session user has permission to become that role. (We cannot check
+ * here because this routine must be able to execute in a failed transaction
+ * to restore a prior value of the ROLE GUC variable.)
+ */
+void
+SetCurrentRoleId(Oid roleid, bool is_superuser)
+{
+ /*
+ * Get correct info if it's SET ROLE NONE
+ *
+ * If SessionUserId hasn't been set yet, just do nothing --- the eventual
+ * SetSessionUserId call will fix everything. This is needed since we
+ * will get called during GUC initialization.
+ */
+ if (!OidIsValid(roleid))
+ {
+ if (!OidIsValid(SessionUserId))
+ return;
+
+ roleid = SessionUserId;
+ is_superuser = SessionUserIsSuperuser;
+
+ SetRoleIsActive = false;
+ }
+ else
+ SetRoleIsActive = true;
- SetSessionUserId(roleid);
- SetUserId(roleid);
+ SetOuterUserId(roleid);
SetConfigOption("is_superuser",
is_superuser ? "on" : "off",
pid_t my_pid = getpid();
/*
- * We need a loop here because of race conditions. But don't loop
- * forever (for example, a non-writable $PGDATA directory might cause
- * a failure that won't go away). 100 tries seems like plenty.
+ * We need a loop here because of race conditions. But don't loop forever
+ * (for example, a non-writable $PGDATA directory might cause a failure
+ * that won't go away). 100 tries seems like plenty.
*/
for (ntries = 0;; ntries++)
{
/*
* Try to create the lock file --- O_EXCL makes this atomic.
*
- * Think not to make the file protection weaker than 0600. See
+ * Think not to make the file protection weaker than 0600. See
* comments below.
*/
fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
/*
* Check to see if the other process still exists
*
- * If the PID in the lockfile is our own PID or our parent's PID,
- * then the file must be stale (probably left over from a previous
- * system boot cycle). We need this test because of the likelihood
- * that a reboot will assign exactly the same PID as we had in the
- * previous reboot. Also, if there is just one more process launch
- * in this reboot than in the previous one, the lockfile might mention
- * our parent's PID. We can reject that since we'd never be launched
- * directly by a competing postmaster. We can't detect grandparent
- * processes unfortunately, but if the init script is written carefully
- * then all but the immediate parent shell will be root-owned processes
- * and so the kill test will fail with EPERM.
+ * If the PID in the lockfile is our own PID or our parent's PID, then
+ * the file must be stale (probably left over from a previous system
+ * boot cycle). We need this test because of the likelihood that a
+ * reboot will assign exactly the same PID as we had in the previous
+ * reboot. Also, if there is just one more process launch in this
+ * reboot than in the previous one, the lockfile might mention our
+ * parent's PID. We can reject that since we'd never be launched
+ * directly by a competing postmaster. We can't detect grandparent
+ * processes unfortunately, but if the init script is written
+ * carefully then all but the immediate parent shell will be
+ * root-owned processes and so the kill test will fail with EPERM.
*
- * We can treat the EPERM-error case as okay because that error implies
- * that the existing process has a different userid than we do, which
- * means it cannot be a competing postmaster. A postmaster cannot
- * successfully attach to a data directory owned by a userid other
- * than its own. (This is now checked directly in checkDataDir(),
- * but has been true for a long time because of the restriction that
- * the data directory isn't group- or world-accessible.) Also,
- * since we create the lockfiles mode 600, we'd have failed above
- * if the lockfile belonged to another userid --- which means that
- * whatever process kill() is reporting about isn't the one that
- * made the lockfile. (NOTE: this last consideration is the only
- * one that keeps us from blowing away a Unix socket file belonging
- * to an instance of Postgres being run by someone else, at least
- * on machines where /tmp hasn't got a stickybit.)
+ * We can treat the EPERM-error case as okay because that error
+ * implies that the existing process has a different userid than we
+ * do, which means it cannot be a competing postmaster. A postmaster
+ * cannot successfully attach to a data directory owned by a userid
+ * other than its own. (This is now checked directly in
+ * checkDataDir(), but has been true for a long time because of the
+ * restriction that the data directory isn't group- or
+ * world-accessible.) Also, since we create the lockfiles mode 600,
+ * we'd have failed above if the lockfile belonged to another userid
+ * --- which means that whatever process kill() is reporting about
+ * isn't the one that made the lockfile. (NOTE: this last
+ * consideration is the only one that keeps us from blowing away a
+ * Unix socket file belonging to an instance of Postgres being run by
+ * someone else, at least on machines where /tmp hasn't got a
+ * stickybit.)
*
* Windows hasn't got getppid(), but doesn't need it since it's not
* using real kill() either...
*
* Normally kill() will fail with ESRCH if the given PID doesn't
- * exist. BeOS returns EINVAL for some silly reason, however.
+ * exist.
*/
if (other_pid != my_pid
#ifndef WIN32
)
{
if (kill(other_pid, 0) == 0 ||
- (errno != ESRCH &&
-#ifdef __BEOS__
- errno != EINVAL &&
-#endif
- errno != EPERM))
+ (errno != ESRCH && errno != EPERM))
{
/* lockfile belongs to a live process */
ereport(FATAL,
}
/*
- * No, the creating process did not exist. However, it could be
- * that the postmaster crashed (or more likely was kill -9'd by a
- * clueless admin) but has left orphan backends behind. Check for
- * this by looking to see if there is an associated shmem segment
- * that is still in use.
+ * No, the creating process did not exist. However, it could be that
+ * the postmaster crashed (or more likely was kill -9'd by a clueless
+ * admin) but has left orphan backends behind. Check for this by
+ * looking to see if there is an associated shmem segment that is
+ * still in use.
*/
if (isDDLock)
{
if (PGSharedMemoryIsInUse(id1, id2))
ereport(FATAL,
(errcode(ERRCODE_LOCK_FILE_EXISTS),
- errmsg("pre-existing shared memory block "
- "(key %lu, ID %lu) is still in use",
- id1, id2),
- errhint("If you're sure there are no old "
- "server processes still running, remove "
- "the shared memory block with "
- "the command \"ipcclean\", \"ipcrm\", "
- "or just delete the file \"%s\".",
- filename)));
+ errmsg("pre-existing shared memory block "
+ "(key %lu, ID %lu) is still in use",
+ id1, id2),
+ errhint("If you're sure there are no old "
+ "server processes still running, remove "
+ "the shared memory block with "
+ "the command \"ipcclean\", \"ipcrm\", "
+ "or just delete the file \"%s\".",
+ filename)));
}
}
}
/*
- * Looks like nobody's home. Unlink the file and try again to
- * create it. Need a loop because of possible race condition
- * against other would-be creators.
+ * Looks like nobody's home. Unlink the file and try again to create
+ * it. Need a loop because of possible race condition against other
+ * would-be creators.
*/
if (unlink(filename) < 0)
ereport(FATAL,
errmsg("could not remove old lock file \"%s\": %m",
filename),
errhint("The file seems accidentally left over, but "
- "it could not be removed. Please remove the file "
+ "it could not be removed. Please remove the file "
"by hand and try again.")));
}
errno = save_errno ? save_errno : ENOSPC;
ereport(FATAL,
(errcode_for_file_access(),
- errmsg("could not write lock file \"%s\": %m", filename)));
+ errmsg("could not write lock file \"%s\": %m", filename)));
}
if (close(fd))
{
errno = save_errno;
ereport(FATAL,
(errcode_for_file_access(),
- errmsg("could not write lock file \"%s\": %m", filename)));
+ errmsg("could not write lock file \"%s\": %m", filename)));
}
/*
if (socketLockFile[0] != '\0')
{
/*
- * utime() is POSIX standard, utimes() is a common alternative; if
- * we have neither, fall back to actually reading the file (which
- * only sets the access time not mod time, but that should be
- * enough in most cases). In all paths, we ignore errors.
+ * utime() is POSIX standard, utimes() is a common alternative; if we
+ * have neither, fall back to actually reading the file (which only
+ * sets the access time not mod time, but that should be enough in
+ * most cases). In all paths, we ignore errors.
*/
#ifdef HAVE_UTIME
utime(socketLockFile, NULL);
else
ereport(FATAL,
(errcode_for_file_access(),
- errmsg("could not open file \"%s\": %m", full_path)));
+ errmsg("could not open file \"%s\": %m", full_path)));
}
ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("database files are incompatible with server"),
errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
- "which is not compatible with this version %s.",
+ "which is not compatible with this version %s.",
file_major, file_minor, version_string)));
}
*-------------------------------------------------------------------------
*/
-typedef void (*func_ptr) ();
+/*
+ * GUC variables: lists of library names to be preloaded at postmaster
+ * start and at backend start
+ */
+char *shared_preload_libraries_string = NULL;
+char *local_preload_libraries_string = NULL;
/*
- * process any libraries that should be preloaded and
- * optionally pre-initialized
+ * load the shared libraries listed in 'libraries'
+ *
+ * 'gucname': name of GUC variable, for error reports
+ * 'restricted': if true, force libraries to be in $libdir/plugins/
*/
-void
-process_preload_libraries(char *preload_libraries_string)
+static void
+load_libraries(const char *libraries, const char *gucname, bool restricted)
{
char *rawstring;
List *elemlist;
ListCell *l;
- if (preload_libraries_string == NULL)
- return;
+ if (libraries == NULL || libraries[0] == '\0')
+ return; /* nothing to do */
/* Need a modifiable copy of string */
- rawstring = pstrdup(preload_libraries_string);
+ rawstring = pstrdup(libraries);
/* Parse string into list of identifiers */
if (!SplitIdentifierString(rawstring, ',', &elemlist))
list_free(elemlist);
ereport(LOG,
(errcode(ERRCODE_SYNTAX_ERROR),
- errmsg("invalid list syntax for parameter \"preload_libraries\"")));
+ errmsg("invalid list syntax in parameter \"%s\"",
+ gucname)));
return;
}
foreach(l, elemlist)
{
char *tok = (char *) lfirst(l);
- char *sep = strstr(tok, ":");
- char *filename = NULL;
- char *funcname = NULL;
- func_ptr initfunc;
-
- if (sep)
- {
- /*
- * a colon separator implies there is an initialization
- * function that we need to run in addition to loading the
- * library
- */
- size_t filename_len = sep - tok;
- size_t funcname_len = strlen(tok) - filename_len - 1;
-
- filename = (char *) palloc(filename_len + 1);
- memcpy(filename, tok, filename_len);
- filename[filename_len] = '\0';
-
- funcname = (char *) palloc(funcname_len + 1);
- strcpy(funcname, sep + 1);
- }
- else
- {
- /*
- * no separator -- just load the library
- */
- filename = pstrdup(tok);
- funcname = NULL;
- }
+ char *filename;
+ filename = pstrdup(tok);
canonicalize_path(filename);
- initfunc = (func_ptr) load_external_function(filename, funcname,
- true, NULL);
- if (initfunc)
- (*initfunc) ();
-
- if (funcname)
- ereport(LOG,
- (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
- filename, funcname)));
- else
- ereport(LOG,
- (errmsg("preloaded library \"%s\"",
- filename)));
+ /* If restricting, insert $libdir/plugins if not mentioned already */
+ if (restricted && first_dir_separator(filename) == NULL)
+ {
+ char *expanded;
+ expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
+ strcpy(expanded, "$libdir/plugins/");
+ strcat(expanded, filename);
+ pfree(filename);
+ filename = expanded;
+ }
+ load_file(filename, restricted);
+ ereport(LOG,
+ (errmsg("loaded library \"%s\"", filename)));
pfree(filename);
- if (funcname)
- pfree(funcname);
}
pfree(rawstring);
list_free(elemlist);
}
+
+/*
+ * process any libraries that should be preloaded at postmaster start
+ */
+void
+process_shared_preload_libraries(void)
+{
+ load_libraries(shared_preload_libraries_string,
+ "shared_preload_libraries",
+ false);
+}
+
+/*
+ * process any libraries that should be preloaded at backend start
+ */
+void
+process_local_preload_libraries(void)
+{
+ load_libraries(local_preload_libraries_string,
+ "local_preload_libraries",
+ true);
+}