1
0
mirror of https://github.com/postgres/postgres.git synced 2025-11-12 05:01:15 +03:00

Postgres95 1.01 Distribution - Virgin Sources

This commit is contained in:
Marc G. Fournier
1996-07-09 06:22:35 +00:00
commit d31084e9d1
868 changed files with 242656 additions and 0 deletions

View File

@@ -0,0 +1,14 @@
#-------------------------------------------------------------------------
#
# Makefile.inc--
# Makefile for utils/init
#
# Copyright (c) 1994, Regents of the University of California
#
#
# IDENTIFICATION
# $Header: /cvsroot/pgsql/src/backend/utils/init/Attic/Makefile.inc,v 1.1.1.1 1996/07/09 06:22:08 scrappy Exp $
#
#-------------------------------------------------------------------------
SUBSRCS+= enbl.c findbe.c globals.c magic.c miscinit.c postinit.c

View File

@@ -0,0 +1,45 @@
/*-------------------------------------------------------------------------
*
* enbl.c--
* POSTGRES module enable and disable support code.
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/Attic/enbl.c,v 1.1.1.1 1996/07/09 06:22:08 scrappy Exp $
*
*-------------------------------------------------------------------------
*/
#include "c.h"
#include "utils/module.h" /* where the declarations go */
/*
* BypassEnable --
* False iff enable/disable processing is required given on and "*countP."
*
* Note:
* As a side-effect, *countP is modified. It should be 0 initially.
*
* Exceptions:
* BadState if called with pointer to value 0 and false.
* BadArg if "countP" is invalid pointer.
* BadArg if on is invalid.
*/
bool
BypassEnable(int *enableCountInOutP, bool on)
{
AssertArg(PointerIsValid(enableCountInOutP));
AssertArg(BoolIsValid(on));
if (on) {
*enableCountInOutP += 1;
return ((bool)(*enableCountInOutP >= 2));
}
AssertState(*enableCountInOutP >= 1);
*enableCountInOutP -= 1;
return ((bool)(*enableCountInOutP >= 1));
}

View File

@@ -0,0 +1,251 @@
/*-------------------------------------------------------------------------
*
* findbe.c --
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/Attic/findbe.c,v 1.1.1.1 1996/07/09 06:22:08 scrappy Exp $
*
*-------------------------------------------------------------------------
*/
#include <stdio.h>
#ifndef WIN32
#include <grp.h>
#else
#include <windows.h>
#endif /* WIN32 */
#include <pwd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "c.h"
#include "miscadmin.h" /* for DebugLvl */
#ifndef S_IRUSR /* XXX [TRH] should be in a header */
# define S_IRUSR S_IREAD
# define S_IWUSR S_IWRITE
# define S_IXUSR S_IEXEC
# define S_IRGRP ((S_IRUSR)>>3)
# define S_IWGRP ((S_IWUSR)>>3)
# define S_IXGRP ((S_IXUSR)>>3)
# define S_IROTH ((S_IRUSR)>>6)
# define S_IWOTH ((S_IWUSR)>>6)
# define S_IXOTH ((S_IXUSR)>>6)
#endif
/*
* ValidateBackend -- validate "path" as a POSTGRES executable file
*
* returns 0 if the file is found and no error is encountered.
* -1 if the regular file "path" does not exist or cannot be executed.
* -2 if the file is otherwise valid but cannot be read.
*/
int
ValidateBackend(char *path)
{
#ifndef WIN32
struct stat buf;
uid_t euid;
struct group *gp;
struct passwd *pwp;
int i;
int is_r = 0;
int is_x = 0;
int in_grp = 0;
#else
DWORD file_attributes;
#endif /* WIN32 */
/*
* Ensure that the file exists and is a regular file.
*
* XXX if you have a broken system where stat() looks at the symlink
* instead of the underlying file, you lose.
*/
if (strlen(path) >= MAXPGPATH) {
if (DebugLvl > 1)
fprintf(stderr, "ValidateBackend: pathname \"%s\" is too long\n",
path);
return(-1);
}
#ifndef WIN32
if (stat(path, &buf) < 0) {
if (DebugLvl > 1)
fprintf(stderr, "ValidateBackend: can't stat \"%s\"\n",
path);
return(-1);
}
if (!(buf.st_mode & S_IFREG)) {
if (DebugLvl > 1)
fprintf(stderr, "ValidateBackend: \"%s\" is not a regular file\n",
path);
return(-1);
}
/*
* Ensure that we are using an authorized backend.
*
* XXX I'm open to suggestions here. I would like to enforce ownership
* of backends by user "postgres" but people seem to like to run
* as users other than "postgres"...
*/
/*
* Ensure that the file is both executable and readable (required for
* dynamic loading).
*
* We use the effective uid here because the backend will not have
* executed setuid() by the time it calls this routine.
*/
euid = geteuid();
if (euid == buf.st_uid) {
is_r = buf.st_mode & S_IRUSR;
is_x = buf.st_mode & S_IXUSR;
if (DebugLvl > 1 && !(is_r && is_x))
fprintf(stderr, "ValidateBackend: \"%s\" is not user read/execute\n",
path);
return(is_x ? (is_r ? 0 : -2) : -1);
}
pwp = getpwuid(euid);
if (pwp) {
if (pwp->pw_gid == buf.st_gid) {
++in_grp;
} else if (pwp->pw_name &&
(gp = getgrgid(buf.st_gid))) {
for (i = 0; gp->gr_mem[i]; ++i) {
if (!strcmp(gp->gr_mem[i], pwp->pw_name)) {
++in_grp;
break;
}
}
}
if (in_grp) {
is_r = buf.st_mode & S_IRGRP;
is_x = buf.st_mode & S_IXGRP;
if (DebugLvl > 1 && !(is_r && is_x))
fprintf(stderr, "ValidateBackend: \"%s\" is not group read/execute\n",
path);
return(is_x ? (is_r ? 0 : -2) : -1);
}
}
is_r = buf.st_mode & S_IROTH;
is_x = buf.st_mode & S_IXOTH;
if (DebugLvl > 1 && !(is_r && is_x))
fprintf(stderr, "ValidateBackend: \"%s\" is not other read/execute\n",
path);
return(is_x ? (is_r ? 0 : -2) : -1);
#else
file_attributes = GetFileAttributes(path);
if(file_attributes != 0xFFFFFFFF)
return(0);
else
return(-1);
#endif /* WIN32 */
}
/*
* FindBackend -- find an absolute path to a valid backend executable
*
* The reason we have to work so hard to find an absolute path is that
* we need to feed the backend server the location of its actual
* executable file -- otherwise, we can't do dynamic loading.
*/
int
FindBackend(char *backend, char *argv0)
{
char buf[MAXPGPATH + 2];
char *p;
char *path, *startp, *endp;
int pathlen;
#ifdef WIN32
strcpy(backend, argv0);
return(0);
#endif /* WIN32 */
/*
* for the postmaster:
* First try: use the backend that's located in the same directory
* as the postmaster, if it was invoked with an explicit path.
* Presumably the user used an explicit path because it wasn't in
* PATH, and we don't want to use incompatible executables.
*
* This has the neat property that it works for installed binaries,
* old source trees (obj/support/post{master,gres}) and new marc
* source trees (obj/post{master,gres}) because they all put the
* two binaries in the same place.
*
* for the backend server:
* First try: if we're given some kind of path, use it (making sure
* that a relative path is made absolute before returning it).
*/
if (argv0 && (p = strrchr(argv0, '/')) && *++p) {
if (*argv0 == '/' || !getcwd(buf, MAXPGPATH))
buf[0] = '\0';
else
(void) strcat(buf, "/");
(void) strcat(buf, argv0);
p = strrchr(buf, '/');
(void) strcpy(++p, "postgres");
if (!ValidateBackend(buf)) {
(void) strncpy(backend, buf, MAXPGPATH);
if (DebugLvl)
fprintf(stderr, "FindBackend: found \"%s\" using argv[0]\n",
backend);
return(0);
}
fprintf(stderr, "FindBackend: invalid backend \"%s\"\n",
buf);
return(-1);
}
/*
* Second try: since no explicit path was supplied, the user must
* have been relying on PATH. We'll use the same PATH.
*/
if ((p = getenv("PATH")) && *p) {
if (DebugLvl)
fprintf(stderr, "FindBackend: searching PATH ...\n");
pathlen = strlen(p);
path = malloc(pathlen + 1);
(void) strcpy(path, p);
for (startp = path, endp = strchr(path, ':');
startp && *startp;
startp = endp + 1, endp = strchr(startp, ':')) {
if (startp == endp) /* it's a "::" */
continue;
if (endp)
*endp = '\0';
if (*startp == '/' || !getcwd(buf, MAXPGPATH))
buf[0] = '\0';
(void) strcat(buf, startp);
(void) strcat(buf, "/postgres");
switch (ValidateBackend(buf)) {
case 0: /* found ok */
(void) strncpy(backend, buf, MAXPGPATH);
if (DebugLvl)
fprintf(stderr, "FindBackend: found \"%s\" using PATH\n",
backend);
free(path);
return(0);
case -1: /* wasn't even a candidate, keep looking */
break;
case -2: /* found but disqualified */
fprintf(stderr, "FindBackend: could not read backend \"%s\"\n",
buf);
free(path);
return(-1);
}
if (!endp) /* last one */
break;
}
free(path);
}
fprintf(stderr, "FindBackend: could not find a backend to execute...\n");
return(-1);
}

View File

@@ -0,0 +1,108 @@
/*-------------------------------------------------------------------------
*
* globals.c--
* global variable declarations
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/globals.c,v 1.1.1.1 1996/07/09 06:22:08 scrappy Exp $
*
* NOTES
* Globals used all over the place should be declared here and not
* in other modules.
*
*-------------------------------------------------------------------------
*/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>
#include <sys/types.h>
#include <math.h>
#include "postgres.h"
#include "miscadmin.h" /* where the declarations go */
#include "access/heapam.h"
#include "utils/tqual.h"
#include "storage/sinval.h"
#include "storage/sinvaladt.h"
#include "storage/lmgr.h"
#include "utils/elog.h"
#include "catalog/catname.h"
int Portfd = -1;
int Noversion = 0;
int Quiet = 1;
int MasterPid;
char* DataDir;
char OutputFileName[MAXPGPATH] = "";
BackendId MyBackendId;
BackendTag MyBackendTag;
char *UserName = NULL;
char *DatabaseName = NULL;
char *DatabasePath = NULL;
bool MyDatabaseIdIsInitialized = false;
Oid MyDatabaseId = InvalidOid;
bool TransactionInitWasProcessed = false;
bool IsUnderPostmaster = false;
bool IsPostmaster = false;
short DebugLvl = 0;
char *IndexedCatalogNames[] = {
AttributeRelationName,
ProcedureRelationName,
TypeRelationName,
RelationRelationName,
0
};
/* ----------------
* we just do a linear search now so there's no requirement that the list
* be ordered. The list is so small it shouldn't make much difference.
* make sure the list is null-terminated
* - jolly 8/19/95
*
* OLD COMMENT
* WARNING WARNING WARNING WARNING WARNING WARNING
*
* keep SharedSystemRelationNames[] in SORTED order! A binary search
* is done on it in catalog.c!
*
* XXX this is a serious hack which should be fixed -cim 1/26/90
* ----------------
*/
char *SharedSystemRelationNames[] = {
DatabaseRelationName,
DefaultsRelationName,
DemonRelationName,
GroupRelationName,
HostsRelationName,
LogRelationName,
MagicRelationName,
ServerRelationName,
TimeRelationName,
UserRelationName,
VariableRelationName,
0
};
/* set up global variables, pointers, etc. */
void InitGlobals()
{
MasterPid = getpid();
DataDir = GetPGData();
}

View File

@@ -0,0 +1,167 @@
/*-------------------------------------------------------------------------
*
* magic.c--
* magic number management routines
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/Attic/magic.c,v 1.1.1.1 1996/07/09 06:22:09 scrappy Exp $
*
* NOTES
* XXX eventually, should be able to handle version identifiers
* of length != 4.
*
* STANDALONE CODE - do not use error routines as this code is linked with
* stuff that does not cinterface.a
*-------------------------------------------------------------------------
*/
#include <sys/file.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include "postgres.h"
#include "utils/elog.h"
#include "miscadmin.h" /* for global decls */
#include "storage/fd.h" /* for O_ */
static char Pg_verfile[] = PG_VERFILE;
/*
* private function prototypes
*/
static void PathSetVersionFilePath(char path[], char filepathbuf[]);
/*
* DatabaseMetaGunkIsConsistent
*
* Returns 1 iff all version numbers and ownerships are consistent.
*
* Note that we have to go through the whole rigmarole of generating the path
* and checking the existence of the database whether Noversion is set or not.
*/
int
DatabaseMetaGunkIsConsistent(char *database, char *path)
{
int isValid;
#ifndef WIN32
struct stat statbuf;
#else
struct _stat statbuf;
#endif
/* XXX We haven't changed PG_VERSION since 1.1! */
#ifndef WIN32
isValid = ValidPgVersion(DataDir);
sprintf(path, "%s/base/%s", DataDir, database);
isValid = ValidPgVersion(path) || isValid;
#endif /* WIN32 */
if (stat(path, &statbuf) < 0)
elog(FATAL, "database %s does not exist, bailing out...",
database);
return(isValid);
}
/*
* ValidPgVersion - verifies the consistency of the database
*
* Returns 1 iff the catalog version number (from the version number file
* in the directory specified in "path") is consistent with the backend
* version number.
*/
int
ValidPgVersion(char *path)
{
int fd;
char version[4], buf[MAXPGPATH+1];
#ifndef WIN32
struct stat statbuf;
#else
struct _stat statbuf;
#endif
u_short my_euid = geteuid();
PathSetVersionFilePath(path, buf);
if (stat(buf, &statbuf) >= 0) {
if (statbuf.st_uid != my_euid && my_euid != 0)
elog(FATAL,
"process userid (%d) != database owner (%d)",
my_euid, statbuf.st_uid);
} else
return(0);
if ((fd = open(buf, O_RDONLY, 0)) < 0) {
if (!Noversion)
elog(DEBUG, "ValidPgVersion: %s: %m", buf);
return(0);
}
if (read(fd, version, 4) < 4 ||
!isascii(version[0]) || !isdigit(version[0]) ||
version[1] != '.' ||
!isascii(version[2]) || !isdigit(version[2]) ||
version[3] != '\n')
elog(FATAL, "ValidPgVersion: %s: bad format", buf);
if (version[2] != '0' + PG_VERSION ||
version[0] != '0' + PG_RELEASE) {
if (!Noversion)
elog(DEBUG,
"ValidPgVersion: should be %d.%d not %c.%c",
PG_RELEASE, PG_VERSION, version[0], version[2]);
close(fd);
return(0);
}
close(fd);
return(1);
}
/*
* SetPgVersion - writes the version to a database directory
*/
void
SetPgVersion(char *path)
{
int fd;
char version[4], buf[MAXPGPATH+1];
PathSetVersionFilePath(path, buf);
if ((fd = open(buf, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0)
elog(FATAL, "SetPgVersion: %s: %m", buf);
version[0] = '0' + PG_RELEASE;
version[1] = '.';
version[2] = '0' + PG_VERSION;
version[3] = '\n';
if (write(fd, version, 4) != 4)
elog(WARN, "SetPgVersion: %s: %m", buf);
close(fd);
}
/*
* PathSetVersionFilePath
*
* Destructively change "filepathbuf" to contain the concatenation of "path"
* and the name of the version file name.
*/
static void
PathSetVersionFilePath(char *path, char *filepathbuf)
{
if (strlen(path) > (MAXPGPATH - sizeof(Pg_verfile) - 1))
elog(FATAL, "PathSetVersionFilePath: %s: path too long");
(void) sprintf(filepathbuf, "%s%c%s", path, SEP_CHAR, Pg_verfile);
}

View File

@@ -0,0 +1,378 @@
/*-------------------------------------------------------------------------
*
* miscinit.c--
* miscellanious initialization support stuff
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.1.1.1 1996/07/09 06:22:09 scrappy Exp $
*
*-------------------------------------------------------------------------
*/
#include <string.h>
#include <sys/param.h> /* for MAXPATHLEN */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <stdio.h>
#ifndef WIN32
#include <grp.h> /* for getgrgid */
#include <pwd.h> /* for getpwuid */
#endif /* WIN32 */
#include "postgres.h"
#include "utils/portal.h" /* for EnablePortalManager, etc. */
#include "utils/exc.h" /* for EnableExceptionHandling, etc. */
#include "utils/mcxt.h" /* for EnableMemoryContext, etc. */
#include "utils/elog.h"
#include "utils/builtins.h"
#include "miscadmin.h" /* where the declarations go */
#include "catalog/catname.h"
#include "catalog/pg_user.h"
#include "catalog/pg_proc.h"
#include "utils/syscache.h"
#include "storage/fd.h" /* for O_ */
/*
* EnableAbortEnvVarName --
* Enables system abort iff set to a non-empty string in environment.
*/
#define EnableAbortEnvVarName "POSTGRESABORT"
extern char *getenv(const char *name); /* XXX STDLIB */
/* from globals.c */
extern char *DatabaseName;
extern char *UserName;
extern char *DatabasePath;
/*
* Define USE_ENVIRONMENT to get PGDATA, etc. from environment variables.
* This is the default on UNIX platforms.
*/
#ifndef WIN32
#define USE_ENVIRONMENT
#endif
/* ----------------------------------------------------------------
* some of the 19 ways to leave postgres
* ----------------------------------------------------------------
*/
/*
* ExitPostgres --
* Exit POSTGRES with a status code.
*
* Note:
* This function never returns.
* ...
*
* Side effects:
* ...
*
* Exceptions:
* none
*/
void
ExitPostgres(ExitStatus status)
{
#ifdef __SABER__
saber_stop();
#endif
exitpg(status);
}
/*
* AbortPostgres --
* Abort POSTGRES dumping core.
*
* Note:
* This function never returns.
* ...
*
* Side effects:
* Core is dumped iff EnableAbortEnvVarName is set to a non-empty string.
* ...
*
* Exceptions:
* none
*/
void
AbortPostgres()
{
char *abortValue = getenv(EnableAbortEnvVarName);
#ifdef __SABER__
saber_stop();
#endif
if (PointerIsValid(abortValue) && abortValue[0] != '\0')
abort();
else
exitpg(FatalExitStatus);
}
/* ----------------
* StatusBackendExit
* ----------------
*/
void
StatusBackendExit(int status)
{
/* someday, do some real cleanup and then call the LISP exit */
/* someday, call StatusPostmasterExit if running without postmaster */
exitpg(status);
}
/* ----------------
* StatusPostmasterExit
* ----------------
*/
void
StatusPostmasterExit(int status)
{
/* someday, do some real cleanup and then call the LISP exit */
exitpg(status);
}
/* ----------------------------------------------------------------
* processing mode support stuff (used to be in pmod.c)
* ----------------------------------------------------------------
*/
static ProcessingMode Mode = NoProcessing;
/*
* IsNoProcessingMode --
* True iff processing mode is NoProcessing.
*/
bool
IsNoProcessingMode()
{
return ((bool)(Mode == NoProcessing));
}
/*
* IsBootstrapProcessingMode --
* True iff processing mode is BootstrapProcessing.
*/
bool
IsBootstrapProcessingMode()
{
return ((bool)(Mode == BootstrapProcessing));
}
/*
* IsInitProcessingMode --
* True iff processing mode is InitProcessing.
*/
bool
IsInitProcessingMode()
{
return ((bool)(Mode == InitProcessing));
}
/*
* IsNormalProcessingMode --
* True iff processing mode is NormalProcessing.
*/
bool
IsNormalProcessingMode()
{
return ((bool)(Mode == NormalProcessing));
}
/*
* SetProcessingMode --
* Sets mode of processing as specified.
*
* Exceptions:
* BadArg if called with invalid mode.
*
* Note:
* Mode is NoProcessing before the first time this is called.
*/
void
SetProcessingMode(ProcessingMode mode)
{
AssertArg(mode == NoProcessing || mode == BootstrapProcessing ||
mode == InitProcessing || mode == NormalProcessing);
Mode = mode;
}
ProcessingMode
GetProcessingMode()
{
return (Mode);
}
/* ----------------------------------------------------------------
* database path / name support stuff
* ----------------------------------------------------------------
*/
/*
* GetDatabasePath --
* Returns path to database.
*
*/
char*
GetDatabasePath()
{
return DatabasePath;
}
/*
* GetDatabaseName --
* Returns name of database.
*/
char*
GetDatabaseName()
{
return DatabaseName;
}
void
SetDatabasePath(char *path)
{
/* use malloc since this is done before memory contexts are set up */
if (DatabasePath)
free(DatabasePath);
DatabasePath = malloc(strlen(path)+1);
strcpy(DatabasePath, path);
}
void
SetDatabaseName(char *name)
{
if (DatabaseName)
free (DatabaseName);
DatabaseName = malloc(strlen(name)+1);
strcpy(DatabaseName, name);
}
/* ----------------
* GetPgUserName and SetPgUserName
*
* SetPgUserName must be called before InitPostgres, since the setuid()
* is done there.
* ----------------
*/
char*
GetPgUserName()
{
return UserName;
}
void
SetPgUserName()
{
#ifndef NO_SECURITY
char *p;
struct passwd *pw;
if (IsUnderPostmaster) {
/* use the (possibly) authenticated name that's provided */
if (!(p = getenv("PG_USER")))
elog(FATAL, "SetPgUserName: PG_USER environment variable unset");
} else {
/* setuid() has not yet been done, see above comment */
if (!(pw = getpwuid(geteuid())))
elog(FATAL, "SetPgUserName: no entry in passwd file");
p = pw->pw_name;
}
if (UserName)
free(UserName);
UserName = malloc(strlen(p)+1);
strcpy(UserName, p);
#endif /* NO_SECURITY */
#ifdef WIN32
/* XXX We'll figure out how to get the user name later */
if (UserName)
free(UserName);
UserName = malloc(strlen(p)+1);
strcpy(UserName, "postgres");
#endif /* WIN32 */
}
/* ----------------------------------------------------------------
* GetUserId and SetUserId
* ----------------------------------------------------------------
*/
static Oid UserId = InvalidOid;
Oid
GetUserId()
{
Assert(OidIsValid(UserId));
return(UserId);
}
void
SetUserId()
{
HeapTuple userTup;
char *userName;
Assert(!OidIsValid(UserId)); /* only once */
/*
* Don't do scans if we're bootstrapping, none of the system
* catalogs exist yet, and they should be owned by postgres
* anyway.
*/
if (IsBootstrapProcessingMode()) {
UserId = geteuid();
return;
}
userName = GetPgUserName();
userTup = SearchSysCacheTuple(USENAME, PointerGetDatum(userName),
0,0,0);
if (!HeapTupleIsValid(userTup))
elog(FATAL, "SetUserId: user \"%s\" is not in \"%s\"",
userName,
UserRelationName);
UserId = (Oid) ((Form_pg_user) GETSTRUCT(userTup))->usesysid;
}
/* ----------------
* GetPGHome
*
* Get POSTGRESHOME from environment, or return default.
* ----------------
*/
char *
GetPGHome()
{
#ifdef USE_ENVIRONMENT
char *h;
if ((h = getenv("POSTGRESHOME")) != (char *) NULL)
return (h);
#endif /* USE_ENVIRONMENT */
return (POSTGRESDIR);
}
char *
GetPGData()
{
#ifdef USE_ENVIRONMENT
char *p;
if ((p = getenv("PGDATA")) != (char *) NULL) {
return (p);
}
#endif /* USE_ENVIRONMENT */
return (PGDATADIR);
}

View File

@@ -0,0 +1,648 @@
/*-------------------------------------------------------------------------
*
* postinit.c--
* postgres initialization utilities
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.1.1.1 1996/07/09 06:22:09 scrappy Exp $
*
* NOTES
* InitPostgres() is the function called from PostgresMain
* which does all non-trival initialization, mainly by calling
* all the other initialization functions. InitPostgres()
* is only used within the "postgres" backend and so that routine
* is in tcop/postgres.c InitPostgres() is needed in cinterface.a
* because things like the bootstrap backend program need it. Hence
* you find that in this file...
*
* If you feel the need to add more initialization code, it should be
* done in InitPostgres() or someplace lower. Do not start
* putting stuff in PostgresMain - if you do then someone
* will have to clean it up later, and it's not going to be me!
* -cim 10/3/90
*
*-------------------------------------------------------------------------
*/
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>
#include <sys/types.h>
#include <math.h>
#include "postgres.h"
#include "machine.h" /* for BLCKSZ, for InitMyDatabaseId()
* and where the decarations for this file go
*/
#include "access/heapam.h"
#include "access/xact.h"
#include "storage/bufmgr.h"
#include "access/transam.h" /* XXX dependency problem */
#include "utils/tqual.h"
#include "utils/syscache.h"
#include "storage/bufpage.h" /* for page layout, for InitMyDatabaseId() */
#include "storage/sinval.h"
#include "storage/sinvaladt.h"
#include "storage/lmgr.h"
#include "miscadmin.h" /* for global decls */
#include "utils/portal.h" /* for EnablePortalManager, etc. */
#include "utils/exc.h" /* for EnableExceptionHandling, etc. */
#include "fmgr.h" /* for EnableDynamicFunctionManager, etc. */
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/mcxt.h" /* for EnableMemoryContext, etc. */
#include "catalog/catname.h"
#include "catalog/pg_database.h"
#include "port-protos.h"
#include "libpq/libpq-be.h"
static IPCKey PostgresIpcKey;
#ifndef private
#ifndef EBUG
#define private static
#else /* !defined(EBUG) */
#define private
#endif /* !defined(EBUG) */
#endif /* !defined(private) */
/* ----------------------------------------------------------------
* InitPostgres support
* ----------------------------------------------------------------
*/
/* --------------------------------
* InitMyDatabaseId() -- Find and record the OID of the database we are
* to open.
*
* The database's oid forms half of the unique key for the system
* caches and lock tables. We therefore want it initialized before
* we open any relations, since opening relations puts things in the
* cache. To get around this problem, this code opens and scans the
* pg_database relation by hand.
*
* This algorithm relies on the fact that first attribute in the
* pg_database relation schema is the database name. It also knows
* about the internal format of tuples on disk and the length of
* the datname attribute. It knows the location of the pg_database
* file.
*
* This code is called from InitDatabase(), after we chdir() to the
* database directory but before we open any relations.
* --------------------------------
*/
void
InitMyDatabaseId()
{
int dbfd;
int fileflags;
int nbytes;
int max, i;
HeapTuple tup;
Page pg;
PageHeader ph;
char *dbfname;
Form_pg_database tup_db;
/*
* At bootstrap time, we don't need to check the oid of the database
* in use, since we're not using shared memory. This is lucky, since
* the database may not be in the tables yet.
*/
if (IsBootstrapProcessingMode()) {
LockDisable(true);
return;
}
dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2);
sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR);
fileflags = O_RDONLY;
#ifdef WIN32
fileflags |= _O_BINARY;
#endif /* WIN32 */
if ((dbfd = open(dbfname, O_RDONLY, 0666)) < 0)
elog(FATAL, "Cannot open %s", dbfname);
pfree(dbfname);
/* ----------------
* read and examine every page in pg_database
*
* Raw I/O! Read those tuples the hard way! Yow!
*
* Why don't we use the access methods or move this code
* someplace else? This is really pg_database schema dependent
* code. Perhaps it should go in lib/catalog/pg_database?
* -cim 10/3/90
*
* mao replies 4 apr 91: yeah, maybe this should be moved to
* lib/catalog. however, we CANNOT use the access methods since
* those use the buffer cache, which uses the relation cache, which
* requires that the dbid be set, which is what we're trying to do
* here.
* ----------------
*/
pg = (Page) palloc(BLCKSZ);
ph = (PageHeader) pg;
while ((nbytes = read(dbfd, pg, BLCKSZ)) == BLCKSZ) {
max = PageGetMaxOffsetNumber(pg);
/* look at each tuple on the page */
for (i = 0; i <= max; i++) {
int offset;
/* if it's a freed tuple, ignore it */
if (!(ph->pd_linp[i].lp_flags & LP_USED))
continue;
/* get a pointer to the tuple itself */
offset = (int) ph->pd_linp[i].lp_off;
tup = (HeapTuple) (((char *) pg) + offset);
/*
* if the tuple has been deleted (the database was destroyed),
* skip this tuple. XXX warning, will robinson: violation of
* transaction semantics happens right here. we should check
* to be sure that the xact that deleted this tuple actually
* committed. only way to do this at init time is to paw over
* the log relation by hand, too. let's be optimistic.
*
* XXX This is an evil type cast. tup->t_xmax is char[5] while
* TransactionId is struct * { char data[5] }. It works but
* if data is ever moved and no longer the first field this
* will be broken!! -mer 11 Nov 1991.
*/
if (TransactionIdIsValid((TransactionId)tup->t_xmax))
continue;
/*
* Okay, see if this is the one we want.
* XXX 1 july 91: mao and mer discover that tuples now squash
* t_bits. Why is this?
*
* 24 july 92: mer realizes that the t_bits field is only
* used in the event of null values. If no
* fields are null we reduce the header size
* by doing the squash. t_hoff tells you exactly
* how big the header actually is. use the PC
* means of getting at sys cat attrs.
*/
tup_db = (Form_pg_database)GETSTRUCT(tup);
if (strncmp(GetDatabaseName(),
&(tup_db->datname.data[0]),
16) == 0)
{
MyDatabaseId = tup->t_oid;
goto done;
}
}
}
done:
(void) close(dbfd);
pfree(pg);
if (!OidIsValid(MyDatabaseId))
elog(FATAL,
"Database %s does not exist in %s",
GetDatabaseName(),
DatabaseRelationName);
}
/*
* DoChdirAndInitDatabaseNameAndPath --
* Sets current directory appropriately for given path and name.
*
* Arguments:
* Path and name are invalid if it invalid as a string.
* Path is "badly formated" if it is not a string containing a path
* to a writable directory.
* Name is "badly formated" if it contains more than 16 characters or if
* it is a bad file name (e.g., it contains a '/' or an 8-bit character).
*
* Side effects:
* Initially, DatabasePath and DatabaseName are invalid. They are
* set to valid strings before this function returns.
*
* Exceptions:
* BadState if called more than once.
* BadArg if both path and name are "badly formated" or invalid.
* BadArg if path and name are both "inconsistent" and valid.
*/
/* ----------------
* DoChdirAndInitDatabaseNameAndPath
*
* this just chdir's to the proper data/base directory
* XXX clean this up more.
*
* XXX The following code is an incorrect of the semantics
* XXX described in the header file. Handling of defaults
* XXX should happen here, too.
* ----------------
*/
void
DoChdirAndInitDatabaseNameAndPath(char *name, /* name of database */
char *path) /* full path to database */
{
/* ----------------
* check the path
* ----------------
*/
if (path)
SetDatabasePath(path);
else
elog(FATAL, "DoChdirAndInitDatabaseNameAndPath: path:%s is not valid",
path);
/* ----------------
* check the name
* ----------------
*/
if (name)
SetDatabaseName(name);
else
elog(FATAL, "DoChdirAndInitDatabaseNameAndPath: name:%s is not valid",
name);
/* ----------------
* change to the directory, or die trying.
*
* XXX unless the path hasn't been set because we're bootstrapping.
* HP-UX doesn't like chdir("") so check for that case before
* doing anything drastic.
* ----------------
*/
if (*path && (chdir(path) < 0))
elog(FATAL, "DoChdirAndInitDatabaseNameAndPath: chdir(\"%s\"): %m",
path);
}
/* --------------------------------
* InitUserid
*
* initializes crap associated with the user id.
* --------------------------------
*/
void
InitUserid()
{
setuid(geteuid());
SetUserId();
}
/* --------------------------------
* InitCommunication
*
* This routine initializes stuff needed for ipc, locking, etc.
* it should be called something more informative.
*
* Note:
* This does not set MyBackendId. MyBackendTag is set, however.
* --------------------------------
*/
void
InitCommunication()
{
char *getenv(); /* XXX style */
char *postid;
char *postport;
IPCKey key;
/* ----------------
* try and get the backend tag from POSTID
* ----------------
*/
MyBackendId = -1;
postid = getenv("POSTID");
if (!PointerIsValid(postid)) {
MyBackendTag = -1;
} else {
MyBackendTag = atoi(postid);
Assert(MyBackendTag >= 0);
}
/* ----------------
* try and get the ipc key from POSTPORT
* ----------------
*/
postport = getenv("POSTPORT");
if (PointerIsValid(postport)) {
SystemPortAddress address = atoi(postport);
if (address == 0)
elog(FATAL, "InitCommunication: invalid POSTPORT");
if (MyBackendTag == -1)
elog(FATAL, "InitCommunication: missing POSTID");
key = SystemPortAddressCreateIPCKey(address);
/*
* Enable this if you are trying to force the backend to run as if it
* is running under the postmaster.
*
* This goto forces Postgres to attach to shared memory instead of
* using malloc'ed memory (which is the normal behavior if run
* directly).
*
* To enable emulation, run the following shell commands (in addition
* to enabling this goto)
*
* % setenv POSTID 1
* % setenv POSTPORT 4321
* % postmaster &
* % kill -9 %1
*
* Upon doing this, Postmaster will have allocated the shared memory
* resources that Postgres will attach to if you enable
* EMULATE_UNDER_POSTMASTER.
*
* This comment may well age with time - it is current as of
* 8 January 1990
*
* Greg
*/
#ifdef EMULATE_UNDER_POSTMASTER
goto forcesharedmemory;
#endif
} else if (IsUnderPostmaster) {
elog(FATAL,
"InitCommunication: under postmaster and POSTPORT not set");
} else {
/* ----------------
* assume we're running a postgres backend by itself with
* no front end or postmaster.
* ----------------
*/
if (MyBackendTag == -1) {
MyBackendTag = 1;
}
key = PrivateIPCKey;
}
/* ----------------
* initialize shared memory and semaphores appropriately.
* ----------------
*/
#ifdef EMULATE_UNDER_POSTMASTER
forcesharedmemory:
#endif
PostgresIpcKey = key;
AttachSharedMemoryAndSemaphores(key);
}
/* --------------------------------
* InitStdio
*
* this routine consists of a bunch of code fragments
* that used to be randomly scattered through cinit().
* they all seem to do stuff associated with io.
* --------------------------------
*/
void
InitStdio()
{
(void) DebugFileOpen();
}
/* --------------------------------
* InitPostgres --
* Initialize POSTGRES.
*
* Note:
* Be very careful with the order of calls in the InitPostgres function.
* --------------------------------
*/
bool PostgresIsInitialized = false;
extern int NBuffers;
/*
* this global is used by wei for testing his code, but must be declared
* here rather than in postgres.c so that it's defined for cinterface.a
* applications.
*/
/*int testFlag = 0;*/
int lockingOff = 0;
/*
*/
void
InitPostgres(char *name) /* database name */
{
bool bootstrap; /* true if BootstrapProcessing */
/* ----------------
* see if we're running in BootstrapProcessing mode
* ----------------
*/
bootstrap = IsBootstrapProcessingMode();
/* ----------------
* turn on the exception handler. Note: we cannot use elog, Assert,
* AssertState, etc. until after exception handling is on.
* ----------------
*/
EnableExceptionHandling(true);
/* ----------------
* A stupid check to make sure we don't call this more than once.
* But things like ReinitPostgres() get around this by just diddling
* the PostgresIsInitialized flag.
* ----------------
*/
AssertState(!PostgresIsInitialized);
/* ----------------
* Memory system initialization.
* (we may call palloc after EnableMemoryContext())
*
* Note EnableMemoryContext() must happen before EnablePortalManager().
* ----------------
*/
EnableMemoryContext(true); /* initializes the "top context" */
EnablePortalManager(true); /* memory for portal/transaction stuff */
/* ----------------
* initialize the backend local portal stack used by
* internal PQ function calls. see src/lib/libpq/be-dumpdata.c
* This is different from the "portal manager" so this goes here.
* -cim 2/12/91
* ----------------
*/
be_portalinit();
/* ----------------
* attach to shared memory and semaphores, and initialize our
* input/output/debugging file descriptors.
* ----------------
*/
InitCommunication();
InitStdio();
/*
* initialize the local buffer manager
*/
InitLocalBuffer();
if (!TransactionFlushEnabled())
on_exitpg(FlushBufferPool, (caddr_t) NULL);
/* ----------------
* check for valid "meta gunk" (??? -cim 10/5/90) and change to
* database directory.
*
* Note: DatabaseName, MyDatabaseName, and DatabasePath are all
* initialized with DatabaseMetaGunkIsConsistent(), strncpy() and
* DoChdirAndInitDatabase() below! XXX clean this crap up!
* -cim 10/5/90
* ----------------
*/
{
char myPath[MAXPGPATH] = "."; /* DatabasePath points here! */
/* ----------------
* DatabaseMetaGunkIsConsistent fills in myPath, but what about
* when bootstrap or Noversion is true?? -cim 10/5/90
* ----------------
*/
if (! bootstrap &&
! DatabaseMetaGunkIsConsistent(name, myPath) &&
! Noversion) {
elog(NOTICE, "InitPostgres: could not locate valid PG_VERSION\n");
elog(NOTICE, "files for %s and %s.", DataDir, name);
elog(FATAL, "Have you run initdb/createdb and set PGDATA properly?");
}
/* ----------------
* ok, we've figured out myName and myPath, now save these
* and chdir to myPath.
* ----------------
*/
DoChdirAndInitDatabaseNameAndPath(name, myPath);
}
/* ********************************
* code after this point assumes we are in the proper directory!
* ********************************
*/
/* ----------------
* initialize the database id used for system caches and lock tables
* ----------------
*/
InitMyDatabaseId();
smgrinit();
/* ----------------
* initialize the transaction system and the relation descriptor
* cache. Note we have to make certain the lock manager is off while
* we do this.
* ----------------
*/
AmiTransactionOverride(IsBootstrapProcessingMode());
LockDisable(true);
/*
* Part of the initialization processing done here sets a read
* lock on pg_log. Since locking is disabled the set doesn't have
* intended effect of locking out writers, but this is ok, since
* we only lock it to examine AMI transaction status, and this is
* never written after initdb is done. -mer 15 June 1992
*/
RelationInitialize(); /* pre-allocated reldescs created here */
InitializeTransactionSystem(); /* pg_log,etc init/crash recovery here */
LockDisable(false);
/* ----------------
* anyone knows what this does? something having to do with
* system catalog cache invalidation in the case of multiple
* backends, I think -cim 10/3/90
* Sets up MyBackendId a unique backend identifier.
* ----------------
*/
InitSharedInvalidationState();
/* ----------------
* Set up a per backend process in shared memory. Must be done after
* InitSharedInvalidationState() as it relies on MyBackendId being
* initialized already. XXX -mer 11 Aug 1991
* ----------------
*/
InitProcess(PostgresIpcKey);
if (MyBackendId > MaxBackendId || MyBackendId <= 0) {
elog(FATAL, "cinit2: bad backend id %d (%d)",
MyBackendTag,
MyBackendId);
}
/* ----------------
* initialize the access methods.
* ----------------
*/
initam();
/* ----------------
* initialize all the system catalog caches.
* ----------------
*/
zerocaches();
InitCatalogCache();
/* ----------------
* set ourselves to the proper user id and figure out our postgres
* user id. If we ever add security so that we check for valid
* postgres users, we might do it here.
* ----------------
*/
InitUserid();
/* ----------------
* ok, all done, now let's make sure we don't do it again.
* ----------------
*/
PostgresIsInitialized = true;
/* on_exitpg(DestroyLocalRelList, (caddr_t) NULL); */
/* ----------------
* Done with "InitPostgres", now change to NormalProcessing unless
* we're in BootstrapProcessing mode.
* ----------------
*/
if (!bootstrap)
SetProcessingMode(NormalProcessing);
/* if (testFlag || lockingOff) */
if (lockingOff)
LockDisable(true);
}