1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.64 2001/03/22 04:00:00 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
18 #include <sys/types.h>
29 #include "catalog/catname.h"
30 #include "catalog/pg_shadow.h"
31 #include "miscadmin.h"
32 #include "utils/builtins.h"
33 #include "utils/syscache.h"
37 unsigned char RecodeForwTable[128];
38 unsigned char RecodeBackTable[128];
42 ProcessingMode Mode = InitProcessing;
44 /* Note: we rely on these to initialize as zeroes */
45 static char directoryLockFile[MAXPGPATH];
46 static char socketLockFile[MAXPGPATH];
49 /* ----------------------------------------------------------------
50 * ignoring system indexes support stuff
51 * ----------------------------------------------------------------
54 static bool isIgnoringSystemIndexes = false;
57 * IsIgnoringSystemIndexes
58 * True if ignoring system indexes.
61 IsIgnoringSystemIndexes()
63 return isIgnoringSystemIndexes;
68 * Set true or false whether PostgreSQL ignores system indexes.
72 IgnoreSystemIndexes(bool mode)
74 isIgnoringSystemIndexes = mode;
77 /* ----------------------------------------------------------------
78 * database path / name support stuff
79 * ----------------------------------------------------------------
83 SetDatabasePath(const char *path)
86 /* use strdup since this is done before memory contexts are set up */
89 DatabasePath = strdup(path);
90 AssertState(DatabasePath);
95 SetDatabaseName(const char *name)
100 DatabaseName = strdup(name);
101 AssertState(DatabaseName);
106 * Set data directory, but make sure it's an absolute path. Use this,
107 * never set DataDir directly.
110 SetDataDir(const char *dir)
126 buf = malloc(buflen);
128 elog(FATAL, "out of memory");
130 if (getcwd(buf, buflen))
132 else if (errno == ERANGE)
141 elog(FATAL, "cannot get current working directory: %m");
145 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
146 sprintf(new, "%s/%s", buf, dir);
153 elog(FATAL, "out of memory");
158 /* ----------------------------------------------------------------
159 * MULTIBYTE stub code
161 * Even if MULTIBYTE is not enabled, these functions are necessary
162 * since pg_proc.h has references to them.
163 * ----------------------------------------------------------------
169 getdatabaseencoding(PG_FUNCTION_ARGS)
171 PG_RETURN_NAME("SQL_ASCII");
175 PG_encoding_to_char(PG_FUNCTION_ARGS)
177 PG_RETURN_NAME("SQL_ASCII");
181 PG_char_to_encoding(PG_FUNCTION_ARGS)
188 /* ----------------------------------------------------------------
190 * ----------------------------------------------------------------
197 /* Some standard C libraries, including GNU, have an isblank() function.
198 Others, including Solaris, do not. So we have our own.
201 isblank(const char c)
203 return c == ' ' || c == 9 /* tab */ ;
207 next_token(FILE *fp, char *buf, const int bufsz)
209 /*--------------------------------------------------------------------------
210 Grab one token out of fp. Tokens are strings of non-blank
211 characters bounded by blank characters, beginning of line, and end
212 of line. Blank means space or tab. Return the token as *buf.
213 Leave file positioned to character immediately after the token or
214 EOF, whichever comes first. If no more tokens on line, return null
215 string as *buf and position file to beginning of next line or EOF,
216 whichever comes first.
217 --------------------------------------------------------------------------*/
219 char *eb = buf + (bufsz - 1);
221 /* Move over inital token-delimiting blanks */
222 while (isblank(c = getc(fp)));
228 * build a token in buf of next characters up to EOF, eol, or
231 while (c != EOF && c != '\n' && !isblank(c))
238 * Put back the char right after the token (putting back EOF
248 read_through_eol(FILE *file)
254 while (c != '\n' && c != EOF);
267 unsigned char FromChar,
270 for (i = 0; i < 128; i++)
272 RecodeForwTable[i] = i + 128;
273 RecodeBackTable[i] = i + 128;
276 p = getenv("PG_RECODETABLE");
279 map_file = (char *) malloc((strlen(DataDir) +
280 strlen(p) + 2) * sizeof(char));
281 sprintf(map_file, "%s/%s", DataDir, p);
282 file = AllocateFile(map_file, PG_BINARY_R);
295 read_through_eol(file);
298 /* Read the FromChar */
299 next_token(file, buf, sizeof(buf));
302 FromChar = strtoul(buf, 0, 0);
303 /* Read the ToChar */
304 next_token(file, buf, sizeof(buf));
307 ToChar = strtoul(buf, 0, 0);
308 RecodeForwTable[FromChar - 128] = ToChar;
309 RecodeBackTable[ToChar - 128] = FromChar;
311 read_through_eol(file);
322 convertstr(unsigned char *buff, int len, int dest)
327 for (i = 0; i < len; i++, buff++)
332 *buff = RecodeForwTable[*buff - 128];
334 *buff = RecodeBackTable[*buff - 128];
344 /* ----------------------------------------------------------------
347 * The session user is determined at connection start and never
348 * changes. The current user may change when "setuid" functions
349 * are implemented. Conceptually there is a stack, whose bottom
350 * is the session user. You are yourself responsible to save and
351 * restore the current user id if you need to change it.
352 * ----------------------------------------------------------------
354 static Oid CurrentUserId = InvalidOid;
355 static Oid SessionUserId = InvalidOid;
359 * This function is relevant for all privilege checks.
364 AssertState(OidIsValid(CurrentUserId));
365 return CurrentUserId;
372 AssertArg(OidIsValid(newid));
373 CurrentUserId = newid;
378 * This value is only relevant for informational purposes.
381 GetSessionUserId(void)
383 AssertState(OidIsValid(SessionUserId));
384 return SessionUserId;
389 SetSessionUserId(Oid newid)
391 AssertArg(OidIsValid(newid));
392 SessionUserId = newid;
393 /* Current user defaults to session user. */
394 if (!OidIsValid(CurrentUserId))
395 CurrentUserId = newid;
400 SetSessionUserIdFromUserName(const char *username)
405 * Don't do scans if we're bootstrapping, none of the system catalogs
406 * exist yet, and they should be owned by postgres anyway.
408 AssertState(!IsBootstrapProcessingMode());
410 userTup = SearchSysCache(SHADOWNAME,
411 PointerGetDatum(username),
413 if (!HeapTupleIsValid(userTup))
414 elog(FATAL, "user \"%s\" does not exist", username);
416 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
418 ReleaseSysCache(userTup);
423 * Get user name from user id
426 GetUserName(Oid userid)
431 tuple = SearchSysCache(SHADOWSYSID,
432 ObjectIdGetDatum(userid),
434 if (!HeapTupleIsValid(tuple))
435 elog(ERROR, "invalid user id %u", (unsigned) userid);
437 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
439 ReleaseSysCache(tuple);
445 /*-------------------------------------------------------------------------
446 * Interlock-file support
448 * These routines are used to create both a data-directory lockfile
449 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
450 * Both kinds of files contain the same info:
452 * Owning process' PID
453 * Data directory path
455 * By convention, the owning process' PID is negated if it is a standalone
456 * backend rather than a postmaster. This is just for informational purposes.
457 * The path is also just for informational purposes (so that a socket lockfile
458 * can be more easily traced to the associated postmaster).
460 * A data-directory lockfile can optionally contain a third line, containing
461 * the key and ID for the shared memory block used by this postmaster.
463 * On successful lockfile creation, a proc_exit callback to remove the
464 * lockfile is automatically created.
465 *-------------------------------------------------------------------------
469 * proc_exit callback to remove a lockfile.
472 UnlinkLockFile(int status, Datum filename)
474 unlink((char *) DatumGetPointer(filename));
475 /* Should we complain if the unlink fails? */
479 * Create a lockfile, if possible
481 * Call CreateLockFile with the name of the lockfile to be created.
482 * Returns true if successful, false if not (with a message on stderr).
484 * amPostmaster is used to determine how to encode the output PID.
485 * isDDLock and refName are used to determine what error message to produce.
488 CreateLockFile(const char *filename, bool amPostmaster,
489 bool isDDLock, const char *refName)
492 char buffer[MAXPGPATH + 100];
496 pid_t my_pid = getpid();
499 * We need a loop here because of race conditions.
505 * Try to create the lock file --- O_EXCL makes this atomic.
507 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
509 break; /* Success; exit the retry loop */
512 * Couldn't create the pid file. Probably it already exists.
514 if (errno != EEXIST && errno != EACCES)
515 elog(FATAL, "Can't create lock file %s: %m", filename);
518 * Read the file to get the old owner's PID. Note race condition
519 * here: file might have been deleted since we tried to create it.
521 fd = open(filename, O_RDONLY, 0600);
525 continue; /* race condition; try again */
526 elog(FATAL, "Can't read lock file %s: %m", filename);
528 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
529 elog(FATAL, "Can't read lock file %s: %m", filename);
533 encoded_pid = atoi(buffer);
535 /* if pid < 0, the pid is for postgres, not postmaster */
536 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
539 elog(FATAL, "Bogus data in lock file %s", filename);
542 * Check to see if the other process still exists
544 * Normally kill() will fail with ESRCH if the given PID doesn't
545 * exist. BeOS returns EINVAL for some silly reason, however.
547 if (other_pid != my_pid)
549 if (kill(other_pid, 0) == 0 ||
556 /* lockfile belongs to a live process */
557 fprintf(stderr, "Lock file \"%s\" already exists.\n",
561 "Is another %s (pid %d) running in \"%s\"?\n",
562 (encoded_pid < 0 ? "postgres" : "postmaster"),
566 "Is another %s (pid %d) using \"%s\"?\n",
567 (encoded_pid < 0 ? "postgres" : "postmaster"),
574 * No, the creating process did not exist. However, it could be
575 * that the postmaster crashed (or more likely was kill -9'd by a
576 * clueless admin) but has left orphan backends behind. Check for
577 * this by looking to see if there is an associated shmem segment
578 * that is still in use.
583 unsigned long shmKey,
586 ptr = strchr(buffer, '\n');
588 (ptr = strchr(ptr + 1, '\n')) != NULL)
591 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
593 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
594 (IpcMemoryId) shmId))
597 "Found a pre-existing shared memory block (ID %d) still in use.\n"
598 "If you're sure there are no old backends still running,\n"
599 "remove the shared memory block with ipcrm(1), or just\n"
601 (int) shmId, filename);
609 * Looks like nobody's home. Unlink the file and try again to
610 * create it. Need a loop because of possible race condition
611 * against other would-be creators.
613 if (unlink(filename) < 0)
614 elog(FATAL, "Can't remove old lock file %s: %m"
615 "\n\tThe file seems accidentally left, but I couldn't remove it."
616 "\n\tPlease remove the file by hand and try again.",
621 * Successfully created the file, now fill it.
623 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
624 amPostmaster ? (int) my_pid : -((int) my_pid),
626 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
628 int save_errno = errno;
633 elog(FATAL, "Can't write lock file %s: %m", filename);
638 * Arrange for automatic removal of lockfile at proc_exit.
640 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
642 return true; /* Success! */
646 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
648 char lockfile[MAXPGPATH];
650 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
651 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
653 /* Save name of lockfile for RecordSharedMemoryInLockFile */
654 strcpy(directoryLockFile, lockfile);
659 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
661 char lockfile[MAXPGPATH];
663 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
664 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
666 /* Save name of lockfile for TouchSocketLockFile */
667 strcpy(socketLockFile, lockfile);
672 * Re-read the socket lock file. This should be called every so often
673 * to ensure that the lock file has a recent access date. That saves it
674 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
675 * (Another reason we should never have put the socket file in /tmp...)
678 TouchSocketLockFile(void)
683 /* Do nothing if we did not create a socket... */
684 if (socketLockFile[0] != '\0')
686 /* XXX any need to complain about errors here? */
687 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
690 read(fd, buffer, sizeof(buffer));
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 anyway; but for the purposes here, if we did have more than
704 * one then any one of them would do anyway.)
707 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
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);
724 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
727 len = read(fd, buffer, sizeof(buffer) - 100);
730 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
737 * Skip over first two lines (PID and path).
739 ptr = strchr(buffer, '\n');
741 (ptr = strchr(ptr + 1, '\n')) == NULL)
743 elog(DEBUG, "Bogus data in %s", directoryLockFile);
750 * Append shm key and ID. Format to try to keep it the same length
751 * always (trailing junk won't hurt, but might confuse humans).
753 sprintf(ptr, "%9lu %9lu\n",
754 (unsigned long) shmKey, (unsigned long) shmId);
757 * And rewrite the data. Since we write in a single kernel call, this
758 * update should appear atomic to onlookers.
760 len = strlen(buffer);
761 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
762 (int) write(fd, buffer, len) != len)
764 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
772 /*-------------------------------------------------------------------------
773 * Version checking support
774 *-------------------------------------------------------------------------
778 * Determine whether the PG_VERSION file in directory `path' indicates
779 * a data version compatible with the version of this program.
781 * If compatible, return. Otherwise, elog(FATAL).
784 ValidatePgVersion(const char *path)
786 char full_path[MAXPGPATH];
794 const char *version_string = PG_VERSION;
796 my_major = strtol(version_string, &endptr, 10);
798 my_minor = strtol(endptr + 1, NULL, 10);
800 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
802 file = AllocateFile(full_path, "r");
806 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
808 elog(FATAL, "cannot open %s: %m", full_path);
811 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
813 elog(FATAL, "cannot read %s: %m", full_path);
815 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
819 if (my_major != file_major || my_minor != file_minor)
820 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
821 "which is not compatible with this version %s.",
822 file_major, file_minor, version_string);