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.70 2001/06/13 19:52:33 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];
41 ProcessingMode Mode = InitProcessing;
43 /* Note: we rely on these to initialize as zeroes */
44 static char directoryLockFile[MAXPGPATH];
45 static char socketLockFile[MAXPGPATH];
48 /* ----------------------------------------------------------------
49 * ignoring system indexes support stuff
50 * ----------------------------------------------------------------
53 static bool isIgnoringSystemIndexes = false;
56 * IsIgnoringSystemIndexes
57 * True if ignoring system indexes.
60 IsIgnoringSystemIndexes()
62 return isIgnoringSystemIndexes;
67 * Set true or false whether PostgreSQL ignores system indexes.
71 IgnoreSystemIndexes(bool mode)
73 isIgnoringSystemIndexes = mode;
76 /* ----------------------------------------------------------------
77 * database path / name support stuff
78 * ----------------------------------------------------------------
82 SetDatabasePath(const char *path)
89 /* use strdup since this is done before memory contexts are set up */
92 DatabasePath = strdup(path);
93 AssertState(DatabasePath);
98 SetDatabaseName(const char *name)
105 /* use strdup since this is done before memory contexts are set up */
108 DatabaseName = strdup(name);
109 AssertState(DatabaseName);
114 * Set data directory, but make sure it's an absolute path. Use this,
115 * never set DataDir directly.
118 SetDataDir(const char *dir)
132 buf = malloc(buflen);
134 elog(FATAL, "out of memory");
136 if (getcwd(buf, buflen))
138 else if (errno == ERANGE)
147 elog(FATAL, "cannot get current working directory: %m");
151 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
153 elog(FATAL, "out of memory");
154 sprintf(new, "%s/%s", buf, dir);
161 elog(FATAL, "out of memory");
170 /* ----------------------------------------------------------------
171 * MULTIBYTE stub code
173 * Even if MULTIBYTE is not enabled, these functions are necessary
174 * since pg_proc.h has references to them.
175 * ----------------------------------------------------------------
181 getdatabaseencoding(PG_FUNCTION_ARGS)
183 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
187 PG_encoding_to_char(PG_FUNCTION_ARGS)
189 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
193 PG_char_to_encoding(PG_FUNCTION_ARGS)
200 /* ----------------------------------------------------------------
202 * ----------------------------------------------------------------
209 /* Some standard C libraries, including GNU, have an isblank() function.
210 Others, including Solaris, do not. So we have our own.
213 isblank(const char c)
215 return c == ' ' || c == 9 /* tab */ ;
219 next_token(FILE *fp, char *buf, const int bufsz)
221 /*--------------------------------------------------------------------------
222 Grab one token out of fp. Tokens are strings of non-blank
223 characters bounded by blank characters, beginning of line, and end
224 of line. Blank means space or tab. Return the token as *buf.
225 Leave file positioned to character immediately after the token or
226 EOF, whichever comes first. If no more tokens on line, return null
227 string as *buf and position file to beginning of next line or EOF,
228 whichever comes first.
229 --------------------------------------------------------------------------*/
231 char *eb = buf + (bufsz - 1);
233 /* Move over inital token-delimiting blanks */
234 while (isblank(c = getc(fp)));
240 * build a token in buf of next characters up to EOF, eol, or
243 while (c != EOF && c != '\n' && !isblank(c))
250 * Put back the char right after the token (putting back EOF
260 read_through_eol(FILE *file)
266 while (c != '\n' && c != EOF);
279 unsigned char FromChar,
282 for (i = 0; i < 128; i++)
284 RecodeForwTable[i] = i + 128;
285 RecodeBackTable[i] = i + 128;
288 p = getenv("PG_RECODETABLE");
291 map_file = (char *) malloc((strlen(DataDir) +
292 strlen(p) + 2) * sizeof(char));
294 elog(FATAL, "out of memory");
295 sprintf(map_file, "%s/%s", DataDir, p);
296 file = AllocateFile(map_file, PG_BINARY_R);
312 read_through_eol(file);
315 /* Read the FromChar */
316 next_token(file, buf, sizeof(buf));
319 FromChar = strtoul(buf, 0, 0);
320 /* Read the ToChar */
321 next_token(file, buf, sizeof(buf));
324 ToChar = strtoul(buf, 0, 0);
325 RecodeForwTable[FromChar - 128] = ToChar;
326 RecodeBackTable[ToChar - 128] = FromChar;
328 read_through_eol(file);
339 convertstr(unsigned char *buff, int len, int dest)
344 for (i = 0; i < len; i++, buff++)
349 *buff = RecodeForwTable[*buff - 128];
351 *buff = RecodeBackTable[*buff - 128];
361 /* ----------------------------------------------------------------
364 * The session user is determined at connection start and never
365 * changes. The current user may change when "setuid" functions
366 * are implemented. Conceptually there is a stack, whose bottom
367 * is the session user. You are yourself responsible to save and
368 * restore the current user id if you need to change it.
369 * ----------------------------------------------------------------
371 static Oid CurrentUserId = InvalidOid;
372 static Oid SessionUserId = InvalidOid;
374 static bool AuthenticatedUserIsSuperuser = false;
377 * This function is relevant for all privilege checks.
382 AssertState(OidIsValid(CurrentUserId));
383 return CurrentUserId;
390 AssertArg(OidIsValid(newid));
391 CurrentUserId = newid;
396 * This value is only relevant for informational purposes.
399 GetSessionUserId(void)
401 AssertState(OidIsValid(SessionUserId));
402 return SessionUserId;
407 SetSessionUserId(Oid newid)
409 AssertArg(OidIsValid(newid));
410 SessionUserId = newid;
411 /* Current user defaults to session user. */
412 if (!OidIsValid(CurrentUserId))
413 CurrentUserId = newid;
418 InitializeSessionUserId(const char *username)
423 * Don't do scans if we're bootstrapping, none of the system catalogs
424 * exist yet, and they should be owned by postgres anyway.
426 AssertState(!IsBootstrapProcessingMode());
429 AssertState(!OidIsValid(SessionUserId));
431 userTup = SearchSysCache(SHADOWNAME,
432 PointerGetDatum(username),
434 if (!HeapTupleIsValid(userTup))
435 elog(FATAL, "user \"%s\" does not exist", username);
437 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
439 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
441 ReleaseSysCache(userTup);
446 void SetSessionAuthorization(const char * username)
450 if (!AuthenticatedUserIsSuperuser)
451 elog(ERROR, "permission denied");
453 userTup = SearchSysCache(SHADOWNAME,
454 PointerGetDatum(username),
456 if (!HeapTupleIsValid(userTup))
457 elog(ERROR, "user \"%s\" does not exist", username);
459 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
460 SetUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
462 ReleaseSysCache(userTup);
467 * Get user name from user id
470 GetUserName(Oid userid)
475 tuple = SearchSysCache(SHADOWSYSID,
476 ObjectIdGetDatum(userid),
478 if (!HeapTupleIsValid(tuple))
479 elog(ERROR, "invalid user id %u", (unsigned) userid);
481 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
483 ReleaseSysCache(tuple);
489 /*-------------------------------------------------------------------------
490 * Interlock-file support
492 * These routines are used to create both a data-directory lockfile
493 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
494 * Both kinds of files contain the same info:
496 * Owning process' PID
497 * Data directory path
499 * By convention, the owning process' PID is negated if it is a standalone
500 * backend rather than a postmaster. This is just for informational purposes.
501 * The path is also just for informational purposes (so that a socket lockfile
502 * can be more easily traced to the associated postmaster).
504 * A data-directory lockfile can optionally contain a third line, containing
505 * the key and ID for the shared memory block used by this postmaster.
507 * On successful lockfile creation, a proc_exit callback to remove the
508 * lockfile is automatically created.
509 *-------------------------------------------------------------------------
513 * proc_exit callback to remove a lockfile.
516 UnlinkLockFile(int status, Datum filename)
518 unlink((char *) DatumGetPointer(filename));
519 /* Should we complain if the unlink fails? */
523 * Create a lockfile, if possible
525 * Call CreateLockFile with the name of the lockfile to be created.
526 * Returns true if successful, false if not (with a message on stderr).
528 * amPostmaster is used to determine how to encode the output PID.
529 * isDDLock and refName are used to determine what error message to produce.
532 CreateLockFile(const char *filename, bool amPostmaster,
533 bool isDDLock, const char *refName)
536 char buffer[MAXPGPATH + 100];
540 pid_t my_pid = getpid();
543 * We need a loop here because of race conditions.
549 * Try to create the lock file --- O_EXCL makes this atomic.
551 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
553 break; /* Success; exit the retry loop */
556 * Couldn't create the pid file. Probably it already exists.
558 if (errno != EEXIST && errno != EACCES)
559 elog(FATAL, "Can't create lock file %s: %m", filename);
562 * Read the file to get the old owner's PID. Note race condition
563 * here: file might have been deleted since we tried to create it.
565 fd = open(filename, O_RDONLY, 0600);
569 continue; /* race condition; try again */
570 elog(FATAL, "Can't read lock file %s: %m", filename);
572 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
573 elog(FATAL, "Can't read lock file %s: %m", filename);
577 encoded_pid = atoi(buffer);
579 /* if pid < 0, the pid is for postgres, not postmaster */
580 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
583 elog(FATAL, "Bogus data in lock file %s", filename);
586 * Check to see if the other process still exists
588 * Normally kill() will fail with ESRCH if the given PID doesn't
589 * exist. BeOS returns EINVAL for some silly reason, however.
591 if (other_pid != my_pid)
593 if (kill(other_pid, 0) == 0 ||
600 /* lockfile belongs to a live process */
601 fprintf(stderr, "Lock file \"%s\" already exists.\n",
605 "Is another %s (pid %d) running in \"%s\"?\n",
606 (encoded_pid < 0 ? "postgres" : "postmaster"),
607 (int) other_pid, refName);
610 "Is another %s (pid %d) using \"%s\"?\n",
611 (encoded_pid < 0 ? "postgres" : "postmaster"),
612 (int) other_pid, refName);
618 * No, the creating process did not exist. However, it could be
619 * that the postmaster crashed (or more likely was kill -9'd by a
620 * clueless admin) but has left orphan backends behind. Check for
621 * this by looking to see if there is an associated shmem segment
622 * that is still in use.
627 unsigned long shmKey,
630 ptr = strchr(buffer, '\n');
632 (ptr = strchr(ptr + 1, '\n')) != NULL)
635 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
637 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
638 (IpcMemoryId) shmId))
641 "Found a pre-existing shared memory block (ID %d) still in use.\n"
642 "If you're sure there are no old backends still running,\n"
643 "remove the shared memory block with ipcrm(1), or just\n"
645 (int) shmId, filename);
653 * Looks like nobody's home. Unlink the file and try again to
654 * create it. Need a loop because of possible race condition
655 * against other would-be creators.
657 if (unlink(filename) < 0)
658 elog(FATAL, "Can't remove old lock file %s: %m"
659 "\n\tThe file seems accidentally left, but I couldn't remove it."
660 "\n\tPlease remove the file by hand and try again.",
665 * Successfully created the file, now fill it.
667 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
668 amPostmaster ? (int) my_pid : -((int) my_pid),
671 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
673 int save_errno = errno;
677 /* if write didn't set errno, assume problem is no disk space */
678 errno = save_errno ? save_errno : ENOSPC;
679 elog(FATAL, "Can't write lock file %s: %m", filename);
684 * Arrange for automatic removal of lockfile at proc_exit.
686 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
688 return true; /* Success! */
692 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
694 char lockfile[MAXPGPATH];
696 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
697 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
699 /* Save name of lockfile for RecordSharedMemoryInLockFile */
700 strcpy(directoryLockFile, lockfile);
705 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
707 char lockfile[MAXPGPATH];
709 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
710 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
712 /* Save name of lockfile for TouchSocketLockFile */
713 strcpy(socketLockFile, lockfile);
718 * Re-read the socket lock file. This should be called every so often
719 * to ensure that the lock file has a recent access date. That saves it
720 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
721 * (Another reason we should never have put the socket file in /tmp...)
724 TouchSocketLockFile(void)
729 /* Do nothing if we did not create a socket... */
730 if (socketLockFile[0] != '\0')
732 /* XXX any need to complain about errors here? */
733 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
736 read(fd, buffer, sizeof(buffer));
743 * Append information about a shared memory segment to the data directory
744 * lock file (if we have created one).
746 * This may be called multiple times in the life of a postmaster, if we
747 * delete and recreate shmem due to backend crash. Therefore, be prepared
748 * to overwrite existing information. (As of 7.1, a postmaster only creates
749 * one shm seg anyway; but for the purposes here, if we did have more than
750 * one then any one of them would do anyway.)
753 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
761 * Do nothing if we did not create a lockfile (probably because we are
762 * running standalone).
764 if (directoryLockFile[0] == '\0')
767 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
770 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
773 len = read(fd, buffer, sizeof(buffer) - 100);
776 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
783 * Skip over first two lines (PID and path).
785 ptr = strchr(buffer, '\n');
787 (ptr = strchr(ptr + 1, '\n')) == NULL)
789 elog(DEBUG, "Bogus data in %s", directoryLockFile);
796 * Append shm key and ID. Format to try to keep it the same length
797 * always (trailing junk won't hurt, but might confuse humans).
799 sprintf(ptr, "%9lu %9lu\n",
800 (unsigned long) shmKey, (unsigned long) shmId);
803 * And rewrite the data. Since we write in a single kernel call, this
804 * update should appear atomic to onlookers.
806 len = strlen(buffer);
808 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
809 (int) write(fd, buffer, len) != len)
811 /* if write didn't set errno, assume problem is no disk space */
814 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
822 /*-------------------------------------------------------------------------
823 * Version checking support
824 *-------------------------------------------------------------------------
828 * Determine whether the PG_VERSION file in directory `path' indicates
829 * a data version compatible with the version of this program.
831 * If compatible, return. Otherwise, elog(FATAL).
834 ValidatePgVersion(const char *path)
836 char full_path[MAXPGPATH];
844 const char *version_string = PG_VERSION;
846 my_major = strtol(version_string, &endptr, 10);
848 my_minor = strtol(endptr + 1, NULL, 10);
850 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
852 file = AllocateFile(full_path, "r");
856 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
858 elog(FATAL, "cannot open %s: %m", full_path);
861 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
863 elog(FATAL, "cannot read %s: %m", full_path);
865 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
869 if (my_major != file_major || my_minor != file_minor)
870 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
871 "which is not compatible with this version %s.",
872 file_major, file_minor, version_string);