1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2002, 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.104 2003/06/27 19:08:37 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
33 #include "catalog/catname.h"
34 #include "catalog/pg_shadow.h"
35 #include "libpq/libpq-be.h"
36 #include "miscadmin.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "utils/builtins.h"
40 #include "utils/guc.h"
41 #include "utils/lsyscache.h"
42 #include "utils/syscache.h"
45 ProcessingMode Mode = InitProcessing;
47 /* Note: we rely on these to initialize as zeroes */
48 static char directoryLockFile[MAXPGPATH];
49 static char socketLockFile[MAXPGPATH];
52 static unsigned char RecodeForwTable[128];
53 static unsigned char RecodeBackTable[128];
55 static void GetCharSetByHost(char *TableName, int host, const char *DataDir);
59 /* ----------------------------------------------------------------
60 * ignoring system indexes support stuff
61 * ----------------------------------------------------------------
64 static bool isIgnoringSystemIndexes = false;
67 * IsIgnoringSystemIndexes
68 * True if ignoring system indexes.
71 IsIgnoringSystemIndexes()
73 return isIgnoringSystemIndexes;
78 * Set true or false whether PostgreSQL ignores system indexes.
82 IgnoreSystemIndexes(bool mode)
84 isIgnoringSystemIndexes = mode;
87 /* ----------------------------------------------------------------
88 * database path / name support stuff
89 * ----------------------------------------------------------------
93 SetDatabasePath(const char *path)
100 /* use strdup since this is done before memory contexts are set up */
103 DatabasePath = strdup(path);
104 AssertState(DatabasePath);
109 * Set data directory, but make sure it's an absolute path. Use this,
110 * never set DataDir directly.
113 SetDataDir(const char *dir)
120 /* If presented path is relative, convert to absolute */
121 if (!is_absolute_path(dir))
129 buf = malloc(buflen);
131 elog(FATAL, "out of memory");
133 if (getcwd(buf, buflen))
135 else if (errno == ERANGE)
144 elog(FATAL, "cannot get current working directory: %m");
148 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
150 elog(FATAL, "out of memory");
151 sprintf(new, "%s/%s", buf, dir);
158 elog(FATAL, "out of memory");
162 * Strip any trailing slash. Not strictly necessary, but avoids
163 * generating funny-looking paths to individual files.
165 newlen = strlen(new);
166 if (newlen > 1 && new[newlen - 1] == '/'
168 || new[newlen - 1] == '\\'
171 new[newlen - 1] = '\0';
178 /* ----------------------------------------------------------------
180 * ----------------------------------------------------------------
193 unsigned char FromChar,
195 char ChTable[MAX_TOKEN];
197 for (i = 0; i < 128; i++)
199 RecodeForwTable[i] = i + 128;
200 RecodeBackTable[i] = i + 128;
203 if (IsUnderPostmaster)
205 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
209 filename = getenv("PG_RECODETABLE");
211 if (filename && *filename != '\0')
213 map_file = palloc(strlen(DataDir) + strlen(filename) + 2);
214 sprintf(map_file, "%s/%s", DataDir, filename);
215 file = AllocateFile(map_file, "r");
222 next_token(file, buf, sizeof(buf));
225 FromChar = strtoul(buf, 0, 0);
226 /* Read the ToChar */
227 next_token(file, buf, sizeof(buf));
230 ToChar = strtoul(buf, 0, 0);
231 RecodeForwTable[FromChar - 128] = ToChar;
232 RecodeBackTable[ToChar - 128] = FromChar;
235 while (!feof(file) && buf[0])
237 next_token(file, buf, sizeof(buf));
238 elog(LOG, "SetCharSet: unknown tag %s in file %s",
250 convertstr(unsigned char *buff, int len, int dest)
255 for (i = 0; i < len; i++, buff++)
260 *buff = RecodeForwTable[*buff - 128];
262 *buff = RecodeBackTable[*buff - 128];
268 #define CHARSET_FILE "charset.conf"
269 #define MAX_CHARSETS 10
276 char Orig[MAX_TOKEN];
277 char Dest[MAX_TOKEN];
278 char Table[MAX_TOKEN];
283 CharSetInRange(char *buf, int host)
290 struct in_addr file_ip_addr;
292 unsigned int one = 0x80000000,
296 p = strchr(buf, '/');
300 valid = inet_aton(buf, &file_ip_addr);
303 mask = strtoul(p, 0, 0);
304 FromAddr = ntohl(file_ip_addr.s_addr);
305 ToAddr = ntohl(file_ip_addr.s_addr);
306 for (i = 0; i < mask; i++)
312 ToAddr = ToAddr | ~NetMask;
314 return ((unsigned) tmp >= (unsigned) FromAddr &&
315 (unsigned) tmp <= (unsigned) ToAddr);
320 p = strchr(buf, '-');
324 valid = inet_aton(buf, &file_ip_addr);
327 FromAddr = ntohl(file_ip_addr.s_addr);
328 valid = inet_aton(p, &file_ip_addr);
331 ToAddr = ntohl(file_ip_addr.s_addr);
333 return ((unsigned) tmp >= (unsigned) FromAddr &&
334 (unsigned) tmp <= (unsigned) ToAddr);
340 valid = inet_aton(buf, &file_ip_addr);
343 FromAddr = file_ip_addr.s_addr;
344 return (unsigned) FromAddr == (unsigned) host;
353 GetCharSetByHost(char *TableName, int host, const char *DataDir)
357 BaseCharset[MAX_TOKEN],
358 OrigCharset[MAX_TOKEN],
359 DestCharset[MAX_TOKEN],
360 HostCharset[MAX_TOKEN],
366 struct CharsetItem *ChArray[MAX_CHARSETS];
369 bufsize = (strlen(DataDir) + strlen(CHARSET_FILE) + 2) * sizeof(char);
370 map_file = (char *) palloc(bufsize);
371 snprintf(map_file, bufsize, "%s/%s", DataDir, CHARSET_FILE);
372 file = AllocateFile(map_file, "r");
376 /* XXX should we log a complaint? */
382 next_token(file, buf, sizeof(buf));
386 if (strcasecmp(buf, "HostCharset") == 0)
388 else if (strcasecmp(buf, "BaseCharset") == 0)
390 else if (strcasecmp(buf, "RecodeTable") == 0)
393 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
400 next_token(file, buf, sizeof(buf));
403 if (CharSetInRange(buf, host))
405 /* Read the charset */
406 next_token(file, buf, sizeof(buf));
408 strcpy(HostCharset, buf);
413 /* Read the base charset */
414 next_token(file, buf, sizeof(buf));
416 strcpy(BaseCharset, buf);
419 /* Read the original charset */
420 next_token(file, buf, sizeof(buf));
423 strcpy(OrigCharset, buf);
424 /* Read the destination charset */
425 next_token(file, buf, sizeof(buf));
428 strcpy(DestCharset, buf);
429 /* Read the table filename */
430 next_token(file, buf, sizeof(buf));
434 (struct CharsetItem *) palloc(sizeof(struct CharsetItem));
435 strcpy(ChArray[ChIndex]->Orig, OrigCharset);
436 strcpy(ChArray[ChIndex]->Dest, DestCharset);
437 strcpy(ChArray[ChIndex]->Table, buf);
446 while (!feof(file) && buf[0])
448 next_token(file, buf, sizeof(buf));
449 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
456 for (i = 0; i < ChIndex; i++)
458 if (strcasecmp(BaseCharset, ChArray[i]->Orig) == 0 &&
459 strcasecmp(HostCharset, ChArray[i]->Dest) == 0)
460 strncpy(TableName, ChArray[i]->Table, 79);
464 #endif /* CYR_RECODE */
468 /* ----------------------------------------------------------------
471 * The authenticated user is determined at connection start and never
472 * changes. The session user can be changed only by SET SESSION
473 * AUTHORIZATION. The current user may change when "setuid" functions
474 * are implemented. Conceptually there is a stack, whose bottom
475 * is the session user. You are yourself responsible to save and
476 * restore the current user id if you need to change it.
477 * ----------------------------------------------------------------
479 static AclId AuthenticatedUserId = 0;
480 static AclId SessionUserId = 0;
481 static AclId CurrentUserId = 0;
483 static bool AuthenticatedUserIsSuperuser = false;
486 * This function is relevant for all privilege checks.
491 AssertState(AclIdIsValid(CurrentUserId));
492 return CurrentUserId;
497 SetUserId(AclId newid)
499 AssertArg(AclIdIsValid(newid));
500 CurrentUserId = newid;
505 * This value is only relevant for informational purposes.
508 GetSessionUserId(void)
510 AssertState(AclIdIsValid(SessionUserId));
511 return SessionUserId;
516 SetSessionUserId(AclId newid)
518 AssertArg(AclIdIsValid(newid));
519 SessionUserId = newid;
520 /* Current user defaults to session user. */
521 if (!AclIdIsValid(CurrentUserId))
522 CurrentUserId = newid;
527 InitializeSessionUserId(const char *username)
535 * Don't do scans if we're bootstrapping, none of the system catalogs
536 * exist yet, and they should be owned by postgres anyway.
538 AssertState(!IsBootstrapProcessingMode());
541 AssertState(!OidIsValid(AuthenticatedUserId));
543 userTup = SearchSysCache(SHADOWNAME,
544 PointerGetDatum(username),
546 if (!HeapTupleIsValid(userTup))
547 elog(FATAL, "user \"%s\" does not exist", username);
549 usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
551 AuthenticatedUserId = usesysid;
552 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
554 SetSessionUserId(usesysid); /* sets CurrentUserId too */
556 /* Record username and superuser status as GUC settings too */
557 SetConfigOption("session_authorization", username,
558 PGC_BACKEND, PGC_S_OVERRIDE);
559 SetConfigOption("is_superuser",
560 AuthenticatedUserIsSuperuser ? "on" : "off",
561 PGC_INTERNAL, PGC_S_OVERRIDE);
564 * Set up user-specific configuration variables. This is a good place
565 * to do it so we don't have to read pg_shadow twice during session
568 datum = SysCacheGetAttr(SHADOWNAME, userTup,
569 Anum_pg_shadow_useconfig, &isnull);
572 ArrayType *a = DatumGetArrayTypeP(datum);
574 ProcessGUCArray(a, PGC_S_USER);
577 ReleaseSysCache(userTup);
582 InitializeSessionUserIdStandalone(void)
584 /* This function should only be called in a single-user backend. */
585 AssertState(!IsUnderPostmaster);
588 AssertState(!OidIsValid(AuthenticatedUserId));
590 AuthenticatedUserId = BOOTSTRAP_USESYSID;
591 AuthenticatedUserIsSuperuser = true;
593 SetSessionUserId(BOOTSTRAP_USESYSID);
598 * Change session auth ID while running
600 * Only a superuser may set auth ID to something other than himself. Note
601 * that in case of multiple SETs in a single session, the original userid's
602 * superuserness is what matters. But we set the GUC variable is_superuser
603 * to indicate whether the *current* session userid is a superuser.
606 SetSessionAuthorization(AclId userid, bool is_superuser)
608 /* Must have authenticated already, else can't make permission check */
609 AssertState(AclIdIsValid(AuthenticatedUserId));
611 if (userid != AuthenticatedUserId &&
612 !AuthenticatedUserIsSuperuser)
613 elog(ERROR, "SET SESSION AUTHORIZATION: permission denied");
615 SetSessionUserId(userid);
618 SetConfigOption("is_superuser",
619 is_superuser ? "on" : "off",
620 PGC_INTERNAL, PGC_S_OVERRIDE);
625 * Get user name from user id
628 GetUserNameFromId(AclId userid)
633 tuple = SearchSysCache(SHADOWSYSID,
634 ObjectIdGetDatum(userid),
636 if (!HeapTupleIsValid(tuple))
637 elog(ERROR, "invalid user id %d", userid);
639 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
641 ReleaseSysCache(tuple);
647 /*-------------------------------------------------------------------------
648 * Interlock-file support
650 * These routines are used to create both a data-directory lockfile
651 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
652 * Both kinds of files contain the same info:
654 * Owning process' PID
655 * Data directory path
657 * By convention, the owning process' PID is negated if it is a standalone
658 * backend rather than a postmaster. This is just for informational purposes.
659 * The path is also just for informational purposes (so that a socket lockfile
660 * can be more easily traced to the associated postmaster).
662 * A data-directory lockfile can optionally contain a third line, containing
663 * the key and ID for the shared memory block used by this postmaster.
665 * On successful lockfile creation, a proc_exit callback to remove the
666 * lockfile is automatically created.
667 *-------------------------------------------------------------------------
671 * proc_exit callback to remove a lockfile.
674 UnlinkLockFile(int status, Datum filename)
676 unlink((char *) DatumGetPointer(filename));
677 /* Should we complain if the unlink fails? */
681 * Create a lockfile, if possible
683 * Call CreateLockFile with the name of the lockfile to be created.
684 * Returns true if successful, false if not (with a message on stderr).
686 * amPostmaster is used to determine how to encode the output PID.
687 * isDDLock and refName are used to determine what error message to produce.
690 CreateLockFile(const char *filename, bool amPostmaster,
691 bool isDDLock, const char *refName)
694 char buffer[MAXPGPATH + 100];
699 pid_t my_pid = getpid();
702 * We need a loop here because of race conditions. But don't loop
703 * forever (for example, a non-writable $PGDATA directory might cause
704 * a failure that won't go away). 100 tries seems like plenty.
706 for (ntries = 0;; ntries++)
709 * Try to create the lock file --- O_EXCL makes this atomic.
711 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
713 break; /* Success; exit the retry loop */
716 * Couldn't create the pid file. Probably it already exists.
718 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
719 elog(FATAL, "Can't create lock file %s: %m", filename);
722 * Read the file to get the old owner's PID. Note race condition
723 * here: file might have been deleted since we tried to create it.
725 fd = open(filename, O_RDONLY, 0600);
729 continue; /* race condition; try again */
730 elog(FATAL, "Can't read lock file %s: %m", filename);
732 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
733 elog(FATAL, "Can't read lock file %s: %m", filename);
737 encoded_pid = atoi(buffer);
739 /* if pid < 0, the pid is for postgres, not postmaster */
740 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
743 elog(FATAL, "Bogus data in lock file %s", filename);
746 * Check to see if the other process still exists
748 * Normally kill() will fail with ESRCH if the given PID doesn't
749 * exist. BeOS returns EINVAL for some silly reason, however.
751 if (other_pid != my_pid)
753 if (kill(other_pid, 0) == 0 ||
760 /* lockfile belongs to a live process */
761 fprintf(stderr, "Lock file \"%s\" already exists.\n",
765 "Is another %s (pid %d) running in \"%s\"?\n",
766 (encoded_pid < 0 ? "postgres" : "postmaster"),
767 (int) other_pid, refName);
770 "Is another %s (pid %d) using \"%s\"?\n",
771 (encoded_pid < 0 ? "postgres" : "postmaster"),
772 (int) other_pid, refName);
778 * No, the creating process did not exist. However, it could be
779 * that the postmaster crashed (or more likely was kill -9'd by a
780 * clueless admin) but has left orphan backends behind. Check for
781 * this by looking to see if there is an associated shmem segment
782 * that is still in use.
790 ptr = strchr(buffer, '\n');
792 (ptr = strchr(ptr + 1, '\n')) != NULL)
795 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
797 if (PGSharedMemoryIsInUse(id1, id2))
800 "Found a pre-existing shared memory block (key %lu, id %lu) still in use.\n"
801 "If you're sure there are no old backends still running,\n"
802 "remove the shared memory block with ipcrm(1), or just\n"
812 * Looks like nobody's home. Unlink the file and try again to
813 * create it. Need a loop because of possible race condition
814 * against other would-be creators.
816 if (unlink(filename) < 0)
817 elog(FATAL, "Can't remove old lock file %s: %m"
818 "\n\tThe file seems accidentally left, but I couldn't remove it."
819 "\n\tPlease remove the file by hand and try again.",
824 * Successfully created the file, now fill it.
826 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
827 amPostmaster ? (int) my_pid : -((int) my_pid),
830 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
832 int save_errno = errno;
836 /* if write didn't set errno, assume problem is no disk space */
837 errno = save_errno ? save_errno : ENOSPC;
838 elog(FATAL, "Can't write lock file %s: %m", filename);
843 * Arrange for automatic removal of lockfile at proc_exit.
845 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
847 return true; /* Success! */
851 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
853 char lockfile[MAXPGPATH];
855 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
856 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
858 /* Save name of lockfile for RecordSharedMemoryInLockFile */
859 strcpy(directoryLockFile, lockfile);
864 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
866 char lockfile[MAXPGPATH];
868 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
869 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
871 /* Save name of lockfile for TouchSocketLockFile */
872 strcpy(socketLockFile, lockfile);
877 * TouchSocketLockFile -- mark socket lock file as recently accessed
879 * This routine should be called every so often to ensure that the lock file
880 * has a recent mod or access date. That saves it
881 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
882 * (Another reason we should never have put the socket file in /tmp...)
885 TouchSocketLockFile(void)
887 /* Do nothing if we did not create a socket... */
888 if (socketLockFile[0] != '\0')
891 * utime() is POSIX standard, utimes() is a common alternative;
892 * if we have neither, fall back to actually reading the file
893 * (which only sets the access time not mod time, but that should
894 * be enough in most cases). In all paths, we ignore errors.
897 utime(socketLockFile, NULL);
898 #else /* !HAVE_UTIME */
900 utimes(socketLockFile, NULL);
901 #else /* !HAVE_UTIMES */
905 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
908 read(fd, buffer, sizeof(buffer));
911 #endif /* HAVE_UTIMES */
912 #endif /* HAVE_UTIME */
917 * Append information about a shared memory segment to the data directory
918 * lock file (if we have created one).
920 * This may be called multiple times in the life of a postmaster, if we
921 * delete and recreate shmem due to backend crash. Therefore, be prepared
922 * to overwrite existing information. (As of 7.1, a postmaster only creates
923 * one shm seg at a time; but for the purposes here, if we did have more than
924 * one then any one of them would do anyway.)
927 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
935 * Do nothing if we did not create a lockfile (probably because we are
936 * running standalone).
938 if (directoryLockFile[0] == '\0')
941 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
944 elog(LOG, "Failed to rewrite %s: %m", directoryLockFile);
947 len = read(fd, buffer, sizeof(buffer) - 100);
950 elog(LOG, "Failed to read %s: %m", directoryLockFile);
957 * Skip over first two lines (PID and path).
959 ptr = strchr(buffer, '\n');
961 (ptr = strchr(ptr + 1, '\n')) == NULL)
963 elog(LOG, "Bogus data in %s", directoryLockFile);
970 * Append key information. Format to try to keep it the same length
971 * always (trailing junk won't hurt, but might confuse humans).
973 sprintf(ptr, "%9lu %9lu\n", id1, id2);
976 * And rewrite the data. Since we write in a single kernel call, this
977 * update should appear atomic to onlookers.
979 len = strlen(buffer);
981 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
982 (int) write(fd, buffer, len) != len)
984 /* if write didn't set errno, assume problem is no disk space */
987 elog(LOG, "Failed to write %s: %m", directoryLockFile);
995 /*-------------------------------------------------------------------------
996 * Version checking support
997 *-------------------------------------------------------------------------
1001 * Determine whether the PG_VERSION file in directory `path' indicates
1002 * a data version compatible with the version of this program.
1004 * If compatible, return. Otherwise, elog(FATAL).
1007 ValidatePgVersion(const char *path)
1009 char full_path[MAXPGPATH];
1017 const char *version_string = PG_VERSION;
1019 my_major = strtol(version_string, &endptr, 10);
1021 my_minor = strtol(endptr + 1, NULL, 10);
1023 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
1025 file = AllocateFile(full_path, "r");
1028 if (errno == ENOENT)
1029 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
1031 elog(FATAL, "cannot open %s: %m", full_path);
1034 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1036 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
1040 if (my_major != file_major || my_minor != file_minor)
1041 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
1042 "which is not compatible with this version %s.",
1043 file_major, file_minor, version_string);
1046 /*-------------------------------------------------------------------------
1047 * Library preload support
1048 *-------------------------------------------------------------------------
1051 #if defined(__mc68000__) && defined(__ELF__)
1052 typedef int32 ((*func_ptr) ());
1054 typedef char *((*func_ptr) ());
1058 * process any libraries that should be preloaded and
1059 * optionally pre-initialized
1062 process_preload_libraries(char *preload_libraries_string)
1068 if (preload_libraries_string == NULL)
1071 /* Need a modifiable copy of string */
1072 rawstring = pstrdup(preload_libraries_string);
1074 /* Parse string into list of identifiers */
1075 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1077 /* syntax error in list */
1080 elog(LOG, "invalid list syntax for preload_libraries configuration option");
1083 foreach(l, elemlist)
1085 char *tok = (char *) lfirst(l);
1086 char *sep = strstr(tok, ":");
1087 char *filename = NULL;
1088 char *funcname = NULL;
1094 * a colon separator implies there is an initialization function
1095 * that we need to run in addition to loading the library
1097 size_t filename_len = sep - tok;
1098 size_t funcname_len = strlen(tok) - filename_len - 1;
1100 filename = (char *) palloc(filename_len + 1);
1101 memset(filename, '\0', filename_len + 1);
1102 snprintf(filename, filename_len + 1, "%s", tok);
1104 funcname = (char *) palloc(funcname_len + 1);
1105 memset(funcname, '\0', funcname_len + 1);
1106 snprintf(funcname, funcname_len + 1, "%s", sep + 1);
1111 * no separator -- just load the library
1113 filename = pstrdup(tok);
1117 initfunc = (func_ptr) load_external_function(filename, funcname, false, NULL);
1121 elog(LOG, "preloaded library %s with initialization function %s", filename, funcname);
1123 if (filename != NULL)
1126 if (funcname != NULL)