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.61 2001/01/27 00:05:31 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 "miscadmin.h"
32 #include "utils/builtins.h"
33 #include "utils/syscache.h"
37 unsigned char RecodeForwTable[128];
38 unsigned char RecodeBackTable[128];
42 ProcessingMode Mode = InitProcessing;
44 /* Note: we rely on this to initialize as zeroes */
45 static char socketLockFile[MAXPGPATH];
48 /* ----------------------------------------------------------------
49 * ignoring system indexes support stuff
50 * ----------------------------------------------------------------
53 static bool isIgnoringSystemIndexes = false;
56 * IsIgnoringSystemIndexes
57 * True if ignoring system indexes.
60 IsIgnoringSystemIndexes()
62 return isIgnoringSystemIndexes;
67 * Set true or false whether PostgreSQL ignores system indexes.
71 IgnoreSystemIndexes(bool mode)
73 isIgnoringSystemIndexes = mode;
76 /* ----------------------------------------------------------------
77 * database path / name support stuff
78 * ----------------------------------------------------------------
82 SetDatabasePath(const char *path)
85 /* use strdup since this is done before memory contexts are set up */
88 DatabasePath = strdup(path);
89 AssertState(DatabasePath);
94 SetDatabaseName(const char *name)
99 DatabaseName = strdup(name);
100 AssertState(DatabaseName);
105 * Set data directory, but make sure it's an absolute path. Use this,
106 * never set DataDir directly.
109 SetDataDir(const char *dir)
125 buf = malloc(buflen);
127 elog(FATAL, "out of memory");
129 if (getcwd(buf, buflen))
131 else if (errno == ERANGE)
140 elog(FATAL, "cannot get current working directory: %m");
144 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
145 sprintf(new, "%s/%s", buf, dir);
154 elog(FATAL, "out of memory");
159 /* ----------------------------------------------------------------
160 * MULTIBYTE stub code
162 * Even if MULTIBYTE is not enabled, these functions are necessary
163 * since pg_proc.h has references to them.
164 * ----------------------------------------------------------------
170 getdatabaseencoding(PG_FUNCTION_ARGS)
172 PG_RETURN_NAME("SQL_ASCII");
176 PG_encoding_to_char(PG_FUNCTION_ARGS)
178 PG_RETURN_NAME("SQL_ASCII");
182 PG_char_to_encoding(PG_FUNCTION_ARGS)
189 /* ----------------------------------------------------------------
191 * ----------------------------------------------------------------
198 /* Some standard C libraries, including GNU, have an isblank() function.
199 Others, including Solaris, do not. So we have our own.
202 isblank(const char c)
204 return c == ' ' || c == 9 /* tab */ ;
208 next_token(FILE *fp, char *buf, const int bufsz)
210 /*--------------------------------------------------------------------------
211 Grab one token out of fp. Tokens are strings of non-blank
212 characters bounded by blank characters, beginning of line, and end
213 of line. Blank means space or tab. Return the token as *buf.
214 Leave file positioned to character immediately after the token or
215 EOF, whichever comes first. If no more tokens on line, return null
216 string as *buf and position file to beginning of next line or EOF,
217 whichever comes first.
218 --------------------------------------------------------------------------*/
220 char *eb = buf + (bufsz - 1);
222 /* Move over inital token-delimiting blanks */
223 while (isblank(c = getc(fp)));
229 * build a token in buf of next characters up to EOF, eol, or
232 while (c != EOF && c != '\n' && !isblank(c))
239 * Put back the char right after the token (putting back EOF
249 read_through_eol(FILE *file)
255 while (c != '\n' && c != EOF);
268 unsigned char FromChar,
271 for (i = 0; i < 128; i++)
273 RecodeForwTable[i] = i + 128;
274 RecodeBackTable[i] = i + 128;
277 p = getenv("PG_RECODETABLE");
280 map_file = (char *) malloc((strlen(DataDir) +
281 strlen(p) + 2) * sizeof(char));
282 sprintf(map_file, "%s/%s", DataDir, p);
283 file = AllocateFile(map_file, PG_BINARY_R);
296 read_through_eol(file);
299 /* Read the FromChar */
300 next_token(file, buf, sizeof(buf));
303 FromChar = strtoul(buf, 0, 0);
304 /* Read the ToChar */
305 next_token(file, buf, sizeof(buf));
308 ToChar = strtoul(buf, 0, 0);
309 RecodeForwTable[FromChar - 128] = ToChar;
310 RecodeBackTable[ToChar - 128] = FromChar;
312 read_through_eol(file);
323 convertstr(unsigned char *buff, int len, int dest)
328 for (i = 0; i < len; i++, buff++)
333 *buff = RecodeForwTable[*buff - 128];
335 *buff = RecodeBackTable[*buff - 128];
345 /* ----------------------------------------------------------------
348 * The session user is determined at connection start and never
349 * changes. The current user may change when "setuid" functions
350 * are implemented. Conceptually there is a stack, whose bottom
351 * is the session user. You are yourself responsible to save and
352 * restore the current user id if you need to change it.
353 * ----------------------------------------------------------------
355 static Oid CurrentUserId = InvalidOid;
356 static Oid SessionUserId = InvalidOid;
360 * This function is relevant for all privilege checks.
365 AssertState(OidIsValid(CurrentUserId));
366 return CurrentUserId;
373 AssertArg(OidIsValid(newid));
374 CurrentUserId = newid;
379 * This value is only relevant for informational purposes.
382 GetSessionUserId(void)
384 AssertState(OidIsValid(SessionUserId));
385 return SessionUserId;
390 SetSessionUserId(Oid newid)
392 AssertArg(OidIsValid(newid));
393 SessionUserId = newid;
394 /* Current user defaults to session user. */
395 if (!OidIsValid(CurrentUserId))
396 CurrentUserId = newid;
401 SetSessionUserIdFromUserName(const char *username)
406 * Don't do scans if we're bootstrapping, none of the system catalogs
407 * exist yet, and they should be owned by postgres anyway.
409 AssertState(!IsBootstrapProcessingMode());
411 userTup = SearchSysCache(SHADOWNAME,
412 PointerGetDatum(username),
414 if (!HeapTupleIsValid(userTup))
415 elog(FATAL, "user \"%s\" does not exist", username);
417 SetSessionUserId( ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid );
419 ReleaseSysCache(userTup);
424 * Get user name from user id
427 GetUserName(Oid userid)
432 tuple = SearchSysCache(SHADOWSYSID,
433 ObjectIdGetDatum(userid),
435 if (!HeapTupleIsValid(tuple))
436 elog(ERROR, "invalid user id %u", (unsigned) userid);
438 result = pstrdup( NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename) );
440 ReleaseSysCache(tuple);
446 /*-------------------------------------------------------------------------
447 * Interlock-file support
449 * These routines are used to create both a data-directory lockfile
450 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
451 * Both kinds of files contain the same info:
453 * Owning process' PID
454 * Data directory path
456 * By convention, the owning process' PID is negated if it is a standalone
457 * backend rather than a postmaster. This is just for informational purposes.
458 * The path is also just for informational purposes (so that a socket lockfile
459 * can be more easily traced to the associated postmaster).
461 * On successful lockfile creation, a proc_exit callback to remove the
462 * lockfile is automatically created.
463 *-------------------------------------------------------------------------
467 * proc_exit callback to remove a lockfile.
470 UnlinkLockFile(int status, Datum filename)
472 unlink((char *) DatumGetPointer(filename));
473 /* Should we complain if the unlink fails? */
477 * Create a lockfile, if possible
479 * Call CreateLockFile with the name of the lockfile to be created. If
480 * successful, it returns zero. On detecting a collision, it returns
481 * the PID or negated PID of the lockfile owner --- the caller is responsible
482 * for producing an appropriate error message.
485 CreateLockFile(const char *filename, bool amPostmaster)
488 char buffer[MAXPGPATH + 32];
492 pid_t my_pid = getpid();
495 * We need a loop here because of race conditions.
500 * Try to create the lock file --- O_EXCL makes this atomic.
502 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
504 break; /* Success; exit the retry loop */
506 * Couldn't create the pid file. Probably it already exists.
508 if (errno != EEXIST && errno != EACCES)
509 elog(FATAL, "Can't create lock file %s: %m", filename);
512 * Read the file to get the old owner's PID. Note race condition
513 * here: file might have been deleted since we tried to create it.
515 fd = open(filename, O_RDONLY, 0600);
519 continue; /* race condition; try again */
520 elog(FATAL, "Can't read lock file %s: %m", filename);
522 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
523 elog(FATAL, "Can't read lock file %s: %m", filename);
527 encoded_pid = atoi(buffer);
529 /* if pid < 0, the pid is for postgres, not postmaster */
530 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
533 elog(FATAL, "Bogus data in lock file %s", filename);
536 * Check to see if the other process still exists
538 if (other_pid != my_pid)
540 if (kill(other_pid, 0) == 0 ||
542 return encoded_pid; /* lockfile belongs to a live process */
546 * No, the process did not exist. Unlink the file and try again to
547 * create it. Need a loop because of possible race condition against
548 * other would-be creators.
550 if (unlink(filename) < 0)
551 elog(FATAL, "Can't remove old lock file %s: %m"
552 "\n\tThe file seems accidentally left, but I couldn't remove it."
553 "\n\tPlease remove the file by hand and try again.",
558 * Successfully created the file, now fill it.
560 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
561 amPostmaster ? (int) my_pid : - ((int) my_pid),
563 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
565 int save_errno = errno;
570 elog(FATAL, "Can't write lock file %s: %m", filename);
575 * Arrange for automatic removal of lockfile at proc_exit.
577 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
579 return 0; /* Success! */
583 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
585 char lockfile[MAXPGPATH];
588 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
589 encoded_pid = CreateLockFile(lockfile, amPostmaster);
590 if (encoded_pid != 0)
592 fprintf(stderr, "Lock file \"%s\" already exists.\n", lockfile);
594 fprintf(stderr, "Is another postgres (pid %d) running in \"%s\"?\n",
595 -encoded_pid, datadir);
597 fprintf(stderr, "Is another postmaster (pid %d) running in \"%s\"?\n",
598 encoded_pid, datadir);
605 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
607 char lockfile[MAXPGPATH];
610 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
611 encoded_pid = CreateLockFile(lockfile, amPostmaster);
612 if (encoded_pid != 0)
614 fprintf(stderr, "Lock file \"%s\" already exists.\n", lockfile);
616 fprintf(stderr, "Is another postgres (pid %d) using \"%s\"?\n",
617 -encoded_pid, socketfile);
619 fprintf(stderr, "Is another postmaster (pid %d) using \"%s\"?\n",
620 encoded_pid, socketfile);
623 /* Save name of lockfile for TouchSocketLockFile */
624 strcpy(socketLockFile, lockfile);
629 * Re-read the socket lock file. This should be called every so often
630 * to ensure that the lock file has a recent access date. That saves it
631 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
632 * (Another reason we should never have put the socket file in /tmp...)
635 TouchSocketLockFile(void)
640 /* Do nothing if we did not create a socket... */
641 if (socketLockFile[0] != '\0')
643 /* XXX any need to complain about errors here? */
644 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
647 read(fd, buffer, sizeof(buffer));
654 /*-------------------------------------------------------------------------
655 * Version checking support
656 *-------------------------------------------------------------------------
660 * Determine whether the PG_VERSION file in directory `path' indicates
661 * a data version compatible with the version of this program.
663 * If compatible, return. Otherwise, elog(FATAL).
666 ValidatePgVersion(const char *path)
668 char full_path[MAXPGPATH];
671 long file_major, file_minor;
672 long my_major = 0, my_minor = 0;
674 const char *version_string = PG_VERSION;
676 my_major = strtol(version_string, &endptr, 10);
678 my_minor = strtol(endptr+1, NULL, 10);
680 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
682 file = AllocateFile(full_path, "r");
686 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
688 elog(FATAL, "cannot open %s: %m", full_path);
691 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
693 elog(FATAL, "cannot read %s: %m", full_path);
695 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
699 if (my_major != file_major || my_minor != file_minor)
700 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
701 "which is not compatible with this version %s.",
702 file_major, file_minor, version_string);