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.118 2004/01/07 23:03:06 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
33 #include "catalog/catname.h"
34 #include "catalog/pg_shadow.h"
35 #include "libpq/libpq-be.h"
36 #include "miscadmin.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)
164 /* If presented path is relative, convert to absolute */
165 if (!is_absolute_path(dir))
173 buf = malloc(buflen);
176 (errcode(ERRCODE_OUT_OF_MEMORY),
177 errmsg("out of memory")));
179 if (getcwd(buf, buflen))
181 else if (errno == ERANGE)
190 elog(FATAL, "could not get current working directory: %m");
194 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
197 (errcode(ERRCODE_OUT_OF_MEMORY),
198 errmsg("out of memory")));
199 sprintf(new, "%s/%s", buf, dir);
207 (errcode(ERRCODE_OUT_OF_MEMORY),
208 errmsg("out of memory")));
212 * Strip any trailing slash. Not strictly necessary, but avoids
213 * generating funny-looking paths to individual files.
215 newlen = strlen(new);
216 if (newlen > 1 && new[newlen - 1] == '/'
218 || new[newlen - 1] == '\\'
221 new[newlen - 1] = '\0';
229 /* ----------------------------------------------------------------
232 * The authenticated user is determined at connection start and never
233 * changes. The session user can be changed only by SET SESSION
234 * AUTHORIZATION. The current user may change when "setuid" functions
235 * are implemented. Conceptually there is a stack, whose bottom
236 * is the session user. You are yourself responsible to save and
237 * restore the current user id if you need to change it.
238 * ----------------------------------------------------------------
240 static AclId AuthenticatedUserId = 0;
241 static AclId SessionUserId = 0;
242 static AclId CurrentUserId = 0;
244 static bool AuthenticatedUserIsSuperuser = false;
247 * This function is relevant for all privilege checks.
252 AssertState(AclIdIsValid(CurrentUserId));
253 return CurrentUserId;
258 SetUserId(AclId newid)
260 AssertArg(AclIdIsValid(newid));
261 CurrentUserId = newid;
266 * This value is only relevant for informational purposes.
269 GetSessionUserId(void)
271 AssertState(AclIdIsValid(SessionUserId));
272 return SessionUserId;
277 SetSessionUserId(AclId newid)
279 AssertArg(AclIdIsValid(newid));
280 SessionUserId = newid;
281 /* Current user defaults to session user. */
282 if (!AclIdIsValid(CurrentUserId))
283 CurrentUserId = newid;
288 InitializeSessionUserId(const char *username)
296 * Don't do scans if we're bootstrapping, none of the system catalogs
297 * exist yet, and they should be owned by postgres anyway.
299 AssertState(!IsBootstrapProcessingMode());
302 AssertState(!OidIsValid(AuthenticatedUserId));
304 userTup = SearchSysCache(SHADOWNAME,
305 PointerGetDatum(username),
307 if (!HeapTupleIsValid(userTup))
309 (errcode(ERRCODE_UNDEFINED_OBJECT),
310 errmsg("user \"%s\" does not exist", username)));
312 usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
314 AuthenticatedUserId = usesysid;
315 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
317 SetSessionUserId(usesysid); /* sets CurrentUserId too */
319 /* Record username and superuser status as GUC settings too */
320 SetConfigOption("session_authorization", username,
321 PGC_BACKEND, PGC_S_OVERRIDE);
322 SetConfigOption("is_superuser",
323 AuthenticatedUserIsSuperuser ? "on" : "off",
324 PGC_INTERNAL, PGC_S_OVERRIDE);
327 * Set up user-specific configuration variables. This is a good place
328 * to do it so we don't have to read pg_shadow twice during session
331 datum = SysCacheGetAttr(SHADOWNAME, userTup,
332 Anum_pg_shadow_useconfig, &isnull);
335 ArrayType *a = DatumGetArrayTypeP(datum);
337 ProcessGUCArray(a, PGC_S_USER);
340 ReleaseSysCache(userTup);
345 InitializeSessionUserIdStandalone(void)
347 /* This function should only be called in a single-user backend. */
348 AssertState(!IsUnderPostmaster);
351 AssertState(!OidIsValid(AuthenticatedUserId));
353 AuthenticatedUserId = BOOTSTRAP_USESYSID;
354 AuthenticatedUserIsSuperuser = true;
356 SetSessionUserId(BOOTSTRAP_USESYSID);
361 * Change session auth ID while running
363 * Only a superuser may set auth ID to something other than himself. Note
364 * that in case of multiple SETs in a single session, the original userid's
365 * superuserness is what matters. But we set the GUC variable is_superuser
366 * to indicate whether the *current* session userid is a superuser.
369 SetSessionAuthorization(AclId userid, bool is_superuser)
371 /* Must have authenticated already, else can't make permission check */
372 AssertState(AclIdIsValid(AuthenticatedUserId));
374 if (userid != AuthenticatedUserId &&
375 !AuthenticatedUserIsSuperuser)
377 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
378 errmsg("permission denied to set session authorization")));
380 SetSessionUserId(userid);
383 SetConfigOption("is_superuser",
384 is_superuser ? "on" : "off",
385 PGC_INTERNAL, PGC_S_OVERRIDE);
390 * Get user name from user id
393 GetUserNameFromId(AclId userid)
398 tuple = SearchSysCache(SHADOWSYSID,
399 ObjectIdGetDatum(userid),
401 if (!HeapTupleIsValid(tuple))
403 (errcode(ERRCODE_UNDEFINED_OBJECT),
404 errmsg("invalid user ID: %d", userid)));
406 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
408 ReleaseSysCache(tuple);
414 /*-------------------------------------------------------------------------
415 * Interlock-file support
417 * These routines are used to create both a data-directory lockfile
418 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
419 * Both kinds of files contain the same info:
421 * Owning process' PID
422 * Data directory path
424 * By convention, the owning process' PID is negated if it is a standalone
425 * backend rather than a postmaster. This is just for informational purposes.
426 * The path is also just for informational purposes (so that a socket lockfile
427 * can be more easily traced to the associated postmaster).
429 * A data-directory lockfile can optionally contain a third line, containing
430 * the key and ID for the shared memory block used by this postmaster.
432 * On successful lockfile creation, a proc_exit callback to remove the
433 * lockfile is automatically created.
434 *-------------------------------------------------------------------------
438 * proc_exit callback to remove a lockfile.
441 UnlinkLockFile(int status, Datum filename)
443 char *fname = (char *) DatumGetPointer(filename);
447 if (unlink(fname) != 0)
449 /* Should we complain if the unlink fails? */
458 * filename is the name of the lockfile to create.
459 * amPostmaster is used to determine how to encode the output PID.
460 * isDDLock and refName are used to determine what error message to produce.
463 CreateLockFile(const char *filename, bool amPostmaster,
464 bool isDDLock, const char *refName)
467 char buffer[MAXPGPATH + 100];
472 pid_t my_pid = getpid();
475 * We need a loop here because of race conditions. But don't loop
476 * forever (for example, a non-writable $PGDATA directory might cause
477 * a failure that won't go away). 100 tries seems like plenty.
479 for (ntries = 0;; ntries++)
482 * Try to create the lock file --- O_EXCL makes this atomic.
484 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
486 break; /* Success; exit the retry loop */
489 * Couldn't create the pid file. Probably it already exists.
491 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
493 (errcode_for_file_access(),
494 errmsg("could not create lock file \"%s\": %m",
498 * Read the file to get the old owner's PID. Note race condition
499 * here: file might have been deleted since we tried to create it.
501 fd = open(filename, O_RDONLY, 0600);
505 continue; /* race condition; try again */
507 (errcode_for_file_access(),
508 errmsg("could not open lock file \"%s\": %m",
511 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
513 (errcode_for_file_access(),
514 errmsg("could not read lock file \"%s\": %m",
519 encoded_pid = atoi(buffer);
521 /* if pid < 0, the pid is for postgres, not postmaster */
522 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
525 elog(FATAL, "bogus data in lock file \"%s\"", filename);
528 * Check to see if the other process still exists
530 * Normally kill() will fail with ESRCH if the given PID doesn't
531 * exist. BeOS returns EINVAL for some silly reason, however.
533 if (other_pid != my_pid)
535 if (kill(other_pid, 0) == 0 ||
542 /* lockfile belongs to a live process */
544 (errcode(ERRCODE_LOCK_FILE_EXISTS),
545 errmsg("lock file \"%s\" already exists",
548 errhint("Is another %s (PID %d) running in data directory \"%s\"?",
549 (encoded_pid < 0 ? "postgres" : "postmaster"),
550 (int) other_pid, refName) :
551 errhint("Is another %s (PID %d) using socket file \"%s\"?",
552 (encoded_pid < 0 ? "postgres" : "postmaster"),
553 (int) other_pid, refName)));
558 * No, the creating process did not exist. However, it could be
559 * that the postmaster crashed (or more likely was kill -9'd by a
560 * clueless admin) but has left orphan backends behind. Check for
561 * this by looking to see if there is an associated shmem segment
562 * that is still in use.
570 ptr = strchr(buffer, '\n');
572 (ptr = strchr(ptr + 1, '\n')) != NULL)
575 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
577 if (PGSharedMemoryIsInUse(id1, id2))
579 (errcode(ERRCODE_LOCK_FILE_EXISTS),
580 errmsg("pre-existing shared memory block "
581 "(key %lu, ID %lu) is still in use",
583 errhint("If you're sure there are no old "
584 "server processes still running, remove "
585 "the shared memory block with "
586 "the command \"ipcrm\", or just delete the file \"%s\".",
593 * Looks like nobody's home. Unlink the file and try again to
594 * create it. Need a loop because of possible race condition
595 * against other would-be creators.
597 if (unlink(filename) < 0)
599 (errcode_for_file_access(),
600 errmsg("could not remove old lock file \"%s\": %m",
602 errhint("The file seems accidentally left over, but "
603 "it could not be removed. Please remove the file "
604 "by hand and try again.")));
608 * Successfully created the file, now fill it.
610 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
611 amPostmaster ? (int) my_pid : -((int) my_pid),
614 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
616 int save_errno = errno;
620 /* if write didn't set errno, assume problem is no disk space */
621 errno = save_errno ? save_errno : ENOSPC;
623 (errcode_for_file_access(),
624 errmsg("could not write lock file \"%s\": %m", filename)));
629 * Arrange for automatic removal of lockfile at proc_exit.
631 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
635 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
637 char lockfile[MAXPGPATH];
639 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
640 CreateLockFile(lockfile, amPostmaster, true, datadir);
641 /* Save name of lockfile for RecordSharedMemoryInLockFile */
642 strcpy(directoryLockFile, lockfile);
646 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
648 char lockfile[MAXPGPATH];
650 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
651 CreateLockFile(lockfile, amPostmaster, false, socketfile);
652 /* Save name of lockfile for TouchSocketLockFile */
653 strcpy(socketLockFile, lockfile);
657 * TouchSocketLockFile -- mark socket lock file as recently accessed
659 * This routine should be called every so often to ensure that the lock file
660 * has a recent mod or access date. That saves it
661 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
662 * (Another reason we should never have put the socket file in /tmp...)
665 TouchSocketLockFile(void)
667 /* Do nothing if we did not create a socket... */
668 if (socketLockFile[0] != '\0')
671 * utime() is POSIX standard, utimes() is a common alternative; if
672 * we have neither, fall back to actually reading the file (which
673 * only sets the access time not mod time, but that should be
674 * enough in most cases). In all paths, we ignore errors.
677 utime(socketLockFile, NULL);
678 #else /* !HAVE_UTIME */
680 utimes(socketLockFile, NULL);
681 #else /* !HAVE_UTIMES */
685 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
688 read(fd, buffer, sizeof(buffer));
691 #endif /* HAVE_UTIMES */
692 #endif /* HAVE_UTIME */
697 * Append information about a shared memory segment to the data directory
698 * lock file (if we have created one).
700 * This may be called multiple times in the life of a postmaster, if we
701 * delete and recreate shmem due to backend crash. Therefore, be prepared
702 * to overwrite existing information. (As of 7.1, a postmaster only creates
703 * one shm seg at a time; but for the purposes here, if we did have more than
704 * one then any one of them would do anyway.)
707 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
715 * Do nothing if we did not create a lockfile (probably because we are
716 * running standalone).
718 if (directoryLockFile[0] == '\0')
721 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
725 (errcode_for_file_access(),
726 errmsg("could not open file \"%s\": %m",
727 directoryLockFile)));
730 len = read(fd, buffer, sizeof(buffer) - 100);
734 (errcode_for_file_access(),
735 errmsg("could not read from file \"%s\": %m",
736 directoryLockFile)));
743 * Skip over first two lines (PID and path).
745 ptr = strchr(buffer, '\n');
747 (ptr = strchr(ptr + 1, '\n')) == NULL)
749 elog(LOG, "bogus data in \"%s\"", directoryLockFile);
756 * Append key information. Format to try to keep it the same length
757 * always (trailing junk won't hurt, but might confuse humans).
759 sprintf(ptr, "%9lu %9lu\n", id1, id2);
762 * And rewrite the data. Since we write in a single kernel call, this
763 * update should appear atomic to onlookers.
765 len = strlen(buffer);
767 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
768 (int) write(fd, buffer, len) != len)
770 /* if write didn't set errno, assume problem is no disk space */
774 (errcode_for_file_access(),
775 errmsg("could not write to file \"%s\": %m",
776 directoryLockFile)));
784 /*-------------------------------------------------------------------------
785 * Version checking support
786 *-------------------------------------------------------------------------
790 * Determine whether the PG_VERSION file in directory `path' indicates
791 * a data version compatible with the version of this program.
793 * If compatible, return. Otherwise, ereport(FATAL).
796 ValidatePgVersion(const char *path)
798 char full_path[MAXPGPATH];
806 const char *version_string = PG_VERSION;
808 my_major = strtol(version_string, &endptr, 10);
810 my_minor = strtol(endptr + 1, NULL, 10);
812 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
814 file = AllocateFile(full_path, "r");
819 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
820 errmsg("\"%s\" is not a valid data directory",
822 errdetail("File \"%s\" is missing.", full_path)));
825 (errcode_for_file_access(),
826 errmsg("could not open file \"%s\": %m", full_path)));
829 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
832 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
833 errmsg("\"%s\" is not a valid data directory",
835 errdetail("File \"%s\" does not contain valid data.",
837 errhint("You may need to initdb.")));
841 if (my_major != file_major || my_minor != file_minor)
843 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
844 errmsg("database files are incompatible with server"),
845 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
846 "which is not compatible with this version %s.",
847 file_major, file_minor, version_string)));
850 /*-------------------------------------------------------------------------
851 * Library preload support
852 *-------------------------------------------------------------------------
855 #if defined(__mc68000__) && defined(__ELF__)
856 typedef int32 ((*func_ptr) ());
859 typedef char *((*func_ptr) ());
863 * process any libraries that should be preloaded and
864 * optionally pre-initialized
867 process_preload_libraries(char *preload_libraries_string)
873 if (preload_libraries_string == NULL)
876 /* Need a modifiable copy of string */
877 rawstring = pstrdup(preload_libraries_string);
879 /* Parse string into list of identifiers */
880 if (!SplitIdentifierString(rawstring, ',', &elemlist))
882 /* syntax error in list */
886 (errcode(ERRCODE_SYNTAX_ERROR),
887 errmsg("invalid list syntax for parameter \"preload_libraries\"")));
893 char *tok = (char *) lfirst(l);
894 char *sep = strstr(tok, ":");
895 char *filename = NULL;
896 char *funcname = NULL;
902 * a colon separator implies there is an initialization
903 * function that we need to run in addition to loading the
906 size_t filename_len = sep - tok;
907 size_t funcname_len = strlen(tok) - filename_len - 1;
909 filename = (char *) palloc(filename_len + 1);
910 memcpy(filename, tok, filename_len);
911 filename[filename_len] = '\0';
913 funcname = (char *) palloc(funcname_len + 1);
914 strcpy(funcname, sep + 1);
919 * no separator -- just load the library
921 filename = pstrdup(tok);
925 initfunc = (func_ptr) load_external_function(filename, funcname,
932 (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
933 filename, funcname)));
936 (errmsg("preloaded library \"%s\"",