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.77 2001/09/08 15:24:00 petere 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 "libpq/libpq-be.h"
32 #include "miscadmin.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
39 unsigned char RecodeForwTable[128];
40 unsigned char RecodeBackTable[128];
43 ProcessingMode Mode = InitProcessing;
45 /* Note: we rely on these to initialize as zeroes */
46 static char directoryLockFile[MAXPGPATH];
47 static char socketLockFile[MAXPGPATH];
50 /* ----------------------------------------------------------------
51 * ignoring system indexes support stuff
52 * ----------------------------------------------------------------
55 static bool isIgnoringSystemIndexes = false;
58 * IsIgnoringSystemIndexes
59 * True if ignoring system indexes.
62 IsIgnoringSystemIndexes()
64 return isIgnoringSystemIndexes;
69 * Set true or false whether PostgreSQL ignores system indexes.
73 IgnoreSystemIndexes(bool mode)
75 isIgnoringSystemIndexes = mode;
78 /* ----------------------------------------------------------------
79 * database path / name support stuff
80 * ----------------------------------------------------------------
84 SetDatabasePath(const char *path)
91 /* use strdup since this is done before memory contexts are set up */
94 DatabasePath = strdup(path);
95 AssertState(DatabasePath);
100 SetDatabaseName(const char *name)
107 /* use strdup since this is done before memory contexts are set up */
110 DatabaseName = strdup(name);
111 AssertState(DatabaseName);
116 * Set data directory, but make sure it's an absolute path. Use this,
117 * never set DataDir directly.
120 SetDataDir(const char *dir)
123 struct stat stat_buf;
135 buf = malloc(buflen);
137 elog(FATAL, "out of memory");
139 if (getcwd(buf, buflen))
141 else if (errno == ERANGE)
150 elog(FATAL, "cannot get current working directory: %m");
154 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
156 elog(FATAL, "out of memory");
157 sprintf(new, "%s/%s", buf, dir);
164 elog(FATAL, "out of memory");
168 * Check if the directory has group or world access. If so, reject.
170 if (stat(new, &stat_buf) == -1)
171 elog(FATAL, "could not read permissions of directory %s: %s",
172 new, strerror(errno));
174 if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
175 elog(FATAL, "data directory %s has group or world access; permissions should be u=rwx (0700)",
184 /* ----------------------------------------------------------------
185 * MULTIBYTE stub code
187 * Even if MULTIBYTE is not enabled, these functions are necessary
188 * since pg_proc.h has references to them.
189 * ----------------------------------------------------------------
195 getdatabaseencoding(PG_FUNCTION_ARGS)
197 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
201 PG_encoding_to_char(PG_FUNCTION_ARGS)
203 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
207 PG_char_to_encoding(PG_FUNCTION_ARGS)
213 pg_convert(PG_FUNCTION_ARGS)
215 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
216 return DirectFunctionCall1(textin, CStringGetDatum(""));
220 pg_convert2(PG_FUNCTION_ARGS)
222 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
223 return DirectFunctionCall1(textin, CStringGetDatum(""));
227 /* ----------------------------------------------------------------
229 * ----------------------------------------------------------------
236 /* Some standard C libraries, including GNU, have an isblank() function.
237 Others, including Solaris, do not. So we have our own.
240 isblank(const char c)
242 return c == ' ' || c == 9 /* tab */ ;
246 next_token(FILE *fp, char *buf, const int bufsz)
248 /*--------------------------------------------------------------------------
249 Grab one token out of fp. Tokens are strings of non-blank
250 characters bounded by blank characters, beginning of line, and end
251 of line. Blank means space or tab. Return the token as *buf.
252 Leave file positioned to character immediately after the token or
253 EOF, whichever comes first. If no more tokens on line, return null
254 string as *buf and position file to beginning of next line or EOF,
255 whichever comes first.
256 --------------------------------------------------------------------------*/
258 char *eb = buf + (bufsz - 1);
260 /* Move over inital token-delimiting blanks */
261 while (isblank(c = getc(fp)));
267 * build a token in buf of next characters up to EOF, eol, or
270 while (c != EOF && c != '\n' && !isblank(c))
277 * Put back the char right after the token (putting back EOF
287 read_through_eol(FILE *file)
293 while (c != '\n' && c != EOF);
306 unsigned char FromChar,
310 for (i = 0; i < 128; i++)
312 RecodeForwTable[i] = i + 128;
313 RecodeBackTable[i] = i + 128;
316 if (IsUnderPostmaster)
318 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
322 p = getenv("PG_RECODETABLE");
326 map_file = malloc(strlen(DataDir) + strlen(p) + 2);
328 elog(FATAL, "out of memory");
329 sprintf(map_file, "%s/%s", DataDir, p);
330 file = AllocateFile(map_file, PG_BINARY_R);
346 read_through_eol(file);
349 /* Read the FromChar */
350 next_token(file, buf, sizeof(buf));
353 FromChar = strtoul(buf, 0, 0);
354 /* Read the ToChar */
355 next_token(file, buf, sizeof(buf));
358 ToChar = strtoul(buf, 0, 0);
359 RecodeForwTable[FromChar - 128] = ToChar;
360 RecodeBackTable[ToChar - 128] = FromChar;
362 read_through_eol(file);
373 convertstr(unsigned char *buff, int len, int dest)
378 for (i = 0; i < len; i++, buff++)
383 *buff = RecodeForwTable[*buff - 128];
385 *buff = RecodeBackTable[*buff - 128];
395 /* ----------------------------------------------------------------
398 * The session user is determined at connection start and never
399 * changes. The current user may change when "setuid" functions
400 * are implemented. Conceptually there is a stack, whose bottom
401 * is the session user. You are yourself responsible to save and
402 * restore the current user id if you need to change it.
403 * ----------------------------------------------------------------
405 static Oid CurrentUserId = InvalidOid;
406 static Oid SessionUserId = InvalidOid;
408 static bool AuthenticatedUserIsSuperuser = false;
411 * This function is relevant for all privilege checks.
416 AssertState(OidIsValid(CurrentUserId));
417 return CurrentUserId;
424 AssertArg(OidIsValid(newid));
425 CurrentUserId = newid;
430 * This value is only relevant for informational purposes.
433 GetSessionUserId(void)
435 AssertState(OidIsValid(SessionUserId));
436 return SessionUserId;
441 SetSessionUserId(Oid newid)
443 AssertArg(OidIsValid(newid));
444 SessionUserId = newid;
445 /* Current user defaults to session user. */
446 if (!OidIsValid(CurrentUserId))
447 CurrentUserId = newid;
452 InitializeSessionUserId(const char *username)
457 * Don't do scans if we're bootstrapping, none of the system catalogs
458 * exist yet, and they should be owned by postgres anyway.
460 AssertState(!IsBootstrapProcessingMode());
463 AssertState(!OidIsValid(SessionUserId));
465 userTup = SearchSysCache(SHADOWNAME,
466 PointerGetDatum(username),
468 if (!HeapTupleIsValid(userTup))
469 elog(FATAL, "user \"%s\" does not exist", username);
471 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
473 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
475 ReleaseSysCache(userTup);
480 InitializeSessionUserIdStandalone(void)
482 /* This function should only be called in a single-user backend. */
483 AssertState(!IsUnderPostmaster);
486 AssertState(!OidIsValid(SessionUserId));
488 SetSessionUserId(BOOTSTRAP_USESYSID);
489 AuthenticatedUserIsSuperuser = true;
494 * Change session auth ID while running
496 void SetSessionAuthorization(const char * username)
500 if (!AuthenticatedUserIsSuperuser)
501 elog(ERROR, "permission denied");
503 userid = get_usesysid(username);
505 SetSessionUserId(userid);
511 * Get user name from user id
514 GetUserName(Oid userid)
519 tuple = SearchSysCache(SHADOWSYSID,
520 ObjectIdGetDatum(userid),
522 if (!HeapTupleIsValid(tuple))
523 elog(ERROR, "invalid user id %u", (unsigned) userid);
525 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
527 ReleaseSysCache(tuple);
533 /*-------------------------------------------------------------------------
534 * Interlock-file support
536 * These routines are used to create both a data-directory lockfile
537 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
538 * Both kinds of files contain the same info:
540 * Owning process' PID
541 * Data directory path
543 * By convention, the owning process' PID is negated if it is a standalone
544 * backend rather than a postmaster. This is just for informational purposes.
545 * The path is also just for informational purposes (so that a socket lockfile
546 * can be more easily traced to the associated postmaster).
548 * A data-directory lockfile can optionally contain a third line, containing
549 * the key and ID for the shared memory block used by this postmaster.
551 * On successful lockfile creation, a proc_exit callback to remove the
552 * lockfile is automatically created.
553 *-------------------------------------------------------------------------
557 * proc_exit callback to remove a lockfile.
560 UnlinkLockFile(int status, Datum filename)
562 unlink((char *) DatumGetPointer(filename));
563 /* Should we complain if the unlink fails? */
567 * Create a lockfile, if possible
569 * Call CreateLockFile with the name of the lockfile to be created.
570 * Returns true if successful, false if not (with a message on stderr).
572 * amPostmaster is used to determine how to encode the output PID.
573 * isDDLock and refName are used to determine what error message to produce.
576 CreateLockFile(const char *filename, bool amPostmaster,
577 bool isDDLock, const char *refName)
580 char buffer[MAXPGPATH + 100];
585 pid_t my_pid = getpid();
588 * We need a loop here because of race conditions. But don't loop
589 * forever (for example, a non-writable $PGDATA directory might cause
590 * a failure that won't go away). 100 tries seems like plenty.
592 for (ntries = 0; ; ntries++)
596 * Try to create the lock file --- O_EXCL makes this atomic.
598 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
600 break; /* Success; exit the retry loop */
603 * Couldn't create the pid file. Probably it already exists.
605 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
606 elog(FATAL, "Can't create lock file %s: %m", filename);
609 * Read the file to get the old owner's PID. Note race condition
610 * here: file might have been deleted since we tried to create it.
612 fd = open(filename, O_RDONLY, 0600);
616 continue; /* race condition; try again */
617 elog(FATAL, "Can't read lock file %s: %m", filename);
619 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
620 elog(FATAL, "Can't read lock file %s: %m", filename);
624 encoded_pid = atoi(buffer);
626 /* if pid < 0, the pid is for postgres, not postmaster */
627 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
630 elog(FATAL, "Bogus data in lock file %s", filename);
633 * Check to see if the other process still exists
635 * Normally kill() will fail with ESRCH if the given PID doesn't
636 * exist. BeOS returns EINVAL for some silly reason, however.
638 if (other_pid != my_pid)
640 if (kill(other_pid, 0) == 0 ||
647 /* lockfile belongs to a live process */
648 fprintf(stderr, "Lock file \"%s\" already exists.\n",
652 "Is another %s (pid %d) running in \"%s\"?\n",
653 (encoded_pid < 0 ? "postgres" : "postmaster"),
654 (int) other_pid, refName);
657 "Is another %s (pid %d) using \"%s\"?\n",
658 (encoded_pid < 0 ? "postgres" : "postmaster"),
659 (int) other_pid, refName);
665 * No, the creating process did not exist. However, it could be
666 * that the postmaster crashed (or more likely was kill -9'd by a
667 * clueless admin) but has left orphan backends behind. Check for
668 * this by looking to see if there is an associated shmem segment
669 * that is still in use.
674 unsigned long shmKey,
677 ptr = strchr(buffer, '\n');
679 (ptr = strchr(ptr + 1, '\n')) != NULL)
682 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
684 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
685 (IpcMemoryId) shmId))
688 "Found a pre-existing shared memory block (ID %d) still in use.\n"
689 "If you're sure there are no old backends still running,\n"
690 "remove the shared memory block with ipcrm(1), or just\n"
692 (int) shmId, filename);
700 * Looks like nobody's home. Unlink the file and try again to
701 * create it. Need a loop because of possible race condition
702 * against other would-be creators.
704 if (unlink(filename) < 0)
705 elog(FATAL, "Can't remove old lock file %s: %m"
706 "\n\tThe file seems accidentally left, but I couldn't remove it."
707 "\n\tPlease remove the file by hand and try again.",
712 * Successfully created the file, now fill it.
714 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
715 amPostmaster ? (int) my_pid : -((int) my_pid),
718 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
720 int save_errno = errno;
724 /* if write didn't set errno, assume problem is no disk space */
725 errno = save_errno ? save_errno : ENOSPC;
726 elog(FATAL, "Can't write lock file %s: %m", filename);
731 * Arrange for automatic removal of lockfile at proc_exit.
733 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
735 return true; /* Success! */
739 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
741 char lockfile[MAXPGPATH];
743 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
744 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
746 /* Save name of lockfile for RecordSharedMemoryInLockFile */
747 strcpy(directoryLockFile, lockfile);
752 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
754 char lockfile[MAXPGPATH];
756 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
757 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
759 /* Save name of lockfile for TouchSocketLockFile */
760 strcpy(socketLockFile, lockfile);
765 * Re-read the socket lock file. This should be called every so often
766 * to ensure that the lock file has a recent access date. That saves it
767 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
768 * (Another reason we should never have put the socket file in /tmp...)
771 TouchSocketLockFile(void)
776 /* Do nothing if we did not create a socket... */
777 if (socketLockFile[0] != '\0')
779 /* XXX any need to complain about errors here? */
780 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
783 read(fd, buffer, sizeof(buffer));
790 * Append information about a shared memory segment to the data directory
791 * lock file (if we have created one).
793 * This may be called multiple times in the life of a postmaster, if we
794 * delete and recreate shmem due to backend crash. Therefore, be prepared
795 * to overwrite existing information. (As of 7.1, a postmaster only creates
796 * one shm seg anyway; but for the purposes here, if we did have more than
797 * one then any one of them would do anyway.)
800 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
808 * Do nothing if we did not create a lockfile (probably because we are
809 * running standalone).
811 if (directoryLockFile[0] == '\0')
814 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
817 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
820 len = read(fd, buffer, sizeof(buffer) - 100);
823 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
830 * Skip over first two lines (PID and path).
832 ptr = strchr(buffer, '\n');
834 (ptr = strchr(ptr + 1, '\n')) == NULL)
836 elog(DEBUG, "Bogus data in %s", directoryLockFile);
843 * Append shm key and ID. Format to try to keep it the same length
844 * always (trailing junk won't hurt, but might confuse humans).
846 sprintf(ptr, "%9lu %9lu\n",
847 (unsigned long) shmKey, (unsigned long) shmId);
850 * And rewrite the data. Since we write in a single kernel call, this
851 * update should appear atomic to onlookers.
853 len = strlen(buffer);
855 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
856 (int) write(fd, buffer, len) != len)
858 /* if write didn't set errno, assume problem is no disk space */
861 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
869 /*-------------------------------------------------------------------------
870 * Version checking support
871 *-------------------------------------------------------------------------
875 * Determine whether the PG_VERSION file in directory `path' indicates
876 * a data version compatible with the version of this program.
878 * If compatible, return. Otherwise, elog(FATAL).
881 ValidatePgVersion(const char *path)
883 char full_path[MAXPGPATH];
891 const char *version_string = PG_VERSION;
893 my_major = strtol(version_string, &endptr, 10);
895 my_minor = strtol(endptr + 1, NULL, 10);
897 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
899 file = AllocateFile(full_path, "r");
903 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
905 elog(FATAL, "cannot open %s: %m", full_path);
908 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
910 elog(FATAL, "cannot read %s: %m", full_path);
912 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
916 if (my_major != file_major || my_minor != file_minor)
917 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
918 "which is not compatible with this version %s.",
919 file_major, file_minor, version_string);