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.68 2001/06/01 20:27:41 tgl 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);
147 elog(FATAL, "out of memory");
148 sprintf(new, "%s/%s", buf, dir);
155 elog(FATAL, "out of memory");
162 /* ----------------------------------------------------------------
163 * MULTIBYTE stub code
165 * Even if MULTIBYTE is not enabled, these functions are necessary
166 * since pg_proc.h has references to them.
167 * ----------------------------------------------------------------
173 getdatabaseencoding(PG_FUNCTION_ARGS)
175 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
179 PG_encoding_to_char(PG_FUNCTION_ARGS)
181 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
185 PG_char_to_encoding(PG_FUNCTION_ARGS)
192 /* ----------------------------------------------------------------
194 * ----------------------------------------------------------------
201 /* Some standard C libraries, including GNU, have an isblank() function.
202 Others, including Solaris, do not. So we have our own.
205 isblank(const char c)
207 return c == ' ' || c == 9 /* tab */ ;
211 next_token(FILE *fp, char *buf, const int bufsz)
213 /*--------------------------------------------------------------------------
214 Grab one token out of fp. Tokens are strings of non-blank
215 characters bounded by blank characters, beginning of line, and end
216 of line. Blank means space or tab. Return the token as *buf.
217 Leave file positioned to character immediately after the token or
218 EOF, whichever comes first. If no more tokens on line, return null
219 string as *buf and position file to beginning of next line or EOF,
220 whichever comes first.
221 --------------------------------------------------------------------------*/
223 char *eb = buf + (bufsz - 1);
225 /* Move over inital token-delimiting blanks */
226 while (isblank(c = getc(fp)));
232 * build a token in buf of next characters up to EOF, eol, or
235 while (c != EOF && c != '\n' && !isblank(c))
242 * Put back the char right after the token (putting back EOF
252 read_through_eol(FILE *file)
258 while (c != '\n' && c != EOF);
271 unsigned char FromChar,
274 for (i = 0; i < 128; i++)
276 RecodeForwTable[i] = i + 128;
277 RecodeBackTable[i] = i + 128;
280 p = getenv("PG_RECODETABLE");
283 map_file = (char *) malloc((strlen(DataDir) +
284 strlen(p) + 2) * sizeof(char));
286 elog(FATAL, "out of memory");
287 sprintf(map_file, "%s/%s", DataDir, p);
288 file = AllocateFile(map_file, PG_BINARY_R);
304 read_through_eol(file);
307 /* Read the FromChar */
308 next_token(file, buf, sizeof(buf));
311 FromChar = strtoul(buf, 0, 0);
312 /* Read the ToChar */
313 next_token(file, buf, sizeof(buf));
316 ToChar = strtoul(buf, 0, 0);
317 RecodeForwTable[FromChar - 128] = ToChar;
318 RecodeBackTable[ToChar - 128] = FromChar;
320 read_through_eol(file);
331 convertstr(unsigned char *buff, int len, int dest)
336 for (i = 0; i < len; i++, buff++)
341 *buff = RecodeForwTable[*buff - 128];
343 *buff = RecodeBackTable[*buff - 128];
353 /* ----------------------------------------------------------------
356 * The session user is determined at connection start and never
357 * changes. The current user may change when "setuid" functions
358 * are implemented. Conceptually there is a stack, whose bottom
359 * is the session user. You are yourself responsible to save and
360 * restore the current user id if you need to change it.
361 * ----------------------------------------------------------------
363 static Oid CurrentUserId = InvalidOid;
364 static Oid SessionUserId = InvalidOid;
366 static bool AuthenticatedUserIsSuperuser = false;
369 * This function is relevant for all privilege checks.
374 AssertState(OidIsValid(CurrentUserId));
375 return CurrentUserId;
382 AssertArg(OidIsValid(newid));
383 CurrentUserId = newid;
388 * This value is only relevant for informational purposes.
391 GetSessionUserId(void)
393 AssertState(OidIsValid(SessionUserId));
394 return SessionUserId;
399 SetSessionUserId(Oid newid)
401 AssertArg(OidIsValid(newid));
402 SessionUserId = newid;
403 /* Current user defaults to session user. */
404 if (!OidIsValid(CurrentUserId))
405 CurrentUserId = newid;
410 InitializeSessionUserId(const char *username)
415 * Don't do scans if we're bootstrapping, none of the system catalogs
416 * exist yet, and they should be owned by postgres anyway.
418 AssertState(!IsBootstrapProcessingMode());
421 AssertState(!OidIsValid(SessionUserId));
423 userTup = SearchSysCache(SHADOWNAME,
424 PointerGetDatum(username),
426 if (!HeapTupleIsValid(userTup))
427 elog(FATAL, "user \"%s\" does not exist", username);
429 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
431 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
433 ReleaseSysCache(userTup);
438 void SetSessionAuthorization(const char * username)
442 if (!AuthenticatedUserIsSuperuser)
443 elog(ERROR, "permission denied");
445 userTup = SearchSysCache(SHADOWNAME,
446 PointerGetDatum(username),
448 if (!HeapTupleIsValid(userTup))
449 elog(ERROR, "user \"%s\" does not exist", username);
451 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
452 SetUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
454 ReleaseSysCache(userTup);
459 * Get user name from user id
462 GetUserName(Oid userid)
467 tuple = SearchSysCache(SHADOWSYSID,
468 ObjectIdGetDatum(userid),
470 if (!HeapTupleIsValid(tuple))
471 elog(ERROR, "invalid user id %u", (unsigned) userid);
473 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
475 ReleaseSysCache(tuple);
481 /*-------------------------------------------------------------------------
482 * Interlock-file support
484 * These routines are used to create both a data-directory lockfile
485 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
486 * Both kinds of files contain the same info:
488 * Owning process' PID
489 * Data directory path
491 * By convention, the owning process' PID is negated if it is a standalone
492 * backend rather than a postmaster. This is just for informational purposes.
493 * The path is also just for informational purposes (so that a socket lockfile
494 * can be more easily traced to the associated postmaster).
496 * A data-directory lockfile can optionally contain a third line, containing
497 * the key and ID for the shared memory block used by this postmaster.
499 * On successful lockfile creation, a proc_exit callback to remove the
500 * lockfile is automatically created.
501 *-------------------------------------------------------------------------
505 * proc_exit callback to remove a lockfile.
508 UnlinkLockFile(int status, Datum filename)
510 unlink((char *) DatumGetPointer(filename));
511 /* Should we complain if the unlink fails? */
515 * Create a lockfile, if possible
517 * Call CreateLockFile with the name of the lockfile to be created.
518 * Returns true if successful, false if not (with a message on stderr).
520 * amPostmaster is used to determine how to encode the output PID.
521 * isDDLock and refName are used to determine what error message to produce.
524 CreateLockFile(const char *filename, bool amPostmaster,
525 bool isDDLock, const char *refName)
528 char buffer[MAXPGPATH + 100];
532 pid_t my_pid = getpid();
535 * We need a loop here because of race conditions.
541 * Try to create the lock file --- O_EXCL makes this atomic.
543 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
545 break; /* Success; exit the retry loop */
548 * Couldn't create the pid file. Probably it already exists.
550 if (errno != EEXIST && errno != EACCES)
551 elog(FATAL, "Can't create lock file %s: %m", filename);
554 * Read the file to get the old owner's PID. Note race condition
555 * here: file might have been deleted since we tried to create it.
557 fd = open(filename, O_RDONLY, 0600);
561 continue; /* race condition; try again */
562 elog(FATAL, "Can't read lock file %s: %m", filename);
564 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
565 elog(FATAL, "Can't read lock file %s: %m", filename);
569 encoded_pid = atoi(buffer);
571 /* if pid < 0, the pid is for postgres, not postmaster */
572 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
575 elog(FATAL, "Bogus data in lock file %s", filename);
578 * Check to see if the other process still exists
580 * Normally kill() will fail with ESRCH if the given PID doesn't
581 * exist. BeOS returns EINVAL for some silly reason, however.
583 if (other_pid != my_pid)
585 if (kill(other_pid, 0) == 0 ||
592 /* lockfile belongs to a live process */
593 fprintf(stderr, "Lock file \"%s\" already exists.\n",
597 "Is another %s (pid %d) running in \"%s\"?\n",
598 (encoded_pid < 0 ? "postgres" : "postmaster"),
599 (int) other_pid, refName);
602 "Is another %s (pid %d) using \"%s\"?\n",
603 (encoded_pid < 0 ? "postgres" : "postmaster"),
604 (int) other_pid, refName);
610 * No, the creating process did not exist. However, it could be
611 * that the postmaster crashed (or more likely was kill -9'd by a
612 * clueless admin) but has left orphan backends behind. Check for
613 * this by looking to see if there is an associated shmem segment
614 * that is still in use.
619 unsigned long shmKey,
622 ptr = strchr(buffer, '\n');
624 (ptr = strchr(ptr + 1, '\n')) != NULL)
627 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
629 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
630 (IpcMemoryId) shmId))
633 "Found a pre-existing shared memory block (ID %d) still in use.\n"
634 "If you're sure there are no old backends still running,\n"
635 "remove the shared memory block with ipcrm(1), or just\n"
637 (int) shmId, filename);
645 * Looks like nobody's home. Unlink the file and try again to
646 * create it. Need a loop because of possible race condition
647 * against other would-be creators.
649 if (unlink(filename) < 0)
650 elog(FATAL, "Can't remove old lock file %s: %m"
651 "\n\tThe file seems accidentally left, but I couldn't remove it."
652 "\n\tPlease remove the file by hand and try again.",
657 * Successfully created the file, now fill it.
659 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
660 amPostmaster ? (int) my_pid : -((int) my_pid),
662 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
664 int save_errno = errno;
669 elog(FATAL, "Can't write lock file %s: %m", filename);
674 * Arrange for automatic removal of lockfile at proc_exit.
676 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
678 return true; /* Success! */
682 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
684 char lockfile[MAXPGPATH];
686 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
687 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
689 /* Save name of lockfile for RecordSharedMemoryInLockFile */
690 strcpy(directoryLockFile, lockfile);
695 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
697 char lockfile[MAXPGPATH];
699 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
700 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
702 /* Save name of lockfile for TouchSocketLockFile */
703 strcpy(socketLockFile, lockfile);
708 * Re-read the socket lock file. This should be called every so often
709 * to ensure that the lock file has a recent access date. That saves it
710 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
711 * (Another reason we should never have put the socket file in /tmp...)
714 TouchSocketLockFile(void)
719 /* Do nothing if we did not create a socket... */
720 if (socketLockFile[0] != '\0')
722 /* XXX any need to complain about errors here? */
723 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
726 read(fd, buffer, sizeof(buffer));
733 * Append information about a shared memory segment to the data directory
734 * lock file (if we have created one).
736 * This may be called multiple times in the life of a postmaster, if we
737 * delete and recreate shmem due to backend crash. Therefore, be prepared
738 * to overwrite existing information. (As of 7.1, a postmaster only creates
739 * one shm seg anyway; but for the purposes here, if we did have more than
740 * one then any one of them would do anyway.)
743 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
751 * Do nothing if we did not create a lockfile (probably because we are
752 * running standalone).
754 if (directoryLockFile[0] == '\0')
757 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
760 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
763 len = read(fd, buffer, sizeof(buffer) - 100);
766 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
773 * Skip over first two lines (PID and path).
775 ptr = strchr(buffer, '\n');
777 (ptr = strchr(ptr + 1, '\n')) == NULL)
779 elog(DEBUG, "Bogus data in %s", directoryLockFile);
786 * Append shm key and ID. Format to try to keep it the same length
787 * always (trailing junk won't hurt, but might confuse humans).
789 sprintf(ptr, "%9lu %9lu\n",
790 (unsigned long) shmKey, (unsigned long) shmId);
793 * And rewrite the data. Since we write in a single kernel call, this
794 * update should appear atomic to onlookers.
796 len = strlen(buffer);
797 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
798 (int) write(fd, buffer, len) != len)
800 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
808 /*-------------------------------------------------------------------------
809 * Version checking support
810 *-------------------------------------------------------------------------
814 * Determine whether the PG_VERSION file in directory `path' indicates
815 * a data version compatible with the version of this program.
817 * If compatible, return. Otherwise, elog(FATAL).
820 ValidatePgVersion(const char *path)
822 char full_path[MAXPGPATH];
830 const char *version_string = PG_VERSION;
832 my_major = strtol(version_string, &endptr, 10);
834 my_minor = strtol(endptr + 1, NULL, 10);
836 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
838 file = AllocateFile(full_path, "r");
842 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
844 elog(FATAL, "cannot open %s: %m", full_path);
847 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
849 elog(FATAL, "cannot read %s: %m", full_path);
851 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
855 if (my_major != file_major || my_minor != file_minor)
856 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
857 "which is not compatible with this version %s.",
858 file_major, file_minor, version_string);