1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.129 2004/07/12 00:09:06 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
32 #include "catalog/catname.h"
33 #include "catalog/pg_shadow.h"
34 #include "libpq/libpq-be.h"
35 #include "miscadmin.h"
36 #include "storage/fd.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "utils/builtins.h"
40 #include "utils/guc.h"
41 #include "utils/lsyscache.h"
42 #include "utils/syscache.h"
45 ProcessingMode Mode = InitProcessing;
47 /* Note: we rely on these to initialize as zeroes */
48 static char directoryLockFile[MAXPGPATH];
49 static char socketLockFile[MAXPGPATH];
52 /* ----------------------------------------------------------------
53 * ignoring system indexes support stuff
55 * NOTE: "ignoring system indexes" means we do not use the system indexes
56 * for lookups (either in hardwired catalog accesses or in planner-generated
57 * plans). We do, however, still update the indexes when a catalog
58 * modification is made.
59 * ----------------------------------------------------------------
62 static bool isIgnoringSystemIndexes = false;
65 * IsIgnoringSystemIndexes
66 * True if ignoring system indexes.
69 IsIgnoringSystemIndexes(void)
71 return isIgnoringSystemIndexes;
76 * Set true or false whether PostgreSQL ignores system indexes.
79 IgnoreSystemIndexes(bool mode)
81 isIgnoringSystemIndexes = mode;
84 /* ----------------------------------------------------------------
85 * system index reindexing support
87 * When we are busy reindexing a system index, this code provides support
88 * for preventing catalog lookups from using that index.
89 * ----------------------------------------------------------------
92 static Oid currentlyReindexedHeap = InvalidOid;
93 static Oid currentlyReindexedIndex = InvalidOid;
96 * ReindexIsProcessingHeap
97 * True if heap specified by OID is currently being reindexed.
100 ReindexIsProcessingHeap(Oid heapOid)
102 return heapOid == currentlyReindexedHeap;
106 * ReindexIsProcessingIndex
107 * True if index specified by OID is currently being reindexed.
110 ReindexIsProcessingIndex(Oid indexOid)
112 return indexOid == currentlyReindexedIndex;
116 * SetReindexProcessing
117 * Set flag that specified heap/index are being reindexed.
118 * Pass InvalidOid to indicate that reindexing is not active.
121 SetReindexProcessing(Oid heapOid, Oid indexOid)
123 /* Args should be both, or neither, InvalidOid */
124 Assert((heapOid == InvalidOid) == (indexOid == InvalidOid));
125 /* Reindexing is not re-entrant. */
126 Assert(indexOid == InvalidOid || currentlyReindexedIndex == InvalidOid);
127 currentlyReindexedHeap = heapOid;
128 currentlyReindexedIndex = indexOid;
131 /* ----------------------------------------------------------------
132 * database path / name support stuff
133 * ----------------------------------------------------------------
137 SetDatabasePath(const char *path)
144 /* use strdup since this is done before memory contexts are set up */
147 DatabasePath = strdup(path);
148 AssertState(DatabasePath);
153 * Set data directory, but make sure it's an absolute path. Use this,
154 * never set DataDir directly.
157 SetDataDir(const char *dir)
163 /* If presented path is relative, convert to absolute */
164 if (!is_absolute_path(dir))
172 buf = malloc(buflen);
175 (errcode(ERRCODE_OUT_OF_MEMORY),
176 errmsg("out of memory")));
178 if (getcwd(buf, buflen))
180 else if (errno == ERANGE)
189 elog(FATAL, "could not get current working directory: %m");
193 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
196 (errcode(ERRCODE_OUT_OF_MEMORY),
197 errmsg("out of memory")));
198 sprintf(new, "%s/%s", buf, dir);
206 (errcode(ERRCODE_OUT_OF_MEMORY),
207 errmsg("out of memory")));
210 canonicalize_path(new);
218 /* ----------------------------------------------------------------
221 * The authenticated user is determined at connection start and never
222 * changes. The session user can be changed only by SET SESSION
223 * AUTHORIZATION. The current user may change when "setuid" functions
224 * are implemented. Conceptually there is a stack, whose bottom
225 * is the session user. You are yourself responsible to save and
226 * restore the current user id if you need to change it.
227 * ----------------------------------------------------------------
229 static AclId AuthenticatedUserId = 0;
230 static AclId SessionUserId = 0;
231 static AclId CurrentUserId = 0;
233 static bool AuthenticatedUserIsSuperuser = false;
236 * This function is relevant for all privilege checks.
241 AssertState(AclIdIsValid(CurrentUserId));
242 return CurrentUserId;
247 SetUserId(AclId newid)
249 AssertArg(AclIdIsValid(newid));
250 CurrentUserId = newid;
255 * This value is only relevant for informational purposes.
258 GetSessionUserId(void)
260 AssertState(AclIdIsValid(SessionUserId));
261 return SessionUserId;
266 SetSessionUserId(AclId newid)
268 AssertArg(AclIdIsValid(newid));
269 SessionUserId = newid;
270 /* Current user defaults to session user. */
271 if (!AclIdIsValid(CurrentUserId))
272 CurrentUserId = newid;
277 InitializeSessionUserId(const char *username)
285 * Don't do scans if we're bootstrapping, none of the system catalogs
286 * exist yet, and they should be owned by postgres anyway.
288 AssertState(!IsBootstrapProcessingMode());
291 AssertState(!OidIsValid(AuthenticatedUserId));
293 userTup = SearchSysCache(SHADOWNAME,
294 PointerGetDatum(username),
296 if (!HeapTupleIsValid(userTup))
298 (errcode(ERRCODE_UNDEFINED_OBJECT),
299 errmsg("user \"%s\" does not exist", username)));
301 usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
303 AuthenticatedUserId = usesysid;
304 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
306 SetSessionUserId(usesysid); /* sets CurrentUserId too */
308 /* Record username and superuser status as GUC settings too */
309 SetConfigOption("session_authorization", username,
310 PGC_BACKEND, PGC_S_OVERRIDE);
311 SetConfigOption("is_superuser",
312 AuthenticatedUserIsSuperuser ? "on" : "off",
313 PGC_INTERNAL, PGC_S_OVERRIDE);
316 * Set up user-specific configuration variables. This is a good place
317 * to do it so we don't have to read pg_shadow twice during session
320 datum = SysCacheGetAttr(SHADOWNAME, userTup,
321 Anum_pg_shadow_useconfig, &isnull);
324 ArrayType *a = DatumGetArrayTypeP(datum);
326 ProcessGUCArray(a, PGC_S_USER);
329 ReleaseSysCache(userTup);
334 InitializeSessionUserIdStandalone(void)
336 /* This function should only be called in a single-user backend. */
337 AssertState(!IsUnderPostmaster);
340 AssertState(!OidIsValid(AuthenticatedUserId));
342 AuthenticatedUserId = BOOTSTRAP_USESYSID;
343 AuthenticatedUserIsSuperuser = true;
345 SetSessionUserId(BOOTSTRAP_USESYSID);
350 * Change session auth ID while running
352 * Only a superuser may set auth ID to something other than himself. Note
353 * that in case of multiple SETs in a single session, the original userid's
354 * superuserness is what matters. But we set the GUC variable is_superuser
355 * to indicate whether the *current* session userid is a superuser.
358 SetSessionAuthorization(AclId userid, bool is_superuser)
360 /* Must have authenticated already, else can't make permission check */
361 AssertState(AclIdIsValid(AuthenticatedUserId));
363 if (userid != AuthenticatedUserId &&
364 !AuthenticatedUserIsSuperuser)
366 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
367 errmsg("permission denied to set session authorization")));
369 SetSessionUserId(userid);
372 SetConfigOption("is_superuser",
373 is_superuser ? "on" : "off",
374 PGC_INTERNAL, PGC_S_OVERRIDE);
379 * Get user name from user id
382 GetUserNameFromId(AclId userid)
387 tuple = SearchSysCache(SHADOWSYSID,
388 ObjectIdGetDatum(userid),
390 if (!HeapTupleIsValid(tuple))
392 (errcode(ERRCODE_UNDEFINED_OBJECT),
393 errmsg("invalid user ID: %d", userid)));
395 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
397 ReleaseSysCache(tuple);
403 /*-------------------------------------------------------------------------
404 * Interlock-file support
406 * These routines are used to create both a data-directory lockfile
407 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
408 * Both kinds of files contain the same info:
410 * Owning process' PID
411 * Data directory path
413 * By convention, the owning process' PID is negated if it is a standalone
414 * backend rather than a postmaster. This is just for informational purposes.
415 * The path is also just for informational purposes (so that a socket lockfile
416 * can be more easily traced to the associated postmaster).
418 * A data-directory lockfile can optionally contain a third line, containing
419 * the key and ID for the shared memory block used by this postmaster.
421 * On successful lockfile creation, a proc_exit callback to remove the
422 * lockfile is automatically created.
423 *-------------------------------------------------------------------------
427 * proc_exit callback to remove a lockfile.
430 UnlinkLockFile(int status, Datum filename)
432 char *fname = (char *) DatumGetPointer(filename);
436 if (unlink(fname) != 0)
438 /* Should we complain if the unlink fails? */
447 * filename is the name of the lockfile to create.
448 * amPostmaster is used to determine how to encode the output PID.
449 * isDDLock and refName are used to determine what error message to produce.
452 CreateLockFile(const char *filename, bool amPostmaster,
453 bool isDDLock, const char *refName)
456 char buffer[MAXPGPATH + 100];
461 pid_t my_pid = getpid();
464 * We need a loop here because of race conditions. But don't loop
465 * forever (for example, a non-writable $PGDATA directory might cause
466 * a failure that won't go away). 100 tries seems like plenty.
468 for (ntries = 0;; ntries++)
471 * Try to create the lock file --- O_EXCL makes this atomic.
473 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
475 break; /* Success; exit the retry loop */
478 * Couldn't create the pid file. Probably it already exists.
480 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
482 (errcode_for_file_access(),
483 errmsg("could not create lock file \"%s\": %m",
487 * Read the file to get the old owner's PID. Note race condition
488 * here: file might have been deleted since we tried to create it.
490 fd = open(filename, O_RDONLY, 0600);
494 continue; /* race condition; try again */
496 (errcode_for_file_access(),
497 errmsg("could not open lock file \"%s\": %m",
500 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
502 (errcode_for_file_access(),
503 errmsg("could not read lock file \"%s\": %m",
508 encoded_pid = atoi(buffer);
510 /* if pid < 0, the pid is for postgres, not postmaster */
511 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
514 elog(FATAL, "bogus data in lock file \"%s\"", filename);
517 * Check to see if the other process still exists
519 * Normally kill() will fail with ESRCH if the given PID doesn't
520 * exist. BeOS returns EINVAL for some silly reason, however.
522 if (other_pid != my_pid)
524 if (kill(other_pid, 0) == 0 ||
531 /* lockfile belongs to a live process */
533 (errcode(ERRCODE_LOCK_FILE_EXISTS),
534 errmsg("lock file \"%s\" already exists",
537 errhint("Is another %s (PID %d) running in data directory \"%s\"?",
538 (encoded_pid < 0 ? "postgres" : "postmaster"),
539 (int) other_pid, refName) :
540 errhint("Is another %s (PID %d) using socket file \"%s\"?",
541 (encoded_pid < 0 ? "postgres" : "postmaster"),
542 (int) other_pid, refName)));
547 * No, the creating process did not exist. However, it could be
548 * that the postmaster crashed (or more likely was kill -9'd by a
549 * clueless admin) but has left orphan backends behind. Check for
550 * this by looking to see if there is an associated shmem segment
551 * that is still in use.
559 ptr = strchr(buffer, '\n');
561 (ptr = strchr(ptr + 1, '\n')) != NULL)
564 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
566 if (PGSharedMemoryIsInUse(id1, id2))
568 (errcode(ERRCODE_LOCK_FILE_EXISTS),
569 errmsg("pre-existing shared memory block "
570 "(key %lu, ID %lu) is still in use",
572 errhint("If you're sure there are no old "
573 "server processes still running, remove "
574 "the shared memory block with "
575 "the command \"ipcrm\", or just delete the file \"%s\".",
582 * Looks like nobody's home. Unlink the file and try again to
583 * create it. Need a loop because of possible race condition
584 * against other would-be creators.
586 if (unlink(filename) < 0)
588 (errcode_for_file_access(),
589 errmsg("could not remove old lock file \"%s\": %m",
591 errhint("The file seems accidentally left over, but "
592 "it could not be removed. Please remove the file "
593 "by hand and try again.")));
597 * Successfully created the file, now fill it.
599 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
600 amPostmaster ? (int) my_pid : -((int) my_pid),
603 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
605 int save_errno = errno;
609 /* if write didn't set errno, assume problem is no disk space */
610 errno = save_errno ? save_errno : ENOSPC;
612 (errcode_for_file_access(),
613 errmsg("could not write lock file \"%s\": %m", filename)));
617 int save_errno = errno;
622 (errcode_for_file_access(),
623 errmsg("could not write lock file \"%s\": %m", filename)));
627 * Arrange for automatic removal of lockfile at proc_exit.
629 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
633 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
635 char lockfile[MAXPGPATH];
637 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
638 CreateLockFile(lockfile, amPostmaster, true, datadir);
639 /* Save name of lockfile for RecordSharedMemoryInLockFile */
640 strcpy(directoryLockFile, lockfile);
644 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
646 char lockfile[MAXPGPATH];
648 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
649 CreateLockFile(lockfile, amPostmaster, false, socketfile);
650 /* Save name of lockfile for TouchSocketLockFile */
651 strcpy(socketLockFile, lockfile);
655 * TouchSocketLockFile -- mark socket lock file as recently accessed
657 * This routine should be called every so often to ensure that the lock file
658 * has a recent mod or access date. That saves it
659 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
660 * (Another reason we should never have put the socket file in /tmp...)
663 TouchSocketLockFile(void)
665 /* Do nothing if we did not create a socket... */
666 if (socketLockFile[0] != '\0')
669 * utime() is POSIX standard, utimes() is a common alternative; if
670 * we have neither, fall back to actually reading the file (which
671 * only sets the access time not mod time, but that should be
672 * enough in most cases). In all paths, we ignore errors.
675 utime(socketLockFile, NULL);
676 #else /* !HAVE_UTIME */
678 utimes(socketLockFile, NULL);
679 #else /* !HAVE_UTIMES */
683 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
686 read(fd, buffer, sizeof(buffer));
689 #endif /* HAVE_UTIMES */
690 #endif /* HAVE_UTIME */
695 * Append information about a shared memory segment to the data directory
696 * lock file (if we have created one).
698 * This may be called multiple times in the life of a postmaster, if we
699 * delete and recreate shmem due to backend crash. Therefore, be prepared
700 * to overwrite existing information. (As of 7.1, a postmaster only creates
701 * one shm seg at a time; but for the purposes here, if we did have more than
702 * one then any one of them would do anyway.)
705 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
713 * Do nothing if we did not create a lockfile (probably because we are
714 * running standalone).
716 if (directoryLockFile[0] == '\0')
719 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
723 (errcode_for_file_access(),
724 errmsg("could not open file \"%s\": %m",
725 directoryLockFile)));
728 len = read(fd, buffer, sizeof(buffer) - 100);
732 (errcode_for_file_access(),
733 errmsg("could not read from file \"%s\": %m",
734 directoryLockFile)));
741 * Skip over first two lines (PID and path).
743 ptr = strchr(buffer, '\n');
745 (ptr = strchr(ptr + 1, '\n')) == NULL)
747 elog(LOG, "bogus data in \"%s\"", directoryLockFile);
754 * Append key information. Format to try to keep it the same length
755 * always (trailing junk won't hurt, but might confuse humans).
757 sprintf(ptr, "%9lu %9lu\n", id1, id2);
760 * And rewrite the data. Since we write in a single kernel call, this
761 * update should appear atomic to onlookers.
763 len = strlen(buffer);
765 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
766 (int) write(fd, buffer, len) != len)
768 /* if write didn't set errno, assume problem is no disk space */
772 (errcode_for_file_access(),
773 errmsg("could not write to file \"%s\": %m",
774 directoryLockFile)));
781 (errcode_for_file_access(),
782 errmsg("could not write to file \"%s\": %m",
783 directoryLockFile)));
788 /*-------------------------------------------------------------------------
789 * Version checking support
790 *-------------------------------------------------------------------------
794 * Determine whether the PG_VERSION file in directory `path' indicates
795 * a data version compatible with the version of this program.
797 * If compatible, return. Otherwise, ereport(FATAL).
800 ValidatePgVersion(const char *path)
802 char full_path[MAXPGPATH];
810 const char *version_string = PG_VERSION;
812 my_major = strtol(version_string, &endptr, 10);
814 my_minor = strtol(endptr + 1, NULL, 10);
816 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
818 file = AllocateFile(full_path, "r");
823 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
824 errmsg("\"%s\" is not a valid data directory",
826 errdetail("File \"%s\" is missing.", full_path)));
829 (errcode_for_file_access(),
830 errmsg("could not open file \"%s\": %m", full_path)));
833 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
836 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
837 errmsg("\"%s\" is not a valid data directory",
839 errdetail("File \"%s\" does not contain valid data.",
841 errhint("You may need to initdb.")));
845 if (my_major != file_major || my_minor != file_minor)
847 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
848 errmsg("database files are incompatible with server"),
849 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
850 "which is not compatible with this version %s.",
851 file_major, file_minor, version_string)));
854 /*-------------------------------------------------------------------------
855 * Library preload support
856 *-------------------------------------------------------------------------
859 #if defined(__mc68000__) && defined(__ELF__)
860 typedef int32 ((*func_ptr) ());
863 typedef char *((*func_ptr) ());
867 * process any libraries that should be preloaded and
868 * optionally pre-initialized
871 process_preload_libraries(char *preload_libraries_string)
877 if (preload_libraries_string == NULL)
880 /* Need a modifiable copy of string */
881 rawstring = pstrdup(preload_libraries_string);
883 /* Parse string into list of identifiers */
884 if (!SplitIdentifierString(rawstring, ',', &elemlist))
886 /* syntax error in list */
890 (errcode(ERRCODE_SYNTAX_ERROR),
891 errmsg("invalid list syntax for parameter \"preload_libraries\"")));
897 char *tok = (char *) lfirst(l);
898 char *sep = strstr(tok, ":");
899 char *filename = NULL;
900 char *funcname = NULL;
906 * a colon separator implies there is an initialization
907 * function that we need to run in addition to loading the
910 size_t filename_len = sep - tok;
911 size_t funcname_len = strlen(tok) - filename_len - 1;
913 filename = (char *) palloc(filename_len + 1);
914 memcpy(filename, tok, filename_len);
915 filename[filename_len] = '\0';
917 funcname = (char *) palloc(funcname_len + 1);
918 strcpy(funcname, sep + 1);
923 * no separator -- just load the library
925 filename = pstrdup(tok);
929 canonicalize_path(filename);
930 initfunc = (func_ptr) load_external_function(filename, funcname,
937 (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
938 filename, funcname)));
941 (errmsg("preloaded library \"%s\"",