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.60 2001/01/24 19:43:16 momjian 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;
45 /* ----------------------------------------------------------------
46 * ignoring system indexes support stuff
47 * ----------------------------------------------------------------
50 static bool isIgnoringSystemIndexes = false;
53 * IsIgnoringSystemIndexes
54 * True if ignoring system indexes.
57 IsIgnoringSystemIndexes()
59 return isIgnoringSystemIndexes;
64 * Set true or false whether PostgreSQL ignores system indexes.
68 IgnoreSystemIndexes(bool mode)
70 isIgnoringSystemIndexes = mode;
73 /* ----------------------------------------------------------------
74 * database path / name support stuff
75 * ----------------------------------------------------------------
79 SetDatabasePath(const char *path)
82 /* use strdup since this is done before memory contexts are set up */
85 DatabasePath = strdup(path);
86 AssertState(DatabasePath);
91 SetDatabaseName(const char *name)
96 DatabaseName = strdup(name);
97 AssertState(DatabaseName);
102 * Set data directory, but make sure it's an absolute path. Use this,
103 * never set DataDir directly.
106 SetDataDir(const char *dir)
122 buf = malloc(buflen);
124 elog(FATAL, "out of memory");
126 if (getcwd(buf, buflen))
128 else if (errno == ERANGE)
137 elog(FATAL, "cannot get current working directory: %m");
141 new = malloc(strlen(buf) + 1 + strlen(dir) + 1);
142 sprintf(new, "%s/%s", buf, dir);
151 elog(FATAL, "out of memory");
156 /* ----------------------------------------------------------------
157 * MULTIBYTE stub code
159 * Even if MULTIBYTE is not enabled, these functions are necessary
160 * since pg_proc.h has references to them.
161 * ----------------------------------------------------------------
167 getdatabaseencoding(PG_FUNCTION_ARGS)
169 PG_RETURN_NAME("SQL_ASCII");
173 PG_encoding_to_char(PG_FUNCTION_ARGS)
175 PG_RETURN_NAME("SQL_ASCII");
179 PG_char_to_encoding(PG_FUNCTION_ARGS)
186 /* ----------------------------------------------------------------
188 * ----------------------------------------------------------------
195 /* Some standard C libraries, including GNU, have an isblank() function.
196 Others, including Solaris, do not. So we have our own.
199 isblank(const char c)
201 return c == ' ' || c == 9 /* tab */ ;
205 next_token(FILE *fp, char *buf, const int bufsz)
207 /*--------------------------------------------------------------------------
208 Grab one token out of fp. Tokens are strings of non-blank
209 characters bounded by blank characters, beginning of line, and end
210 of line. Blank means space or tab. Return the token as *buf.
211 Leave file positioned to character immediately after the token or
212 EOF, whichever comes first. If no more tokens on line, return null
213 string as *buf and position file to beginning of next line or EOF,
214 whichever comes first.
215 --------------------------------------------------------------------------*/
217 char *eb = buf + (bufsz - 1);
219 /* Move over inital token-delimiting blanks */
220 while (isblank(c = getc(fp)));
226 * build a token in buf of next characters up to EOF, eol, or
229 while (c != EOF && c != '\n' && !isblank(c))
236 * Put back the char right after the token (putting back EOF
246 read_through_eol(FILE *file)
252 while (c != '\n' && c != EOF);
265 unsigned char FromChar,
268 for (i = 0; i < 128; i++)
270 RecodeForwTable[i] = i + 128;
271 RecodeBackTable[i] = i + 128;
274 p = getenv("PG_RECODETABLE");
277 map_file = (char *) malloc((strlen(DataDir) +
278 strlen(p) + 2) * sizeof(char));
279 sprintf(map_file, "%s/%s", DataDir, p);
280 file = AllocateFile(map_file, PG_BINARY_R);
293 read_through_eol(file);
296 /* Read the FromChar */
297 next_token(file, buf, sizeof(buf));
300 FromChar = strtoul(buf, 0, 0);
301 /* Read the ToChar */
302 next_token(file, buf, sizeof(buf));
305 ToChar = strtoul(buf, 0, 0);
306 RecodeForwTable[FromChar - 128] = ToChar;
307 RecodeBackTable[ToChar - 128] = FromChar;
309 read_through_eol(file);
320 convertstr(unsigned char *buff, int len, int dest)
325 for (i = 0; i < len; i++, buff++)
330 *buff = RecodeForwTable[*buff - 128];
332 *buff = RecodeBackTable[*buff - 128];
342 /* ----------------------------------------------------------------
345 * The session user is determined at connection start and never
346 * changes. The current user may change when "setuid" functions
347 * are implemented. Conceptually there is a stack, whose bottom
348 * is the session user. You are yourself responsible to save and
349 * restore the current user id if you need to change it.
350 * ----------------------------------------------------------------
352 static Oid CurrentUserId = InvalidOid;
353 static Oid SessionUserId = InvalidOid;
357 * This function is relevant for all privilege checks.
362 AssertState(OidIsValid(CurrentUserId));
363 return CurrentUserId;
370 AssertArg(OidIsValid(newid));
371 CurrentUserId = newid;
376 * This value is only relevant for informational purposes.
379 GetSessionUserId(void)
381 AssertState(OidIsValid(SessionUserId));
382 return SessionUserId;
387 SetSessionUserId(Oid newid)
389 AssertArg(OidIsValid(newid));
390 SessionUserId = newid;
391 /* Current user defaults to session user. */
392 if (!OidIsValid(CurrentUserId))
393 CurrentUserId = newid;
398 SetSessionUserIdFromUserName(const char *username)
403 * Don't do scans if we're bootstrapping, none of the system catalogs
404 * exist yet, and they should be owned by postgres anyway.
406 AssertState(!IsBootstrapProcessingMode());
408 userTup = SearchSysCache(SHADOWNAME,
409 PointerGetDatum(username),
411 if (!HeapTupleIsValid(userTup))
412 elog(FATAL, "user \"%s\" does not exist", username);
414 SetSessionUserId( ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid );
416 ReleaseSysCache(userTup);
421 * Get user name from user id
424 GetUserName(Oid userid)
429 tuple = SearchSysCache(SHADOWSYSID,
430 ObjectIdGetDatum(userid),
432 if (!HeapTupleIsValid(tuple))
433 elog(ERROR, "invalid user id %u", (unsigned) userid);
435 result = pstrdup( NameStr(((Form_pg_shadow) GETSTRUCT(tuple))->usename) );
437 ReleaseSysCache(tuple);
443 /*-------------------------------------------------------------------------
444 * Interlock-file support
446 * These routines are used to create both a data-directory lockfile
447 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
448 * Both kinds of files contain the same info:
450 * Owning process' PID
451 * Data directory path
453 * By convention, the owning process' PID is negated if it is a standalone
454 * backend rather than a postmaster. This is just for informational purposes.
455 * The path is also just for informational purposes (so that a socket lockfile
456 * can be more easily traced to the associated postmaster).
458 * On successful lockfile creation, a proc_exit callback to remove the
459 * lockfile is automatically created.
460 *-------------------------------------------------------------------------
464 * proc_exit callback to remove a lockfile.
467 UnlinkLockFile(int status, Datum filename)
469 unlink((char *) DatumGetPointer(filename));
470 /* Should we complain if the unlink fails? */
474 * Create a lockfile, if possible
476 * Call CreateLockFile with the name of the lockfile to be created. If
477 * successful, it returns zero. On detecting a collision, it returns
478 * the PID or negated PID of the lockfile owner --- the caller is responsible
479 * for producing an appropriate error message.
482 CreateLockFile(const char *filename, bool amPostmaster)
485 char buffer[MAXPGPATH + 32];
489 pid_t my_pid = getpid();
492 * We need a loop here because of race conditions.
497 * Try to create the lock file --- O_EXCL makes this atomic.
499 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
501 break; /* Success; exit the retry loop */
503 * Couldn't create the pid file. Probably it already exists.
505 if (errno != EEXIST && errno != EACCES)
506 elog(FATAL, "Can't create lock file %s: %m", filename);
509 * Read the file to get the old owner's PID. Note race condition
510 * here: file might have been deleted since we tried to create it.
512 fd = open(filename, O_RDONLY, 0600);
516 continue; /* race condition; try again */
517 elog(FATAL, "Can't read lock file %s: %m", filename);
519 if ((len = read(fd, buffer, sizeof(buffer) - 1)) <= 0)
520 elog(FATAL, "Can't read lock file %s: %m", filename);
524 encoded_pid = atoi(buffer);
526 /* if pid < 0, the pid is for postgres, not postmaster */
527 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
530 elog(FATAL, "Bogus data in lock file %s", filename);
533 * Check to see if the other process still exists
535 if (other_pid != my_pid)
537 if (kill(other_pid, 0) == 0 ||
539 return encoded_pid; /* lockfile belongs to a live process */
543 * No, the process did not exist. Unlink the file and try again to
544 * create it. Need a loop because of possible race condition against
545 * other would-be creators.
547 if (unlink(filename) < 0)
548 elog(FATAL, "Can't remove old lock file %s: %m"
549 "\n\tThe file seems accidentally left, but I couldn't remove it."
550 "\n\tPlease remove the file by hand and try again.",
555 * Successfully created the file, now fill it.
557 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
558 amPostmaster ? (int) my_pid : - ((int) my_pid),
560 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
562 int save_errno = errno;
567 elog(FATAL, "Can't write lock file %s: %m", filename);
572 * Arrange for automatic removal of lockfile at proc_exit.
574 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
576 return 0; /* Success! */
580 CreateDataDirLockFile(const char *datadir, bool amPostmaster)
582 char lockfile[MAXPGPATH];
585 snprintf(lockfile, sizeof(lockfile), "%s/postmaster.pid", datadir);
586 encoded_pid = CreateLockFile(lockfile, amPostmaster);
587 if (encoded_pid != 0)
589 fprintf(stderr, "Lock file \"%s\" already exists.\n", lockfile);
591 fprintf(stderr, "Is another postgres (pid %d) running in \"%s\"?\n",
592 -encoded_pid, datadir);
594 fprintf(stderr, "Is another postmaster (pid %d) running in \"%s\"?\n",
595 encoded_pid, datadir);
602 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
604 char lockfile[MAXPGPATH];
607 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
608 encoded_pid = CreateLockFile(lockfile, amPostmaster);
609 if (encoded_pid != 0)
611 fprintf(stderr, "Lock file \"%s\" already exists.\n", lockfile);
613 fprintf(stderr, "Is another postgres (pid %d) using \"%s\"?\n",
614 -encoded_pid, socketfile);
616 fprintf(stderr, "Is another postmaster (pid %d) using \"%s\"?\n",
617 encoded_pid, socketfile);
623 /*-------------------------------------------------------------------------
624 * Version checking support
625 *-------------------------------------------------------------------------
629 * Determine whether the PG_VERSION file in directory `path' indicates
630 * a data version compatible with the version of this program.
632 * If compatible, return. Otherwise, elog(FATAL).
635 ValidatePgVersion(const char *path)
637 char full_path[MAXPGPATH];
640 long file_major, file_minor;
641 long my_major = 0, my_minor = 0;
643 const char *version_string = PG_VERSION;
645 my_major = strtol(version_string, &endptr, 10);
647 my_minor = strtol(endptr+1, NULL, 10);
649 snprintf(full_path, MAXPGPATH, "%s/PG_VERSION", path);
651 file = AllocateFile(full_path, "r");
655 elog(FATAL, "File %s is missing. This is not a valid data directory.", full_path);
657 elog(FATAL, "cannot open %s: %m", full_path);
660 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
662 elog(FATAL, "cannot read %s: %m", full_path);
664 elog(FATAL, "`%s' does not have a valid format. You need to initdb.", full_path);
668 if (my_major != file_major || my_minor != file_minor)
669 elog(FATAL, "The data directory was initialized by PostgreSQL version %ld.%ld, "
670 "which is not compatible with this version %s.",
671 file_major, file_minor, version_string);