1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/init/miscinit.c
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
23 #include <sys/types.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
34 #include "access/htup_details.h"
35 #include "catalog/pg_authid.h"
36 #include "libpq/libpq.h"
37 #include "mb/pg_wchar.h"
38 #include "miscadmin.h"
39 #include "postmaster/autovacuum.h"
40 #include "postmaster/postmaster.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/latch.h"
44 #include "storage/pg_shmem.h"
45 #include "storage/proc.h"
46 #include "storage/procarray.h"
47 #include "utils/builtins.h"
48 #include "utils/guc.h"
49 #include "utils/memutils.h"
50 #include "utils/syscache.h"
51 #include "utils/varlena.h"
54 #define DIRECTORY_LOCK_FILE "postmaster.pid"
56 ProcessingMode Mode = InitProcessing;
58 /* List of lock files to be removed at proc exit */
59 static List *lock_files = NIL;
61 static Latch LocalLatchData;
63 /* ----------------------------------------------------------------
64 * ignoring system indexes support stuff
66 * NOTE: "ignoring system indexes" means we do not use the system indexes
67 * for lookups (either in hardwired catalog accesses or in planner-generated
68 * plans). We do, however, still update the indexes when a catalog
69 * modification is made.
70 * ----------------------------------------------------------------
73 bool IgnoreSystemIndexes = false;
76 /* ----------------------------------------------------------------
77 * database path / name support stuff
78 * ----------------------------------------------------------------
82 SetDatabasePath(const char *path)
84 /* This should happen only once per process */
85 Assert(!DatabasePath);
86 DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
90 * Set data directory, but make sure it's an absolute path. Use this,
91 * never set DataDir directly.
94 SetDataDir(const char *dir)
100 /* If presented path is relative, convert to absolute */
101 new = make_absolute_path(dir);
109 * Change working directory to DataDir. Most of the postmaster and backend
110 * code assumes that we are in DataDir so it can use relative paths to access
111 * stuff in and under the data directory. For convenience during path
112 * setup, however, we don't force the chdir to occur during SetDataDir.
115 ChangeToDataDir(void)
117 AssertState(DataDir);
119 if (chdir(DataDir) < 0)
121 (errcode_for_file_access(),
122 errmsg("could not change directory to \"%s\": %m",
127 /* ----------------------------------------------------------------
130 * We have to track several different values associated with the concept
133 * AuthenticatedUserId is determined at connection start and never changes.
135 * SessionUserId is initially the same as AuthenticatedUserId, but can be
136 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
137 * This is the ID reported by the SESSION_USER SQL function.
139 * OuterUserId is the current user ID in effect at the "outer level" (outside
140 * any transaction or function). This is initially the same as SessionUserId,
141 * but can be changed by SET ROLE to any role that SessionUserId is a
142 * member of. (XXX rename to something like CurrentRoleId?)
144 * CurrentUserId is the current effective user ID; this is the one to use
145 * for all normal permissions-checking purposes. At outer level this will
146 * be the same as OuterUserId, but it changes during calls to SECURITY
147 * DEFINER functions, as well as locally in some specialized commands.
149 * SecurityRestrictionContext holds flags indicating reason(s) for changing
150 * CurrentUserId. In some cases we need to lock down operations that are
151 * not directly controlled by privilege settings, and this provides a
152 * convenient way to do it.
153 * ----------------------------------------------------------------
155 static Oid AuthenticatedUserId = InvalidOid;
156 static Oid SessionUserId = InvalidOid;
157 static Oid OuterUserId = InvalidOid;
158 static Oid CurrentUserId = InvalidOid;
160 /* We also have to remember the superuser state of some of these levels */
161 static bool AuthenticatedUserIsSuperuser = false;
162 static bool SessionUserIsSuperuser = false;
164 static int SecurityRestrictionContext = 0;
166 /* We also remember if a SET ROLE is currently active */
167 static bool SetRoleIsActive = false;
170 * Initialize the basic environment for a postmaster child
172 * Should be called as early as possible after the child's startup.
175 InitPostmasterChild(void)
177 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
179 MyProcPid = getpid(); /* reset MyProcPid */
181 MyStartTime = time(NULL); /* set our start time in case we call elog */
184 * make sure stderr is in binary mode before anything can possibly be
185 * written to it, in case it's actually the syslogger pipe, so the pipe
186 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
187 * redirection (e.g. via pg_ctl -l) anyway.
190 _setmode(fileno(stderr), _O_BINARY);
193 /* We don't want the postmaster's proc_exit() handlers */
196 /* Initialize process-local latch support */
197 InitializeLatchSupport();
198 MyLatch = &LocalLatchData;
202 * If possible, make this process a group leader, so that the postmaster
203 * can signal any child processes too. Not all processes will have
204 * children, but for consistency we make all postmaster child processes do
209 elog(FATAL, "setsid() failed: %m");
214 * Initialize the basic environment for a standalone process.
216 * argv0 has to be suitable to find the program's executable.
219 InitStandaloneProcess(const char *argv0)
221 Assert(!IsPostmasterEnvironment);
223 MyProcPid = getpid(); /* reset MyProcPid */
225 MyStartTime = time(NULL); /* set our start time in case we call elog */
227 /* Initialize process-local latch support */
228 InitializeLatchSupport();
229 MyLatch = &LocalLatchData;
232 /* Compute paths, no postmaster to inherit from */
233 if (my_exec_path[0] == '\0')
235 if (find_my_exec(argv0, my_exec_path) < 0)
236 elog(FATAL, "%s: could not locate my own executable path",
240 if (pkglib_path[0] == '\0')
241 get_pkglib_path(my_exec_path, pkglib_path);
245 SwitchToSharedLatch(void)
247 Assert(MyLatch == &LocalLatchData);
248 Assert(MyProc != NULL);
250 MyLatch = &MyProc->procLatch;
253 ModifyWaitEvent(FeBeWaitSet, 1, WL_LATCH_SET, MyLatch);
256 * Set the shared latch as the local one might have been set. This
257 * shouldn't normally be necessary as code is supposed to check the
258 * condition before waiting for the latch, but a bit care can't hurt.
264 SwitchBackToLocalLatch(void)
266 Assert(MyLatch != &LocalLatchData);
267 Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
269 MyLatch = &LocalLatchData;
272 ModifyWaitEvent(FeBeWaitSet, 1, WL_LATCH_SET, MyLatch);
278 * GetUserId - get the current effective user ID.
280 * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
285 AssertState(OidIsValid(CurrentUserId));
286 return CurrentUserId;
291 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
296 AssertState(OidIsValid(OuterUserId));
302 SetOuterUserId(Oid userid)
304 AssertState(SecurityRestrictionContext == 0);
305 AssertArg(OidIsValid(userid));
306 OuterUserId = userid;
308 /* We force the effective user ID to match, too */
309 CurrentUserId = userid;
314 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
317 GetSessionUserId(void)
319 AssertState(OidIsValid(SessionUserId));
320 return SessionUserId;
325 SetSessionUserId(Oid userid, bool is_superuser)
327 AssertState(SecurityRestrictionContext == 0);
328 AssertArg(OidIsValid(userid));
329 SessionUserId = userid;
330 SessionUserIsSuperuser = is_superuser;
331 SetRoleIsActive = false;
333 /* We force the effective user IDs to match, too */
334 OuterUserId = userid;
335 CurrentUserId = userid;
339 * GetAuthenticatedUserId - get the authenticated user ID
342 GetAuthenticatedUserId(void)
344 AssertState(OidIsValid(AuthenticatedUserId));
345 return AuthenticatedUserId;
350 * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
351 * and the SecurityRestrictionContext flags.
353 * Currently there are three valid bits in SecurityRestrictionContext:
355 * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
356 * that is temporarily changing CurrentUserId via these functions. This is
357 * needed to indicate that the actual value of CurrentUserId is not in sync
358 * with guc.c's internal state, so SET ROLE has to be disallowed.
360 * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
361 * that does not wish to trust called user-defined functions at all. This
362 * bit prevents not only SET ROLE, but various other changes of session state
363 * that normally is unprotected but might possibly be used to subvert the
364 * calling session later. An example is replacing an existing prepared
365 * statement with new code, which will then be executed with the outer
366 * session's permissions when the prepared statement is next used. Since
367 * these restrictions are fairly draconian, we apply them only in contexts
368 * where the called functions are really supposed to be side-effect-free
369 * anyway, such as VACUUM/ANALYZE/REINDEX.
371 * SECURITY_NOFORCE_RLS indicates that we are inside an operation which should
372 * ignore the FORCE ROW LEVEL SECURITY per-table indication. This is used to
373 * ensure that FORCE RLS does not mistakenly break referential integrity
374 * checks. Note that this is intentionally only checked when running as the
375 * owner of the table (which should always be the case for referential
378 * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
379 * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
380 * the new value to be valid. In fact, these routines had better not
381 * ever throw any kind of error. This is because they are used by
382 * StartTransaction and AbortTransaction to save/restore the settings,
383 * and during the first transaction within a backend, the value to be saved
384 * and perhaps restored is indeed invalid. We have to be able to get
385 * through AbortTransaction without asserting in case InitPostgres fails.
388 GetUserIdAndSecContext(Oid *userid, int *sec_context)
390 *userid = CurrentUserId;
391 *sec_context = SecurityRestrictionContext;
395 SetUserIdAndSecContext(Oid userid, int sec_context)
397 CurrentUserId = userid;
398 SecurityRestrictionContext = sec_context;
403 * InLocalUserIdChange - are we inside a local change of CurrentUserId?
406 InLocalUserIdChange(void)
408 return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
412 * InSecurityRestrictedOperation - are we inside a security-restricted command?
415 InSecurityRestrictedOperation(void)
417 return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
421 * InNoForceRLSOperation - are we ignoring FORCE ROW LEVEL SECURITY ?
424 InNoForceRLSOperation(void)
426 return (SecurityRestrictionContext & SECURITY_NOFORCE_RLS) != 0;
431 * These are obsolete versions of Get/SetUserIdAndSecContext that are
432 * only provided for bug-compatibility with some rather dubious code in
433 * pljava. We allow the userid to be set, but only when not inside a
434 * security restriction context.
437 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
439 *userid = CurrentUserId;
440 *sec_def_context = InLocalUserIdChange();
444 SetUserIdAndContext(Oid userid, bool sec_def_context)
446 /* We throw the same error SET ROLE would. */
447 if (InSecurityRestrictedOperation())
449 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
450 errmsg("cannot set parameter \"%s\" within security-restricted operation",
452 CurrentUserId = userid;
454 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
456 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
461 * Check whether specified role has explicit REPLICATION privilege
464 has_rolreplication(Oid roleid)
469 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
470 if (HeapTupleIsValid(utup))
472 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
473 ReleaseSysCache(utup);
479 * Initialize user identity during normal backend startup
482 InitializeSessionUserId(const char *rolename, Oid roleid)
485 Form_pg_authid rform;
489 * Don't do scans if we're bootstrapping, none of the system catalogs
490 * exist yet, and they should be owned by postgres anyway.
492 AssertState(!IsBootstrapProcessingMode());
495 AssertState(!OidIsValid(AuthenticatedUserId));
497 if (rolename != NULL)
499 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
500 if (!HeapTupleIsValid(roleTup))
502 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
503 errmsg("role \"%s\" does not exist", rolename)));
507 roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
508 if (!HeapTupleIsValid(roleTup))
510 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
511 errmsg("role with OID %u does not exist", roleid)));
514 rform = (Form_pg_authid) GETSTRUCT(roleTup);
515 roleid = HeapTupleGetOid(roleTup);
516 rname = NameStr(rform->rolname);
518 AuthenticatedUserId = roleid;
519 AuthenticatedUserIsSuperuser = rform->rolsuper;
521 /* This sets OuterUserId/CurrentUserId too */
522 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
524 /* Also mark our PGPROC entry with the authenticated user id */
525 /* (We assume this is an atomic store so no lock is needed) */
526 MyProc->roleId = roleid;
529 * These next checks are not enforced when in standalone mode, so that
530 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
531 * rolcanlogin = false;".
533 if (IsUnderPostmaster)
536 * Is role allowed to login at all?
538 if (!rform->rolcanlogin)
540 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
541 errmsg("role \"%s\" is not permitted to log in",
545 * Check connection limit for this role.
547 * There is a race condition here --- we create our PGPROC before
548 * checking for other PGPROCs. If two backends did this at about the
549 * same time, they might both think they were over the limit, while
550 * ideally one should succeed and one fail. Getting that to work
551 * exactly seems more trouble than it is worth, however; instead we
552 * just document that the connection limit is approximate.
554 if (rform->rolconnlimit >= 0 &&
555 !AuthenticatedUserIsSuperuser &&
556 CountUserBackends(roleid) > rform->rolconnlimit)
558 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
559 errmsg("too many connections for role \"%s\"",
563 /* Record username and superuser status as GUC settings too */
564 SetConfigOption("session_authorization", rname,
565 PGC_BACKEND, PGC_S_OVERRIDE);
566 SetConfigOption("is_superuser",
567 AuthenticatedUserIsSuperuser ? "on" : "off",
568 PGC_INTERNAL, PGC_S_OVERRIDE);
570 ReleaseSysCache(roleTup);
575 * Initialize user identity during special backend startup
578 InitializeSessionUserIdStandalone(void)
581 * This function should only be called in single-user mode, in autovacuum
582 * workers, and in background workers.
584 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess() || IsBackgroundWorker);
587 AssertState(!OidIsValid(AuthenticatedUserId));
589 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
590 AuthenticatedUserIsSuperuser = true;
592 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
597 * Change session auth ID while running
599 * Only a superuser may set auth ID to something other than himself. Note
600 * that in case of multiple SETs in a single session, the original userid's
601 * superuserness is what matters. But we set the GUC variable is_superuser
602 * to indicate whether the *current* session userid is a superuser.
604 * Note: this is not an especially clean place to do the permission check.
605 * It's OK because the check does not require catalog access and can't
606 * fail during an end-of-transaction GUC reversion, but we may someday
607 * have to push it up into assign_session_authorization.
610 SetSessionAuthorization(Oid userid, bool is_superuser)
612 /* Must have authenticated already, else can't make permission check */
613 AssertState(OidIsValid(AuthenticatedUserId));
615 if (userid != AuthenticatedUserId &&
616 !AuthenticatedUserIsSuperuser)
618 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
619 errmsg("permission denied to set session authorization")));
621 SetSessionUserId(userid, is_superuser);
623 SetConfigOption("is_superuser",
624 is_superuser ? "on" : "off",
625 PGC_INTERNAL, PGC_S_OVERRIDE);
629 * Report current role id
630 * This follows the semantics of SET ROLE, ie return the outer-level ID
631 * not the current effective ID, and return InvalidOid when the setting
632 * is logically SET ROLE NONE.
635 GetCurrentRoleId(void)
644 * Change Role ID while running (SET ROLE)
646 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
647 * session user authorization. In this case the is_superuser argument
650 * When roleid is not InvalidOid, the caller must have checked whether
651 * the session user has permission to become that role. (We cannot check
652 * here because this routine must be able to execute in a failed transaction
653 * to restore a prior value of the ROLE GUC variable.)
656 SetCurrentRoleId(Oid roleid, bool is_superuser)
659 * Get correct info if it's SET ROLE NONE
661 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
662 * SetSessionUserId call will fix everything. This is needed since we
663 * will get called during GUC initialization.
665 if (!OidIsValid(roleid))
667 if (!OidIsValid(SessionUserId))
670 roleid = SessionUserId;
671 is_superuser = SessionUserIsSuperuser;
673 SetRoleIsActive = false;
676 SetRoleIsActive = true;
678 SetOuterUserId(roleid);
680 SetConfigOption("is_superuser",
681 is_superuser ? "on" : "off",
682 PGC_INTERNAL, PGC_S_OVERRIDE);
687 * Get user name from user oid, returns NULL for nonexistent roleid if noerr
691 GetUserNameFromId(Oid roleid, bool noerr)
696 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
697 if (!HeapTupleIsValid(tuple))
701 (errcode(ERRCODE_UNDEFINED_OBJECT),
702 errmsg("invalid role OID: %u", roleid)));
707 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
708 ReleaseSysCache(tuple);
714 /*-------------------------------------------------------------------------
715 * Interlock-file support
717 * These routines are used to create both a data-directory lockfile
718 * ($DATADIR/postmaster.pid) and Unix-socket-file lockfiles ($SOCKFILE.lock).
719 * Both kinds of files contain the same info initially, although we can add
720 * more information to a data-directory lockfile after it's created, using
721 * AddToDataDirLockFile(). See miscadmin.h for documentation of the contents
722 * of these lockfiles.
724 * On successful lockfile creation, a proc_exit callback to remove the
725 * lockfile is automatically created.
726 *-------------------------------------------------------------------------
730 * proc_exit callback to remove lockfiles.
733 UnlinkLockFiles(int status, Datum arg)
737 foreach(l, lock_files)
739 char *curfile = (char *) lfirst(l);
742 /* Should we complain if the unlink fails? */
744 /* Since we're about to exit, no need to reclaim storage */
748 * Lock file removal should always be the last externally visible action
749 * of a postmaster or standalone backend, while we won't come here at all
750 * when exiting postmaster child processes. Therefore, this is a good
751 * place to log completion of shutdown. We could alternatively teach
752 * proc_exit() to do it, but that seems uglier. In a standalone backend,
753 * use NOTICE elevel to be less chatty.
755 ereport(IsPostmasterEnvironment ? LOG : NOTICE,
756 (errmsg("database system is shut down")));
762 * filename is the path name of the lockfile to create.
763 * amPostmaster is used to determine how to encode the output PID.
764 * socketDir is the Unix socket directory path to include (possibly empty).
765 * isDDLock and refName are used to determine what error message to produce.
768 CreateLockFile(const char *filename, bool amPostmaster,
769 const char *socketDir,
770 bool isDDLock, const char *refName)
773 char buffer[MAXPGPATH * 2 + 256];
784 * If the PID in the lockfile is our own PID or our parent's or
785 * grandparent's PID, then the file must be stale (probably left over from
786 * a previous system boot cycle). We need to check this because of the
787 * likelihood that a reboot will assign exactly the same PID as we had in
788 * the previous reboot, or one that's only one or two counts larger and
789 * hence the lockfile's PID now refers to an ancestor shell process. We
790 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
791 * via the environment variable PG_GRANDPARENT_PID; this is so that
792 * launching the postmaster via pg_ctl can be just as reliable as
793 * launching it directly. There is no provision for detecting
794 * further-removed ancestor processes, but if the init script is written
795 * carefully then all but the immediate parent shell will be root-owned
796 * processes and so the kill test will fail with EPERM. Note that we
797 * cannot get a false negative this way, because an existing postmaster
798 * would surely never launch a competing postmaster or pg_ctl process
804 my_p_pid = getppid();
808 * Windows hasn't got getppid(), but doesn't need it since it's not using
809 * real kill() either...
814 envvar = getenv("PG_GRANDPARENT_PID");
816 my_gp_pid = atoi(envvar);
821 * We need a loop here because of race conditions. But don't loop forever
822 * (for example, a non-writable $PGDATA directory might cause a failure
823 * that won't go away). 100 tries seems like plenty.
825 for (ntries = 0;; ntries++)
828 * Try to create the lock file --- O_EXCL makes this atomic.
830 * Think not to make the file protection weaker than 0600. See
833 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
835 break; /* Success; exit the retry loop */
838 * Couldn't create the pid file. Probably it already exists.
840 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
842 (errcode_for_file_access(),
843 errmsg("could not create lock file \"%s\": %m",
847 * Read the file to get the old owner's PID. Note race condition
848 * here: file might have been deleted since we tried to create it.
850 fd = open(filename, O_RDONLY, 0600);
854 continue; /* race condition; try again */
856 (errcode_for_file_access(),
857 errmsg("could not open lock file \"%s\": %m",
860 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
862 (errcode_for_file_access(),
863 errmsg("could not read lock file \"%s\": %m",
870 (errcode(ERRCODE_LOCK_FILE_EXISTS),
871 errmsg("lock file \"%s\" is empty", filename),
872 errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
876 encoded_pid = atoi(buffer);
878 /* if pid < 0, the pid is for postgres, not postmaster */
879 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
882 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
886 * Check to see if the other process still exists
888 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
889 * ignored as false matches.
891 * Normally kill() will fail with ESRCH if the given PID doesn't
894 * We can treat the EPERM-error case as okay because that error
895 * implies that the existing process has a different userid than we
896 * do, which means it cannot be a competing postmaster. A postmaster
897 * cannot successfully attach to a data directory owned by a userid
898 * other than its own. (This is now checked directly in
899 * checkDataDir(), but has been true for a long time because of the
900 * restriction that the data directory isn't group- or
901 * world-accessible.) Also, since we create the lockfiles mode 600,
902 * we'd have failed above if the lockfile belonged to another userid
903 * --- which means that whatever process kill() is reporting about
904 * isn't the one that made the lockfile. (NOTE: this last
905 * consideration is the only one that keeps us from blowing away a
906 * Unix socket file belonging to an instance of Postgres being run by
907 * someone else, at least on machines where /tmp hasn't got a
910 if (other_pid != my_pid && other_pid != my_p_pid &&
911 other_pid != my_gp_pid)
913 if (kill(other_pid, 0) == 0 ||
914 (errno != ESRCH && errno != EPERM))
916 /* lockfile belongs to a live process */
918 (errcode(ERRCODE_LOCK_FILE_EXISTS),
919 errmsg("lock file \"%s\" already exists",
923 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
924 (int) other_pid, refName) :
925 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
926 (int) other_pid, refName)) :
928 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
929 (int) other_pid, refName) :
930 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
931 (int) other_pid, refName))));
936 * No, the creating process did not exist. However, it could be that
937 * the postmaster crashed (or more likely was kill -9'd by a clueless
938 * admin) but has left orphan backends behind. Check for this by
939 * looking to see if there is an associated shmem segment that is
942 * Note: because postmaster.pid is written in multiple steps, we might
943 * not find the shmem ID values in it; we can't treat that as an
953 for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
955 if ((ptr = strchr(ptr, '\n')) == NULL)
961 sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
963 if (PGSharedMemoryIsInUse(id1, id2))
965 (errcode(ERRCODE_LOCK_FILE_EXISTS),
966 errmsg("pre-existing shared memory block "
967 "(key %lu, ID %lu) is still in use",
969 errhint("If you're sure there are no old "
970 "server processes still running, remove "
971 "the shared memory block "
972 "or just delete the file \"%s\".",
978 * Looks like nobody's home. Unlink the file and try again to create
979 * it. Need a loop because of possible race condition against other
982 if (unlink(filename) < 0)
984 (errcode_for_file_access(),
985 errmsg("could not remove old lock file \"%s\": %m",
987 errhint("The file seems accidentally left over, but "
988 "it could not be removed. Please remove the file "
989 "by hand and try again.")));
993 * Successfully created the file, now fill it. See comment in miscadmin.h
994 * about the contents. Note that we write the same first five lines into
995 * both datadir and socket lockfiles; although more stuff may get added to
996 * the datadir lockfile later.
998 snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
999 amPostmaster ? (int) my_pid : -((int) my_pid),
1006 * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1007 * will never receive data, so fill it in as empty now.
1009 if (isDDLock && !amPostmaster)
1010 strlcat(buffer, "\n", sizeof(buffer));
1013 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1015 int save_errno = errno;
1019 /* if write didn't set errno, assume problem is no disk space */
1020 errno = save_errno ? save_errno : ENOSPC;
1022 (errcode_for_file_access(),
1023 errmsg("could not write lock file \"%s\": %m", filename)));
1025 if (pg_fsync(fd) != 0)
1027 int save_errno = errno;
1033 (errcode_for_file_access(),
1034 errmsg("could not write lock file \"%s\": %m", filename)));
1038 int save_errno = errno;
1043 (errcode_for_file_access(),
1044 errmsg("could not write lock file \"%s\": %m", filename)));
1048 * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1049 * one, set up the on_proc_exit function to do it; then add this lock file
1050 * to the list of files to unlink.
1052 if (lock_files == NIL)
1053 on_proc_exit(UnlinkLockFiles, 0);
1056 * Use lcons so that the lock files are unlinked in reverse order of
1057 * creation; this is critical!
1059 lock_files = lcons(pstrdup(filename), lock_files);
1063 * Create the data directory lockfile.
1065 * When this is called, we must have already switched the working
1066 * directory to DataDir, so we can just use a relative path. This
1067 * helps ensure that we are locking the directory we should be.
1069 * Note that the socket directory path line is initially written as empty.
1070 * postmaster.c will rewrite it upon creating the first Unix socket.
1073 CreateDataDirLockFile(bool amPostmaster)
1075 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1079 * Create a lockfile for the specified Unix socket file.
1082 CreateSocketLockFile(const char *socketfile, bool amPostmaster,
1083 const char *socketDir)
1085 char lockfile[MAXPGPATH];
1087 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1088 CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1092 * TouchSocketLockFiles -- mark socket lock files as recently accessed
1094 * This routine should be called every so often to ensure that the socket
1095 * lock files have a recent mod or access date. That saves them
1096 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
1097 * (Another reason we should never have put the socket file in /tmp...)
1100 TouchSocketLockFiles(void)
1104 foreach(l, lock_files)
1106 char *socketLockFile = (char *) lfirst(l);
1108 /* No need to touch the data directory lock file, we trust */
1109 if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1113 * utime() is POSIX standard, utimes() is a common alternative; if we
1114 * have neither, fall back to actually reading the file (which only
1115 * sets the access time not mod time, but that should be enough in
1116 * most cases). In all paths, we ignore errors.
1119 utime(socketLockFile, NULL);
1120 #else /* !HAVE_UTIME */
1122 utimes(socketLockFile, NULL);
1123 #else /* !HAVE_UTIMES */
1127 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1130 read(fd, buffer, sizeof(buffer));
1133 #endif /* HAVE_UTIMES */
1134 #endif /* HAVE_UTIME */
1140 * Add (or replace) a line in the data directory lock file.
1141 * The given string should not include a trailing newline.
1143 * Note: because we don't truncate the file, if we were to rewrite a line
1144 * with less data than it had before, there would be garbage after the last
1145 * line. We don't ever actually do that, so not worth adding another kernel
1146 * call to cover the possibility.
1149 AddToDataDirLockFile(int target_line, const char *str)
1156 char srcbuffer[BLCKSZ];
1157 char destbuffer[BLCKSZ];
1159 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1163 (errcode_for_file_access(),
1164 errmsg("could not open file \"%s\": %m",
1165 DIRECTORY_LOCK_FILE)));
1168 len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1172 (errcode_for_file_access(),
1173 errmsg("could not read from file \"%s\": %m",
1174 DIRECTORY_LOCK_FILE)));
1178 srcbuffer[len] = '\0';
1181 * Advance over lines we are not supposed to rewrite, then copy them to
1185 for (lineno = 1; lineno < target_line; lineno++)
1187 if ((srcptr = strchr(srcptr, '\n')) == NULL)
1189 elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
1190 DIRECTORY_LOCK_FILE, lineno - 1, target_line);
1196 memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1197 destptr = destbuffer + (srcptr - srcbuffer);
1200 * Write or rewrite the target line.
1202 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1203 destptr += strlen(destptr);
1206 * If there are more lines in the old file, append them to destbuffer.
1208 if ((srcptr = strchr(srcptr, '\n')) != NULL)
1211 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1216 * And rewrite the data. Since we write in a single kernel call, this
1217 * update should appear atomic to onlookers.
1219 len = strlen(destbuffer);
1221 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1222 (int) write(fd, destbuffer, len) != len)
1224 /* if write didn't set errno, assume problem is no disk space */
1228 (errcode_for_file_access(),
1229 errmsg("could not write to file \"%s\": %m",
1230 DIRECTORY_LOCK_FILE)));
1234 if (pg_fsync(fd) != 0)
1237 (errcode_for_file_access(),
1238 errmsg("could not write to file \"%s\": %m",
1239 DIRECTORY_LOCK_FILE)));
1244 (errcode_for_file_access(),
1245 errmsg("could not write to file \"%s\": %m",
1246 DIRECTORY_LOCK_FILE)));
1252 * Recheck that the data directory lock file still exists with expected
1253 * content. Return TRUE if the lock file appears OK, FALSE if it isn't.
1255 * We call this periodically in the postmaster. The idea is that if the
1256 * lock file has been removed or replaced by another postmaster, we should
1257 * do a panic database shutdown. Therefore, we should return TRUE if there
1258 * is any doubt: we do not want to cause a panic shutdown unnecessarily.
1259 * Transient failures like EINTR or ENFILE should not cause us to fail.
1260 * (If there really is something wrong, we'll detect it on a future recheck.)
1263 RecheckDataDirLockFile(void)
1268 char buffer[BLCKSZ];
1270 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1274 * There are many foreseeable false-positive error conditions. For
1275 * safety, fail only on enumerated clearly-something-is-wrong
1284 (errcode_for_file_access(),
1285 errmsg("could not open file \"%s\": %m",
1286 DIRECTORY_LOCK_FILE)));
1289 /* non-fatal, at least for now */
1291 (errcode_for_file_access(),
1292 errmsg("could not open file \"%s\": %m; continuing anyway",
1293 DIRECTORY_LOCK_FILE)));
1297 len = read(fd, buffer, sizeof(buffer) - 1);
1301 (errcode_for_file_access(),
1302 errmsg("could not read from file \"%s\": %m",
1303 DIRECTORY_LOCK_FILE)));
1305 return true; /* treat read failure as nonfatal */
1309 file_pid = atol(buffer);
1310 if (file_pid == getpid())
1311 return true; /* all is well */
1313 /* Trouble: someone's overwritten the lock file */
1315 (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1316 DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1321 /*-------------------------------------------------------------------------
1322 * Version checking support
1323 *-------------------------------------------------------------------------
1327 * Determine whether the PG_VERSION file in directory `path' indicates
1328 * a data version compatible with the version of this program.
1330 * If compatible, return. Otherwise, ereport(FATAL).
1333 ValidatePgVersion(const char *path)
1335 char full_path[MAXPGPATH];
1341 char file_version_string[64];
1342 const char *my_version_string = PG_VERSION;
1344 my_major = strtol(my_version_string, &endptr, 10);
1346 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1348 file = AllocateFile(full_path, "r");
1351 if (errno == ENOENT)
1353 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1354 errmsg("\"%s\" is not a valid data directory",
1356 errdetail("File \"%s\" is missing.", full_path)));
1359 (errcode_for_file_access(),
1360 errmsg("could not open file \"%s\": %m", full_path)));
1363 file_version_string[0] = '\0';
1364 ret = fscanf(file, "%63s", file_version_string);
1365 file_major = strtol(file_version_string, &endptr, 10);
1367 if (ret != 1 || endptr == file_version_string)
1369 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1370 errmsg("\"%s\" is not a valid data directory",
1372 errdetail("File \"%s\" does not contain valid data.",
1374 errhint("You might need to initdb.")));
1378 if (my_major != file_major)
1380 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1381 errmsg("database files are incompatible with server"),
1382 errdetail("The data directory was initialized by PostgreSQL version %s, "
1383 "which is not compatible with this version %s.",
1384 file_version_string, my_version_string)));
1387 /*-------------------------------------------------------------------------
1388 * Library preload support
1389 *-------------------------------------------------------------------------
1393 * GUC variables: lists of library names to be preloaded at postmaster
1394 * start and at backend start
1396 char *session_preload_libraries_string = NULL;
1397 char *shared_preload_libraries_string = NULL;
1398 char *local_preload_libraries_string = NULL;
1400 /* Flag telling that we are loading shared_preload_libraries */
1401 bool process_shared_preload_libraries_in_progress = false;
1404 * load the shared libraries listed in 'libraries'
1406 * 'gucname': name of GUC variable, for error reports
1407 * 'restricted': if true, force libraries to be in $libdir/plugins/
1410 load_libraries(const char *libraries, const char *gucname, bool restricted)
1416 if (libraries == NULL || libraries[0] == '\0')
1417 return; /* nothing to do */
1419 /* Need a modifiable copy of string */
1420 rawstring = pstrdup(libraries);
1422 /* Parse string into list of identifiers */
1423 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1425 /* syntax error in list */
1427 list_free(elemlist);
1429 (errcode(ERRCODE_SYNTAX_ERROR),
1430 errmsg("invalid list syntax in parameter \"%s\"",
1435 foreach(l, elemlist)
1437 char *tok = (char *) lfirst(l);
1440 filename = pstrdup(tok);
1441 canonicalize_path(filename);
1442 /* If restricting, insert $libdir/plugins if not mentioned already */
1443 if (restricted && first_dir_separator(filename) == NULL)
1447 expanded = psprintf("$libdir/plugins/%s", filename);
1449 filename = expanded;
1451 load_file(filename, restricted);
1453 (errmsg("loaded library \"%s\"", filename)));
1458 list_free(elemlist);
1462 * process any libraries that should be preloaded at postmaster start
1465 process_shared_preload_libraries(void)
1467 process_shared_preload_libraries_in_progress = true;
1468 load_libraries(shared_preload_libraries_string,
1469 "shared_preload_libraries",
1471 process_shared_preload_libraries_in_progress = false;
1475 * process any libraries that should be preloaded at backend start
1478 process_session_preload_libraries(void)
1480 load_libraries(session_preload_libraries_string,
1481 "session_preload_libraries",
1483 load_libraries(local_preload_libraries_string,
1484 "local_preload_libraries",
1489 pg_bindtextdomain(const char *domain)
1492 if (my_exec_path[0] != '\0')
1494 char locale_path[MAXPGPATH];
1496 get_locale_path(my_exec_path, locale_path);
1497 bindtextdomain(domain, locale_path);
1498 pg_bind_textdomain_codeset(domain);