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.80 2001/10/19 18:19: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 * ----------------------------------------------------------------
230 /* Some standard C libraries, including GNU, have an isblank() function.
231 Others, including Solaris, do not. So we have our own.
234 isblank(const char c)
236 return c == ' ' || c == 9 /* tab */ ;
240 next_token(FILE *fp, char *buf, const int bufsz)
242 /*--------------------------------------------------------------------------
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.
250 --------------------------------------------------------------------------*/
252 char *eb = buf + (bufsz - 1);
254 /* Move over inital token-delimiting blanks */
255 while (isblank(c = getc(fp)));
261 * build a token in buf of next characters up to EOF, eol, or
264 while (c != EOF && c != '\n' && !isblank(c))
271 * Put back the char right after the token (putting back EOF
281 read_through_eol(FILE *file)
287 while (c != '\n' && c != EOF);
300 unsigned char FromChar,
304 for (i = 0; i < 128; i++)
306 RecodeForwTable[i] = i + 128;
307 RecodeBackTable[i] = i + 128;
310 if (IsUnderPostmaster)
312 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
316 p = getenv("PG_RECODETABLE");
320 map_file = malloc(strlen(DataDir) + strlen(p) + 2);
322 elog(FATAL, "out of memory");
323 sprintf(map_file, "%s/%s", DataDir, p);
324 file = AllocateFile(map_file, PG_BINARY_R);
340 read_through_eol(file);
343 /* Read the FromChar */
344 next_token(file, buf, sizeof(buf));
347 FromChar = strtoul(buf, 0, 0);
348 /* Read the ToChar */
349 next_token(file, buf, sizeof(buf));
352 ToChar = strtoul(buf, 0, 0);
353 RecodeForwTable[FromChar - 128] = ToChar;
354 RecodeBackTable[ToChar - 128] = FromChar;
356 read_through_eol(file);
367 convertstr(unsigned char *buff, int len, int dest)
372 for (i = 0; i < len; i++, buff++)
377 *buff = RecodeForwTable[*buff - 128];
379 *buff = RecodeBackTable[*buff - 128];
389 /* ----------------------------------------------------------------
392 * The session user is determined at connection start and never
393 * changes. The current user may change when "setuid" functions
394 * are implemented. Conceptually there is a stack, whose bottom
395 * is the session user. You are yourself responsible to save and
396 * restore the current user id if you need to change it.
397 * ----------------------------------------------------------------
399 static Oid CurrentUserId = InvalidOid;
400 static Oid SessionUserId = InvalidOid;
402 static bool AuthenticatedUserIsSuperuser = false;
405 * This function is relevant for all privilege checks.
410 AssertState(OidIsValid(CurrentUserId));
411 return CurrentUserId;
418 AssertArg(OidIsValid(newid));
419 CurrentUserId = newid;
424 * This value is only relevant for informational purposes.
427 GetSessionUserId(void)
429 AssertState(OidIsValid(SessionUserId));
430 return SessionUserId;
435 SetSessionUserId(Oid newid)
437 AssertArg(OidIsValid(newid));
438 SessionUserId = newid;
439 /* Current user defaults to session user. */
440 if (!OidIsValid(CurrentUserId))
441 CurrentUserId = newid;
446 InitializeSessionUserId(const char *username)
451 * Don't do scans if we're bootstrapping, none of the system catalogs
452 * exist yet, and they should be owned by postgres anyway.
454 AssertState(!IsBootstrapProcessingMode());
457 AssertState(!OidIsValid(SessionUserId));
459 userTup = SearchSysCache(SHADOWNAME,
460 PointerGetDatum(username),
462 if (!HeapTupleIsValid(userTup))
463 elog(FATAL, "user \"%s\" does not exist", username);
465 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
467 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
469 ReleaseSysCache(userTup);
474 InitializeSessionUserIdStandalone(void)
476 /* This function should only be called in a single-user backend. */
477 AssertState(!IsUnderPostmaster);
480 AssertState(!OidIsValid(SessionUserId));
482 SetSessionUserId(BOOTSTRAP_USESYSID);
483 AuthenticatedUserIsSuperuser = true;
488 * Change session auth ID while running
490 void SetSessionAuthorization(const char * username)
494 if (!AuthenticatedUserIsSuperuser)
495 elog(ERROR, "permission denied");
497 userid = get_usesysid(username);
499 SetSessionUserId(userid);
505 * Get user name from user id
508 GetUserName(Oid userid)
513 tuple = SearchSysCache(SHADOWSYSID,
514 ObjectIdGetDatum(userid),
516 if (!HeapTupleIsValid(tuple))
517 elog(ERROR, "invalid user id %u", (unsigned) userid);
519 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
521 ReleaseSysCache(tuple);
527 /*-------------------------------------------------------------------------
528 * Interlock-file support
530 * These routines are used to create both a data-directory lockfile
531 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
532 * Both kinds of files contain the same info:
534 * Owning process' PID
535 * Data directory path
537 * By convention, the owning process' PID is negated if it is a standalone
538 * backend rather than a postmaster. This is just for informational purposes.
539 * The path is also just for informational purposes (so that a socket lockfile
540 * can be more easily traced to the associated postmaster).
542 * A data-directory lockfile can optionally contain a third line, containing
543 * the key and ID for the shared memory block used by this postmaster.
545 * On successful lockfile creation, a proc_exit callback to remove the
546 * lockfile is automatically created.
547 *-------------------------------------------------------------------------
551 * proc_exit callback to remove a lockfile.
554 UnlinkLockFile(int status, Datum filename)
556 unlink((char *) DatumGetPointer(filename));
557 /* Should we complain if the unlink fails? */
561 * Create a lockfile, if possible
563 * Call CreateLockFile with the name of the lockfile to be created.
564 * Returns true if successful, false if not (with a message on stderr).
566 * amPostmaster is used to determine how to encode the output PID.
567 * isDDLock and refName are used to determine what error message to produce.
570 CreateLockFile(const char *filename, bool amPostmaster,
571 bool isDDLock, const char *refName)
574 char buffer[MAXPGPATH + 100];
579 pid_t my_pid = getpid();
582 * We need a loop here because of race conditions. But don't loop
583 * forever (for example, a non-writable $PGDATA directory might cause
584 * a failure that won't go away). 100 tries seems like plenty.
586 for (ntries = 0; ; ntries++)
590 * Try to create the lock file --- O_EXCL makes this atomic.
592 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
594 break; /* Success; exit the retry loop */
597 * Couldn't create the pid file. Probably it already exists.
599 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
600 elog(FATAL, "Can't create lock file %s: %m", filename);
603 * Read the file to get the old owner's PID. Note race condition
604 * here: file might have been deleted since we tried to create it.
606 fd = open(filename, O_RDONLY, 0600);
610 continue; /* race condition; try again */
611 elog(FATAL, "Can't read lock file %s: %m", filename);
613 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
614 elog(FATAL, "Can't read lock file %s: %m", filename);
618 encoded_pid = atoi(buffer);
620 /* if pid < 0, the pid is for postgres, not postmaster */
621 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
624 elog(FATAL, "Bogus data in lock file %s", filename);
627 * Check to see if the other process still exists
629 * Normally kill() will fail with ESRCH if the given PID doesn't
630 * exist. BeOS returns EINVAL for some silly reason, however.
632 if (other_pid != my_pid)
634 if (kill(other_pid, 0) == 0 ||
641 /* lockfile belongs to a live process */
642 fprintf(stderr, "Lock file \"%s\" already exists.\n",
646 "Is another %s (pid %d) running in \"%s\"?\n",
647 (encoded_pid < 0 ? "postgres" : "postmaster"),
648 (int) other_pid, refName);
651 "Is another %s (pid %d) using \"%s\"?\n",
652 (encoded_pid < 0 ? "postgres" : "postmaster"),
653 (int) other_pid, refName);
659 * No, the creating process did not exist. However, it could be
660 * that the postmaster crashed (or more likely was kill -9'd by a
661 * clueless admin) but has left orphan backends behind. Check for
662 * this by looking to see if there is an associated shmem segment
663 * that is still in use.
668 unsigned long shmKey,
671 ptr = strchr(buffer, '\n');
673 (ptr = strchr(ptr + 1, '\n')) != NULL)
676 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
678 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
679 (IpcMemoryId) shmId))
682 "Found a pre-existing shared memory block (ID %d) still in use.\n"
683 "If you're sure there are no old backends still running,\n"
684 "remove the shared memory block with ipcrm(1), or just\n"
686 (int) shmId, filename);
694 * Looks like nobody's home. Unlink the file and try again to
695 * create it. Need a loop because of possible race condition
696 * against other would-be creators.
698 if (unlink(filename) < 0)
699 elog(FATAL, "Can't remove old lock file %s: %m"
700 "\n\tThe file seems accidentally left, but I couldn't remove it."
701 "\n\tPlease remove the file by hand and try again.",
706 * Successfully created the file, now fill it.
708 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
709 amPostmaster ? (int) my_pid : -((int) my_pid),
712 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
714 int save_errno = errno;
718 /* if write didn't set errno, assume problem is no disk space */
719 errno = save_errno ? save_errno : ENOSPC;
720 elog(FATAL, "Can't write lock file %s: %m", filename);
725 * Arrange for automatic removal of lockfile at proc_exit.
727 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
729 return true; /* Success! */
733 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
735 char lockfile[MAXPGPATH];
737 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
738 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
740 /* Save name of lockfile for RecordSharedMemoryInLockFile */
741 strcpy(directoryLockFile, lockfile);
746 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
748 char lockfile[MAXPGPATH];
750 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
751 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
753 /* Save name of lockfile for TouchSocketLockFile */
754 strcpy(socketLockFile, lockfile);
759 * Re-read the socket lock file. This should be called every so often
760 * to ensure that the lock file has a recent access date. That saves it
761 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
762 * (Another reason we should never have put the socket file in /tmp...)
765 TouchSocketLockFile(void)
770 /* Do nothing if we did not create a socket... */
771 if (socketLockFile[0] != '\0')
773 /* XXX any need to complain about errors here? */
774 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
777 read(fd, buffer, sizeof(buffer));
784 * Append information about a shared memory segment to the data directory
785 * lock file (if we have created one).
787 * This may be called multiple times in the life of a postmaster, if we
788 * delete and recreate shmem due to backend crash. Therefore, be prepared
789 * to overwrite existing information. (As of 7.1, a postmaster only creates
790 * one shm seg anyway; but for the purposes here, if we did have more than
791 * one then any one of them would do anyway.)
794 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
802 * Do nothing if we did not create a lockfile (probably because we are
803 * running standalone).
805 if (directoryLockFile[0] == '\0')
808 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
811 elog(DEBUG, "Failed to rewrite %s: %m", directoryLockFile);
814 len = read(fd, buffer, sizeof(buffer) - 100);
817 elog(DEBUG, "Failed to read %s: %m", directoryLockFile);
824 * Skip over first two lines (PID and path).
826 ptr = strchr(buffer, '\n');
828 (ptr = strchr(ptr + 1, '\n')) == NULL)
830 elog(DEBUG, "Bogus data in %s", directoryLockFile);
837 * Append shm key and ID. Format to try to keep it the same length
838 * always (trailing junk won't hurt, but might confuse humans).
840 sprintf(ptr, "%9lu %9lu\n",
841 (unsigned long) shmKey, (unsigned long) shmId);
844 * And rewrite the data. Since we write in a single kernel call, this
845 * update should appear atomic to onlookers.
847 len = strlen(buffer);
849 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
850 (int) write(fd, buffer, len) != len)
852 /* if write didn't set errno, assume problem is no disk space */
855 elog(DEBUG, "Failed to write %s: %m", directoryLockFile);
863 /*-------------------------------------------------------------------------
864 * Version checking support
865 *-------------------------------------------------------------------------
869 * Determine whether the PG_VERSION file in directory `path' indicates
870 * a data version compatible with the version of this program.
872 * If compatible, return. Otherwise, elog(FATAL).
875 ValidatePgVersion(const char *path)
877 char full_path[MAXPGPATH];
885 const char *version_string = PG_VERSION;
887 my_major = strtol(version_string, &endptr, 10);
889 my_minor = strtol(endptr + 1, NULL, 10);
891 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
893 file = AllocateFile(full_path, "r");
897 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
899 elog(FATAL, "cannot open %s: %m", full_path);
902 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
904 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
908 if (my_major != file_major || my_minor != file_minor)
909 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
910 "which is not compatible with this version %s.",
911 file_major, file_minor, version_string);