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.83 2002/03/01 22:45:15 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/guc.h"
35 #include "utils/lsyscache.h"
36 #include "utils/syscache.h"
40 unsigned char RecodeForwTable[128];
41 unsigned char RecodeBackTable[128];
44 ProcessingMode Mode = InitProcessing;
46 /* Note: we rely on these to initialize as zeroes */
47 static char directoryLockFile[MAXPGPATH];
48 static char socketLockFile[MAXPGPATH];
51 /* ----------------------------------------------------------------
52 * ignoring system indexes support stuff
53 * ----------------------------------------------------------------
56 static bool isIgnoringSystemIndexes = false;
59 * IsIgnoringSystemIndexes
60 * True if ignoring system indexes.
63 IsIgnoringSystemIndexes()
65 return isIgnoringSystemIndexes;
70 * Set true or false whether PostgreSQL ignores system indexes.
74 IgnoreSystemIndexes(bool mode)
76 isIgnoringSystemIndexes = mode;
79 /* ----------------------------------------------------------------
80 * database path / name support stuff
81 * ----------------------------------------------------------------
85 SetDatabasePath(const char *path)
92 /* use strdup since this is done before memory contexts are set up */
95 DatabasePath = strdup(path);
96 AssertState(DatabasePath);
101 SetDatabaseName(const char *name)
108 /* use strdup since this is done before memory contexts are set up */
111 DatabaseName = strdup(name);
112 AssertState(DatabaseName);
117 * Set data directory, but make sure it's an absolute path. Use this,
118 * never set DataDir directly.
121 SetDataDir(const char *dir)
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");
173 /* ----------------------------------------------------------------
174 * MULTIBYTE stub code
176 * Even if MULTIBYTE is not enabled, these functions are necessary
177 * since pg_proc.h has references to them.
178 * ----------------------------------------------------------------
184 getdatabaseencoding(PG_FUNCTION_ARGS)
186 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
190 pg_client_encoding(PG_FUNCTION_ARGS)
192 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
196 PG_encoding_to_char(PG_FUNCTION_ARGS)
198 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
202 PG_char_to_encoding(PG_FUNCTION_ARGS)
208 pg_convert(PG_FUNCTION_ARGS)
210 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
211 return DirectFunctionCall1(textin, CStringGetDatum(""));
215 pg_convert2(PG_FUNCTION_ARGS)
217 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
218 return DirectFunctionCall1(textin, CStringGetDatum(""));
222 /* ----------------------------------------------------------------
224 * ----------------------------------------------------------------
232 * Some standard C libraries, including GNU, have an isblank() function.
233 * Others, including Solaris, do not. So we have our own.
236 isblank(const char c)
238 return c == ' ' || c == '\t';
243 * Grab one token out of fp. Tokens are strings of non-blank
244 * characters bounded by blank characters, beginning of line, and end
245 * of line. Blank means space or tab. Return the token as *buf.
246 * Leave file positioned to character immediately after the token or
247 * EOF, whichever comes first. If no more tokens on line, return null
248 * string as *buf and position file to beginning of next line or EOF,
249 * whichever comes first.
252 next_token(FILE *fp, char *buf, const int bufsz)
255 char *eb = buf + (bufsz - 1);
257 /* Move over initial token-delimiting blanks */
258 while ((c = getc(fp)) != EOF && isblank(c))
261 if (c != EOF && c != '\n')
264 * build a token in buf of next characters up to EOF, eol, or
265 * blank. If the token gets too long, we still parse it
266 * correctly, but the excess characters are not stored into *buf.
268 while (c != EOF && c != '\n' && !isblank(c))
276 * Put back the char right after the token (critical in case it is
277 * eol, since we need to detect end-of-line at next call).
287 read_through_eol(FILE *file)
291 while ((c = getc(file)) != EOF && c != '\n')
305 unsigned char FromChar,
309 for (i = 0; i < 128; i++)
311 RecodeForwTable[i] = i + 128;
312 RecodeBackTable[i] = i + 128;
315 if (IsUnderPostmaster)
317 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
321 p = getenv("PG_RECODETABLE");
325 map_file = palloc(strlen(DataDir) + strlen(p) + 2);
326 sprintf(map_file, "%s/%s", DataDir, p);
327 file = AllocateFile(map_file, PG_BINARY_R);
331 while ((c = getc(file)) != EOF)
334 read_through_eol(file);
337 /* Read the FromChar */
339 next_token(file, buf, sizeof(buf));
342 FromChar = strtoul(buf, 0, 0);
343 /* Read the ToChar */
344 next_token(file, buf, sizeof(buf));
347 ToChar = strtoul(buf, 0, 0);
348 RecodeForwTable[FromChar - 128] = ToChar;
349 RecodeBackTable[ToChar - 128] = FromChar;
350 read_through_eol(file);
360 convertstr(unsigned char *buff, int len, int dest)
365 for (i = 0; i < len; i++, buff++)
370 *buff = RecodeForwTable[*buff - 128];
372 *buff = RecodeBackTable[*buff - 128];
381 /* ----------------------------------------------------------------
384 * The session user is determined at connection start and never
385 * changes. The current user may change when "setuid" functions
386 * are implemented. Conceptually there is a stack, whose bottom
387 * is the session user. You are yourself responsible to save and
388 * restore the current user id if you need to change it.
389 * ----------------------------------------------------------------
391 static Oid CurrentUserId = InvalidOid;
392 static Oid SessionUserId = InvalidOid;
394 static bool AuthenticatedUserIsSuperuser = false;
397 * This function is relevant for all privilege checks.
402 AssertState(OidIsValid(CurrentUserId));
403 return CurrentUserId;
410 AssertArg(OidIsValid(newid));
411 CurrentUserId = newid;
416 * This value is only relevant for informational purposes.
419 GetSessionUserId(void)
421 AssertState(OidIsValid(SessionUserId));
422 return SessionUserId;
427 SetSessionUserId(Oid newid)
429 AssertArg(OidIsValid(newid));
430 SessionUserId = newid;
431 /* Current user defaults to session user. */
432 if (!OidIsValid(CurrentUserId))
433 CurrentUserId = newid;
438 InitializeSessionUserId(const char *username)
445 * Don't do scans if we're bootstrapping, none of the system catalogs
446 * exist yet, and they should be owned by postgres anyway.
448 AssertState(!IsBootstrapProcessingMode());
451 AssertState(!OidIsValid(SessionUserId));
453 userTup = SearchSysCache(SHADOWNAME,
454 PointerGetDatum(username),
456 if (!HeapTupleIsValid(userTup))
457 elog(FATAL, "user \"%s\" does not exist", username);
459 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
461 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
464 * Set up user-specific configuration variables. This is a good
465 * place to do it so we don't have to read pg_shadow twice during
468 datum = SysCacheGetAttr(SHADOWNAME, userTup,
469 Anum_pg_shadow_useconfig, &isnull);
474 a = (ArrayType *) pg_detoast_datum((struct varlena *)datum);
475 ProcessGUCArray(a, PGC_S_USER);
478 ReleaseSysCache(userTup);
483 InitializeSessionUserIdStandalone(void)
485 /* This function should only be called in a single-user backend. */
486 AssertState(!IsUnderPostmaster);
489 AssertState(!OidIsValid(SessionUserId));
491 SetSessionUserId(BOOTSTRAP_USESYSID);
492 AuthenticatedUserIsSuperuser = true;
497 * Change session auth ID while running
500 SetSessionAuthorization(const char *username)
504 if (!AuthenticatedUserIsSuperuser)
505 elog(ERROR, "permission denied");
507 userid = get_usesysid(username);
509 SetSessionUserId(userid);
515 * Get user name from user id
518 GetUserName(Oid userid)
523 tuple = SearchSysCache(SHADOWSYSID,
524 ObjectIdGetDatum(userid),
526 if (!HeapTupleIsValid(tuple))
527 elog(ERROR, "invalid user id %u", (unsigned) userid);
529 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
531 ReleaseSysCache(tuple);
537 /*-------------------------------------------------------------------------
538 * Interlock-file support
540 * These routines are used to create both a data-directory lockfile
541 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
542 * Both kinds of files contain the same info:
544 * Owning process' PID
545 * Data directory path
547 * By convention, the owning process' PID is negated if it is a standalone
548 * backend rather than a postmaster. This is just for informational purposes.
549 * The path is also just for informational purposes (so that a socket lockfile
550 * can be more easily traced to the associated postmaster).
552 * A data-directory lockfile can optionally contain a third line, containing
553 * the key and ID for the shared memory block used by this postmaster.
555 * On successful lockfile creation, a proc_exit callback to remove the
556 * lockfile is automatically created.
557 *-------------------------------------------------------------------------
561 * proc_exit callback to remove a lockfile.
564 UnlinkLockFile(int status, Datum filename)
566 unlink((char *) DatumGetPointer(filename));
567 /* Should we complain if the unlink fails? */
571 * Create a lockfile, if possible
573 * Call CreateLockFile with the name of the lockfile to be created.
574 * Returns true if successful, false if not (with a message on stderr).
576 * amPostmaster is used to determine how to encode the output PID.
577 * isDDLock and refName are used to determine what error message to produce.
580 CreateLockFile(const char *filename, bool amPostmaster,
581 bool isDDLock, const char *refName)
584 char buffer[MAXPGPATH + 100];
589 pid_t my_pid = getpid();
592 * We need a loop here because of race conditions. But don't loop
593 * forever (for example, a non-writable $PGDATA directory might cause
594 * a failure that won't go away). 100 tries seems like plenty.
596 for (ntries = 0;; ntries++)
599 * Try to create the lock file --- O_EXCL makes this atomic.
601 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
603 break; /* Success; exit the retry loop */
606 * Couldn't create the pid file. Probably it already exists.
608 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
609 elog(FATAL, "Can't create lock file %s: %m", filename);
612 * Read the file to get the old owner's PID. Note race condition
613 * here: file might have been deleted since we tried to create it.
615 fd = open(filename, O_RDONLY, 0600);
619 continue; /* race condition; try again */
620 elog(FATAL, "Can't read lock file %s: %m", filename);
622 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
623 elog(FATAL, "Can't read lock file %s: %m", filename);
627 encoded_pid = atoi(buffer);
629 /* if pid < 0, the pid is for postgres, not postmaster */
630 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
633 elog(FATAL, "Bogus data in lock file %s", filename);
636 * Check to see if the other process still exists
638 * Normally kill() will fail with ESRCH if the given PID doesn't
639 * exist. BeOS returns EINVAL for some silly reason, however.
641 if (other_pid != my_pid)
643 if (kill(other_pid, 0) == 0 ||
650 /* lockfile belongs to a live process */
651 fprintf(stderr, "Lock file \"%s\" already exists.\n",
655 "Is another %s (pid %d) running in \"%s\"?\n",
656 (encoded_pid < 0 ? "postgres" : "postmaster"),
657 (int) other_pid, refName);
660 "Is another %s (pid %d) using \"%s\"?\n",
661 (encoded_pid < 0 ? "postgres" : "postmaster"),
662 (int) other_pid, refName);
668 * No, the creating process did not exist. However, it could be
669 * that the postmaster crashed (or more likely was kill -9'd by a
670 * clueless admin) but has left orphan backends behind. Check for
671 * this by looking to see if there is an associated shmem segment
672 * that is still in use.
677 unsigned long shmKey,
680 ptr = strchr(buffer, '\n');
682 (ptr = strchr(ptr + 1, '\n')) != NULL)
685 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
687 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
688 (IpcMemoryId) shmId))
691 "Found a pre-existing shared memory block (ID %d) still in use.\n"
692 "If you're sure there are no old backends still running,\n"
693 "remove the shared memory block with ipcrm(1), or just\n"
695 (int) shmId, filename);
703 * Looks like nobody's home. Unlink the file and try again to
704 * create it. Need a loop because of possible race condition
705 * against other would-be creators.
707 if (unlink(filename) < 0)
708 elog(FATAL, "Can't remove old lock file %s: %m"
709 "\n\tThe file seems accidentally left, but I couldn't remove it."
710 "\n\tPlease remove the file by hand and try again.",
715 * Successfully created the file, now fill it.
717 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
718 amPostmaster ? (int) my_pid : -((int) my_pid),
721 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
723 int save_errno = errno;
727 /* if write didn't set errno, assume problem is no disk space */
728 errno = save_errno ? save_errno : ENOSPC;
729 elog(FATAL, "Can't write lock file %s: %m", filename);
734 * Arrange for automatic removal of lockfile at proc_exit.
736 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
738 return true; /* Success! */
742 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
744 char lockfile[MAXPGPATH];
746 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
747 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
749 /* Save name of lockfile for RecordSharedMemoryInLockFile */
750 strcpy(directoryLockFile, lockfile);
755 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
757 char lockfile[MAXPGPATH];
759 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
760 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
762 /* Save name of lockfile for TouchSocketLockFile */
763 strcpy(socketLockFile, lockfile);
768 * Re-read the socket lock file. This should be called every so often
769 * to ensure that the lock file has a recent access date. That saves it
770 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
771 * (Another reason we should never have put the socket file in /tmp...)
774 TouchSocketLockFile(void)
779 /* Do nothing if we did not create a socket... */
780 if (socketLockFile[0] != '\0')
782 /* XXX any need to complain about errors here? */
783 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
786 read(fd, buffer, sizeof(buffer));
793 * Append information about a shared memory segment to the data directory
794 * lock file (if we have created one).
796 * This may be called multiple times in the life of a postmaster, if we
797 * delete and recreate shmem due to backend crash. Therefore, be prepared
798 * to overwrite existing information. (As of 7.1, a postmaster only creates
799 * one shm seg anyway; but for the purposes here, if we did have more than
800 * one then any one of them would do anyway.)
803 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
811 * Do nothing if we did not create a lockfile (probably because we are
812 * running standalone).
814 if (directoryLockFile[0] == '\0')
817 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
820 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
823 len = read(fd, buffer, sizeof(buffer) - 100);
826 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
833 * Skip over first two lines (PID and path).
835 ptr = strchr(buffer, '\n');
837 (ptr = strchr(ptr + 1, '\n')) == NULL)
839 elog(DEBUG, "Bogus data in %s", directoryLockFile);
846 * Append shm key and ID. Format to try to keep it the same length
847 * always (trailing junk won't hurt, but might confuse humans).
849 sprintf(ptr, "%9lu %9lu\n",
850 (unsigned long) shmKey, (unsigned long) shmId);
853 * And rewrite the data. Since we write in a single kernel call, this
854 * update should appear atomic to onlookers.
856 len = strlen(buffer);
858 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
859 (int) write(fd, buffer, len) != len)
861 /* if write didn't set errno, assume problem is no disk space */
864 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
872 /*-------------------------------------------------------------------------
873 * Version checking support
874 *-------------------------------------------------------------------------
878 * Determine whether the PG_VERSION file in directory `path' indicates
879 * a data version compatible with the version of this program.
881 * If compatible, return. Otherwise, elog(FATAL).
884 ValidatePgVersion(const char *path)
886 char full_path[MAXPGPATH];
894 const char *version_string = PG_VERSION;
896 my_major = strtol(version_string, &endptr, 10);
898 my_minor = strtol(endptr + 1, NULL, 10);
900 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
902 file = AllocateFile(full_path, "r");
906 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
908 elog(FATAL, "cannot open %s: %m", full_path);
911 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
913 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
917 if (my_major != file_major || my_minor != file_minor)
918 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
919 "which is not compatible with this version %s.",
920 file_major, file_minor, version_string);