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 * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.180 2010/01/02 16:57:56 momjian Exp $
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 "storage/fd.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "utils/builtins.h"
42 #include "utils/guc.h"
43 #include "utils/memutils.h"
44 #include "utils/syscache.h"
47 #define DIRECTORY_LOCK_FILE "postmaster.pid"
49 ProcessingMode Mode = InitProcessing;
51 /* Note: we rely on this to initialize as zeroes */
52 static char socketLockFile[MAXPGPATH];
55 /* ----------------------------------------------------------------
56 * ignoring system indexes support stuff
58 * NOTE: "ignoring system indexes" means we do not use the system indexes
59 * for lookups (either in hardwired catalog accesses or in planner-generated
60 * plans). We do, however, still update the indexes when a catalog
61 * modification is made.
62 * ----------------------------------------------------------------
65 bool IgnoreSystemIndexes = false;
67 /* ----------------------------------------------------------------
68 * system index reindexing support
70 * When we are busy reindexing a system index, this code provides support
71 * for preventing catalog lookups from using that index.
72 * ----------------------------------------------------------------
75 static Oid currentlyReindexedHeap = InvalidOid;
76 static Oid currentlyReindexedIndex = InvalidOid;
79 * ReindexIsProcessingHeap
80 * True if heap specified by OID is currently being reindexed.
83 ReindexIsProcessingHeap(Oid heapOid)
85 return heapOid == currentlyReindexedHeap;
89 * ReindexIsProcessingIndex
90 * True if index specified by OID is currently being reindexed.
93 ReindexIsProcessingIndex(Oid indexOid)
95 return indexOid == currentlyReindexedIndex;
99 * SetReindexProcessing
100 * Set flag that specified heap/index are being reindexed.
103 SetReindexProcessing(Oid heapOid, Oid indexOid)
105 Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
106 /* Reindexing is not re-entrant. */
107 if (OidIsValid(currentlyReindexedIndex))
108 elog(ERROR, "cannot reindex while reindexing");
109 currentlyReindexedHeap = heapOid;
110 currentlyReindexedIndex = indexOid;
114 * ResetReindexProcessing
115 * Unset reindexing status.
118 ResetReindexProcessing(void)
120 currentlyReindexedHeap = InvalidOid;
121 currentlyReindexedIndex = InvalidOid;
124 /* ----------------------------------------------------------------
125 * database path / name support stuff
126 * ----------------------------------------------------------------
130 SetDatabasePath(const char *path)
132 /* This should happen only once per process */
133 Assert(!DatabasePath);
134 DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
138 * Set data directory, but make sure it's an absolute path. Use this,
139 * never set DataDir directly.
142 SetDataDir(const char *dir)
148 /* If presented path is relative, convert to absolute */
149 new = make_absolute_path(dir);
157 * Change working directory to DataDir. Most of the postmaster and backend
158 * code assumes that we are in DataDir so it can use relative paths to access
159 * stuff in and under the data directory. For convenience during path
160 * setup, however, we don't force the chdir to occur during SetDataDir.
163 ChangeToDataDir(void)
165 AssertState(DataDir);
167 if (chdir(DataDir) < 0)
169 (errcode_for_file_access(),
170 errmsg("could not change directory to \"%s\": %m",
175 * If the given pathname isn't already absolute, make it so, interpreting
176 * it relative to the current working directory.
178 * Also canonicalizes the path. The result is always a malloc'd copy.
180 * Note: interpretation of relative-path arguments during postmaster startup
181 * should happen before doing ChangeToDataDir(), else the user will probably
182 * not like the results.
185 make_absolute_path(const char *path)
189 /* Returning null for null input is convenient for some callers */
193 if (!is_absolute_path(path))
201 buf = malloc(buflen);
204 (errcode(ERRCODE_OUT_OF_MEMORY),
205 errmsg("out of memory")));
207 if (getcwd(buf, buflen))
209 else if (errno == ERANGE)
218 elog(FATAL, "could not get current working directory: %m");
222 new = malloc(strlen(buf) + strlen(path) + 2);
225 (errcode(ERRCODE_OUT_OF_MEMORY),
226 errmsg("out of memory")));
227 sprintf(new, "%s/%s", buf, path);
235 (errcode(ERRCODE_OUT_OF_MEMORY),
236 errmsg("out of memory")));
239 /* Make sure punctuation is canonical, too */
240 canonicalize_path(new);
246 /* ----------------------------------------------------------------
249 * We have to track several different values associated with the concept
252 * AuthenticatedUserId is determined at connection start and never changes.
254 * SessionUserId is initially the same as AuthenticatedUserId, but can be
255 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
256 * This is the ID reported by the SESSION_USER SQL function.
258 * OuterUserId is the current user ID in effect at the "outer level" (outside
259 * any transaction or function). This is initially the same as SessionUserId,
260 * but can be changed by SET ROLE to any role that SessionUserId is a
261 * member of. (XXX rename to something like CurrentRoleId?)
263 * CurrentUserId is the current effective user ID; this is the one to use
264 * for all normal permissions-checking purposes. At outer level this will
265 * be the same as OuterUserId, but it changes during calls to SECURITY
266 * DEFINER functions, as well as locally in some specialized commands.
268 * SecurityRestrictionContext holds flags indicating reason(s) for changing
269 * CurrentUserId. In some cases we need to lock down operations that are
270 * not directly controlled by privilege settings, and this provides a
271 * convenient way to do it.
272 * ----------------------------------------------------------------
274 static Oid AuthenticatedUserId = InvalidOid;
275 static Oid SessionUserId = InvalidOid;
276 static Oid OuterUserId = InvalidOid;
277 static Oid CurrentUserId = InvalidOid;
279 /* We also have to remember the superuser state of some of these levels */
280 static bool AuthenticatedUserIsSuperuser = false;
281 static bool SessionUserIsSuperuser = false;
283 static int SecurityRestrictionContext = 0;
285 /* We also remember if a SET ROLE is currently active */
286 static bool SetRoleIsActive = false;
290 * GetUserId - get the current effective user ID.
292 * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
297 AssertState(OidIsValid(CurrentUserId));
298 return CurrentUserId;
303 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
308 AssertState(OidIsValid(OuterUserId));
314 SetOuterUserId(Oid userid)
316 AssertState(SecurityRestrictionContext == 0);
317 AssertArg(OidIsValid(userid));
318 OuterUserId = userid;
320 /* We force the effective user ID to match, too */
321 CurrentUserId = userid;
326 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
329 GetSessionUserId(void)
331 AssertState(OidIsValid(SessionUserId));
332 return SessionUserId;
337 SetSessionUserId(Oid userid, bool is_superuser)
339 AssertState(SecurityRestrictionContext == 0);
340 AssertArg(OidIsValid(userid));
341 SessionUserId = userid;
342 SessionUserIsSuperuser = is_superuser;
343 SetRoleIsActive = false;
345 /* We force the effective user IDs to match, too */
346 OuterUserId = userid;
347 CurrentUserId = userid;
352 * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
353 * and the SecurityRestrictionContext flags.
355 * Currently there are two valid bits in SecurityRestrictionContext:
357 * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
358 * that is temporarily changing CurrentUserId via these functions. This is
359 * needed to indicate that the actual value of CurrentUserId is not in sync
360 * with guc.c's internal state, so SET ROLE has to be disallowed.
362 * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
363 * that does not wish to trust called user-defined functions at all. This
364 * bit prevents not only SET ROLE, but various other changes of session state
365 * that normally is unprotected but might possibly be used to subvert the
366 * calling session later. An example is replacing an existing prepared
367 * statement with new code, which will then be executed with the outer
368 * session's permissions when the prepared statement is next used. Since
369 * these restrictions are fairly draconian, we apply them only in contexts
370 * where the called functions are really supposed to be side-effect-free
371 * anyway, such as VACUUM/ANALYZE/REINDEX.
373 * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
374 * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
375 * the new value to be valid. In fact, these routines had better not
376 * ever throw any kind of error. This is because they are used by
377 * StartTransaction and AbortTransaction to save/restore the settings,
378 * and during the first transaction within a backend, the value to be saved
379 * and perhaps restored is indeed invalid. We have to be able to get
380 * through AbortTransaction without asserting in case InitPostgres fails.
383 GetUserIdAndSecContext(Oid *userid, int *sec_context)
385 *userid = CurrentUserId;
386 *sec_context = SecurityRestrictionContext;
390 SetUserIdAndSecContext(Oid userid, int sec_context)
392 CurrentUserId = userid;
393 SecurityRestrictionContext = sec_context;
398 * InLocalUserIdChange - are we inside a local change of CurrentUserId?
401 InLocalUserIdChange(void)
403 return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
407 * InSecurityRestrictedOperation - are we inside a security-restricted command?
410 InSecurityRestrictedOperation(void)
412 return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
417 * These are obsolete versions of Get/SetUserIdAndSecContext that are
418 * only provided for bug-compatibility with some rather dubious code in
419 * pljava. We allow the userid to be set, but only when not inside a
420 * security restriction context.
423 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
425 *userid = CurrentUserId;
426 *sec_def_context = InLocalUserIdChange();
430 SetUserIdAndContext(Oid userid, bool sec_def_context)
432 /* We throw the same error SET ROLE would. */
433 if (InSecurityRestrictedOperation())
435 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
436 errmsg("cannot set parameter \"%s\" within security-restricted operation",
438 CurrentUserId = userid;
440 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
442 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
447 * Initialize user identity during normal backend startup
450 InitializeSessionUserId(const char *rolename)
453 Form_pg_authid rform;
457 * Don't do scans if we're bootstrapping, none of the system catalogs
458 * exist yet, and they should be owned by postgres anyway.
460 AssertState(!IsBootstrapProcessingMode());
463 AssertState(!OidIsValid(AuthenticatedUserId));
465 roleTup = SearchSysCache(AUTHNAME,
466 PointerGetDatum(rolename),
468 if (!HeapTupleIsValid(roleTup))
470 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
471 errmsg("role \"%s\" does not exist", rolename)));
473 rform = (Form_pg_authid) GETSTRUCT(roleTup);
474 roleid = HeapTupleGetOid(roleTup);
476 AuthenticatedUserId = roleid;
477 AuthenticatedUserIsSuperuser = rform->rolsuper;
479 /* This sets OuterUserId/CurrentUserId too */
480 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
482 /* Also mark our PGPROC entry with the authenticated user id */
483 /* (We assume this is an atomic store so no lock is needed) */
484 MyProc->roleId = roleid;
487 * These next checks are not enforced when in standalone mode, so that
488 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
489 * rolcanlogin = false;".
491 * We do not enforce them for the autovacuum process either.
493 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
496 * Is role allowed to login at all?
498 if (!rform->rolcanlogin)
500 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
501 errmsg("role \"%s\" is not permitted to log in",
505 * Check connection limit for this role.
507 * There is a race condition here --- we create our PGPROC before
508 * checking for other PGPROCs. If two backends did this at about the
509 * same time, they might both think they were over the limit, while
510 * ideally one should succeed and one fail. Getting that to work
511 * exactly seems more trouble than it is worth, however; instead we
512 * just document that the connection limit is approximate.
514 if (rform->rolconnlimit >= 0 &&
515 !AuthenticatedUserIsSuperuser &&
516 CountUserBackends(roleid) > rform->rolconnlimit)
518 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
519 errmsg("too many connections for role \"%s\"",
523 /* Record username and superuser status as GUC settings too */
524 SetConfigOption("session_authorization", rolename,
525 PGC_BACKEND, PGC_S_OVERRIDE);
526 SetConfigOption("is_superuser",
527 AuthenticatedUserIsSuperuser ? "on" : "off",
528 PGC_INTERNAL, PGC_S_OVERRIDE);
530 ReleaseSysCache(roleTup);
535 * Initialize user identity during special backend startup
538 InitializeSessionUserIdStandalone(void)
540 /* This function should only be called in a single-user backend. */
541 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
544 AssertState(!OidIsValid(AuthenticatedUserId));
546 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
547 AuthenticatedUserIsSuperuser = true;
549 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
554 * Change session auth ID while running
556 * Only a superuser may set auth ID to something other than himself. Note
557 * that in case of multiple SETs in a single session, the original userid's
558 * superuserness is what matters. But we set the GUC variable is_superuser
559 * to indicate whether the *current* session userid is a superuser.
561 * Note: this is not an especially clean place to do the permission check.
562 * It's OK because the check does not require catalog access and can't
563 * fail during an end-of-transaction GUC reversion, but we may someday
564 * have to push it up into assign_session_authorization.
567 SetSessionAuthorization(Oid userid, bool is_superuser)
569 /* Must have authenticated already, else can't make permission check */
570 AssertState(OidIsValid(AuthenticatedUserId));
572 if (userid != AuthenticatedUserId &&
573 !AuthenticatedUserIsSuperuser)
575 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
576 errmsg("permission denied to set session authorization")));
578 SetSessionUserId(userid, is_superuser);
580 SetConfigOption("is_superuser",
581 is_superuser ? "on" : "off",
582 PGC_INTERNAL, PGC_S_OVERRIDE);
586 * Report current role id
587 * This follows the semantics of SET ROLE, ie return the outer-level ID
588 * not the current effective ID, and return InvalidOid when the setting
589 * is logically SET ROLE NONE.
592 GetCurrentRoleId(void)
601 * Change Role ID while running (SET ROLE)
603 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
604 * session user authorization. In this case the is_superuser argument
607 * When roleid is not InvalidOid, the caller must have checked whether
608 * the session user has permission to become that role. (We cannot check
609 * here because this routine must be able to execute in a failed transaction
610 * to restore a prior value of the ROLE GUC variable.)
613 SetCurrentRoleId(Oid roleid, bool is_superuser)
616 * Get correct info if it's SET ROLE NONE
618 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
619 * SetSessionUserId call will fix everything. This is needed since we
620 * will get called during GUC initialization.
622 if (!OidIsValid(roleid))
624 if (!OidIsValid(SessionUserId))
627 roleid = SessionUserId;
628 is_superuser = SessionUserIsSuperuser;
630 SetRoleIsActive = false;
633 SetRoleIsActive = true;
635 SetOuterUserId(roleid);
637 SetConfigOption("is_superuser",
638 is_superuser ? "on" : "off",
639 PGC_INTERNAL, PGC_S_OVERRIDE);
644 * Get user name from user oid
647 GetUserNameFromId(Oid roleid)
652 tuple = SearchSysCache(AUTHOID,
653 ObjectIdGetDatum(roleid),
655 if (!HeapTupleIsValid(tuple))
657 (errcode(ERRCODE_UNDEFINED_OBJECT),
658 errmsg("invalid role OID: %u", roleid)));
660 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
662 ReleaseSysCache(tuple);
667 /*-------------------------------------------------------------------------
668 * Interlock-file support
670 * These routines are used to create both a data-directory lockfile
671 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
672 * Both kinds of files contain the same info:
674 * Owning process' PID
675 * Data directory path
677 * By convention, the owning process' PID is negated if it is a standalone
678 * backend rather than a postmaster. This is just for informational purposes.
679 * The path is also just for informational purposes (so that a socket lockfile
680 * can be more easily traced to the associated postmaster).
682 * A data-directory lockfile can optionally contain a third line, containing
683 * the key and ID for the shared memory block used by this postmaster.
685 * On successful lockfile creation, a proc_exit callback to remove the
686 * lockfile is automatically created.
687 *-------------------------------------------------------------------------
691 * proc_exit callback to remove a lockfile.
694 UnlinkLockFile(int status, Datum filename)
696 char *fname = (char *) DatumGetPointer(filename);
700 if (unlink(fname) != 0)
702 /* Should we complain if the unlink fails? */
711 * filename is the name of the lockfile to create.
712 * amPostmaster is used to determine how to encode the output PID.
713 * isDDLock and refName are used to determine what error message to produce.
716 CreateLockFile(const char *filename, bool amPostmaster,
717 bool isDDLock, const char *refName)
720 char buffer[MAXPGPATH + 100];
731 * If the PID in the lockfile is our own PID or our parent's or
732 * grandparent's PID, then the file must be stale (probably left over from
733 * a previous system boot cycle). We need to check this because of the
734 * likelihood that a reboot will assign exactly the same PID as we had in
735 * the previous reboot, or one that's only one or two counts larger and
736 * hence the lockfile's PID now refers to an ancestor shell process. We
737 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
738 * via the environment variable PG_GRANDPARENT_PID; this is so that
739 * launching the postmaster via pg_ctl can be just as reliable as
740 * launching it directly. There is no provision for detecting
741 * further-removed ancestor processes, but if the init script is written
742 * carefully then all but the immediate parent shell will be root-owned
743 * processes and so the kill test will fail with EPERM. Note that we
744 * cannot get a false negative this way, because an existing postmaster
745 * would surely never launch a competing postmaster or pg_ctl process
751 my_p_pid = getppid();
754 * Windows hasn't got getppid(), but doesn't need it since it's not
755 * using real kill() either...
760 envvar = getenv("PG_GRANDPARENT_PID");
762 my_gp_pid = atoi(envvar);
767 * We need a loop here because of race conditions. But don't loop forever
768 * (for example, a non-writable $PGDATA directory might cause a failure
769 * that won't go away). 100 tries seems like plenty.
771 for (ntries = 0;; ntries++)
774 * Try to create the lock file --- O_EXCL makes this atomic.
776 * Think not to make the file protection weaker than 0600. See
779 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
781 break; /* Success; exit the retry loop */
784 * Couldn't create the pid file. Probably it already exists.
786 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
788 (errcode_for_file_access(),
789 errmsg("could not create lock file \"%s\": %m",
793 * Read the file to get the old owner's PID. Note race condition
794 * here: file might have been deleted since we tried to create it.
796 fd = open(filename, O_RDONLY, 0600);
800 continue; /* race condition; try again */
802 (errcode_for_file_access(),
803 errmsg("could not open lock file \"%s\": %m",
806 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
808 (errcode_for_file_access(),
809 errmsg("could not read lock file \"%s\": %m",
814 encoded_pid = atoi(buffer);
816 /* if pid < 0, the pid is for postgres, not postmaster */
817 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
820 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
824 * Check to see if the other process still exists
826 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
827 * ignored as false matches.
829 * Normally kill() will fail with ESRCH if the given PID doesn't
832 * We can treat the EPERM-error case as okay because that error
833 * implies that the existing process has a different userid than we
834 * do, which means it cannot be a competing postmaster. A postmaster
835 * cannot successfully attach to a data directory owned by a userid
836 * other than its own. (This is now checked directly in
837 * checkDataDir(), but has been true for a long time because of the
838 * restriction that the data directory isn't group- or
839 * world-accessible.) Also, since we create the lockfiles mode 600,
840 * we'd have failed above if the lockfile belonged to another userid
841 * --- which means that whatever process kill() is reporting about
842 * isn't the one that made the lockfile. (NOTE: this last
843 * consideration is the only one that keeps us from blowing away a
844 * Unix socket file belonging to an instance of Postgres being run by
845 * someone else, at least on machines where /tmp hasn't got a
848 if (other_pid != my_pid && other_pid != my_p_pid &&
849 other_pid != my_gp_pid)
851 if (kill(other_pid, 0) == 0 ||
852 (errno != ESRCH && errno != EPERM))
854 /* lockfile belongs to a live process */
856 (errcode(ERRCODE_LOCK_FILE_EXISTS),
857 errmsg("lock file \"%s\" already exists",
861 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
862 (int) other_pid, refName) :
863 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
864 (int) other_pid, refName)) :
866 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
867 (int) other_pid, refName) :
868 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
869 (int) other_pid, refName))));
874 * No, the creating process did not exist. However, it could be that
875 * the postmaster crashed (or more likely was kill -9'd by a clueless
876 * admin) but has left orphan backends behind. Check for this by
877 * looking to see if there is an associated shmem segment that is
886 ptr = strchr(buffer, '\n');
888 (ptr = strchr(ptr + 1, '\n')) != NULL)
891 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
893 if (PGSharedMemoryIsInUse(id1, id2))
895 (errcode(ERRCODE_LOCK_FILE_EXISTS),
896 errmsg("pre-existing shared memory block "
897 "(key %lu, ID %lu) is still in use",
899 errhint("If you're sure there are no old "
900 "server processes still running, remove "
901 "the shared memory block "
902 "or just delete the file \"%s\".",
909 * Looks like nobody's home. Unlink the file and try again to create
910 * it. Need a loop because of possible race condition against other
913 if (unlink(filename) < 0)
915 (errcode_for_file_access(),
916 errmsg("could not remove old lock file \"%s\": %m",
918 errhint("The file seems accidentally left over, but "
919 "it could not be removed. Please remove the file "
920 "by hand and try again.")));
924 * Successfully created the file, now fill it.
926 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
927 amPostmaster ? (int) my_pid : -((int) my_pid),
930 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
932 int save_errno = errno;
936 /* if write didn't set errno, assume problem is no disk space */
937 errno = save_errno ? save_errno : ENOSPC;
939 (errcode_for_file_access(),
940 errmsg("could not write lock file \"%s\": %m", filename)));
944 int save_errno = errno;
949 (errcode_for_file_access(),
950 errmsg("could not write lock file \"%s\": %m", filename)));
954 * Arrange for automatic removal of lockfile at proc_exit.
956 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
960 * Create the data directory lockfile.
962 * When this is called, we must have already switched the working
963 * directory to DataDir, so we can just use a relative path. This
964 * helps ensure that we are locking the directory we should be.
967 CreateDataDirLockFile(bool amPostmaster)
969 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
973 * Create a lockfile for the specified Unix socket file.
976 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
978 char lockfile[MAXPGPATH];
980 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
981 CreateLockFile(lockfile, amPostmaster, false, socketfile);
982 /* Save name of lockfile for TouchSocketLockFile */
983 strcpy(socketLockFile, lockfile);
987 * TouchSocketLockFile -- mark socket lock file as recently accessed
989 * This routine should be called every so often to ensure that the lock file
990 * has a recent mod or access date. That saves it
991 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
992 * (Another reason we should never have put the socket file in /tmp...)
995 TouchSocketLockFile(void)
997 /* Do nothing if we did not create a socket... */
998 if (socketLockFile[0] != '\0')
1001 * utime() is POSIX standard, utimes() is a common alternative; if we
1002 * have neither, fall back to actually reading the file (which only
1003 * sets the access time not mod time, but that should be enough in
1004 * most cases). In all paths, we ignore errors.
1007 utime(socketLockFile, NULL);
1008 #else /* !HAVE_UTIME */
1010 utimes(socketLockFile, NULL);
1011 #else /* !HAVE_UTIMES */
1015 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1018 read(fd, buffer, sizeof(buffer));
1021 #endif /* HAVE_UTIMES */
1022 #endif /* HAVE_UTIME */
1027 * Append information about a shared memory segment to the data directory
1030 * This may be called multiple times in the life of a postmaster, if we
1031 * delete and recreate shmem due to backend crash. Therefore, be prepared
1032 * to overwrite existing information. (As of 7.1, a postmaster only creates
1033 * one shm seg at a time; but for the purposes here, if we did have more than
1034 * one then any one of them would do anyway.)
1037 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
1042 char buffer[BLCKSZ];
1044 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1048 (errcode_for_file_access(),
1049 errmsg("could not open file \"%s\": %m",
1050 DIRECTORY_LOCK_FILE)));
1053 len = read(fd, buffer, sizeof(buffer) - 100);
1057 (errcode_for_file_access(),
1058 errmsg("could not read from file \"%s\": %m",
1059 DIRECTORY_LOCK_FILE)));
1066 * Skip over first two lines (PID and path).
1068 ptr = strchr(buffer, '\n');
1070 (ptr = strchr(ptr + 1, '\n')) == NULL)
1072 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1079 * Append key information. Format to try to keep it the same length
1080 * always (trailing junk won't hurt, but might confuse humans).
1082 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1085 * And rewrite the data. Since we write in a single kernel call, this
1086 * update should appear atomic to onlookers.
1088 len = strlen(buffer);
1090 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1091 (int) write(fd, buffer, len) != len)
1093 /* if write didn't set errno, assume problem is no disk space */
1097 (errcode_for_file_access(),
1098 errmsg("could not write to file \"%s\": %m",
1099 DIRECTORY_LOCK_FILE)));
1106 (errcode_for_file_access(),
1107 errmsg("could not write to file \"%s\": %m",
1108 DIRECTORY_LOCK_FILE)));
1113 /*-------------------------------------------------------------------------
1114 * Version checking support
1115 *-------------------------------------------------------------------------
1119 * Determine whether the PG_VERSION file in directory `path' indicates
1120 * a data version compatible with the version of this program.
1122 * If compatible, return. Otherwise, ereport(FATAL).
1125 ValidatePgVersion(const char *path)
1127 char full_path[MAXPGPATH];
1135 const char *version_string = PG_VERSION;
1137 my_major = strtol(version_string, &endptr, 10);
1139 my_minor = strtol(endptr + 1, NULL, 10);
1141 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1143 file = AllocateFile(full_path, "r");
1146 if (errno == ENOENT)
1148 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1149 errmsg("\"%s\" is not a valid data directory",
1151 errdetail("File \"%s\" is missing.", full_path)));
1154 (errcode_for_file_access(),
1155 errmsg("could not open file \"%s\": %m", full_path)));
1158 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1161 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1162 errmsg("\"%s\" is not a valid data directory",
1164 errdetail("File \"%s\" does not contain valid data.",
1166 errhint("You might need to initdb.")));
1170 if (my_major != file_major || my_minor != file_minor)
1172 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1173 errmsg("database files are incompatible with server"),
1174 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1175 "which is not compatible with this version %s.",
1176 file_major, file_minor, version_string)));
1179 /*-------------------------------------------------------------------------
1180 * Library preload support
1181 *-------------------------------------------------------------------------
1185 * GUC variables: lists of library names to be preloaded at postmaster
1186 * start and at backend start
1188 char *shared_preload_libraries_string = NULL;
1189 char *local_preload_libraries_string = NULL;
1191 /* Flag telling that we are loading shared_preload_libraries */
1192 bool process_shared_preload_libraries_in_progress = false;
1195 * load the shared libraries listed in 'libraries'
1197 * 'gucname': name of GUC variable, for error reports
1198 * 'restricted': if true, force libraries to be in $libdir/plugins/
1201 load_libraries(const char *libraries, const char *gucname, bool restricted)
1208 if (libraries == NULL || libraries[0] == '\0')
1209 return; /* nothing to do */
1211 /* Need a modifiable copy of string */
1212 rawstring = pstrdup(libraries);
1214 /* Parse string into list of identifiers */
1215 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1217 /* syntax error in list */
1219 list_free(elemlist);
1221 (errcode(ERRCODE_SYNTAX_ERROR),
1222 errmsg("invalid list syntax in parameter \"%s\"",
1228 * Choose notice level: avoid repeat messages when re-loading a library
1229 * that was preloaded into the postmaster. (Only possible in EXEC_BACKEND
1233 if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1239 foreach(l, elemlist)
1241 char *tok = (char *) lfirst(l);
1244 filename = pstrdup(tok);
1245 canonicalize_path(filename);
1246 /* If restricting, insert $libdir/plugins if not mentioned already */
1247 if (restricted && first_dir_separator(filename) == NULL)
1251 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1252 strcpy(expanded, "$libdir/plugins/");
1253 strcat(expanded, filename);
1255 filename = expanded;
1257 load_file(filename, restricted);
1259 (errmsg("loaded library \"%s\"", filename)));
1264 list_free(elemlist);
1268 * process any libraries that should be preloaded at postmaster start
1271 process_shared_preload_libraries(void)
1273 process_shared_preload_libraries_in_progress = true;
1274 load_libraries(shared_preload_libraries_string,
1275 "shared_preload_libraries",
1277 process_shared_preload_libraries_in_progress = false;
1281 * process any libraries that should be preloaded at backend start
1284 process_local_preload_libraries(void)
1286 load_libraries(local_preload_libraries_string,
1287 "local_preload_libraries",
1292 pg_bindtextdomain(const char *domain)
1295 if (my_exec_path[0] != '\0')
1297 char locale_path[MAXPGPATH];
1299 get_locale_path(my_exec_path, locale_path);
1300 bindtextdomain(domain, locale_path);
1301 pg_bind_textdomain_codeset(domain);