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.82 2002/01/09 19:13: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 "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)
134 buf = malloc(buflen);
136 elog(FATAL, "out of memory");
138 if (getcwd(buf, buflen))
140 else if (errno == ERANGE)
149 elog(FATAL, "cannot get current working directory: %m");
153 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
155 elog(FATAL, "out of memory");
156 sprintf(new, "%s/%s", buf, dir);
163 elog(FATAL, "out of memory");
172 /* ----------------------------------------------------------------
173 * MULTIBYTE stub code
175 * Even if MULTIBYTE is not enabled, these functions are necessary
176 * since pg_proc.h has references to them.
177 * ----------------------------------------------------------------
183 getdatabaseencoding(PG_FUNCTION_ARGS)
185 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
189 pg_client_encoding(PG_FUNCTION_ARGS)
191 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
195 PG_encoding_to_char(PG_FUNCTION_ARGS)
197 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
201 PG_char_to_encoding(PG_FUNCTION_ARGS)
207 pg_convert(PG_FUNCTION_ARGS)
209 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
210 return DirectFunctionCall1(textin, CStringGetDatum(""));
214 pg_convert2(PG_FUNCTION_ARGS)
216 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
217 return DirectFunctionCall1(textin, CStringGetDatum(""));
221 /* ----------------------------------------------------------------
223 * ----------------------------------------------------------------
231 * Some standard C libraries, including GNU, have an isblank() function.
232 * Others, including Solaris, do not. So we have our own.
235 isblank(const char c)
237 return c == ' ' || c == '\t';
242 * Grab one token out of fp. Tokens are strings of non-blank
243 * characters bounded by blank characters, beginning of line, and end
244 * of line. Blank means space or tab. Return the token as *buf.
245 * Leave file positioned to character immediately after the token or
246 * EOF, whichever comes first. If no more tokens on line, return null
247 * string as *buf and position file to beginning of next line or EOF,
248 * whichever comes first.
251 next_token(FILE *fp, char *buf, const int bufsz)
254 char *eb = buf + (bufsz - 1);
256 /* Move over initial token-delimiting blanks */
257 while ((c = getc(fp)) != EOF && isblank(c))
260 if (c != EOF && c != '\n')
263 * build a token in buf of next characters up to EOF, eol, or
264 * blank. If the token gets too long, we still parse it
265 * correctly, but the excess characters are not stored into *buf.
267 while (c != EOF && c != '\n' && !isblank(c))
275 * Put back the char right after the token (critical in case it is
276 * eol, since we need to detect end-of-line at next call).
286 read_through_eol(FILE *file)
290 while ((c = getc(file)) != EOF && c != '\n')
304 unsigned char FromChar,
308 for (i = 0; i < 128; i++)
310 RecodeForwTable[i] = i + 128;
311 RecodeBackTable[i] = i + 128;
314 if (IsUnderPostmaster)
316 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
320 p = getenv("PG_RECODETABLE");
324 map_file = palloc(strlen(DataDir) + strlen(p) + 2);
325 sprintf(map_file, "%s/%s", DataDir, p);
326 file = AllocateFile(map_file, PG_BINARY_R);
330 while ((c = getc(file)) != EOF)
333 read_through_eol(file);
336 /* Read the FromChar */
338 next_token(file, buf, sizeof(buf));
341 FromChar = strtoul(buf, 0, 0);
342 /* Read the ToChar */
343 next_token(file, buf, sizeof(buf));
346 ToChar = strtoul(buf, 0, 0);
347 RecodeForwTable[FromChar - 128] = ToChar;
348 RecodeBackTable[ToChar - 128] = FromChar;
349 read_through_eol(file);
359 convertstr(unsigned char *buff, int len, int dest)
364 for (i = 0; i < len; i++, buff++)
369 *buff = RecodeForwTable[*buff - 128];
371 *buff = RecodeBackTable[*buff - 128];
380 /* ----------------------------------------------------------------
383 * The session user is determined at connection start and never
384 * changes. The current user may change when "setuid" functions
385 * are implemented. Conceptually there is a stack, whose bottom
386 * is the session user. You are yourself responsible to save and
387 * restore the current user id if you need to change it.
388 * ----------------------------------------------------------------
390 static Oid CurrentUserId = InvalidOid;
391 static Oid SessionUserId = InvalidOid;
393 static bool AuthenticatedUserIsSuperuser = false;
396 * This function is relevant for all privilege checks.
401 AssertState(OidIsValid(CurrentUserId));
402 return CurrentUserId;
409 AssertArg(OidIsValid(newid));
410 CurrentUserId = newid;
415 * This value is only relevant for informational purposes.
418 GetSessionUserId(void)
420 AssertState(OidIsValid(SessionUserId));
421 return SessionUserId;
426 SetSessionUserId(Oid newid)
428 AssertArg(OidIsValid(newid));
429 SessionUserId = newid;
430 /* Current user defaults to session user. */
431 if (!OidIsValid(CurrentUserId))
432 CurrentUserId = newid;
437 InitializeSessionUserId(const char *username)
442 * Don't do scans if we're bootstrapping, none of the system catalogs
443 * exist yet, and they should be owned by postgres anyway.
445 AssertState(!IsBootstrapProcessingMode());
448 AssertState(!OidIsValid(SessionUserId));
450 userTup = SearchSysCache(SHADOWNAME,
451 PointerGetDatum(username),
453 if (!HeapTupleIsValid(userTup))
454 elog(FATAL, "user \"%s\" does not exist", username);
456 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
458 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
460 ReleaseSysCache(userTup);
465 InitializeSessionUserIdStandalone(void)
467 /* This function should only be called in a single-user backend. */
468 AssertState(!IsUnderPostmaster);
471 AssertState(!OidIsValid(SessionUserId));
473 SetSessionUserId(BOOTSTRAP_USESYSID);
474 AuthenticatedUserIsSuperuser = true;
479 * Change session auth ID while running
482 SetSessionAuthorization(const char *username)
486 if (!AuthenticatedUserIsSuperuser)
487 elog(ERROR, "permission denied");
489 userid = get_usesysid(username);
491 SetSessionUserId(userid);
497 * Get user name from user id
500 GetUserName(Oid userid)
505 tuple = SearchSysCache(SHADOWSYSID,
506 ObjectIdGetDatum(userid),
508 if (!HeapTupleIsValid(tuple))
509 elog(ERROR, "invalid user id %u", (unsigned) userid);
511 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
513 ReleaseSysCache(tuple);
519 /*-------------------------------------------------------------------------
520 * Interlock-file support
522 * These routines are used to create both a data-directory lockfile
523 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
524 * Both kinds of files contain the same info:
526 * Owning process' PID
527 * Data directory path
529 * By convention, the owning process' PID is negated if it is a standalone
530 * backend rather than a postmaster. This is just for informational purposes.
531 * The path is also just for informational purposes (so that a socket lockfile
532 * can be more easily traced to the associated postmaster).
534 * A data-directory lockfile can optionally contain a third line, containing
535 * the key and ID for the shared memory block used by this postmaster.
537 * On successful lockfile creation, a proc_exit callback to remove the
538 * lockfile is automatically created.
539 *-------------------------------------------------------------------------
543 * proc_exit callback to remove a lockfile.
546 UnlinkLockFile(int status, Datum filename)
548 unlink((char *) DatumGetPointer(filename));
549 /* Should we complain if the unlink fails? */
553 * Create a lockfile, if possible
555 * Call CreateLockFile with the name of the lockfile to be created.
556 * Returns true if successful, false if not (with a message on stderr).
558 * amPostmaster is used to determine how to encode the output PID.
559 * isDDLock and refName are used to determine what error message to produce.
562 CreateLockFile(const char *filename, bool amPostmaster,
563 bool isDDLock, const char *refName)
566 char buffer[MAXPGPATH + 100];
571 pid_t my_pid = getpid();
574 * We need a loop here because of race conditions. But don't loop
575 * forever (for example, a non-writable $PGDATA directory might cause
576 * a failure that won't go away). 100 tries seems like plenty.
578 for (ntries = 0;; ntries++)
581 * Try to create the lock file --- O_EXCL makes this atomic.
583 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
585 break; /* Success; exit the retry loop */
588 * Couldn't create the pid file. Probably it already exists.
590 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
591 elog(FATAL, "Can't create lock file %s: %m", filename);
594 * Read the file to get the old owner's PID. Note race condition
595 * here: file might have been deleted since we tried to create it.
597 fd = open(filename, O_RDONLY, 0600);
601 continue; /* race condition; try again */
602 elog(FATAL, "Can't read lock file %s: %m", filename);
604 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
605 elog(FATAL, "Can't read lock file %s: %m", filename);
609 encoded_pid = atoi(buffer);
611 /* if pid < 0, the pid is for postgres, not postmaster */
612 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
615 elog(FATAL, "Bogus data in lock file %s", filename);
618 * Check to see if the other process still exists
620 * Normally kill() will fail with ESRCH if the given PID doesn't
621 * exist. BeOS returns EINVAL for some silly reason, however.
623 if (other_pid != my_pid)
625 if (kill(other_pid, 0) == 0 ||
632 /* lockfile belongs to a live process */
633 fprintf(stderr, "Lock file \"%s\" already exists.\n",
637 "Is another %s (pid %d) running in \"%s\"?\n",
638 (encoded_pid < 0 ? "postgres" : "postmaster"),
639 (int) other_pid, refName);
642 "Is another %s (pid %d) using \"%s\"?\n",
643 (encoded_pid < 0 ? "postgres" : "postmaster"),
644 (int) other_pid, refName);
650 * No, the creating process did not exist. However, it could be
651 * that the postmaster crashed (or more likely was kill -9'd by a
652 * clueless admin) but has left orphan backends behind. Check for
653 * this by looking to see if there is an associated shmem segment
654 * that is still in use.
659 unsigned long shmKey,
662 ptr = strchr(buffer, '\n');
664 (ptr = strchr(ptr + 1, '\n')) != NULL)
667 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
669 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
670 (IpcMemoryId) shmId))
673 "Found a pre-existing shared memory block (ID %d) still in use.\n"
674 "If you're sure there are no old backends still running,\n"
675 "remove the shared memory block with ipcrm(1), or just\n"
677 (int) shmId, filename);
685 * Looks like nobody's home. Unlink the file and try again to
686 * create it. Need a loop because of possible race condition
687 * against other would-be creators.
689 if (unlink(filename) < 0)
690 elog(FATAL, "Can't remove old lock file %s: %m"
691 "\n\tThe file seems accidentally left, but I couldn't remove it."
692 "\n\tPlease remove the file by hand and try again.",
697 * Successfully created the file, now fill it.
699 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
700 amPostmaster ? (int) my_pid : -((int) my_pid),
703 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
705 int save_errno = errno;
709 /* if write didn't set errno, assume problem is no disk space */
710 errno = save_errno ? save_errno : ENOSPC;
711 elog(FATAL, "Can't write lock file %s: %m", filename);
716 * Arrange for automatic removal of lockfile at proc_exit.
718 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
720 return true; /* Success! */
724 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
726 char lockfile[MAXPGPATH];
728 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
729 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
731 /* Save name of lockfile for RecordSharedMemoryInLockFile */
732 strcpy(directoryLockFile, lockfile);
737 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
739 char lockfile[MAXPGPATH];
741 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
742 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
744 /* Save name of lockfile for TouchSocketLockFile */
745 strcpy(socketLockFile, lockfile);
750 * Re-read the socket lock file. This should be called every so often
751 * to ensure that the lock file has a recent access date. That saves it
752 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
753 * (Another reason we should never have put the socket file in /tmp...)
756 TouchSocketLockFile(void)
761 /* Do nothing if we did not create a socket... */
762 if (socketLockFile[0] != '\0')
764 /* XXX any need to complain about errors here? */
765 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
768 read(fd, buffer, sizeof(buffer));
775 * Append information about a shared memory segment to the data directory
776 * lock file (if we have created one).
778 * This may be called multiple times in the life of a postmaster, if we
779 * delete and recreate shmem due to backend crash. Therefore, be prepared
780 * to overwrite existing information. (As of 7.1, a postmaster only creates
781 * one shm seg anyway; but for the purposes here, if we did have more than
782 * one then any one of them would do anyway.)
785 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
793 * Do nothing if we did not create a lockfile (probably because we are
794 * running standalone).
796 if (directoryLockFile[0] == '\0')
799 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
802 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
805 len = read(fd, buffer, sizeof(buffer) - 100);
808 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
815 * Skip over first two lines (PID and path).
817 ptr = strchr(buffer, '\n');
819 (ptr = strchr(ptr + 1, '\n')) == NULL)
821 elog(DEBUG, "Bogus data in %s", directoryLockFile);
828 * Append shm key and ID. Format to try to keep it the same length
829 * always (trailing junk won't hurt, but might confuse humans).
831 sprintf(ptr, "%9lu %9lu\n",
832 (unsigned long) shmKey, (unsigned long) shmId);
835 * And rewrite the data. Since we write in a single kernel call, this
836 * update should appear atomic to onlookers.
838 len = strlen(buffer);
840 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
841 (int) write(fd, buffer, len) != len)
843 /* if write didn't set errno, assume problem is no disk space */
846 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
854 /*-------------------------------------------------------------------------
855 * Version checking support
856 *-------------------------------------------------------------------------
860 * Determine whether the PG_VERSION file in directory `path' indicates
861 * a data version compatible with the version of this program.
863 * If compatible, return. Otherwise, elog(FATAL).
866 ValidatePgVersion(const char *path)
868 char full_path[MAXPGPATH];
876 const char *version_string = PG_VERSION;
878 my_major = strtol(version_string, &endptr, 10);
880 my_minor = strtol(endptr + 1, NULL, 10);
882 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
884 file = AllocateFile(full_path, "r");
888 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
890 elog(FATAL, "cannot open %s: %m", full_path);
893 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
895 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
899 if (my_major != file_major || my_minor != file_minor)
900 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
901 "which is not compatible with this version %s.",
902 file_major, file_minor, version_string);