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.92 2002/06/11 13:40:52 wieck Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
18 #include <sys/types.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
31 #include "catalog/catname.h"
32 #include "catalog/pg_shadow.h"
33 #include "libpq/libpq-be.h"
34 #include "miscadmin.h"
35 #include "storage/ipc.h"
36 #include "storage/pg_shmem.h"
37 #include "utils/builtins.h"
38 #include "utils/guc.h"
39 #include "utils/lsyscache.h"
40 #include "utils/syscache.h"
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 static unsigned char RecodeForwTable[128];
51 static unsigned char RecodeBackTable[128];
53 static void GetCharSetByHost(char *TableName, int host, const char *DataDir);
57 /* ----------------------------------------------------------------
58 * ignoring system indexes support stuff
59 * ----------------------------------------------------------------
62 static bool isIgnoringSystemIndexes = false;
65 * IsIgnoringSystemIndexes
66 * True if ignoring system indexes.
69 IsIgnoringSystemIndexes()
71 return isIgnoringSystemIndexes;
76 * Set true or false whether PostgreSQL ignores system indexes.
80 IgnoreSystemIndexes(bool mode)
82 isIgnoringSystemIndexes = mode;
85 /* ----------------------------------------------------------------
86 * database path / name support stuff
87 * ----------------------------------------------------------------
91 SetDatabasePath(const char *path)
98 /* use strdup since this is done before memory contexts are set up */
101 DatabasePath = strdup(path);
102 AssertState(DatabasePath);
107 SetDatabaseName(const char *name)
114 /* use strdup since this is done before memory contexts are set up */
117 DatabaseName = strdup(name);
118 AssertState(DatabaseName);
123 * Set data directory, but make sure it's an absolute path. Use this,
124 * never set DataDir directly.
127 SetDataDir(const char *dir)
134 /* If presented path is relative, convert to absolute */
143 buf = malloc(buflen);
145 elog(FATAL, "out of memory");
147 if (getcwd(buf, buflen))
149 else if (errno == ERANGE)
158 elog(FATAL, "cannot get current working directory: %m");
162 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
164 elog(FATAL, "out of memory");
165 sprintf(new, "%s/%s", buf, dir);
172 elog(FATAL, "out of memory");
176 * Strip any trailing slash. Not strictly necessary, but avoids
177 * generating funny-looking paths to individual files.
179 newlen = strlen(new);
180 if (newlen > 1 && new[newlen-1] == '/')
181 new[newlen-1] = '\0';
189 /* ----------------------------------------------------------------
190 * MULTIBYTE stub code
192 * Even if MULTIBYTE is not enabled, these functions are necessary
193 * since pg_proc.h has references to them.
194 * ----------------------------------------------------------------
200 getdatabaseencoding(PG_FUNCTION_ARGS)
202 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
206 pg_client_encoding(PG_FUNCTION_ARGS)
208 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
212 PG_encoding_to_char(PG_FUNCTION_ARGS)
214 return DirectFunctionCall1(namein, CStringGetDatum("SQL_ASCII"));
218 PG_char_to_encoding(PG_FUNCTION_ARGS)
224 pg_convert(PG_FUNCTION_ARGS)
226 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
227 return DirectFunctionCall1(textin, CStringGetDatum(""));
231 pg_convert2(PG_FUNCTION_ARGS)
233 elog(ERROR, "convert is not supported. To use convert, you need to enable multibyte capability");
234 return DirectFunctionCall1(textin, CStringGetDatum(""));
238 /* ----------------------------------------------------------------
240 * ----------------------------------------------------------------
253 unsigned char FromChar,
255 char ChTable[MAX_TOKEN];
257 for (i = 0; i < 128; i++)
259 RecodeForwTable[i] = i + 128;
260 RecodeBackTable[i] = i + 128;
263 if (IsUnderPostmaster)
265 GetCharSetByHost(ChTable, MyProcPort->raddr.in.sin_addr.s_addr, DataDir);
269 filename = getenv("PG_RECODETABLE");
271 if (filename && *filename != '\0')
273 map_file = palloc(strlen(DataDir) + strlen(filename) + 2);
274 sprintf(map_file, "%s/%s", DataDir, filename);
275 file = AllocateFile(map_file, "r");
282 next_token(file, buf, sizeof(buf));
285 FromChar = strtoul(buf, 0, 0);
286 /* Read the ToChar */
287 next_token(file, buf, sizeof(buf));
290 ToChar = strtoul(buf, 0, 0);
291 RecodeForwTable[FromChar - 128] = ToChar;
292 RecodeBackTable[ToChar - 128] = FromChar;
295 while (!feof(file) && buf[0])
297 next_token(file, buf, sizeof(buf));
298 elog(LOG, "SetCharSet: unknown tag %s in file %s",
310 convertstr(unsigned char *buff, int len, int dest)
315 for (i = 0; i < len; i++, buff++)
320 *buff = RecodeForwTable[*buff - 128];
322 *buff = RecodeBackTable[*buff - 128];
328 #define CHARSET_FILE "charset.conf"
329 #define MAX_CHARSETS 10
336 char Orig[MAX_TOKEN];
337 char Dest[MAX_TOKEN];
338 char Table[MAX_TOKEN];
343 CharSetInRange(char *buf, int host)
350 struct in_addr file_ip_addr;
352 unsigned int one = 0x80000000,
356 p = strchr(buf, '/');
360 valid = inet_aton(buf, &file_ip_addr);
363 mask = strtoul(p, 0, 0);
364 FromAddr = ntohl(file_ip_addr.s_addr);
365 ToAddr = ntohl(file_ip_addr.s_addr);
366 for (i = 0; i < mask; i++)
372 ToAddr = ToAddr | ~NetMask;
374 return ((unsigned) tmp >= (unsigned) FromAddr &&
375 (unsigned) tmp <= (unsigned) ToAddr);
380 p = strchr(buf, '-');
384 valid = inet_aton(buf, &file_ip_addr);
387 FromAddr = ntohl(file_ip_addr.s_addr);
388 valid = inet_aton(p, &file_ip_addr);
391 ToAddr = ntohl(file_ip_addr.s_addr);
393 return ((unsigned) tmp >= (unsigned) FromAddr &&
394 (unsigned) tmp <= (unsigned) ToAddr);
400 valid = inet_aton(buf, &file_ip_addr);
403 FromAddr = file_ip_addr.s_addr;
404 return (unsigned) FromAddr == (unsigned) host;
413 GetCharSetByHost(char *TableName, int host, const char *DataDir)
417 BaseCharset[MAX_TOKEN],
418 OrigCharset[MAX_TOKEN],
419 DestCharset[MAX_TOKEN],
420 HostCharset[MAX_TOKEN],
426 struct CharsetItem *ChArray[MAX_CHARSETS];
429 bufsize = (strlen(DataDir) + strlen(CHARSET_FILE) + 2) * sizeof(char);
430 map_file = (char *) palloc(bufsize);
431 snprintf(map_file, bufsize, "%s/%s", DataDir, CHARSET_FILE);
432 file = AllocateFile(map_file, "r");
436 /* XXX should we log a complaint? */
442 next_token(file, buf, sizeof(buf));
446 if (strcasecmp(buf, "HostCharset") == 0)
448 else if (strcasecmp(buf, "BaseCharset") == 0)
450 else if (strcasecmp(buf, "RecodeTable") == 0)
453 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
460 next_token(file, buf, sizeof(buf));
463 if (CharSetInRange(buf, host))
465 /* Read the charset */
466 next_token(file, buf, sizeof(buf));
468 strcpy(HostCharset, buf);
473 /* Read the base charset */
474 next_token(file, buf, sizeof(buf));
476 strcpy(BaseCharset, buf);
479 /* Read the original charset */
480 next_token(file, buf, sizeof(buf));
483 strcpy(OrigCharset, buf);
484 /* Read the destination charset */
485 next_token(file, buf, sizeof(buf));
488 strcpy(DestCharset, buf);
489 /* Read the table filename */
490 next_token(file, buf, sizeof(buf));
494 (struct CharsetItem *) palloc(sizeof(struct CharsetItem));
495 strcpy(ChArray[ChIndex]->Orig, OrigCharset);
496 strcpy(ChArray[ChIndex]->Dest, DestCharset);
497 strcpy(ChArray[ChIndex]->Table, buf);
506 while (!feof(file) && buf[0])
508 next_token(file, buf, sizeof(buf));
509 elog(LOG, "GetCharSetByHost: unknown tag %s in file %s",
516 for (i = 0; i < ChIndex; i++)
518 if (strcasecmp(BaseCharset, ChArray[i]->Orig) == 0 &&
519 strcasecmp(HostCharset, ChArray[i]->Dest) == 0)
520 strncpy(TableName, ChArray[i]->Table, 79);
525 #endif /* CYR_RECODE */
529 /* ----------------------------------------------------------------
532 * The authenticated user is determined at connection start and never
533 * changes. The session user can be changed only by SET SESSION
534 * AUTHORIZATION. The current user may change when "setuid" functions
535 * are implemented. Conceptually there is a stack, whose bottom
536 * is the session user. You are yourself responsible to save and
537 * restore the current user id if you need to change it.
538 * ----------------------------------------------------------------
540 static Oid AuthenticatedUserId = InvalidOid;
541 static Oid SessionUserId = InvalidOid;
542 static Oid CurrentUserId = InvalidOid;
544 static bool AuthenticatedUserIsSuperuser = false;
547 * This function is relevant for all privilege checks.
552 AssertState(OidIsValid(CurrentUserId));
553 return CurrentUserId;
560 AssertArg(OidIsValid(newid));
561 CurrentUserId = newid;
566 * This value is only relevant for informational purposes.
569 GetSessionUserId(void)
571 AssertState(OidIsValid(SessionUserId));
572 return SessionUserId;
577 SetSessionUserId(Oid newid)
579 AssertArg(OidIsValid(newid));
580 SessionUserId = newid;
581 /* Current user defaults to session user. */
582 if (!OidIsValid(CurrentUserId))
583 CurrentUserId = newid;
588 InitializeSessionUserId(const char *username)
596 * Don't do scans if we're bootstrapping, none of the system catalogs
597 * exist yet, and they should be owned by postgres anyway.
599 AssertState(!IsBootstrapProcessingMode());
602 AssertState(!OidIsValid(AuthenticatedUserId));
604 userTup = SearchSysCache(SHADOWNAME,
605 PointerGetDatum(username),
607 if (!HeapTupleIsValid(userTup))
608 elog(FATAL, "user \"%s\" does not exist", username);
610 usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;
612 AuthenticatedUserId = usesysid;
613 AuthenticatedUserIsSuperuser = ((Form_pg_shadow) GETSTRUCT(userTup))->usesuper;
615 SetSessionUserId(usesysid); /* sets CurrentUserId too */
617 /* Record username as a config option too */
618 SetConfigOption("session_authorization", username,
619 PGC_BACKEND, PGC_S_OVERRIDE);
622 * Set up user-specific configuration variables. This is a good
623 * place to do it so we don't have to read pg_shadow twice during
626 datum = SysCacheGetAttr(SHADOWNAME, userTup,
627 Anum_pg_shadow_useconfig, &isnull);
630 ArrayType *a = DatumGetArrayTypeP(datum);
632 ProcessGUCArray(a, PGC_S_USER);
635 ReleaseSysCache(userTup);
640 InitializeSessionUserIdStandalone(void)
642 /* This function should only be called in a single-user backend. */
643 AssertState(!IsUnderPostmaster);
646 AssertState(!OidIsValid(AuthenticatedUserId));
648 AuthenticatedUserId = BOOTSTRAP_USESYSID;
649 AuthenticatedUserIsSuperuser = true;
651 SetSessionUserId(BOOTSTRAP_USESYSID);
656 * Change session auth ID while running
658 * Only a superuser may set auth ID to something other than himself.
661 SetSessionAuthorization(Oid userid)
663 /* Must have authenticated already, else can't make permission check */
664 AssertState(OidIsValid(AuthenticatedUserId));
666 if (userid != AuthenticatedUserId &&
667 !AuthenticatedUserIsSuperuser)
668 elog(ERROR, "permission denied");
670 SetSessionUserId(userid);
676 * Get user name from user id
679 GetUserNameFromId(Oid userid)
684 tuple = SearchSysCache(SHADOWSYSID,
685 ObjectIdGetDatum(userid),
687 if (!HeapTupleIsValid(tuple))
688 elog(ERROR, "invalid user id %u", (unsigned) userid);
690 result = pstrdup(NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename));
692 ReleaseSysCache(tuple);
698 /*-------------------------------------------------------------------------
699 * Interlock-file support
701 * These routines are used to create both a data-directory lockfile
702 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
703 * Both kinds of files contain the same info:
705 * Owning process' PID
706 * Data directory path
708 * By convention, the owning process' PID is negated if it is a standalone
709 * backend rather than a postmaster. This is just for informational purposes.
710 * The path is also just for informational purposes (so that a socket lockfile
711 * can be more easily traced to the associated postmaster).
713 * A data-directory lockfile can optionally contain a third line, containing
714 * the key and ID for the shared memory block used by this postmaster.
716 * On successful lockfile creation, a proc_exit callback to remove the
717 * lockfile is automatically created.
718 *-------------------------------------------------------------------------
722 * proc_exit callback to remove a lockfile.
725 UnlinkLockFile(int status, Datum filename)
727 unlink((char *) DatumGetPointer(filename));
728 /* Should we complain if the unlink fails? */
732 * Create a lockfile, if possible
734 * Call CreateLockFile with the name of the lockfile to be created.
735 * Returns true if successful, false if not (with a message on stderr).
737 * amPostmaster is used to determine how to encode the output PID.
738 * isDDLock and refName are used to determine what error message to produce.
741 CreateLockFile(const char *filename, bool amPostmaster,
742 bool isDDLock, const char *refName)
745 char buffer[MAXPGPATH + 100];
750 pid_t my_pid = getpid();
753 * We need a loop here because of race conditions. But don't loop
754 * forever (for example, a non-writable $PGDATA directory might cause
755 * a failure that won't go away). 100 tries seems like plenty.
757 for (ntries = 0;; ntries++)
760 * Try to create the lock file --- O_EXCL makes this atomic.
762 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
764 break; /* Success; exit the retry loop */
767 * Couldn't create the pid file. Probably it already exists.
769 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
770 elog(FATAL, "Can't create lock file %s: %m", filename);
773 * Read the file to get the old owner's PID. Note race condition
774 * here: file might have been deleted since we tried to create it.
776 fd = open(filename, O_RDONLY, 0600);
780 continue; /* race condition; try again */
781 elog(FATAL, "Can't read lock file %s: %m", filename);
783 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
784 elog(FATAL, "Can't read lock file %s: %m", filename);
788 encoded_pid = atoi(buffer);
790 /* if pid < 0, the pid is for postgres, not postmaster */
791 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
794 elog(FATAL, "Bogus data in lock file %s", filename);
797 * Check to see if the other process still exists
799 * Normally kill() will fail with ESRCH if the given PID doesn't
800 * exist. BeOS returns EINVAL for some silly reason, however.
802 if (other_pid != my_pid)
804 if (kill(other_pid, 0) == 0 ||
811 /* lockfile belongs to a live process */
812 fprintf(stderr, "Lock file \"%s\" already exists.\n",
816 "Is another %s (pid %d) running in \"%s\"?\n",
817 (encoded_pid < 0 ? "postgres" : "postmaster"),
818 (int) other_pid, refName);
821 "Is another %s (pid %d) using \"%s\"?\n",
822 (encoded_pid < 0 ? "postgres" : "postmaster"),
823 (int) other_pid, refName);
829 * No, the creating process did not exist. However, it could be
830 * that the postmaster crashed (or more likely was kill -9'd by a
831 * clueless admin) but has left orphan backends behind. Check for
832 * this by looking to see if there is an associated shmem segment
833 * that is still in use.
841 ptr = strchr(buffer, '\n');
843 (ptr = strchr(ptr + 1, '\n')) != NULL)
846 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
848 if (PGSharedMemoryIsInUse(id1, id2))
851 "Found a pre-existing shared memory block (key %lu, id %lu) still in use.\n"
852 "If you're sure there are no old backends still running,\n"
853 "remove the shared memory block with ipcrm(1), or just\n"
863 * Looks like nobody's home. Unlink the file and try again to
864 * create it. Need a loop because of possible race condition
865 * against other would-be creators.
867 if (unlink(filename) < 0)
868 elog(FATAL, "Can't remove old lock file %s: %m"
869 "\n\tThe file seems accidentally left, but I couldn't remove it."
870 "\n\tPlease remove the file by hand and try again.",
875 * Successfully created the file, now fill it.
877 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
878 amPostmaster ? (int) my_pid : -((int) my_pid),
881 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
883 int save_errno = errno;
887 /* if write didn't set errno, assume problem is no disk space */
888 errno = save_errno ? save_errno : ENOSPC;
889 elog(FATAL, "Can't write lock file %s: %m", filename);
894 * Arrange for automatic removal of lockfile at proc_exit.
896 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
898 return true; /* Success! */
902 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
904 char lockfile[MAXPGPATH];
906 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
907 if (!CreateLockFile(lockfile, amPostmaster, true, datadir))
909 /* Save name of lockfile for RecordSharedMemoryInLockFile */
910 strcpy(directoryLockFile, lockfile);
915 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
917 char lockfile[MAXPGPATH];
919 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
920 if (!CreateLockFile(lockfile, amPostmaster, false, socketfile))
922 /* Save name of lockfile for TouchSocketLockFile */
923 strcpy(socketLockFile, lockfile);
928 * Re-read the socket lock file. This should be called every so often
929 * to ensure that the lock file has a recent access date. That saves it
930 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
931 * (Another reason we should never have put the socket file in /tmp...)
934 TouchSocketLockFile(void)
939 /* Do nothing if we did not create a socket... */
940 if (socketLockFile[0] != '\0')
942 /* XXX any need to complain about errors here? */
943 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
946 read(fd, buffer, sizeof(buffer));
953 * Append information about a shared memory segment to the data directory
954 * lock file (if we have created one).
956 * This may be called multiple times in the life of a postmaster, if we
957 * delete and recreate shmem due to backend crash. Therefore, be prepared
958 * to overwrite existing information. (As of 7.1, a postmaster only creates
959 * one shm seg at a time; but for the purposes here, if we did have more than
960 * one then any one of them would do anyway.)
963 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
971 * Do nothing if we did not create a lockfile (probably because we are
972 * running standalone).
974 if (directoryLockFile[0] == '\0')
977 fd = open(directoryLockFile, O_RDWR | PG_BINARY, 0);
980 elog(LOG, "Failed to rewrite %s: %m", directoryLockFile);
983 len = read(fd, buffer, sizeof(buffer) - 100);
986 elog(LOG, "Failed to read %s: %m", directoryLockFile);
993 * Skip over first two lines (PID and path).
995 ptr = strchr(buffer, '\n');
997 (ptr = strchr(ptr + 1, '\n')) == NULL)
999 elog(LOG, "Bogus data in %s", directoryLockFile);
1006 * Append key information. Format to try to keep it the same length
1007 * always (trailing junk won't hurt, but might confuse humans).
1009 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1012 * And rewrite the data. Since we write in a single kernel call, this
1013 * update should appear atomic to onlookers.
1015 len = strlen(buffer);
1017 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1018 (int) write(fd, buffer, len) != len)
1020 /* if write didn't set errno, assume problem is no disk space */
1023 elog(LOG, "Failed to write %s: %m", directoryLockFile);
1031 /*-------------------------------------------------------------------------
1032 * Version checking support
1033 *-------------------------------------------------------------------------
1037 * Determine whether the PG_VERSION file in directory `path' indicates
1038 * a data version compatible with the version of this program.
1040 * If compatible, return. Otherwise, elog(FATAL).
1043 ValidatePgVersion(const char *path)
1045 char full_path[MAXPGPATH];
1053 const char *version_string = PG_VERSION;
1055 my_major = strtol(version_string, &endptr, 10);
1057 my_minor = strtol(endptr + 1, NULL, 10);
1059 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
1061 file = AllocateFile(full_path, "r");
1064 if (errno == ENOENT)
1065 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
1067 elog(FATAL, "cannot open %s: %m", full_path);
1070 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1072 elog(FATAL, "File %s does not contain valid data. You need to initdb.", full_path);
1076 if (my_major != file_major || my_minor != file_minor)
1077 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
1078 "which is not compatible with this version %s.",
1079 file_major, file_minor, version_string);