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.98 2002/12/05 04:04:46 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
29 #include "catalog/catname.h"
30 #include "catalog/pg_shadow.h"
31 #include "libpq/libpq-be.h"
32 #include "miscadmin.h"
33 #include "storage/ipc.h"
34 #include "storage/pg_shmem.h"
35 #include "utils/builtins.h"
36 #include "utils/guc.h"
37 #include "utils/lsyscache.h"
38 #include "utils/syscache.h"
41 ProcessingMode Mode = InitProcessing;
43 /* Note: we rely on these to initialize as zeroes */
44 static char directoryLockFile[MAXPGPATH];
45 static char socketLockFile[MAXPGPATH];
48 static unsigned char RecodeForwTable[128];
49 static unsigned char RecodeBackTable[128];
51 static void GetCharSetByHost(char *TableName, int host, const char *DataDir);
55 /* ----------------------------------------------------------------
56 * ignoring system indexes support stuff
57 * ----------------------------------------------------------------
60 static bool isIgnoringSystemIndexes = false;
63 * IsIgnoringSystemIndexes
64 * True if ignoring system indexes.
67 IsIgnoringSystemIndexes()
69 return isIgnoringSystemIndexes;
74 * Set true or false whether PostgreSQL ignores system indexes.
78 IgnoreSystemIndexes(bool mode)
80 isIgnoringSystemIndexes = mode;
83 /* ----------------------------------------------------------------
84 * database path / name support stuff
85 * ----------------------------------------------------------------
89 SetDatabasePath(const char *path)
96 /* use strdup since this is done before memory contexts are set up */
99 DatabasePath = strdup(path);
100 AssertState(DatabasePath);
105 SetDatabaseName(const char *name)
112 /* use strdup since this is done before memory contexts are set up */
115 DatabaseName = strdup(name);
116 AssertState(DatabaseName);
121 * Set data directory, but make sure it's an absolute path. Use this,
122 * never set DataDir directly.
125 SetDataDir(const char *dir)
132 /* If presented path is relative, convert to absolute */
141 buf = malloc(buflen);
143 elog(FATAL, "out of memory");
145 if (getcwd(buf, buflen))
147 else if (errno == ERANGE)
156 elog(FATAL, "cannot get current working directory: %m");
160 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
162 elog(FATAL, "out of memory");
163 sprintf(new, "%s/%s", buf, dir);
170 elog(FATAL, "out of memory");
174 * Strip any trailing slash. Not strictly necessary, but avoids
175 * generating funny-looking paths to individual files.
177 newlen = strlen(new);
178 if (newlen > 1 && new[newlen - 1] == '/')
179 new[newlen - 1] = '\0';
186 /* ----------------------------------------------------------------
188 * ----------------------------------------------------------------
201 unsigned char FromChar,
203 char ChTable[MAX_TOKEN];
205 for (i = 0; i < 128; i++)
207 RecodeForwTable[i] = i + 128;
208 RecodeBackTable[i] = i + 128;
211 if (IsUnderPostmaster)
213 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
217 filename = getenv("PG_RECODETABLE");
219 if (filename && *filename != '\0')
221 map_file = palloc(strlen(DataDir) + strlen(filename) + 2);
222 sprintf(map_file, "%s/%s", DataDir, filename);
223 file = AllocateFile(map_file, "r");
230 next_token(file, buf, sizeof(buf));
233 FromChar = strtoul(buf, 0, 0);
234 /* Read the ToChar */
235 next_token(file, buf, sizeof(buf));
238 ToChar = strtoul(buf, 0, 0);
239 RecodeForwTable[FromChar - 128] = ToChar;
240 RecodeBackTable[ToChar - 128] = FromChar;
243 while (!feof(file) && buf[0])
245 next_token(file, buf, sizeof(buf));
246 elog(LOG, "SetCharSet: unknown tag %s in file %s",
258 convertstr(unsigned char *buff, int len, int dest)
263 for (i = 0; i < len; i++, buff++)
268 *buff = RecodeForwTable[*buff - 128];
270 *buff = RecodeBackTable[*buff - 128];
276 #define CHARSET_FILE "charset.conf"
277 #define MAX_CHARSETS 10
284 char Orig[MAX_TOKEN];
285 char Dest[MAX_TOKEN];
286 char Table[MAX_TOKEN];
291 CharSetInRange(char *buf, int host)
298 struct in_addr file_ip_addr;
300 unsigned int one = 0x80000000,
304 p = strchr(buf, '/');
308 valid = inet_aton(buf, &file_ip_addr);
311 mask = strtoul(p, 0, 0);
312 FromAddr = ntohl(file_ip_addr.s_addr);
313 ToAddr = ntohl(file_ip_addr.s_addr);
314 for (i = 0; i < mask; i++)
320 ToAddr = ToAddr | ~NetMask;
322 return ((unsigned) tmp >= (unsigned) FromAddr &&
323 (unsigned) tmp <= (unsigned) ToAddr);
328 p = strchr(buf, '-');
332 valid = inet_aton(buf, &file_ip_addr);
335 FromAddr = ntohl(file_ip_addr.s_addr);
336 valid = inet_aton(p, &file_ip_addr);
339 ToAddr = ntohl(file_ip_addr.s_addr);
341 return ((unsigned) tmp >= (unsigned) FromAddr &&
342 (unsigned) tmp <= (unsigned) ToAddr);
348 valid = inet_aton(buf, &file_ip_addr);
351 FromAddr = file_ip_addr.s_addr;
352 return (unsigned) FromAddr == (unsigned) host;
361 GetCharSetByHost(char *TableName, int host, const char *DataDir)
365 BaseCharset[MAX_TOKEN],
366 OrigCharset[MAX_TOKEN],
367 DestCharset[MAX_TOKEN],
368 HostCharset[MAX_TOKEN],
374 struct CharsetItem *ChArray[MAX_CHARSETS];
377 bufsize = (strlen(DataDir) + strlen(CHARSET_FILE) + 2) * sizeof(char);
378 map_file = (char *) palloc(bufsize);
379 snprintf(map_file, bufsize, "%s/%s", DataDir, CHARSET_FILE);
380 file = AllocateFile(map_file, "r");
384 /* XXX should we log a complaint? */
390 next_token(file, buf, sizeof(buf));
394 if (strcasecmp(buf, "HostCharset") == 0)
396 else if (strcasecmp(buf, "BaseCharset") == 0)
398 else if (strcasecmp(buf, "RecodeTable") == 0)
401 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
408 next_token(file, buf, sizeof(buf));
411 if (CharSetInRange(buf, host))
413 /* Read the charset */
414 next_token(file, buf, sizeof(buf));
416 strcpy(HostCharset, buf);
421 /* Read the base charset */
422 next_token(file, buf, sizeof(buf));
424 strcpy(BaseCharset, buf);
427 /* Read the original charset */
428 next_token(file, buf, sizeof(buf));
431 strcpy(OrigCharset, buf);
432 /* Read the destination charset */
433 next_token(file, buf, sizeof(buf));
436 strcpy(DestCharset, buf);
437 /* Read the table filename */
438 next_token(file, buf, sizeof(buf));
442 (struct CharsetItem *) palloc(sizeof(struct CharsetItem));
443 strcpy(ChArray[ChIndex]->Orig, OrigCharset);
444 strcpy(ChArray[ChIndex]->Dest, DestCharset);
445 strcpy(ChArray[ChIndex]->Table, buf);
454 while (!feof(file) && buf[0])
456 next_token(file, buf, sizeof(buf));
457 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
464 for (i = 0; i < ChIndex; i++)
466 if (strcasecmp(BaseCharset, ChArray[i]->Orig) == 0 &&
467 strcasecmp(HostCharset, ChArray[i]->Dest) == 0)
468 strncpy(TableName, ChArray[i]->Table, 79);
472 #endif /* CYR_RECODE */
476 /* ----------------------------------------------------------------
479 * The authenticated user is determined at connection start and never
480 * changes. The session user can be changed only by SET SESSION
481 * AUTHORIZATION. The current user may change when "setuid" functions
482 * are implemented. Conceptually there is a stack, whose bottom
483 * is the session user. You are yourself responsible to save and
484 * restore the current user id if you need to change it.
485 * ----------------------------------------------------------------
487 static AclId AuthenticatedUserId = 0;
488 static AclId SessionUserId = 0;
489 static AclId CurrentUserId = 0;
491 static bool AuthenticatedUserIsSuperuser = false;
494 * This function is relevant for all privilege checks.
499 AssertState(AclIdIsValid(CurrentUserId));
500 return CurrentUserId;
505 SetUserId(AclId newid)
507 AssertArg(AclIdIsValid(newid));
508 CurrentUserId = newid;
513 * This value is only relevant for informational purposes.
516 GetSessionUserId(void)
518 AssertState(AclIdIsValid(SessionUserId));
519 return SessionUserId;
524 SetSessionUserId(AclId newid)
526 AssertArg(AclIdIsValid(newid));
527 SessionUserId = newid;
528 /* Current user defaults to session user. */
529 if (!AclIdIsValid(CurrentUserId))
530 CurrentUserId = newid;
535 InitializeSessionUserId(const char *username)
543 * Don't do scans if we're bootstrapping, none of the system catalogs
544 * exist yet, and they should be owned by postgres anyway.
546 AssertState(!IsBootstrapProcessingMode());
549 AssertState(!OidIsValid(AuthenticatedUserId));
551 userTup = SearchSysCache(SHADOWNAME,
552 PointerGetDatum(username),
554 if (!HeapTupleIsValid(userTup))
555 elog(FATAL, "user \"%s\" does not exist", username);
557 usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
559 AuthenticatedUserId = usesysid;
560 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
562 SetSessionUserId(usesysid); /* sets CurrentUserId too */
564 /* Record username as a config option too */
565 SetConfigOption("session_authorization", username,
566 PGC_BACKEND, PGC_S_OVERRIDE);
569 * Set up user-specific configuration variables. This is a good place
570 * to do it so we don't have to read pg_shadow twice during session
573 datum = SysCacheGetAttr(SHADOWNAME, userTup,
574 Anum_pg_shadow_useconfig, &isnull);
577 ArrayType *a = DatumGetArrayTypeP(datum);
579 ProcessGUCArray(a, PGC_S_USER);
582 ReleaseSysCache(userTup);
587 InitializeSessionUserIdStandalone(void)
589 /* This function should only be called in a single-user backend. */
590 AssertState(!IsUnderPostmaster);
593 AssertState(!OidIsValid(AuthenticatedUserId));
595 AuthenticatedUserId = BOOTSTRAP_USESYSID;
596 AuthenticatedUserIsSuperuser = true;
598 SetSessionUserId(BOOTSTRAP_USESYSID);
603 * Change session auth ID while running
605 * Only a superuser may set auth ID to something other than himself.
608 SetSessionAuthorization(AclId userid)
610 /* Must have authenticated already, else can't make permission check */
611 AssertState(AclIdIsValid(AuthenticatedUserId));
613 if (userid != AuthenticatedUserId &&
614 !AuthenticatedUserIsSuperuser)
615 elog(ERROR, "permission denied");
617 SetSessionUserId(userid);
623 * Get user name from user id
626 GetUserNameFromId(AclId userid)
631 tuple = SearchSysCache(SHADOWSYSID,
632 ObjectIdGetDatum(userid),
634 if (!HeapTupleIsValid(tuple))
635 elog(ERROR, "invalid user id %d", userid);
637 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
639 ReleaseSysCache(tuple);
645 /*-------------------------------------------------------------------------
646 * Interlock-file support
648 * These routines are used to create both a data-directory lockfile
649 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
650 * Both kinds of files contain the same info:
652 * Owning process' PID
653 * Data directory path
655 * By convention, the owning process' PID is negated if it is a standalone
656 * backend rather than a postmaster. This is just for informational purposes.
657 * The path is also just for informational purposes (so that a socket lockfile
658 * can be more easily traced to the associated postmaster).
660 * A data-directory lockfile can optionally contain a third line, containing
661 * the key and ID for the shared memory block used by this postmaster.
663 * On successful lockfile creation, a proc_exit callback to remove the
664 * lockfile is automatically created.
665 *-------------------------------------------------------------------------
669 * proc_exit callback to remove a lockfile.
672 UnlinkLockFile(int status, Datum filename)
674 unlink((char *) DatumGetPointer(filename));
675 /* Should we complain if the unlink fails? */
679 * Create a lockfile, if possible
681 * Call CreateLockFile with the name of the lockfile to be created.
682 * Returns true if successful, false if not (with a message on stderr).
684 * amPostmaster is used to determine how to encode the output PID.
685 * isDDLock and refName are used to determine what error message to produce.
688 CreateLockFile(const char *filename, bool amPostmaster,
689 bool isDDLock, const char *refName)
692 char buffer[MAXPGPATH + 100];
697 pid_t my_pid = getpid();
700 * We need a loop here because of race conditions. But don't loop
701 * forever (for example, a non-writable $PGDATA directory might cause
702 * a failure that won't go away). 100 tries seems like plenty.
704 for (ntries = 0;; ntries++)
707 * Try to create the lock file --- O_EXCL makes this atomic.
709 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
711 break; /* Success; exit the retry loop */
714 * Couldn't create the pid file. Probably it already exists.
716 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
717 elog(FATAL, "Can't create lock file %s: %m", filename);
720 * Read the file to get the old owner's PID. Note race condition
721 * here: file might have been deleted since we tried to create it.
723 fd = open(filename, O_RDONLY, 0600);
727 continue; /* race condition; try again */
728 elog(FATAL, "Can't read lock file %s: %m", filename);
730 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
731 elog(FATAL, "Can't read lock file %s: %m", filename);
735 encoded_pid = atoi(buffer);
737 /* if pid < 0, the pid is for postgres, not postmaster */
738 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
741 elog(FATAL, "Bogus data in lock file %s", filename);
744 * Check to see if the other process still exists
746 * Normally kill() will fail with ESRCH if the given PID doesn't
747 * exist. BeOS returns EINVAL for some silly reason, however.
749 if (other_pid != my_pid)
751 if (kill(other_pid, 0) == 0 ||
758 /* lockfile belongs to a live process */
759 fprintf(stderr, "Lock file \"%s\" already exists.\n",
763 "Is another %s (pid %d) running in \"%s\"?\n",
764 (encoded_pid < 0 ? "postgres" : "postmaster"),
765 (int) other_pid, refName);
768 "Is another %s (pid %d) using \"%s\"?\n",
769 (encoded_pid < 0 ? "postgres" : "postmaster"),
770 (int) other_pid, refName);
776 * No, the creating process did not exist. However, it could be
777 * that the postmaster crashed (or more likely was kill -9'd by a
778 * clueless admin) but has left orphan backends behind. Check for
779 * this by looking to see if there is an associated shmem segment
780 * that is still in use.
788 ptr = strchr(buffer, '\n');
790 (ptr = strchr(ptr + 1, '\n')) != NULL)
793 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
795 if (PGSharedMemoryIsInUse(id1, id2))
798 "Found a pre-existing shared memory block (key %lu, id %lu) still in use.\n"
799 "If you're sure there are no old backends still running,\n"
800 "remove the shared memory block with ipcrm(1), or just\n"
810 * Looks like nobody's home. Unlink the file and try again to
811 * create it. Need a loop because of possible race condition
812 * against other would-be creators.
814 if (unlink(filename) < 0)
815 elog(FATAL, "Can't remove old lock file %s: %m"
816 "\n\tThe file seems accidentally left, but I couldn't remove it."
817 "\n\tPlease remove the file by hand and try again.",
822 * Successfully created the file, now fill it.
824 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
825 amPostmaster ? (int) my_pid : -((int) my_pid),
828 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
830 int save_errno = errno;
834 /* if write didn't set errno, assume problem is no disk space */
835 errno = save_errno ? save_errno : ENOSPC;
836 elog(FATAL, "Can't write lock file %s: %m", filename);
841 * Arrange for automatic removal of lockfile at proc_exit.
843 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
845 return true; /* Success! */
849 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
851 char lockfile[MAXPGPATH];
853 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
854 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
856 /* Save name of lockfile for RecordSharedMemoryInLockFile */
857 strcpy(directoryLockFile, lockfile);
862 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
864 char lockfile[MAXPGPATH];
866 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
867 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
869 /* Save name of lockfile for TouchSocketLockFile */
870 strcpy(socketLockFile, lockfile);
875 * Re-read the socket lock file. This should be called every so often
876 * to ensure that the lock file has a recent access date. That saves it
877 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
878 * (Another reason we should never have put the socket file in /tmp...)
881 TouchSocketLockFile(void)
886 /* Do nothing if we did not create a socket... */
887 if (socketLockFile[0] != '\0')
889 /* XXX any need to complain about errors here? */
890 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
893 read(fd, buffer, sizeof(buffer));
900 * Append information about a shared memory segment to the data directory
901 * lock file (if we have created one).
903 * This may be called multiple times in the life of a postmaster, if we
904 * delete and recreate shmem due to backend crash. Therefore, be prepared
905 * to overwrite existing information. (As of 7.1, a postmaster only creates
906 * one shm seg at a time; but for the purposes here, if we did have more than
907 * one then any one of them would do anyway.)
910 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
918 * Do nothing if we did not create a lockfile (probably because we are
919 * running standalone).
921 if (directoryLockFile[0] == '\0')
924 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
927 elog(LOG, "Failed to rewrite %s: %m", directoryLockFile);
930 len = read(fd, buffer, sizeof(buffer) - 100);
933 elog(LOG, "Failed to read %s: %m", directoryLockFile);
940 * Skip over first two lines (PID and path).
942 ptr = strchr(buffer, '\n');
944 (ptr = strchr(ptr + 1, '\n')) == NULL)
946 elog(LOG, "Bogus data in %s", directoryLockFile);
953 * Append key information. Format to try to keep it the same length
954 * always (trailing junk won't hurt, but might confuse humans).
956 sprintf(ptr, "%9lu %9lu\n", id1, id2);
959 * And rewrite the data. Since we write in a single kernel call, this
960 * update should appear atomic to onlookers.
962 len = strlen(buffer);
964 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
965 (int) write(fd, buffer, len) != len)
967 /* if write didn't set errno, assume problem is no disk space */
970 elog(LOG, "Failed to write %s: %m", directoryLockFile);
978 /*-------------------------------------------------------------------------
979 * Version checking support
980 *-------------------------------------------------------------------------
984 * Determine whether the PG_VERSION file in directory `path' indicates
985 * a data version compatible with the version of this program.
987 * If compatible, return. Otherwise, elog(FATAL).
990 ValidatePgVersion(const char *path)
992 char full_path[MAXPGPATH];
1000 const char *version_string = PG_VERSION;
1002 my_major = strtol(version_string, &endptr, 10);
1004 my_minor = strtol(endptr + 1, NULL, 10);
1006 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
1008 file = AllocateFile(full_path, "r");
1011 if (errno == ENOENT)
1012 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
1014 elog(FATAL, "cannot open %s: %m", full_path);
1017 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1019 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
1023 if (my_major != file_major || my_minor != file_minor)
1024 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
1025 "which is not compatible with this version %s.",
1026 file_major, file_minor, version_string);