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.87 2002/04/27 21:24:34 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/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)
128 /* If presented path is relative, convert to absolute */
137 buf = malloc(buflen);
139 elog(FATAL, "out of memory");
141 if (getcwd(buf, buflen))
143 else if (errno == ERANGE)
152 elog(FATAL, "cannot get current working directory: %m");
156 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
158 elog(FATAL, "out of memory");
159 sprintf(new, "%s/%s", buf, dir);
166 elog(FATAL, "out of memory");
170 * Strip any trailing slash. Not strictly necessary, but avoids
171 * generating funny-looking paths to individual files.
173 newlen = strlen(new);
174 if (newlen > 1 && new[newlen-1] == '/')
175 new[newlen-1] = '\0';
183 /* ----------------------------------------------------------------
184 * MULTIBYTE stub code
186 * Even if MULTIBYTE is not enabled, these functions are necessary
187 * since pg_proc.h has references to them.
188 * ----------------------------------------------------------------
194 getdatabaseencoding(PG_FUNCTION_ARGS)
196 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
200 pg_client_encoding(PG_FUNCTION_ARGS)
202 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
206 PG_encoding_to_char(PG_FUNCTION_ARGS)
208 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
212 PG_char_to_encoding(PG_FUNCTION_ARGS)
218 pg_convert(PG_FUNCTION_ARGS)
220 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
221 return DirectFunctionCall1(textin, CStringGetDatum(""));
225 pg_convert2(PG_FUNCTION_ARGS)
227 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
228 return DirectFunctionCall1(textin, CStringGetDatum(""));
232 /* ----------------------------------------------------------------
234 * ----------------------------------------------------------------
247 unsigned char FromChar,
249 char ChTable[MAX_TOKEN];
251 for (i = 0; i < 128; i++)
253 RecodeForwTable[i] = i + 128;
254 RecodeBackTable[i] = i + 128;
257 if (IsUnderPostmaster)
259 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
263 filename = getenv("PG_RECODETABLE");
265 if (filename && *filename != '\0')
267 map_file = palloc(strlen(DataDir) + strlen(filename) + 2);
268 sprintf(map_file, "%s/%s", DataDir, filename);
269 file = AllocateFile(map_file, "r");
276 next_token(file, buf, sizeof(buf));
279 FromChar = strtoul(buf, 0, 0);
280 /* Read the ToChar */
281 next_token(file, buf, sizeof(buf));
284 ToChar = strtoul(buf, 0, 0);
285 RecodeForwTable[FromChar - 128] = ToChar;
286 RecodeBackTable[ToChar - 128] = FromChar;
289 while (!feof(file) && buf[0])
291 next_token(file, buf, sizeof(buf));
292 elog(LOG, "SetCharSet: unknown tag %s in file %s"
304 convertstr(unsigned char *buff, int len, int dest)
309 for (i = 0; i < len; i++, buff++)
314 *buff = RecodeForwTable[*buff - 128];
316 *buff = RecodeBackTable[*buff - 128];
322 #define CHARSET_FILE "charset.conf"
323 #define MAX_CHARSETS 10
330 char Orig[MAX_TOKEN];
331 char Dest[MAX_TOKEN];
332 char Table[MAX_TOKEN];
337 CharSetInRange(char *buf, int host)
344 struct in_addr file_ip_addr;
346 unsigned int one = 0x80000000,
350 p = strchr(buf, '/');
354 valid = inet_aton(buf, &file_ip_addr);
357 mask = strtoul(p, 0, 0);
358 FromAddr = ntohl(file_ip_addr.s_addr);
359 ToAddr = ntohl(file_ip_addr.s_addr);
360 for (i = 0; i < mask; i++)
366 ToAddr = ToAddr | ~NetMask;
368 return ((unsigned) tmp >= (unsigned) FromAddr &&
369 (unsigned) tmp <= (unsigned) ToAddr);
374 p = strchr(buf, '-');
378 valid = inet_aton(buf, &file_ip_addr);
381 FromAddr = ntohl(file_ip_addr.s_addr);
382 valid = inet_aton(p, &file_ip_addr);
385 ToAddr = ntohl(file_ip_addr.s_addr);
387 return ((unsigned) tmp >= (unsigned) FromAddr &&
388 (unsigned) tmp <= (unsigned) ToAddr);
394 valid = inet_aton(buf, &file_ip_addr);
397 FromAddr = file_ip_addr.s_addr;
398 return (unsigned) FromAddr == (unsigned) host;
407 GetCharSetByHost(char *TableName, int host, const char *DataDir)
411 BaseCharset[MAX_TOKEN],
412 OrigCharset[MAX_TOKEN],
413 DestCharset[MAX_TOKEN],
414 HostCharset[MAX_TOKEN],
421 struct CharsetItem *ChArray[MAX_CHARSETS];
424 bufsize = (strlen(DataDir) + strlen(CHARSET_FILE) + 2) * sizeof(char);
425 map_file = (char *) palloc(bufsize);
426 snprintf(map_file, bufsize, "%s/%s", DataDir, CHARSET_FILE);
427 file = AllocateFile(map_file, "r");
431 /* XXX should we log a complaint? */
437 next_token(file, buf, sizeof(buf));
441 if (strcasecmp(buf, "HostCharset") == 0)
443 else if (strcasecmp(buf, "BaseCharset") == 0)
445 else if (strcasecmp(buf, "RecodeTable") == 0)
448 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s"
455 next_token(file, buf, sizeof(buf));
458 if (CharSetInRange(buf, host))
460 /* Read the charset */
461 next_token(file, buf, sizeof(buf));
463 strcpy(HostCharset, buf);
468 /* Read the base charset */
469 next_token(file, buf, sizeof(buf));
471 strcpy(BaseCharset, buf);
474 /* Read the original charset */
475 next_token(file, buf, sizeof(buf));
478 strcpy(OrigCharset, buf);
479 /* Read the destination charset */
480 next_token(file, buf, sizeof(buf));
483 strcpy(DestCharset, buf);
484 /* Read the table filename */
485 next_token(file, buf, sizeof(buf));
489 (struct CharsetItem *) palloc(sizeof(struct CharsetItem));
490 strcpy(ChArray[ChIndex]->Orig, OrigCharset);
491 strcpy(ChArray[ChIndex]->Dest, DestCharset);
492 strcpy(ChArray[ChIndex]->Table, buf);
501 while (!feof(file) && buf[0])
503 next_token(file, buf, sizeof(buf));
504 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s"
511 for (i = 0; i < ChIndex; i++)
513 if (strcasecmp(BaseCharset, ChArray[i]->Orig) == 0 &&
514 strcasecmp(HostCharset, ChArray[i]->Dest) == 0)
515 strncpy(TableName, ChArray[i]->Table, 79);
520 #endif /* CYR_RECODE */
524 /* ----------------------------------------------------------------
527 * The session user is determined at connection start and never
528 * changes. The current user may change when "setuid" functions
529 * are implemented. Conceptually there is a stack, whose bottom
530 * is the session user. You are yourself responsible to save and
531 * restore the current user id if you need to change it.
532 * ----------------------------------------------------------------
534 static Oid CurrentUserId = InvalidOid;
535 static Oid SessionUserId = InvalidOid;
537 static bool AuthenticatedUserIsSuperuser = false;
540 * This function is relevant for all privilege checks.
545 AssertState(OidIsValid(CurrentUserId));
546 return CurrentUserId;
553 AssertArg(OidIsValid(newid));
554 CurrentUserId = newid;
559 * This value is only relevant for informational purposes.
562 GetSessionUserId(void)
564 AssertState(OidIsValid(SessionUserId));
565 return SessionUserId;
570 SetSessionUserId(Oid newid)
572 AssertArg(OidIsValid(newid));
573 SessionUserId = newid;
574 /* Current user defaults to session user. */
575 if (!OidIsValid(CurrentUserId))
576 CurrentUserId = newid;
581 InitializeSessionUserId(const char *username)
588 * Don't do scans if we're bootstrapping, none of the system catalogs
589 * exist yet, and they should be owned by postgres anyway.
591 AssertState(!IsBootstrapProcessingMode());
594 AssertState(!OidIsValid(SessionUserId));
596 userTup = SearchSysCache(SHADOWNAME,
597 PointerGetDatum(username),
599 if (!HeapTupleIsValid(userTup))
600 elog(FATAL, "user \"%s\" does not exist", username);
602 SetSessionUserId(((Form_pg_shadow) GETSTRUCT(userTup))->usesysid);
604 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
607 * Set up user-specific configuration variables. This is a good
608 * place to do it so we don't have to read pg_shadow twice during
611 datum = SysCacheGetAttr(SHADOWNAME, userTup,
612 Anum_pg_shadow_useconfig, &isnull);
615 ArrayType *a = DatumGetArrayTypeP(datum);
617 ProcessGUCArray(a, PGC_S_USER);
620 ReleaseSysCache(userTup);
625 InitializeSessionUserIdStandalone(void)
627 /* This function should only be called in a single-user backend. */
628 AssertState(!IsUnderPostmaster);
631 AssertState(!OidIsValid(SessionUserId));
633 SetSessionUserId(BOOTSTRAP_USESYSID);
634 AuthenticatedUserIsSuperuser = true;
639 * Change session auth ID while running
642 SetSessionAuthorization(const char *username)
646 if (!AuthenticatedUserIsSuperuser)
647 elog(ERROR, "permission denied");
649 userid = get_usesysid(username);
651 SetSessionUserId(userid);
657 * Get user name from user id
660 GetUserName(Oid userid)
665 tuple = SearchSysCache(SHADOWSYSID,
666 ObjectIdGetDatum(userid),
668 if (!HeapTupleIsValid(tuple))
669 elog(ERROR, "invalid user id %u", (unsigned) userid);
671 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
673 ReleaseSysCache(tuple);
679 /*-------------------------------------------------------------------------
680 * Interlock-file support
682 * These routines are used to create both a data-directory lockfile
683 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
684 * Both kinds of files contain the same info:
686 * Owning process' PID
687 * Data directory path
689 * By convention, the owning process' PID is negated if it is a standalone
690 * backend rather than a postmaster. This is just for informational purposes.
691 * The path is also just for informational purposes (so that a socket lockfile
692 * can be more easily traced to the associated postmaster).
694 * A data-directory lockfile can optionally contain a third line, containing
695 * the key and ID for the shared memory block used by this postmaster.
697 * On successful lockfile creation, a proc_exit callback to remove the
698 * lockfile is automatically created.
699 *-------------------------------------------------------------------------
703 * proc_exit callback to remove a lockfile.
706 UnlinkLockFile(int status, Datum filename)
708 unlink((char *) DatumGetPointer(filename));
709 /* Should we complain if the unlink fails? */
713 * Create a lockfile, if possible
715 * Call CreateLockFile with the name of the lockfile to be created.
716 * Returns true if successful, false if not (with a message on stderr).
718 * amPostmaster is used to determine how to encode the output PID.
719 * isDDLock and refName are used to determine what error message to produce.
722 CreateLockFile(const char *filename, bool amPostmaster,
723 bool isDDLock, const char *refName)
726 char buffer[MAXPGPATH + 100];
731 pid_t my_pid = getpid();
734 * We need a loop here because of race conditions. But don't loop
735 * forever (for example, a non-writable $PGDATA directory might cause
736 * a failure that won't go away). 100 tries seems like plenty.
738 for (ntries = 0;; ntries++)
741 * Try to create the lock file --- O_EXCL makes this atomic.
743 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
745 break; /* Success; exit the retry loop */
748 * Couldn't create the pid file. Probably it already exists.
750 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
751 elog(FATAL, "Can't create lock file %s: %m", filename);
754 * Read the file to get the old owner's PID. Note race condition
755 * here: file might have been deleted since we tried to create it.
757 fd = open(filename, O_RDONLY, 0600);
761 continue; /* race condition; try again */
762 elog(FATAL, "Can't read lock file %s: %m", filename);
764 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
765 elog(FATAL, "Can't read lock file %s: %m", filename);
769 encoded_pid = atoi(buffer);
771 /* if pid < 0, the pid is for postgres, not postmaster */
772 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
775 elog(FATAL, "Bogus data in lock file %s", filename);
778 * Check to see if the other process still exists
780 * Normally kill() will fail with ESRCH if the given PID doesn't
781 * exist. BeOS returns EINVAL for some silly reason, however.
783 if (other_pid != my_pid)
785 if (kill(other_pid, 0) == 0 ||
792 /* lockfile belongs to a live process */
793 fprintf(stderr, "Lock file \"%s\" already exists.\n",
797 "Is another %s (pid %d) running in \"%s\"?\n",
798 (encoded_pid < 0 ? "postgres" : "postmaster"),
799 (int) other_pid, refName);
802 "Is another %s (pid %d) using \"%s\"?\n",
803 (encoded_pid < 0 ? "postgres" : "postmaster"),
804 (int) other_pid, refName);
810 * No, the creating process did not exist. However, it could be
811 * that the postmaster crashed (or more likely was kill -9'd by a
812 * clueless admin) but has left orphan backends behind. Check for
813 * this by looking to see if there is an associated shmem segment
814 * that is still in use.
819 unsigned long shmKey,
822 ptr = strchr(buffer, '\n');
824 (ptr = strchr(ptr + 1, '\n')) != NULL)
827 if (sscanf(ptr, "%lu %lu", &shmKey, &shmId) == 2)
829 if (SharedMemoryIsInUse((IpcMemoryKey) shmKey,
830 (IpcMemoryId) shmId))
833 "Found a pre-existing shared memory block (ID %d) still in use.\n"
834 "If you're sure there are no old backends still running,\n"
835 "remove the shared memory block with ipcrm(1), or just\n"
837 (int) shmId, filename);
845 * Looks like nobody's home. Unlink the file and try again to
846 * create it. Need a loop because of possible race condition
847 * against other would-be creators.
849 if (unlink(filename) < 0)
850 elog(FATAL, "Can't remove old lock file %s: %m"
851 "\n\tThe file seems accidentally left, but I couldn't remove it."
852 "\n\tPlease remove the file by hand and try again.",
857 * Successfully created the file, now fill it.
859 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
860 amPostmaster ? (int) my_pid : -((int) my_pid),
863 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
865 int save_errno = errno;
869 /* if write didn't set errno, assume problem is no disk space */
870 errno = save_errno ? save_errno : ENOSPC;
871 elog(FATAL, "Can't write lock file %s: %m", filename);
876 * Arrange for automatic removal of lockfile at proc_exit.
878 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
880 return true; /* Success! */
884 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
886 char lockfile[MAXPGPATH];
888 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
889 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
891 /* Save name of lockfile for RecordSharedMemoryInLockFile */
892 strcpy(directoryLockFile, lockfile);
897 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
899 char lockfile[MAXPGPATH];
901 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
902 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
904 /* Save name of lockfile for TouchSocketLockFile */
905 strcpy(socketLockFile, lockfile);
910 * Re-read the socket lock file. This should be called every so often
911 * to ensure that the lock file has a recent access date. That saves it
912 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
913 * (Another reason we should never have put the socket file in /tmp...)
916 TouchSocketLockFile(void)
921 /* Do nothing if we did not create a socket... */
922 if (socketLockFile[0] != '\0')
924 /* XXX any need to complain about errors here? */
925 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
928 read(fd, buffer, sizeof(buffer));
935 * Append information about a shared memory segment to the data directory
936 * lock file (if we have created one).
938 * This may be called multiple times in the life of a postmaster, if we
939 * delete and recreate shmem due to backend crash. Therefore, be prepared
940 * to overwrite existing information. (As of 7.1, a postmaster only creates
941 * one shm seg anyway; but for the purposes here, if we did have more than
942 * one then any one of them would do anyway.)
945 RecordSharedMemoryInLockFile(IpcMemoryKey shmKey, IpcMemoryId shmId)
953 * Do nothing if we did not create a lockfile (probably because we are
954 * running standalone).
956 if (directoryLockFile[0] == '\0')
959 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
962 elog(LOG, "Failed to rewrite %s: %m", directoryLockFile);
965 len = read(fd, buffer, sizeof(buffer) - 100);
968 elog(LOG, "Failed to read %s: %m", directoryLockFile);
975 * Skip over first two lines (PID and path).
977 ptr = strchr(buffer, '\n');
979 (ptr = strchr(ptr + 1, '\n')) == NULL)
981 elog(LOG, "Bogus data in %s", directoryLockFile);
988 * Append shm key and ID. Format to try to keep it the same length
989 * always (trailing junk won't hurt, but might confuse humans).
991 sprintf(ptr, "%9lu %9lu\n",
992 (unsigned long) shmKey, (unsigned long) shmId);
995 * And rewrite the data. Since we write in a single kernel call, this
996 * update should appear atomic to onlookers.
998 len = strlen(buffer);
1000 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1001 (int) write(fd, buffer, len) != len)
1003 /* if write didn't set errno, assume problem is no disk space */
1006 elog(LOG, "Failed to write %s: %m", directoryLockFile);
1014 /*-------------------------------------------------------------------------
1015 * Version checking support
1016 *-------------------------------------------------------------------------
1020 * Determine whether the PG_VERSION file in directory `path' indicates
1021 * a data version compatible with the version of this program.
1023 * If compatible, return. Otherwise, elog(FATAL).
1026 ValidatePgVersion(const char *path)
1028 char full_path[MAXPGPATH];
1036 const char *version_string = PG_VERSION;
1038 my_major = strtol(version_string, &endptr, 10);
1040 my_minor = strtol(endptr + 1, NULL, 10);
1042 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
1044 file = AllocateFile(full_path, "r");
1047 if (errno == ENOENT)
1048 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
1050 elog(FATAL, "cannot open %s: %m", full_path);
1053 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1055 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
1059 if (my_major != file_major || my_minor != file_minor)
1060 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
1061 "which is not compatible with this version %s.",
1062 file_major, file_minor, version_string);