📄 miscinit.c
字号:
rform = (Form_pg_authid) GETSTRUCT(roleTup); roleid = HeapTupleGetOid(roleTup); AuthenticatedUserId = roleid; AuthenticatedUserIsSuperuser = rform->rolsuper; /* 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_BACKEND, PGC_S_OVERRIDE); SetConfigOption("is_superuser", AuthenticatedUserIsSuperuser ? "on" : "off", 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. */ datum = SysCacheGetAttr(AUTHNAME, roleTup, Anum_pg_authid_rolconfig, &isnull); if (!isnull) { ArrayType *a = DatumGetArrayTypeP(datum); ProcessGUCArray(a, PGC_S_USER); } ReleaseSysCache(roleTup);}/* * Initialize user identity during special backend startup */voidInitializeSessionUserIdStandalone(void){ /* This function should only be called in a single-user backend. */ AssertState(!IsUnderPostmaster || IsAutoVacuumProcess()); /* call only once */ AssertState(!OidIsValid(AuthenticatedUserId)); AuthenticatedUserId = BOOTSTRAP_SUPERUSERID; AuthenticatedUserIsSuperuser = true; 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. */voidAtAbort_UserId(void){ CurrentUserId = OuterUserId;}/* * Change session auth ID while running * * Only a superuser may set auth ID to something other than himself. Note * 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. */voidSetSessionAuthorization(Oid userid, bool is_superuser){ /* Must have authenticated already, else can't make permission check */ AssertState(OidIsValid(AuthenticatedUserId)); if (userid != AuthenticatedUserId && !AuthenticatedUserIsSuperuser) ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), 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. */OidGetCurrentRoleId(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.) */voidSetCurrentRoleId(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; SetOuterUserId(roleid); SetConfigOption("is_superuser", is_superuser ? "on" : "off", PGC_INTERNAL, PGC_S_OVERRIDE);}/* * Get user name from user oid */char *GetUserNameFromId(Oid roleid){ HeapTuple tuple; char *result; tuple = SearchSysCache(AUTHOID, ObjectIdGetDatum(roleid), 0, 0, 0); if (!HeapTupleIsValid(tuple)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("invalid role OID: %u", roleid))); result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname)); ReleaseSysCache(tuple); return result;}/*------------------------------------------------------------------------- * Interlock-file support * * These routines are used to create both a data-directory lockfile * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock). * Both kinds of files contain the same info: * * Owning process' PID * Data directory path * * By convention, the owning process' PID is negated if it is a standalone * backend rather than a postmaster. This is just for informational purposes. * The path is also just for informational purposes (so that a socket lockfile * can be more easily traced to the associated postmaster). * * A data-directory lockfile can optionally contain a third line, containing * the key and ID for the shared memory block used by this postmaster. * * On successful lockfile creation, a proc_exit callback to remove the * lockfile is automatically created. *------------------------------------------------------------------------- *//* * proc_exit callback to remove a lockfile. */static voidUnlinkLockFile(int status, Datum filename){ char *fname = (char *) DatumGetPointer(filename); if (fname != NULL) { if (unlink(fname) != 0) { /* Should we complain if the unlink fails? */ } free(fname); }}/* * Create a lockfile. * * filename is the name of the lockfile to create. * amPostmaster is used to determine how to encode the output PID. * isDDLock and refName are used to determine what error message to produce. */static voidCreateLockFile(const char *filename, bool amPostmaster, bool isDDLock, const char *refName){ int fd; char buffer[MAXPGPATH + 100]; int ntries; int len; int encoded_pid; pid_t other_pid; 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. */ 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 * comments below. */ fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600); if (fd >= 0) break; /* Success; exit the retry loop */ /* * Couldn't create the pid file. Probably it already exists. */ if ((errno != EEXIST && errno != EACCES) || ntries > 100) ereport(FATAL, (errcode_for_file_access(), errmsg("could not create lock file \"%s\": %m", filename))); /* * Read the file to get the old owner's PID. Note race condition * here: file might have been deleted since we tried to create it. */ fd = open(filename, O_RDONLY, 0600); if (fd < 0) { if (errno == ENOENT) continue; /* race condition; try again */ ereport(FATAL, (errcode_for_file_access(), errmsg("could not open lock file \"%s\": %m", filename))); } if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0) ereport(FATAL, (errcode_for_file_access(), errmsg("could not read lock file \"%s\": %m", filename))); close(fd); buffer[len] = '\0'; encoded_pid = atoi(buffer); /* if pid < 0, the pid is for postgres, not postmaster */ other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid); if (other_pid <= 0) elog(FATAL, "bogus data in lock file \"%s\": \"%s\"", filename, buffer); /* * 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. * * 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. */ if (other_pid != my_pid#ifndef WIN32 && other_pid != getppid()#endif ) { if (kill(other_pid, 0) == 0 || (errno != ESRCH &&#ifdef __BEOS__ errno != EINVAL &&#endif errno != EPERM)) { /* lockfile belongs to a live process */ ereport(FATAL, (errcode(ERRCODE_LOCK_FILE_EXISTS), errmsg("lock file \"%s\" already exists", filename), isDDLock ? (encoded_pid < 0 ? errhint("Is another postgres (PID %d) running in data directory \"%s\"?", (int) other_pid, refName) : errhint("Is another postmaster (PID %d) running in data directory \"%s\"?", (int) other_pid, refName)) : (encoded_pid < 0 ? errhint("Is another postgres (PID %d) using socket file \"%s\"?", (int) other_pid, refName) : errhint("Is another postmaster (PID %d) using socket file \"%s\"?", (int) other_pid, refName))));
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -