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.79 2001/10/19 17:03:08 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 "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_client_encoding(PG_FUNCTION_ARGS)
203 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
207 PG_encoding_to_char(PG_FUNCTION_ARGS)
209 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
213 PG_char_to_encoding(PG_FUNCTION_ARGS)
219 pg_convert(PG_FUNCTION_ARGS)
221 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
222 return DirectFunctionCall1(textin, CStringGetDatum(""));
226 pg_convert2(PG_FUNCTION_ARGS)
228 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
229 return DirectFunctionCall1(textin, CStringGetDatum(""));
233 /* ----------------------------------------------------------------
235 * ----------------------------------------------------------------
242 /* Some standard C libraries, including GNU, have an isblank() function.
243 Others, including Solaris, do not. So we have our own.
246 isblank(const char c)
248 return c == ' ' || c == 9 /* tab */ ;
252 next_token(FILE *fp, char *buf, const int bufsz)
254 /*--------------------------------------------------------------------------
255 Grab one token out of fp. Tokens are strings of non-blank
256 characters bounded by blank characters, beginning of line, and end
257 of line. Blank means space or tab. Return the token as *buf.
258 Leave file positioned to character immediately after the token or
259 EOF, whichever comes first. If no more tokens on line, return null
260 string as *buf and position file to beginning of next line or EOF,
261 whichever comes first.
262 --------------------------------------------------------------------------*/
264 char *eb = buf + (bufsz - 1);
266 /* Move over inital token-delimiting blanks */
267 while (isblank(c = getc(fp)));
273 * build a token in buf of next characters up to EOF, eol, or
276 while (c != EOF && c != '\n' && !isblank(c))
283 * Put back the char right after the token (putting back EOF
293 read_through_eol(FILE *file)
299 while (c != '\n' && c != EOF);
312 unsigned char FromChar,
316 for (i = 0; i < 128; i++)
318 RecodeForwTable[i] = i + 128;
319 RecodeBackTable[i] = i + 128;
322 if (IsUnderPostmaster)
324 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
328 p = getenv("PG_RECODETABLE");
332 map_file = malloc(strlen(DataDir) + strlen(p) + 2);
334 elog(FATAL, "out of memory");
335 sprintf(map_file, "%s/%s", DataDir, p);
336 file = AllocateFile(map_file, PG_BINARY_R);
352 read_through_eol(file);
355 /* Read the FromChar */
356 next_token(file, buf, sizeof(buf));
359 FromChar = strtoul(buf, 0, 0);
360 /* Read the ToChar */
361 next_token(file, buf, sizeof(buf));
364 ToChar = strtoul(buf, 0, 0);
365 RecodeForwTable[FromChar - 128] = ToChar;
366 RecodeBackTable[ToChar - 128] = FromChar;
368 read_through_eol(file);
379 convertstr(unsigned char *buff, int len, int dest)
384 for (i = 0; i < len; i++, buff++)
389 *buff = RecodeForwTable[*buff - 128];
391 *buff = RecodeBackTable[*buff - 128];
401 /* ----------------------------------------------------------------
404 * The session user is determined at connection start and never
405 * changes. The current user may change when "setuid" functions
406 * are implemented. Conceptually there is a stack, whose bottom
407 * is the session user. You are yourself responsible to save and
408 * restore the current user id if you need to change it.
409 * ----------------------------------------------------------------
411 static Oid CurrentUserId = InvalidOid;
412 static Oid SessionUserId = InvalidOid;
414 static bool AuthenticatedUserIsSuperuser = false;
417 * This function is relevant for all privilege checks.
422 AssertState(OidIsValid(CurrentUserId));
423 return CurrentUserId;
430 AssertArg(OidIsValid(newid));
431 CurrentUserId = newid;
436 * This value is only relevant for informational purposes.
439 GetSessionUserId(void)
441 AssertState(OidIsValid(SessionUserId));
442 return SessionUserId;
447 SetSessionUserId(Oid newid)
449 AssertArg(OidIsValid(newid));
450 SessionUserId = newid;
451 /* Current user defaults to session user. */
452 if (!OidIsValid(CurrentUserId))
453 CurrentUserId = newid;
458 InitializeSessionUserId(const char *username)
463 * Don't do scans if we're bootstrapping, none of the system catalogs
464 * exist yet, and they should be owned by postgres anyway.
466 AssertState(!IsBootstrapProcessingMode());
469 AssertState(!OidIsValid(SessionUserId));
471 userTup = SearchSysCache(SHADOWNAME,
472 PointerGetDatum(username),
474 if (!HeapTupleIsValid(userTup))
475 elog(FATAL, "user \"%s\" does not exist", username);
477 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
479 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
481 ReleaseSysCache(userTup);
486 InitializeSessionUserIdStandalone(void)
488 /* This function should only be called in a single-user backend. */
489 AssertState(!IsUnderPostmaster);
492 AssertState(!OidIsValid(SessionUserId));
494 SetSessionUserId(BOOTSTRAP_USESYSID);
495 AuthenticatedUserIsSuperuser = true;
500 * Change session auth ID while running
502 void SetSessionAuthorization(const char * username)
506 if (!AuthenticatedUserIsSuperuser)
507 elog(ERROR, "permission denied");
509 userid = get_usesysid(username);
511 SetSessionUserId(userid);
517 * Get user name from user id
520 GetUserName(Oid userid)
525 tuple = SearchSysCache(SHADOWSYSID,
526 ObjectIdGetDatum(userid),
528 if (!HeapTupleIsValid(tuple))
529 elog(ERROR, "invalid user id %u", (unsigned) userid);
531 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
533 ReleaseSysCache(tuple);
539 /*-------------------------------------------------------------------------
540 * Interlock-file support
542 * These routines are used to create both a data-directory lockfile
543 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
544 * Both kinds of files contain the same info:
546 * Owning process' PID
547 * Data directory path
549 * By convention, the owning process' PID is negated if it is a standalone
550 * backend rather than a postmaster. This is just for informational purposes.
551 * The path is also just for informational purposes (so that a socket lockfile
552 * can be more easily traced to the associated postmaster).
554 * A data-directory lockfile can optionally contain a third line, containing
555 * the key and ID for the shared memory block used by this postmaster.
557 * On successful lockfile creation, a proc_exit callback to remove the
558 * lockfile is automatically created.
559 *-------------------------------------------------------------------------
563 * proc_exit callback to remove a lockfile.
566 UnlinkLockFile(int status, Datum filename)
568 unlink((char *) DatumGetPointer(filename));
569 /* Should we complain if the unlink fails? */
573 * Create a lockfile, if possible
575 * Call CreateLockFile with the name of the lockfile to be created.
576 * Returns true if successful, false if not (with a message on stderr).
578 * amPostmaster is used to determine how to encode the output PID.
579 * isDDLock and refName are used to determine what error message to produce.
582 CreateLockFile(const char *filename, bool amPostmaster,
583 bool isDDLock, const char *refName)
586 char buffer[MAXPGPATH + 100];
591 pid_t my_pid = getpid();
594 * We need a loop here because of race conditions. But don't loop
595 * forever (for example, a non-writable $PGDATA directory might cause
596 * a failure that won't go away). 100 tries seems like plenty.
598 for (ntries = 0; ; ntries++)
602 * Try to create the lock file --- O_EXCL makes this atomic.
604 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
606 break; /* Success; exit the retry loop */
609 * Couldn't create the pid file. Probably it already exists.
611 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
612 elog(FATAL, "Can't create lock file %s: %m", filename);
615 * Read the file to get the old owner's PID. Note race condition
616 * here: file might have been deleted since we tried to create it.
618 fd = open(filename, O_RDONLY, 0600);
622 continue; /* race condition; try again */
623 elog(FATAL, "Can't read lock file %s: %m", filename);
625 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
626 elog(FATAL, "Can't read lock file %s: %m", filename);
630 encoded_pid = atoi(buffer);
632 /* if pid < 0, the pid is for postgres, not postmaster */
633 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
636 elog(FATAL, "Bogus data in lock file %s", filename);
639 * Check to see if the other process still exists
641 * Normally kill() will fail with ESRCH if the given PID doesn't
642 * exist. BeOS returns EINVAL for some silly reason, however.
644 if (other_pid != my_pid)
646 if (kill(other_pid, 0) == 0 ||
653 /* lockfile belongs to a live process */
654 fprintf(stderr, "Lock file \"%s\" already exists.\n",
658 "Is another %s (pid %d) running in \"%s\"?\n",
659 (encoded_pid < 0 ? "postgres" : "postmaster"),
660 (int) other_pid, refName);
663 "Is another %s (pid %d) using \"%s\"?\n",
664 (encoded_pid < 0 ? "postgres" : "postmaster"),
665 (int) other_pid, refName);
671 * No, the creating process did not exist. However, it could be
672 * that the postmaster crashed (or more likely was kill -9'd by a
673 * clueless admin) but has left orphan backends behind. Check for
674 * this by looking to see if there is an associated shmem segment
675 * that is still in use.
680 unsigned long shmKey,
683 ptr = strchr(buffer, '\n');
685 (ptr = strchr(ptr + 1, '\n')) != NULL)
688 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
690 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
691 (IpcMemoryId) shmId))
694 "Found a pre-existing shared memory block (ID %d) still in use.\n"
695 "If you're sure there are no old backends still running,\n"
696 "remove the shared memory block with ipcrm(1), or just\n"
698 (int) shmId, filename);
706 * Looks like nobody's home. Unlink the file and try again to
707 * create it. Need a loop because of possible race condition
708 * against other would-be creators.
710 if (unlink(filename) < 0)
711 elog(FATAL, "Can't remove old lock file %s: %m"
712 "\n\tThe file seems accidentally left, but I couldn't remove it."
713 "\n\tPlease remove the file by hand and try again.",
718 * Successfully created the file, now fill it.
720 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
721 amPostmaster ? (int) my_pid : -((int) my_pid),
724 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
726 int save_errno = errno;
730 /* if write didn't set errno, assume problem is no disk space */
731 errno = save_errno ? save_errno : ENOSPC;
732 elog(FATAL, "Can't write lock file %s: %m", filename);
737 * Arrange for automatic removal of lockfile at proc_exit.
739 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
741 return true; /* Success! */
745 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
747 char lockfile[MAXPGPATH];
749 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
750 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
752 /* Save name of lockfile for RecordSharedMemoryInLockFile */
753 strcpy(directoryLockFile, lockfile);
758 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
760 char lockfile[MAXPGPATH];
762 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
763 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
765 /* Save name of lockfile for TouchSocketLockFile */
766 strcpy(socketLockFile, lockfile);
771 * Re-read the socket lock file. This should be called every so often
772 * to ensure that the lock file has a recent access date. That saves it
773 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
774 * (Another reason we should never have put the socket file in /tmp...)
777 TouchSocketLockFile(void)
782 /* Do nothing if we did not create a socket... */
783 if (socketLockFile[0] != '\0')
785 /* XXX any need to complain about errors here? */
786 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
789 read(fd, buffer, sizeof(buffer));
796 * Append information about a shared memory segment to the data directory
797 * lock file (if we have created one).
799 * This may be called multiple times in the life of a postmaster, if we
800 * delete and recreate shmem due to backend crash. Therefore, be prepared
801 * to overwrite existing information. (As of 7.1, a postmaster only creates
802 * one shm seg anyway; but for the purposes here, if we did have more than
803 * one then any one of them would do anyway.)
806 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
814 * Do nothing if we did not create a lockfile (probably because we are
815 * running standalone).
817 if (directoryLockFile[0] == '\0')
820 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
823 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
826 len = read(fd, buffer, sizeof(buffer) - 100);
829 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
836 * Skip over first two lines (PID and path).
838 ptr = strchr(buffer, '\n');
840 (ptr = strchr(ptr + 1, '\n')) == NULL)
842 elog(DEBUG, "Bogus data in %s", directoryLockFile);
849 * Append shm key and ID. Format to try to keep it the same length
850 * always (trailing junk won't hurt, but might confuse humans).
852 sprintf(ptr, "%9lu %9lu\n",
853 (unsigned long) shmKey, (unsigned long) shmId);
856 * And rewrite the data. Since we write in a single kernel call, this
857 * update should appear atomic to onlookers.
859 len = strlen(buffer);
861 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
862 (int) write(fd, buffer, len) != len)
864 /* if write didn't set errno, assume problem is no disk space */
867 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
875 /*-------------------------------------------------------------------------
876 * Version checking support
877 *-------------------------------------------------------------------------
881 * Determine whether the PG_VERSION file in directory `path' indicates
882 * a data version compatible with the version of this program.
884 * If compatible, return. Otherwise, elog(FATAL).
887 ValidatePgVersion(const char *path)
889 char full_path[MAXPGPATH];
897 const char *version_string = PG_VERSION;
899 my_major = strtol(version_string, &endptr, 10);
901 my_minor = strtol(endptr + 1, NULL, 10);
903 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
905 file = AllocateFile(full_path, "r");
909 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
911 elog(FATAL, "cannot open %s: %m", full_path);
914 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
916 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
920 if (my_major != file_major || my_minor != file_minor)
921 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
922 "which is not compatible with this version %s.",
923 file_major, file_minor, version_string);