1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2005, 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.141 2005/06/07 16:54:18 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
32 #include "catalog/pg_shadow.h"
33 #include "libpq/libpq-be.h"
34 #include "miscadmin.h"
35 #include "storage/fd.h"
36 #include "storage/ipc.h"
37 #include "storage/pg_shmem.h"
38 #include "utils/builtins.h"
39 #include "utils/guc.h"
40 #include "utils/lsyscache.h"
41 #include "utils/syscache.h"
44 ProcessingMode Mode = InitProcessing;
46 /* Note: we rely on these to initialize as zeroes */
47 static char directoryLockFile[MAXPGPATH];
48 static char socketLockFile[MAXPGPATH];
51 /* ----------------------------------------------------------------
52 * ignoring system indexes support stuff
54 * NOTE: "ignoring system indexes" means we do not use the system indexes
55 * for lookups (either in hardwired catalog accesses or in planner-generated
56 * plans). We do, however, still update the indexes when a catalog
57 * modification is made.
58 * ----------------------------------------------------------------
61 static bool isIgnoringSystemIndexes = false;
64 * IsIgnoringSystemIndexes
65 * True if ignoring system indexes.
68 IsIgnoringSystemIndexes(void)
70 return isIgnoringSystemIndexes;
75 * Set true or false whether PostgreSQL ignores system indexes.
78 IgnoreSystemIndexes(bool mode)
80 isIgnoringSystemIndexes = mode;
83 /* ----------------------------------------------------------------
84 * system index reindexing support
86 * When we are busy reindexing a system index, this code provides support
87 * for preventing catalog lookups from using that index.
88 * ----------------------------------------------------------------
91 static Oid currentlyReindexedHeap = InvalidOid;
92 static Oid currentlyReindexedIndex = InvalidOid;
95 * ReindexIsProcessingHeap
96 * True if heap specified by OID is currently being reindexed.
99 ReindexIsProcessingHeap(Oid heapOid)
101 return heapOid == currentlyReindexedHeap;
105 * ReindexIsProcessingIndex
106 * True if index specified by OID is currently being reindexed.
109 ReindexIsProcessingIndex(Oid indexOid)
111 return indexOid == currentlyReindexedIndex;
115 * SetReindexProcessing
116 * Set flag that specified heap/index are being reindexed.
119 SetReindexProcessing(Oid heapOid, Oid indexOid)
121 Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
122 /* Reindexing is not re-entrant. */
123 if (OidIsValid(currentlyReindexedIndex))
124 elog(ERROR, "cannot reindex while reindexing");
125 currentlyReindexedHeap = heapOid;
126 currentlyReindexedIndex = indexOid;
130 * ResetReindexProcessing
131 * Unset reindexing status.
134 ResetReindexProcessing(void)
136 currentlyReindexedHeap = InvalidOid;
137 currentlyReindexedIndex = InvalidOid;
140 /* ----------------------------------------------------------------
141 * database path / name support stuff
142 * ----------------------------------------------------------------
146 SetDatabasePath(const char *path)
153 /* use strdup since this is done before memory contexts are set up */
156 DatabasePath = strdup(path);
157 AssertState(DatabasePath);
162 * Set data directory, but make sure it's an absolute path. Use this,
163 * never set DataDir directly.
166 SetDataDir(const char *dir)
172 /* If presented path is relative, convert to absolute */
173 new = make_absolute_path(dir);
181 * If the given pathname isn't already absolute, make it so, interpreting
182 * it relative to the current working directory.
184 * Also canonicalizes the path. The result is always a malloc'd copy.
186 * Note: it is probably unwise to use this in running backends, since they
187 * have chdir'd to a database-specific subdirectory; the results would not be
188 * consistent across backends. Currently this is used only during postmaster
189 * or standalone-backend startup.
192 make_absolute_path(const char *path)
196 /* Returning null for null input is convenient for some callers */
200 if (!is_absolute_path(path))
208 buf = malloc(buflen);
211 (errcode(ERRCODE_OUT_OF_MEMORY),
212 errmsg("out of memory")));
214 if (getcwd(buf, buflen))
216 else if (errno == ERANGE)
225 elog(FATAL, "could not get current working directory: %m");
229 new = malloc(strlen(buf) + strlen(path) + 2);
232 (errcode(ERRCODE_OUT_OF_MEMORY),
233 errmsg("out of memory")));
234 sprintf(new, "%s/%s", buf, path);
242 (errcode(ERRCODE_OUT_OF_MEMORY),
243 errmsg("out of memory")));
246 /* Make sure punctuation is canonical, too */
247 canonicalize_path(new);
253 /* ----------------------------------------------------------------
256 * The authenticated user is determined at connection start and never
257 * changes. The session user can be changed only by SET SESSION
258 * AUTHORIZATION. The current user may change when "setuid" functions
259 * are implemented. Conceptually there is a stack, whose bottom
260 * is the session user. You are yourself responsible to save and
261 * restore the current user id if you need to change it.
262 * ----------------------------------------------------------------
264 static AclId AuthenticatedUserId = 0;
265 static AclId SessionUserId = 0;
266 static AclId CurrentUserId = 0;
268 static bool AuthenticatedUserIsSuperuser = false;
271 * This function is relevant for all privilege checks.
276 AssertState(AclIdIsValid(CurrentUserId));
277 return CurrentUserId;
282 SetUserId(AclId newid)
284 AssertArg(AclIdIsValid(newid));
285 CurrentUserId = newid;
290 * This value is only relevant for informational purposes.
293 GetSessionUserId(void)
295 AssertState(AclIdIsValid(SessionUserId));
296 return SessionUserId;
301 SetSessionUserId(AclId newid)
303 AssertArg(AclIdIsValid(newid));
304 SessionUserId = newid;
305 /* Current user defaults to session user. */
306 if (!AclIdIsValid(CurrentUserId))
307 CurrentUserId = newid;
312 InitializeSessionUserId(const char *username)
320 * Don't do scans if we're bootstrapping, none of the system catalogs
321 * exist yet, and they should be owned by postgres anyway.
323 AssertState(!IsBootstrapProcessingMode());
326 AssertState(!OidIsValid(AuthenticatedUserId));
328 userTup = SearchSysCache(SHADOWNAME,
329 PointerGetDatum(username),
331 if (!HeapTupleIsValid(userTup))
333 (errcode(ERRCODE_UNDEFINED_OBJECT),
334 errmsg("user \"%s\" does not exist", username)));
336 usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
338 AuthenticatedUserId = usesysid;
339 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
341 SetSessionUserId(usesysid); /* sets CurrentUserId too */
343 /* Record username and superuser status as GUC settings too */
344 SetConfigOption("session_authorization", username,
345 PGC_BACKEND, PGC_S_OVERRIDE);
346 SetConfigOption("is_superuser",
347 AuthenticatedUserIsSuperuser ? "on" : "off",
348 PGC_INTERNAL, PGC_S_OVERRIDE);
351 * Set up user-specific configuration variables. This is a good place
352 * to do it so we don't have to read pg_shadow twice during session
355 datum = SysCacheGetAttr(SHADOWNAME, userTup,
356 Anum_pg_shadow_useconfig, &isnull);
359 ArrayType *a = DatumGetArrayTypeP(datum);
361 ProcessGUCArray(a, PGC_S_USER);
364 ReleaseSysCache(userTup);
369 InitializeSessionUserIdStandalone(void)
371 /* This function should only be called in a single-user backend. */
372 AssertState(!IsUnderPostmaster);
375 AssertState(!OidIsValid(AuthenticatedUserId));
377 AuthenticatedUserId = BOOTSTRAP_USESYSID;
378 AuthenticatedUserIsSuperuser = true;
380 SetSessionUserId(BOOTSTRAP_USESYSID);
385 * Change session auth ID while running
387 * Only a superuser may set auth ID to something other than himself. Note
388 * that in case of multiple SETs in a single session, the original userid's
389 * superuserness is what matters. But we set the GUC variable is_superuser
390 * to indicate whether the *current* session userid is a superuser.
393 SetSessionAuthorization(AclId userid, bool is_superuser)
395 /* Must have authenticated already, else can't make permission check */
396 AssertState(AclIdIsValid(AuthenticatedUserId));
398 if (userid != AuthenticatedUserId &&
399 !AuthenticatedUserIsSuperuser)
401 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
402 errmsg("permission denied to set session authorization")));
404 SetSessionUserId(userid);
407 SetConfigOption("is_superuser",
408 is_superuser ? "on" : "off",
409 PGC_INTERNAL, PGC_S_OVERRIDE);
414 * Get user name from user id
417 GetUserNameFromId(AclId userid)
422 tuple = SearchSysCache(SHADOWSYSID,
423 ObjectIdGetDatum(userid),
425 if (!HeapTupleIsValid(tuple))
427 (errcode(ERRCODE_UNDEFINED_OBJECT),
428 errmsg("invalid user ID: %d", userid)));
430 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
432 ReleaseSysCache(tuple);
438 /*-------------------------------------------------------------------------
439 * Interlock-file support
441 * These routines are used to create both a data-directory lockfile
442 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
443 * Both kinds of files contain the same info:
445 * Owning process' PID
446 * Data directory path
448 * By convention, the owning process' PID is negated if it is a standalone
449 * backend rather than a postmaster. This is just for informational purposes.
450 * The path is also just for informational purposes (so that a socket lockfile
451 * can be more easily traced to the associated postmaster).
453 * A data-directory lockfile can optionally contain a third line, containing
454 * the key and ID for the shared memory block used by this postmaster.
456 * On successful lockfile creation, a proc_exit callback to remove the
457 * lockfile is automatically created.
458 *-------------------------------------------------------------------------
462 * proc_exit callback to remove a lockfile.
465 UnlinkLockFile(int status, Datum filename)
467 char *fname = (char *) DatumGetPointer(filename);
471 if (unlink(fname) != 0)
473 /* Should we complain if the unlink fails? */
482 * filename is the name of the lockfile to create.
483 * amPostmaster is used to determine how to encode the output PID.
484 * isDDLock and refName are used to determine what error message to produce.
487 CreateLockFile(const char *filename, bool amPostmaster,
488 bool isDDLock, const char *refName)
491 char buffer[MAXPGPATH + 100];
496 pid_t my_pid = getpid();
499 * We need a loop here because of race conditions. But don't loop
500 * forever (for example, a non-writable $PGDATA directory might cause
501 * a failure that won't go away). 100 tries seems like plenty.
503 for (ntries = 0;; ntries++)
506 * Try to create the lock file --- O_EXCL makes this atomic.
508 * Think not to make the file protection weaker than 0600. See
511 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
513 break; /* Success; exit the retry loop */
516 * Couldn't create the pid file. Probably it already exists.
518 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
520 (errcode_for_file_access(),
521 errmsg("could not create lock file \"%s\": %m",
525 * Read the file to get the old owner's PID. Note race condition
526 * here: file might have been deleted since we tried to create it.
528 fd = open(filename, O_RDONLY, 0600);
532 continue; /* race condition; try again */
534 (errcode_for_file_access(),
535 errmsg("could not open lock file \"%s\": %m",
538 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
540 (errcode_for_file_access(),
541 errmsg("could not read lock file \"%s\": %m",
546 encoded_pid = atoi(buffer);
548 /* if pid < 0, the pid is for postgres, not postmaster */
549 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
552 elog(FATAL, "bogus data in lock file \"%s\"", filename);
555 * Check to see if the other process still exists
557 * If the PID in the lockfile is our own PID or our parent's PID,
558 * then the file must be stale (probably left over from a previous
559 * system boot cycle). We need this test because of the likelihood
560 * that a reboot will assign exactly the same PID as we had in the
561 * previous reboot. Also, if there is just one more process launch
562 * in this reboot than in the previous one, the lockfile might mention
563 * our parent's PID. We can reject that since we'd never be launched
564 * directly by a competing postmaster. We can't detect grandparent
565 * processes unfortunately, but if the init script is written carefully
566 * then all but the immediate parent shell will be root-owned processes
567 * and so the kill test will fail with EPERM.
569 * We can treat the EPERM-error case as okay because that error implies
570 * that the existing process has a different userid than we do, which
571 * means it cannot be a competing postmaster. A postmaster cannot
572 * successfully attach to a data directory owned by a userid other
573 * than its own. (This is now checked directly in checkDataDir(),
574 * but has been true for a long time because of the restriction that
575 * the data directory isn't group- or world-accessible.) Also,
576 * since we create the lockfiles mode 600, we'd have failed above
577 * if the lockfile belonged to another userid --- which means that
578 * whatever process kill() is reporting about isn't the one that
579 * made the lockfile. (NOTE: this last consideration is the only
580 * one that keeps us from blowing away a Unix socket file belonging
581 * to an instance of Postgres being run by someone else, at least
582 * on machines where /tmp hasn't got a stickybit.)
584 * Windows hasn't got getppid(), but doesn't need it since it's not
585 * using real kill() either...
587 * Normally kill() will fail with ESRCH if the given PID doesn't
588 * exist. BeOS returns EINVAL for some silly reason, however.
590 if (other_pid != my_pid
592 && other_pid != getppid()
596 if (kill(other_pid, 0) == 0 ||
603 /* lockfile belongs to a live process */
605 (errcode(ERRCODE_LOCK_FILE_EXISTS),
606 errmsg("lock file \"%s\" already exists",
610 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
611 (int) other_pid, refName) :
612 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
613 (int) other_pid, refName)) :
615 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
616 (int) other_pid, refName) :
617 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
618 (int) other_pid, refName))));
623 * No, the creating process did not exist. However, it could be
624 * that the postmaster crashed (or more likely was kill -9'd by a
625 * clueless admin) but has left orphan backends behind. Check for
626 * this by looking to see if there is an associated shmem segment
627 * that is still in use.
635 ptr = strchr(buffer, '\n');
637 (ptr = strchr(ptr + 1, '\n')) != NULL)
640 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
642 if (PGSharedMemoryIsInUse(id1, id2))
644 (errcode(ERRCODE_LOCK_FILE_EXISTS),
645 errmsg("pre-existing shared memory block "
646 "(key %lu, ID %lu) is still in use",
648 errhint("If you're sure there are no old "
649 "server processes still running, remove "
650 "the shared memory block with "
651 "the command \"ipcclean\", \"ipcrm\", "
652 "or just delete the file \"%s\".",
659 * Looks like nobody's home. Unlink the file and try again to
660 * create it. Need a loop because of possible race condition
661 * against other would-be creators.
663 if (unlink(filename) < 0)
665 (errcode_for_file_access(),
666 errmsg("could not remove old lock file \"%s\": %m",
668 errhint("The file seems accidentally left over, but "
669 "it could not be removed. Please remove the file "
670 "by hand and try again.")));
674 * Successfully created the file, now fill it.
676 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
677 amPostmaster ? (int) my_pid : -((int) my_pid),
680 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
682 int save_errno = errno;
686 /* if write didn't set errno, assume problem is no disk space */
687 errno = save_errno ? save_errno : ENOSPC;
689 (errcode_for_file_access(),
690 errmsg("could not write lock file \"%s\": %m", filename)));
694 int save_errno = errno;
699 (errcode_for_file_access(),
700 errmsg("could not write lock file \"%s\": %m", filename)));
704 * Arrange for automatic removal of lockfile at proc_exit.
706 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
710 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
712 char lockfile[MAXPGPATH];
714 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
715 CreateLockFile(lockfile, amPostmaster, true, datadir);
716 /* Save name of lockfile for RecordSharedMemoryInLockFile */
717 strcpy(directoryLockFile, lockfile);
721 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
723 char lockfile[MAXPGPATH];
725 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
726 CreateLockFile(lockfile, amPostmaster, false, socketfile);
727 /* Save name of lockfile for TouchSocketLockFile */
728 strcpy(socketLockFile, lockfile);
732 * TouchSocketLockFile -- mark socket lock file as recently accessed
734 * This routine should be called every so often to ensure that the lock file
735 * has a recent mod or access date. That saves it
736 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
737 * (Another reason we should never have put the socket file in /tmp...)
740 TouchSocketLockFile(void)
742 /* Do nothing if we did not create a socket... */
743 if (socketLockFile[0] != '\0')
746 * utime() is POSIX standard, utimes() is a common alternative; if
747 * we have neither, fall back to actually reading the file (which
748 * only sets the access time not mod time, but that should be
749 * enough in most cases). In all paths, we ignore errors.
752 utime(socketLockFile, NULL);
753 #else /* !HAVE_UTIME */
755 utimes(socketLockFile, NULL);
756 #else /* !HAVE_UTIMES */
760 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
763 read(fd, buffer, sizeof(buffer));
766 #endif /* HAVE_UTIMES */
767 #endif /* HAVE_UTIME */
772 * Append information about a shared memory segment to the data directory
773 * lock file (if we have created one).
775 * This may be called multiple times in the life of a postmaster, if we
776 * delete and recreate shmem due to backend crash. Therefore, be prepared
777 * to overwrite existing information. (As of 7.1, a postmaster only creates
778 * one shm seg at a time; but for the purposes here, if we did have more than
779 * one then any one of them would do anyway.)
782 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
790 * Do nothing if we did not create a lockfile (probably because we are
791 * running standalone).
793 if (directoryLockFile[0] == '\0')
796 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
800 (errcode_for_file_access(),
801 errmsg("could not open file \"%s\": %m",
802 directoryLockFile)));
805 len = read(fd, buffer, sizeof(buffer) - 100);
809 (errcode_for_file_access(),
810 errmsg("could not read from file \"%s\": %m",
811 directoryLockFile)));
818 * Skip over first two lines (PID and path).
820 ptr = strchr(buffer, '\n');
822 (ptr = strchr(ptr + 1, '\n')) == NULL)
824 elog(LOG, "bogus data in \"%s\"", directoryLockFile);
831 * Append key information. Format to try to keep it the same length
832 * always (trailing junk won't hurt, but might confuse humans).
834 sprintf(ptr, "%9lu %9lu\n", id1, id2);
837 * And rewrite the data. Since we write in a single kernel call, this
838 * update should appear atomic to onlookers.
840 len = strlen(buffer);
842 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
843 (int) write(fd, buffer, len) != len)
845 /* if write didn't set errno, assume problem is no disk space */
849 (errcode_for_file_access(),
850 errmsg("could not write to file \"%s\": %m",
851 directoryLockFile)));
858 (errcode_for_file_access(),
859 errmsg("could not write to file \"%s\": %m",
860 directoryLockFile)));
865 /*-------------------------------------------------------------------------
866 * Version checking support
867 *-------------------------------------------------------------------------
871 * Determine whether the PG_VERSION file in directory `path' indicates
872 * a data version compatible with the version of this program.
874 * If compatible, return. Otherwise, ereport(FATAL).
877 ValidatePgVersion(const char *path)
879 char full_path[MAXPGPATH];
887 const char *version_string = PG_VERSION;
889 my_major = strtol(version_string, &endptr, 10);
891 my_minor = strtol(endptr + 1, NULL, 10);
893 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
895 file = AllocateFile(full_path, "r");
900 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
901 errmsg("\"%s\" is not a valid data directory",
903 errdetail("File \"%s\" is missing.", full_path)));
906 (errcode_for_file_access(),
907 errmsg("could not open file \"%s\": %m", full_path)));
910 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
913 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
914 errmsg("\"%s\" is not a valid data directory",
916 errdetail("File \"%s\" does not contain valid data.",
918 errhint("You may need to initdb.")));
922 if (my_major != file_major || my_minor != file_minor)
924 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
925 errmsg("database files are incompatible with server"),
926 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
927 "which is not compatible with this version %s.",
928 file_major, file_minor, version_string)));
931 /*-------------------------------------------------------------------------
932 * Library preload support
933 *-------------------------------------------------------------------------
936 typedef void (*func_ptr) ();
939 * process any libraries that should be preloaded and
940 * optionally pre-initialized
943 process_preload_libraries(char *preload_libraries_string)
949 if (preload_libraries_string == NULL)
952 /* Need a modifiable copy of string */
953 rawstring = pstrdup(preload_libraries_string);
955 /* Parse string into list of identifiers */
956 if (!SplitIdentifierString(rawstring, ',', &elemlist))
958 /* syntax error in list */
962 (errcode(ERRCODE_SYNTAX_ERROR),
963 errmsg("invalid list syntax for parameter \"preload_libraries\"")));
969 char *tok = (char *) lfirst(l);
970 char *sep = strstr(tok, ":");
971 char *filename = NULL;
972 char *funcname = NULL;
978 * a colon separator implies there is an initialization
979 * function that we need to run in addition to loading the
982 size_t filename_len = sep - tok;
983 size_t funcname_len = strlen(tok) - filename_len - 1;
985 filename = (char *) palloc(filename_len + 1);
986 memcpy(filename, tok, filename_len);
987 filename[filename_len] = '\0';
989 funcname = (char *) palloc(funcname_len + 1);
990 strcpy(funcname, sep + 1);
995 * no separator -- just load the library
997 filename = pstrdup(tok);
1001 canonicalize_path(filename);
1002 initfunc = (func_ptr) load_external_function(filename, funcname,
1009 (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
1010 filename, funcname)));
1013 (errmsg("preloaded library \"%s\"",
1022 list_free(elemlist);