1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2010, 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>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
32 #include "catalog/pg_authid.h"
33 #include "mb/pg_wchar.h"
34 #include "miscadmin.h"
35 #include "postmaster/autovacuum.h"
36 #include "postmaster/postmaster.h"
37 #include "storage/fd.h"
38 #include "storage/ipc.h"
39 #include "storage/pg_shmem.h"
40 #include "storage/proc.h"
41 #include "storage/procarray.h"
42 #include "utils/builtins.h"
43 #include "utils/guc.h"
44 #include "utils/memutils.h"
45 #include "utils/syscache.h"
48 #define DIRECTORY_LOCK_FILE "postmaster.pid"
50 ProcessingMode Mode = InitProcessing;
52 /* Note: we rely on this to initialize as zeroes */
53 static char socketLockFile[MAXPGPATH];
56 /* ----------------------------------------------------------------
57 * ignoring system indexes support stuff
59 * NOTE: "ignoring system indexes" means we do not use the system indexes
60 * for lookups (either in hardwired catalog accesses or in planner-generated
61 * plans). We do, however, still update the indexes when a catalog
62 * modification is made.
63 * ----------------------------------------------------------------
66 bool IgnoreSystemIndexes = false;
69 /* ----------------------------------------------------------------
70 * database path / name support stuff
71 * ----------------------------------------------------------------
75 SetDatabasePath(const char *path)
77 /* This should happen only once per process */
78 Assert(!DatabasePath);
79 DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
83 * Set data directory, but make sure it's an absolute path. Use this,
84 * never set DataDir directly.
87 SetDataDir(const char *dir)
93 /* If presented path is relative, convert to absolute */
94 new = make_absolute_path(dir);
102 * Change working directory to DataDir. Most of the postmaster and backend
103 * code assumes that we are in DataDir so it can use relative paths to access
104 * stuff in and under the data directory. For convenience during path
105 * setup, however, we don't force the chdir to occur during SetDataDir.
108 ChangeToDataDir(void)
110 AssertState(DataDir);
112 if (chdir(DataDir) < 0)
114 (errcode_for_file_access(),
115 errmsg("could not change directory to \"%s\": %m",
120 * If the given pathname isn't already absolute, make it so, interpreting
121 * it relative to the current working directory.
123 * Also canonicalizes the path. The result is always a malloc'd copy.
125 * Note: interpretation of relative-path arguments during postmaster startup
126 * should happen before doing ChangeToDataDir(), else the user will probably
127 * not like the results.
130 make_absolute_path(const char *path)
134 /* Returning null for null input is convenient for some callers */
138 if (!is_absolute_path(path))
146 buf = malloc(buflen);
149 (errcode(ERRCODE_OUT_OF_MEMORY),
150 errmsg("out of memory")));
152 if (getcwd(buf, buflen))
154 else if (errno == ERANGE)
163 elog(FATAL, "could not get current working directory: %m");
167 new = malloc(strlen(buf) + strlen(path) + 2);
170 (errcode(ERRCODE_OUT_OF_MEMORY),
171 errmsg("out of memory")));
172 sprintf(new, "%s/%s", buf, path);
180 (errcode(ERRCODE_OUT_OF_MEMORY),
181 errmsg("out of memory")));
184 /* Make sure punctuation is canonical, too */
185 canonicalize_path(new);
191 /* ----------------------------------------------------------------
194 * We have to track several different values associated with the concept
197 * AuthenticatedUserId is determined at connection start and never changes.
199 * SessionUserId is initially the same as AuthenticatedUserId, but can be
200 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
201 * This is the ID reported by the SESSION_USER SQL function.
203 * OuterUserId is the current user ID in effect at the "outer level" (outside
204 * any transaction or function). This is initially the same as SessionUserId,
205 * but can be changed by SET ROLE to any role that SessionUserId is a
206 * member of. (XXX rename to something like CurrentRoleId?)
208 * CurrentUserId is the current effective user ID; this is the one to use
209 * for all normal permissions-checking purposes. At outer level this will
210 * be the same as OuterUserId, but it changes during calls to SECURITY
211 * DEFINER functions, as well as locally in some specialized commands.
213 * SecurityRestrictionContext holds flags indicating reason(s) for changing
214 * CurrentUserId. In some cases we need to lock down operations that are
215 * not directly controlled by privilege settings, and this provides a
216 * convenient way to do it.
217 * ----------------------------------------------------------------
219 static Oid AuthenticatedUserId = InvalidOid;
220 static Oid SessionUserId = InvalidOid;
221 static Oid OuterUserId = InvalidOid;
222 static Oid CurrentUserId = InvalidOid;
224 /* We also have to remember the superuser state of some of these levels */
225 static bool AuthenticatedUserIsSuperuser = false;
226 static bool SessionUserIsSuperuser = false;
228 static int SecurityRestrictionContext = 0;
230 /* We also remember if a SET ROLE is currently active */
231 static bool SetRoleIsActive = false;
236 * GetUserId - get the current effective user ID.
238 * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
243 AssertState(OidIsValid(CurrentUserId));
244 return CurrentUserId;
249 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
254 AssertState(OidIsValid(OuterUserId));
260 SetOuterUserId(Oid userid)
262 AssertState(SecurityRestrictionContext == 0);
263 AssertArg(OidIsValid(userid));
264 OuterUserId = userid;
266 /* We force the effective user ID to match, too */
267 CurrentUserId = userid;
272 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
275 GetSessionUserId(void)
277 AssertState(OidIsValid(SessionUserId));
278 return SessionUserId;
283 SetSessionUserId(Oid userid, bool is_superuser)
285 AssertState(SecurityRestrictionContext == 0);
286 AssertArg(OidIsValid(userid));
287 SessionUserId = userid;
288 SessionUserIsSuperuser = is_superuser;
289 SetRoleIsActive = false;
291 /* We force the effective user IDs to match, too */
292 OuterUserId = userid;
293 CurrentUserId = userid;
298 * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
299 * and the SecurityRestrictionContext flags.
301 * Currently there are two valid bits in SecurityRestrictionContext:
303 * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
304 * that is temporarily changing CurrentUserId via these functions. This is
305 * needed to indicate that the actual value of CurrentUserId is not in sync
306 * with guc.c's internal state, so SET ROLE has to be disallowed.
308 * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
309 * that does not wish to trust called user-defined functions at all. This
310 * bit prevents not only SET ROLE, but various other changes of session state
311 * that normally is unprotected but might possibly be used to subvert the
312 * calling session later. An example is replacing an existing prepared
313 * statement with new code, which will then be executed with the outer
314 * session's permissions when the prepared statement is next used. Since
315 * these restrictions are fairly draconian, we apply them only in contexts
316 * where the called functions are really supposed to be side-effect-free
317 * anyway, such as VACUUM/ANALYZE/REINDEX.
319 * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
320 * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
321 * the new value to be valid. In fact, these routines had better not
322 * ever throw any kind of error. This is because they are used by
323 * StartTransaction and AbortTransaction to save/restore the settings,
324 * and during the first transaction within a backend, the value to be saved
325 * and perhaps restored is indeed invalid. We have to be able to get
326 * through AbortTransaction without asserting in case InitPostgres fails.
329 GetUserIdAndSecContext(Oid *userid, int *sec_context)
331 *userid = CurrentUserId;
332 *sec_context = SecurityRestrictionContext;
336 SetUserIdAndSecContext(Oid userid, int sec_context)
338 CurrentUserId = userid;
339 SecurityRestrictionContext = sec_context;
344 * InLocalUserIdChange - are we inside a local change of CurrentUserId?
347 InLocalUserIdChange(void)
349 return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
353 * InSecurityRestrictedOperation - are we inside a security-restricted command?
356 InSecurityRestrictedOperation(void)
358 return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
363 * These are obsolete versions of Get/SetUserIdAndSecContext that are
364 * only provided for bug-compatibility with some rather dubious code in
365 * pljava. We allow the userid to be set, but only when not inside a
366 * security restriction context.
369 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
371 *userid = CurrentUserId;
372 *sec_def_context = InLocalUserIdChange();
376 SetUserIdAndContext(Oid userid, bool sec_def_context)
378 /* We throw the same error SET ROLE would. */
379 if (InSecurityRestrictedOperation())
381 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
382 errmsg("cannot set parameter \"%s\" within security-restricted operation",
384 CurrentUserId = userid;
386 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
388 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
393 * Check if the authenticated user is a replication role
396 is_authenticated_user_replication_role(void)
401 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(AuthenticatedUserId));
402 if (HeapTupleIsValid(utup))
404 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
405 ReleaseSysCache(utup);
411 * Initialize user identity during normal backend startup
414 InitializeSessionUserId(const char *rolename)
417 Form_pg_authid rform;
421 * Don't do scans if we're bootstrapping, none of the system catalogs
422 * exist yet, and they should be owned by postgres anyway.
424 AssertState(!IsBootstrapProcessingMode());
427 AssertState(!OidIsValid(AuthenticatedUserId));
429 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
430 if (!HeapTupleIsValid(roleTup))
432 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
433 errmsg("role \"%s\" does not exist", rolename)));
435 rform = (Form_pg_authid) GETSTRUCT(roleTup);
436 roleid = HeapTupleGetOid(roleTup);
438 AuthenticatedUserId = roleid;
439 AuthenticatedUserIsSuperuser = rform->rolsuper;
441 /* This sets OuterUserId/CurrentUserId too */
442 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
444 /* Also mark our PGPROC entry with the authenticated user id */
445 /* (We assume this is an atomic store so no lock is needed) */
446 MyProc->roleId = roleid;
449 * These next checks are not enforced when in standalone mode, so that
450 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
451 * rolcanlogin = false;".
453 if (IsUnderPostmaster)
456 * Is role allowed to login at all?
458 if (!rform->rolcanlogin)
460 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
461 errmsg("role \"%s\" is not permitted to log in",
465 * Check connection limit for this role.
467 * There is a race condition here --- we create our PGPROC before
468 * checking for other PGPROCs. If two backends did this at about the
469 * same time, they might both think they were over the limit, while
470 * ideally one should succeed and one fail. Getting that to work
471 * exactly seems more trouble than it is worth, however; instead we
472 * just document that the connection limit is approximate.
474 if (rform->rolconnlimit >= 0 &&
475 !AuthenticatedUserIsSuperuser &&
476 CountUserBackends(roleid) > rform->rolconnlimit)
478 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
479 errmsg("too many connections for role \"%s\"",
483 /* Record username and superuser status as GUC settings too */
484 SetConfigOption("session_authorization", rolename,
485 PGC_BACKEND, PGC_S_OVERRIDE);
486 SetConfigOption("is_superuser",
487 AuthenticatedUserIsSuperuser ? "on" : "off",
488 PGC_INTERNAL, PGC_S_OVERRIDE);
490 ReleaseSysCache(roleTup);
495 * Initialize user identity during special backend startup
498 InitializeSessionUserIdStandalone(void)
501 * This function should only be called in single-user mode and in
502 * autovacuum workers.
504 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
507 AssertState(!OidIsValid(AuthenticatedUserId));
509 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
510 AuthenticatedUserIsSuperuser = true;
512 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
517 * Change session auth ID while running
519 * Only a superuser may set auth ID to something other than himself. Note
520 * that in case of multiple SETs in a single session, the original userid's
521 * superuserness is what matters. But we set the GUC variable is_superuser
522 * to indicate whether the *current* session userid is a superuser.
524 * Note: this is not an especially clean place to do the permission check.
525 * It's OK because the check does not require catalog access and can't
526 * fail during an end-of-transaction GUC reversion, but we may someday
527 * have to push it up into assign_session_authorization.
530 SetSessionAuthorization(Oid userid, bool is_superuser)
532 /* Must have authenticated already, else can't make permission check */
533 AssertState(OidIsValid(AuthenticatedUserId));
535 if (userid != AuthenticatedUserId &&
536 !AuthenticatedUserIsSuperuser)
538 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
539 errmsg("permission denied to set session authorization")));
541 SetSessionUserId(userid, is_superuser);
543 SetConfigOption("is_superuser",
544 is_superuser ? "on" : "off",
545 PGC_INTERNAL, PGC_S_OVERRIDE);
549 * Report current role id
550 * This follows the semantics of SET ROLE, ie return the outer-level ID
551 * not the current effective ID, and return InvalidOid when the setting
552 * is logically SET ROLE NONE.
555 GetCurrentRoleId(void)
564 * Change Role ID while running (SET ROLE)
566 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
567 * session user authorization. In this case the is_superuser argument
570 * When roleid is not InvalidOid, the caller must have checked whether
571 * the session user has permission to become that role. (We cannot check
572 * here because this routine must be able to execute in a failed transaction
573 * to restore a prior value of the ROLE GUC variable.)
576 SetCurrentRoleId(Oid roleid, bool is_superuser)
579 * Get correct info if it's SET ROLE NONE
581 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
582 * SetSessionUserId call will fix everything. This is needed since we
583 * will get called during GUC initialization.
585 if (!OidIsValid(roleid))
587 if (!OidIsValid(SessionUserId))
590 roleid = SessionUserId;
591 is_superuser = SessionUserIsSuperuser;
593 SetRoleIsActive = false;
596 SetRoleIsActive = true;
598 SetOuterUserId(roleid);
600 SetConfigOption("is_superuser",
601 is_superuser ? "on" : "off",
602 PGC_INTERNAL, PGC_S_OVERRIDE);
607 * Get user name from user oid
610 GetUserNameFromId(Oid roleid)
615 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
616 if (!HeapTupleIsValid(tuple))
618 (errcode(ERRCODE_UNDEFINED_OBJECT),
619 errmsg("invalid role OID: %u", roleid)));
621 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
623 ReleaseSysCache(tuple);
628 /*-------------------------------------------------------------------------
629 * Interlock-file support
631 * These routines are used to create both a data-directory lockfile
632 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
633 * Both kinds of files contain the same info:
635 * Owning process' PID
636 * Data directory path
638 * By convention, the owning process' PID is negated if it is a standalone
639 * backend rather than a postmaster. This is just for informational purposes.
640 * The path is also just for informational purposes (so that a socket lockfile
641 * can be more easily traced to the associated postmaster).
643 * A data-directory lockfile can optionally contain a third line, containing
644 * the key and ID for the shared memory block used by this postmaster.
646 * On successful lockfile creation, a proc_exit callback to remove the
647 * lockfile is automatically created.
648 *-------------------------------------------------------------------------
652 * proc_exit callback to remove a lockfile.
655 UnlinkLockFile(int status, Datum filename)
657 char *fname = (char *) DatumGetPointer(filename);
661 if (unlink(fname) != 0)
663 /* Should we complain if the unlink fails? */
672 * filename is the name of the lockfile to create.
673 * amPostmaster is used to determine how to encode the output PID.
674 * isDDLock and refName are used to determine what error message to produce.
677 CreateLockFile(const char *filename, bool amPostmaster,
678 bool isDDLock, const char *refName)
681 char buffer[MAXPGPATH * 2 + 256];
692 * If the PID in the lockfile is our own PID or our parent's or
693 * grandparent's PID, then the file must be stale (probably left over from
694 * a previous system boot cycle). We need to check this because of the
695 * likelihood that a reboot will assign exactly the same PID as we had in
696 * the previous reboot, or one that's only one or two counts larger and
697 * hence the lockfile's PID now refers to an ancestor shell process. We
698 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
699 * via the environment variable PG_GRANDPARENT_PID; this is so that
700 * launching the postmaster via pg_ctl can be just as reliable as
701 * launching it directly. There is no provision for detecting
702 * further-removed ancestor processes, but if the init script is written
703 * carefully then all but the immediate parent shell will be root-owned
704 * processes and so the kill test will fail with EPERM. Note that we
705 * cannot get a false negative this way, because an existing postmaster
706 * would surely never launch a competing postmaster or pg_ctl process
712 my_p_pid = getppid();
716 * Windows hasn't got getppid(), but doesn't need it since it's not using
717 * real kill() either...
722 envvar = getenv("PG_GRANDPARENT_PID");
724 my_gp_pid = atoi(envvar);
729 * We need a loop here because of race conditions. But don't loop forever
730 * (for example, a non-writable $PGDATA directory might cause a failure
731 * that won't go away). 100 tries seems like plenty.
733 for (ntries = 0;; ntries++)
736 * Try to create the lock file --- O_EXCL makes this atomic.
738 * Think not to make the file protection weaker than 0600. See
741 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
743 break; /* Success; exit the retry loop */
746 * Couldn't create the pid file. Probably it already exists.
748 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
750 (errcode_for_file_access(),
751 errmsg("could not create lock file \"%s\": %m",
755 * Read the file to get the old owner's PID. Note race condition
756 * here: file might have been deleted since we tried to create it.
758 fd = open(filename, O_RDONLY, 0600);
762 continue; /* race condition; try again */
764 (errcode_for_file_access(),
765 errmsg("could not open lock file \"%s\": %m",
768 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
770 (errcode_for_file_access(),
771 errmsg("could not read lock file \"%s\": %m",
776 encoded_pid = atoi(buffer);
778 /* if pid < 0, the pid is for postgres, not postmaster */
779 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
782 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
786 * Check to see if the other process still exists
788 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
789 * ignored as false matches.
791 * Normally kill() will fail with ESRCH if the given PID doesn't
794 * We can treat the EPERM-error case as okay because that error
795 * implies that the existing process has a different userid than we
796 * do, which means it cannot be a competing postmaster. A postmaster
797 * cannot successfully attach to a data directory owned by a userid
798 * other than its own. (This is now checked directly in
799 * checkDataDir(), but has been true for a long time because of the
800 * restriction that the data directory isn't group- or
801 * world-accessible.) Also, since we create the lockfiles mode 600,
802 * we'd have failed above if the lockfile belonged to another userid
803 * --- which means that whatever process kill() is reporting about
804 * isn't the one that made the lockfile. (NOTE: this last
805 * consideration is the only one that keeps us from blowing away a
806 * Unix socket file belonging to an instance of Postgres being run by
807 * someone else, at least on machines where /tmp hasn't got a
810 if (other_pid != my_pid && other_pid != my_p_pid &&
811 other_pid != my_gp_pid)
813 if (kill(other_pid, 0) == 0 ||
814 (errno != ESRCH && errno != EPERM))
816 /* lockfile belongs to a live process */
818 (errcode(ERRCODE_LOCK_FILE_EXISTS),
819 errmsg("lock file \"%s\" already exists",
823 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
824 (int) other_pid, refName) :
825 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
826 (int) other_pid, refName)) :
828 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
829 (int) other_pid, refName) :
830 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
831 (int) other_pid, refName))));
836 * No, the creating process did not exist. However, it could be that
837 * the postmaster crashed (or more likely was kill -9'd by a clueless
838 * admin) but has left orphan backends behind. Check for this by
839 * looking to see if there is an associated shmem segment that is
842 * Note: because postmaster.pid is written in two steps, we might not
843 * find the shmem ID values in it; we can't treat that as an error.
852 for (lineno = 1; lineno <= 4; lineno++)
854 if ((ptr = strchr(ptr, '\n')) == NULL)
856 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
862 if (ptr && sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
864 if (PGSharedMemoryIsInUse(id1, id2))
866 (errcode(ERRCODE_LOCK_FILE_EXISTS),
867 errmsg("pre-existing shared memory block "
868 "(key %lu, ID %lu) is still in use",
870 errhint("If you're sure there are no old "
871 "server processes still running, remove "
872 "the shared memory block "
873 "or just delete the file \"%s\".",
879 * Looks like nobody's home. Unlink the file and try again to create
880 * it. Need a loop because of possible race condition against other
883 if (unlink(filename) < 0)
885 (errcode_for_file_access(),
886 errmsg("could not remove old lock file \"%s\": %m",
888 errhint("The file seems accidentally left over, but "
889 "it could not be removed. Please remove the file "
890 "by hand and try again.")));
894 * Successfully created the file, now fill it.
896 snprintf(buffer, sizeof(buffer), "%d\n%s\n%d\n%s\n",
897 amPostmaster ? (int) my_pid : -((int) my_pid),
898 DataDir, PostPortNumber, UnixSocketDir);
900 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
902 int save_errno = errno;
906 /* if write didn't set errno, assume problem is no disk space */
907 errno = save_errno ? save_errno : ENOSPC;
909 (errcode_for_file_access(),
910 errmsg("could not write lock file \"%s\": %m", filename)));
912 if (pg_fsync(fd) != 0)
914 int save_errno = errno;
920 (errcode_for_file_access(),
921 errmsg("could not write lock file \"%s\": %m", filename)));
925 int save_errno = errno;
930 (errcode_for_file_access(),
931 errmsg("could not write lock file \"%s\": %m", filename)));
935 * Arrange for automatic removal of lockfile at proc_exit.
937 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
941 * Create the data directory lockfile.
943 * When this is called, we must have already switched the working
944 * directory to DataDir, so we can just use a relative path. This
945 * helps ensure that we are locking the directory we should be.
948 CreateDataDirLockFile(bool amPostmaster)
950 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
954 * Create a lockfile for the specified Unix socket file.
957 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
959 char lockfile[MAXPGPATH];
961 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
962 CreateLockFile(lockfile, amPostmaster, false, socketfile);
963 /* Save name of lockfile for TouchSocketLockFile */
964 strcpy(socketLockFile, lockfile);
968 * TouchSocketLockFile -- mark socket lock file as recently accessed
970 * This routine should be called every so often to ensure that the lock file
971 * has a recent mod or access date. That saves it
972 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
973 * (Another reason we should never have put the socket file in /tmp...)
976 TouchSocketLockFile(void)
978 /* Do nothing if we did not create a socket... */
979 if (socketLockFile[0] != '\0')
982 * utime() is POSIX standard, utimes() is a common alternative; if we
983 * have neither, fall back to actually reading the file (which only
984 * sets the access time not mod time, but that should be enough in
985 * most cases). In all paths, we ignore errors.
988 utime(socketLockFile, NULL);
989 #else /* !HAVE_UTIME */
991 utimes(socketLockFile, NULL);
992 #else /* !HAVE_UTIMES */
996 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
999 read(fd, buffer, sizeof(buffer));
1002 #endif /* HAVE_UTIMES */
1003 #endif /* HAVE_UTIME */
1008 * Append information about a shared memory segment to the data directory
1011 * This may be called multiple times in the life of a postmaster, if we
1012 * delete and recreate shmem due to backend crash. Therefore, be prepared
1013 * to overwrite existing information. (As of 7.1, a postmaster only creates
1014 * one shm seg at a time; but for the purposes here, if we did have more than
1015 * one then any one of them would do anyway.)
1018 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
1024 char buffer[MAXPGPATH * 2 + 256];
1026 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1030 (errcode_for_file_access(),
1031 errmsg("could not open file \"%s\": %m",
1032 DIRECTORY_LOCK_FILE)));
1035 len = read(fd, buffer, sizeof(buffer) - 100);
1039 (errcode_for_file_access(),
1040 errmsg("could not read from file \"%s\": %m",
1041 DIRECTORY_LOCK_FILE)));
1048 * Skip over first four lines (PID, pgdata, portnum, socketdir).
1051 for (lineno = 1; lineno <= 4; lineno++)
1053 if ((ptr = strchr(ptr, '\n')) == NULL)
1055 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1063 * Append key information. Format to try to keep it the same length
1064 * always (trailing junk won't hurt, but might confuse humans).
1066 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1069 * And rewrite the data. Since we write in a single kernel call, this
1070 * update should appear atomic to onlookers.
1072 len = strlen(buffer);
1074 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1075 (int) write(fd, buffer, len) != len)
1077 /* if write didn't set errno, assume problem is no disk space */
1081 (errcode_for_file_access(),
1082 errmsg("could not write to file \"%s\": %m",
1083 DIRECTORY_LOCK_FILE)));
1087 if (pg_fsync(fd) != 0)
1090 (errcode_for_file_access(),
1091 errmsg("could not write to file \"%s\": %m",
1092 DIRECTORY_LOCK_FILE)));
1097 (errcode_for_file_access(),
1098 errmsg("could not write to file \"%s\": %m",
1099 DIRECTORY_LOCK_FILE)));
1104 /*-------------------------------------------------------------------------
1105 * Version checking support
1106 *-------------------------------------------------------------------------
1110 * Determine whether the PG_VERSION file in directory `path' indicates
1111 * a data version compatible with the version of this program.
1113 * If compatible, return. Otherwise, ereport(FATAL).
1116 ValidatePgVersion(const char *path)
1118 char full_path[MAXPGPATH];
1126 const char *version_string = PG_VERSION;
1128 my_major = strtol(version_string, &endptr, 10);
1130 my_minor = strtol(endptr + 1, NULL, 10);
1132 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1134 file = AllocateFile(full_path, "r");
1137 if (errno == ENOENT)
1139 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1140 errmsg("\"%s\" is not a valid data directory",
1142 errdetail("File \"%s\" is missing.", full_path)));
1145 (errcode_for_file_access(),
1146 errmsg("could not open file \"%s\": %m", full_path)));
1149 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1152 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1153 errmsg("\"%s\" is not a valid data directory",
1155 errdetail("File \"%s\" does not contain valid data.",
1157 errhint("You might need to initdb.")));
1161 if (my_major != file_major || my_minor != file_minor)
1163 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1164 errmsg("database files are incompatible with server"),
1165 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1166 "which is not compatible with this version %s.",
1167 file_major, file_minor, version_string)));
1170 /*-------------------------------------------------------------------------
1171 * Library preload support
1172 *-------------------------------------------------------------------------
1176 * GUC variables: lists of library names to be preloaded at postmaster
1177 * start and at backend start
1179 char *shared_preload_libraries_string = NULL;
1180 char *local_preload_libraries_string = NULL;
1182 /* Flag telling that we are loading shared_preload_libraries */
1183 bool process_shared_preload_libraries_in_progress = false;
1186 * load the shared libraries listed in 'libraries'
1188 * 'gucname': name of GUC variable, for error reports
1189 * 'restricted': if true, force libraries to be in $libdir/plugins/
1192 load_libraries(const char *libraries, const char *gucname, bool restricted)
1199 if (libraries == NULL || libraries[0] == '\0')
1200 return; /* nothing to do */
1202 /* Need a modifiable copy of string */
1203 rawstring = pstrdup(libraries);
1205 /* Parse string into list of identifiers */
1206 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1208 /* syntax error in list */
1210 list_free(elemlist);
1212 (errcode(ERRCODE_SYNTAX_ERROR),
1213 errmsg("invalid list syntax in parameter \"%s\"",
1219 * Choose notice level: avoid repeat messages when re-loading a library
1220 * that was preloaded into the postmaster. (Only possible in EXEC_BACKEND
1224 if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1230 foreach(l, elemlist)
1232 char *tok = (char *) lfirst(l);
1235 filename = pstrdup(tok);
1236 canonicalize_path(filename);
1237 /* If restricting, insert $libdir/plugins if not mentioned already */
1238 if (restricted && first_dir_separator(filename) == NULL)
1242 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1243 strcpy(expanded, "$libdir/plugins/");
1244 strcat(expanded, filename);
1246 filename = expanded;
1248 load_file(filename, restricted);
1250 (errmsg("loaded library \"%s\"", filename)));
1255 list_free(elemlist);
1259 * process any libraries that should be preloaded at postmaster start
1262 process_shared_preload_libraries(void)
1264 process_shared_preload_libraries_in_progress = true;
1265 load_libraries(shared_preload_libraries_string,
1266 "shared_preload_libraries",
1268 process_shared_preload_libraries_in_progress = false;
1272 * process any libraries that should be preloaded at backend start
1275 process_local_preload_libraries(void)
1277 load_libraries(local_preload_libraries_string,
1278 "local_preload_libraries",
1283 pg_bindtextdomain(const char *domain)
1286 if (my_exec_path[0] != '\0')
1288 char locale_path[MAXPGPATH];
1290 get_locale_path(my_exec_path, locale_path);
1291 bindtextdomain(domain, locale_path);
1292 pg_bind_textdomain_codeset(domain);