1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2011, 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;
235 * GetUserId - get the current effective user ID.
237 * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
242 AssertState(OidIsValid(CurrentUserId));
243 return CurrentUserId;
248 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
253 AssertState(OidIsValid(OuterUserId));
259 SetOuterUserId(Oid userid)
261 AssertState(SecurityRestrictionContext == 0);
262 AssertArg(OidIsValid(userid));
263 OuterUserId = userid;
265 /* We force the effective user ID to match, too */
266 CurrentUserId = userid;
271 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
274 GetSessionUserId(void)
276 AssertState(OidIsValid(SessionUserId));
277 return SessionUserId;
282 SetSessionUserId(Oid userid, bool is_superuser)
284 AssertState(SecurityRestrictionContext == 0);
285 AssertArg(OidIsValid(userid));
286 SessionUserId = userid;
287 SessionUserIsSuperuser = is_superuser;
288 SetRoleIsActive = false;
290 /* We force the effective user IDs to match, too */
291 OuterUserId = userid;
292 CurrentUserId = userid;
297 * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
298 * and the SecurityRestrictionContext flags.
300 * Currently there are two valid bits in SecurityRestrictionContext:
302 * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
303 * that is temporarily changing CurrentUserId via these functions. This is
304 * needed to indicate that the actual value of CurrentUserId is not in sync
305 * with guc.c's internal state, so SET ROLE has to be disallowed.
307 * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
308 * that does not wish to trust called user-defined functions at all. This
309 * bit prevents not only SET ROLE, but various other changes of session state
310 * that normally is unprotected but might possibly be used to subvert the
311 * calling session later. An example is replacing an existing prepared
312 * statement with new code, which will then be executed with the outer
313 * session's permissions when the prepared statement is next used. Since
314 * these restrictions are fairly draconian, we apply them only in contexts
315 * where the called functions are really supposed to be side-effect-free
316 * anyway, such as VACUUM/ANALYZE/REINDEX.
318 * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
319 * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
320 * the new value to be valid. In fact, these routines had better not
321 * ever throw any kind of error. This is because they are used by
322 * StartTransaction and AbortTransaction to save/restore the settings,
323 * and during the first transaction within a backend, the value to be saved
324 * and perhaps restored is indeed invalid. We have to be able to get
325 * through AbortTransaction without asserting in case InitPostgres fails.
328 GetUserIdAndSecContext(Oid *userid, int *sec_context)
330 *userid = CurrentUserId;
331 *sec_context = SecurityRestrictionContext;
335 SetUserIdAndSecContext(Oid userid, int sec_context)
337 CurrentUserId = userid;
338 SecurityRestrictionContext = sec_context;
343 * InLocalUserIdChange - are we inside a local change of CurrentUserId?
346 InLocalUserIdChange(void)
348 return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
352 * InSecurityRestrictedOperation - are we inside a security-restricted command?
355 InSecurityRestrictedOperation(void)
357 return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
362 * These are obsolete versions of Get/SetUserIdAndSecContext that are
363 * only provided for bug-compatibility with some rather dubious code in
364 * pljava. We allow the userid to be set, but only when not inside a
365 * security restriction context.
368 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
370 *userid = CurrentUserId;
371 *sec_def_context = InLocalUserIdChange();
375 SetUserIdAndContext(Oid userid, bool sec_def_context)
377 /* We throw the same error SET ROLE would. */
378 if (InSecurityRestrictedOperation())
380 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
381 errmsg("cannot set parameter \"%s\" within security-restricted operation",
383 CurrentUserId = userid;
385 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
387 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
392 * Check if the authenticated user is a replication role
395 is_authenticated_user_replication_role(void)
400 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(AuthenticatedUserId));
401 if (HeapTupleIsValid(utup))
403 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
404 ReleaseSysCache(utup);
410 * Initialize user identity during normal backend startup
413 InitializeSessionUserId(const char *rolename)
416 Form_pg_authid rform;
420 * Don't do scans if we're bootstrapping, none of the system catalogs
421 * exist yet, and they should be owned by postgres anyway.
423 AssertState(!IsBootstrapProcessingMode());
426 AssertState(!OidIsValid(AuthenticatedUserId));
428 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
429 if (!HeapTupleIsValid(roleTup))
431 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
432 errmsg("role \"%s\" does not exist", rolename)));
434 rform = (Form_pg_authid) GETSTRUCT(roleTup);
435 roleid = HeapTupleGetOid(roleTup);
437 AuthenticatedUserId = roleid;
438 AuthenticatedUserIsSuperuser = rform->rolsuper;
440 /* This sets OuterUserId/CurrentUserId too */
441 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
443 /* Also mark our PGPROC entry with the authenticated user id */
444 /* (We assume this is an atomic store so no lock is needed) */
445 MyProc->roleId = roleid;
448 * These next checks are not enforced when in standalone mode, so that
449 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
450 * rolcanlogin = false;".
452 if (IsUnderPostmaster)
455 * Is role allowed to login at all?
457 if (!rform->rolcanlogin)
459 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
460 errmsg("role \"%s\" is not permitted to log in",
464 * Check connection limit for this role.
466 * There is a race condition here --- we create our PGPROC before
467 * checking for other PGPROCs. If two backends did this at about the
468 * same time, they might both think they were over the limit, while
469 * ideally one should succeed and one fail. Getting that to work
470 * exactly seems more trouble than it is worth, however; instead we
471 * just document that the connection limit is approximate.
473 if (rform->rolconnlimit >= 0 &&
474 !AuthenticatedUserIsSuperuser &&
475 CountUserBackends(roleid) > rform->rolconnlimit)
477 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
478 errmsg("too many connections for role \"%s\"",
482 /* Record username and superuser status as GUC settings too */
483 SetConfigOption("session_authorization", rolename,
484 PGC_BACKEND, PGC_S_OVERRIDE);
485 SetConfigOption("is_superuser",
486 AuthenticatedUserIsSuperuser ? "on" : "off",
487 PGC_INTERNAL, PGC_S_OVERRIDE);
489 ReleaseSysCache(roleTup);
494 * Initialize user identity during special backend startup
497 InitializeSessionUserIdStandalone(void)
500 * This function should only be called in single-user mode and in
501 * autovacuum workers.
503 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
506 AssertState(!OidIsValid(AuthenticatedUserId));
508 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
509 AuthenticatedUserIsSuperuser = true;
511 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
516 * Change session auth ID while running
518 * Only a superuser may set auth ID to something other than himself. Note
519 * that in case of multiple SETs in a single session, the original userid's
520 * superuserness is what matters. But we set the GUC variable is_superuser
521 * to indicate whether the *current* session userid is a superuser.
523 * Note: this is not an especially clean place to do the permission check.
524 * It's OK because the check does not require catalog access and can't
525 * fail during an end-of-transaction GUC reversion, but we may someday
526 * have to push it up into assign_session_authorization.
529 SetSessionAuthorization(Oid userid, bool is_superuser)
531 /* Must have authenticated already, else can't make permission check */
532 AssertState(OidIsValid(AuthenticatedUserId));
534 if (userid != AuthenticatedUserId &&
535 !AuthenticatedUserIsSuperuser)
537 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
538 errmsg("permission denied to set session authorization")));
540 SetSessionUserId(userid, is_superuser);
542 SetConfigOption("is_superuser",
543 is_superuser ? "on" : "off",
544 PGC_INTERNAL, PGC_S_OVERRIDE);
548 * Report current role id
549 * This follows the semantics of SET ROLE, ie return the outer-level ID
550 * not the current effective ID, and return InvalidOid when the setting
551 * is logically SET ROLE NONE.
554 GetCurrentRoleId(void)
563 * Change Role ID while running (SET ROLE)
565 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
566 * session user authorization. In this case the is_superuser argument
569 * When roleid is not InvalidOid, the caller must have checked whether
570 * the session user has permission to become that role. (We cannot check
571 * here because this routine must be able to execute in a failed transaction
572 * to restore a prior value of the ROLE GUC variable.)
575 SetCurrentRoleId(Oid roleid, bool is_superuser)
578 * Get correct info if it's SET ROLE NONE
580 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
581 * SetSessionUserId call will fix everything. This is needed since we
582 * will get called during GUC initialization.
584 if (!OidIsValid(roleid))
586 if (!OidIsValid(SessionUserId))
589 roleid = SessionUserId;
590 is_superuser = SessionUserIsSuperuser;
592 SetRoleIsActive = false;
595 SetRoleIsActive = true;
597 SetOuterUserId(roleid);
599 SetConfigOption("is_superuser",
600 is_superuser ? "on" : "off",
601 PGC_INTERNAL, PGC_S_OVERRIDE);
606 * Get user name from user oid
609 GetUserNameFromId(Oid roleid)
614 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
615 if (!HeapTupleIsValid(tuple))
617 (errcode(ERRCODE_UNDEFINED_OBJECT),
618 errmsg("invalid role OID: %u", roleid)));
620 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
622 ReleaseSysCache(tuple);
627 /*-------------------------------------------------------------------------
628 * Interlock-file support
630 * These routines are used to create both a data-directory lockfile
631 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
632 * Both kinds of files contain the same info:
634 * Owning process' PID
635 * Data directory path
637 * By convention, the owning process' PID is negated if it is a standalone
638 * backend rather than a postmaster. This is just for informational purposes.
639 * The path is also just for informational purposes (so that a socket lockfile
640 * can be more easily traced to the associated postmaster).
642 * A data-directory lockfile can optionally contain a third line, containing
643 * the key and ID for the shared memory block used by this postmaster.
645 * On successful lockfile creation, a proc_exit callback to remove the
646 * lockfile is automatically created.
647 *-------------------------------------------------------------------------
651 * proc_exit callback to remove a lockfile.
654 UnlinkLockFile(int status, Datum filename)
656 char *fname = (char *) DatumGetPointer(filename);
660 if (unlink(fname) != 0)
662 /* Should we complain if the unlink fails? */
671 * filename is the name of the lockfile to create.
672 * amPostmaster is used to determine how to encode the output PID.
673 * isDDLock and refName are used to determine what error message to produce.
676 CreateLockFile(const char *filename, bool amPostmaster,
677 bool isDDLock, const char *refName)
680 char buffer[MAXPGPATH * 2 + 256];
691 * If the PID in the lockfile is our own PID or our parent's or
692 * grandparent's PID, then the file must be stale (probably left over from
693 * a previous system boot cycle). We need to check this because of the
694 * likelihood that a reboot will assign exactly the same PID as we had in
695 * the previous reboot, or one that's only one or two counts larger and
696 * hence the lockfile's PID now refers to an ancestor shell process. We
697 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
698 * via the environment variable PG_GRANDPARENT_PID; this is so that
699 * launching the postmaster via pg_ctl can be just as reliable as
700 * launching it directly. There is no provision for detecting
701 * further-removed ancestor processes, but if the init script is written
702 * carefully then all but the immediate parent shell will be root-owned
703 * processes and so the kill test will fail with EPERM. Note that we
704 * cannot get a false negative this way, because an existing postmaster
705 * would surely never launch a competing postmaster or pg_ctl process
711 my_p_pid = getppid();
715 * Windows hasn't got getppid(), but doesn't need it since it's not using
716 * real kill() either...
721 envvar = getenv("PG_GRANDPARENT_PID");
723 my_gp_pid = atoi(envvar);
728 * We need a loop here because of race conditions. But don't loop forever
729 * (for example, a non-writable $PGDATA directory might cause a failure
730 * that won't go away). 100 tries seems like plenty.
732 for (ntries = 0;; ntries++)
735 * Try to create the lock file --- O_EXCL makes this atomic.
737 * Think not to make the file protection weaker than 0600. See
740 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
742 break; /* Success; exit the retry loop */
745 * Couldn't create the pid file. Probably it already exists.
747 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
749 (errcode_for_file_access(),
750 errmsg("could not create lock file \"%s\": %m",
754 * Read the file to get the old owner's PID. Note race condition
755 * here: file might have been deleted since we tried to create it.
757 fd = open(filename, O_RDONLY, 0600);
761 continue; /* race condition; try again */
763 (errcode_for_file_access(),
764 errmsg("could not open lock file \"%s\": %m",
767 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
769 (errcode_for_file_access(),
770 errmsg("could not read lock file \"%s\": %m",
775 encoded_pid = atoi(buffer);
777 /* if pid < 0, the pid is for postgres, not postmaster */
778 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
781 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
785 * Check to see if the other process still exists
787 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
788 * ignored as false matches.
790 * Normally kill() will fail with ESRCH if the given PID doesn't
793 * We can treat the EPERM-error case as okay because that error
794 * implies that the existing process has a different userid than we
795 * do, which means it cannot be a competing postmaster. A postmaster
796 * cannot successfully attach to a data directory owned by a userid
797 * other than its own. (This is now checked directly in
798 * checkDataDir(), but has been true for a long time because of the
799 * restriction that the data directory isn't group- or
800 * world-accessible.) Also, since we create the lockfiles mode 600,
801 * we'd have failed above if the lockfile belonged to another userid
802 * --- which means that whatever process kill() is reporting about
803 * isn't the one that made the lockfile. (NOTE: this last
804 * consideration is the only one that keeps us from blowing away a
805 * Unix socket file belonging to an instance of Postgres being run by
806 * someone else, at least on machines where /tmp hasn't got a
809 if (other_pid != my_pid && other_pid != my_p_pid &&
810 other_pid != my_gp_pid)
812 if (kill(other_pid, 0) == 0 ||
813 (errno != ESRCH && errno != EPERM))
815 /* lockfile belongs to a live process */
817 (errcode(ERRCODE_LOCK_FILE_EXISTS),
818 errmsg("lock file \"%s\" already exists",
822 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
823 (int) other_pid, refName) :
824 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
825 (int) other_pid, refName)) :
827 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
828 (int) other_pid, refName) :
829 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
830 (int) other_pid, refName))));
835 * No, the creating process did not exist. However, it could be that
836 * the postmaster crashed (or more likely was kill -9'd by a clueless
837 * admin) but has left orphan backends behind. Check for this by
838 * looking to see if there is an associated shmem segment that is
841 * Note: because postmaster.pid is written in multiple steps, we might
842 * not find the shmem ID values in it; we can't treat that as an
852 for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
854 if ((ptr = strchr(ptr, '\n')) == NULL)
860 sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
862 if (PGSharedMemoryIsInUse(id1, id2))
864 (errcode(ERRCODE_LOCK_FILE_EXISTS),
865 errmsg("pre-existing shared memory block "
866 "(key %lu, ID %lu) is still in use",
868 errhint("If you're sure there are no old "
869 "server processes still running, remove "
870 "the shared memory block "
871 "or just delete the file \"%s\".",
877 * Looks like nobody's home. Unlink the file and try again to create
878 * it. Need a loop because of possible race condition against other
881 if (unlink(filename) < 0)
883 (errcode_for_file_access(),
884 errmsg("could not remove old lock file \"%s\": %m",
886 errhint("The file seems accidentally left over, but "
887 "it could not be removed. Please remove the file "
888 "by hand and try again.")));
892 * Successfully created the file, now fill it. See comment in miscadmin.h
893 * about the contents. Note that we write the same info into both datadir
894 * and socket lockfiles; although more stuff may get added to the datadir
897 snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
898 amPostmaster ? (int) my_pid : -((int) my_pid),
902 #ifdef HAVE_UNIX_SOCKETS
903 (*UnixSocketDir != '\0') ? UnixSocketDir : DEFAULT_PGSOCKET_DIR
910 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
912 int save_errno = errno;
916 /* if write didn't set errno, assume problem is no disk space */
917 errno = save_errno ? save_errno : ENOSPC;
919 (errcode_for_file_access(),
920 errmsg("could not write lock file \"%s\": %m", filename)));
922 if (pg_fsync(fd) != 0)
924 int save_errno = errno;
930 (errcode_for_file_access(),
931 errmsg("could not write lock file \"%s\": %m", filename)));
935 int save_errno = errno;
940 (errcode_for_file_access(),
941 errmsg("could not write lock file \"%s\": %m", filename)));
945 * Arrange for automatic removal of lockfile at proc_exit.
947 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
951 * Create the data directory lockfile.
953 * When this is called, we must have already switched the working
954 * directory to DataDir, so we can just use a relative path. This
955 * helps ensure that we are locking the directory we should be.
958 CreateDataDirLockFile(bool amPostmaster)
960 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
964 * Create a lockfile for the specified Unix socket file.
967 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
969 char lockfile[MAXPGPATH];
971 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
972 CreateLockFile(lockfile, amPostmaster, false, socketfile);
973 /* Save name of lockfile for TouchSocketLockFile */
974 strcpy(socketLockFile, lockfile);
978 * TouchSocketLockFile -- mark socket lock file as recently accessed
980 * This routine should be called every so often to ensure that the lock file
981 * has a recent mod or access date. That saves it
982 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
983 * (Another reason we should never have put the socket file in /tmp...)
986 TouchSocketLockFile(void)
988 /* Do nothing if we did not create a socket... */
989 if (socketLockFile[0] != '\0')
992 * utime() is POSIX standard, utimes() is a common alternative; if we
993 * have neither, fall back to actually reading the file (which only
994 * sets the access time not mod time, but that should be enough in
995 * most cases). In all paths, we ignore errors.
998 utime(socketLockFile, NULL);
999 #else /* !HAVE_UTIME */
1001 utimes(socketLockFile, NULL);
1002 #else /* !HAVE_UTIMES */
1006 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1009 read(fd, buffer, sizeof(buffer));
1012 #endif /* HAVE_UTIMES */
1013 #endif /* HAVE_UTIME */
1019 * Add (or replace) a line in the data directory lock file.
1020 * The given string should not include a trailing newline.
1022 * Caution: this erases all following lines. In current usage that is OK
1023 * because lines are added in order. We could improve it if needed.
1026 AddToDataDirLockFile(int target_line, const char *str)
1032 char buffer[BLCKSZ];
1034 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1038 (errcode_for_file_access(),
1039 errmsg("could not open file \"%s\": %m",
1040 DIRECTORY_LOCK_FILE)));
1043 len = read(fd, buffer, sizeof(buffer) - 1);
1047 (errcode_for_file_access(),
1048 errmsg("could not read from file \"%s\": %m",
1049 DIRECTORY_LOCK_FILE)));
1056 * Skip over lines we are not supposed to rewrite.
1059 for (lineno = 1; lineno < target_line; lineno++)
1061 if ((ptr = strchr(ptr, '\n')) == NULL)
1063 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1071 * Write or rewrite the target line.
1073 snprintf(ptr, buffer + sizeof(buffer) - ptr, "%s\n", str);
1076 * And rewrite the data. Since we write in a single kernel call, this
1077 * update should appear atomic to onlookers.
1079 len = strlen(buffer);
1081 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1082 (int) write(fd, buffer, len) != len)
1084 /* if write didn't set errno, assume problem is no disk space */
1088 (errcode_for_file_access(),
1089 errmsg("could not write to file \"%s\": %m",
1090 DIRECTORY_LOCK_FILE)));
1094 if (pg_fsync(fd) != 0)
1097 (errcode_for_file_access(),
1098 errmsg("could not write to file \"%s\": %m",
1099 DIRECTORY_LOCK_FILE)));
1104 (errcode_for_file_access(),
1105 errmsg("could not write to file \"%s\": %m",
1106 DIRECTORY_LOCK_FILE)));
1111 /*-------------------------------------------------------------------------
1112 * Version checking support
1113 *-------------------------------------------------------------------------
1117 * Determine whether the PG_VERSION file in directory `path' indicates
1118 * a data version compatible with the version of this program.
1120 * If compatible, return. Otherwise, ereport(FATAL).
1123 ValidatePgVersion(const char *path)
1125 char full_path[MAXPGPATH];
1133 const char *version_string = PG_VERSION;
1135 my_major = strtol(version_string, &endptr, 10);
1137 my_minor = strtol(endptr + 1, NULL, 10);
1139 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1141 file = AllocateFile(full_path, "r");
1144 if (errno == ENOENT)
1146 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1147 errmsg("\"%s\" is not a valid data directory",
1149 errdetail("File \"%s\" is missing.", full_path)));
1152 (errcode_for_file_access(),
1153 errmsg("could not open file \"%s\": %m", full_path)));
1156 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1159 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1160 errmsg("\"%s\" is not a valid data directory",
1162 errdetail("File \"%s\" does not contain valid data.",
1164 errhint("You might need to initdb.")));
1168 if (my_major != file_major || my_minor != file_minor)
1170 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1171 errmsg("database files are incompatible with server"),
1172 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1173 "which is not compatible with this version %s.",
1174 file_major, file_minor, version_string)));
1177 /*-------------------------------------------------------------------------
1178 * Library preload support
1179 *-------------------------------------------------------------------------
1183 * GUC variables: lists of library names to be preloaded at postmaster
1184 * start and at backend start
1186 char *shared_preload_libraries_string = NULL;
1187 char *local_preload_libraries_string = NULL;
1189 /* Flag telling that we are loading shared_preload_libraries */
1190 bool process_shared_preload_libraries_in_progress = false;
1193 * load the shared libraries listed in 'libraries'
1195 * 'gucname': name of GUC variable, for error reports
1196 * 'restricted': if true, force libraries to be in $libdir/plugins/
1199 load_libraries(const char *libraries, const char *gucname, bool restricted)
1206 if (libraries == NULL || libraries[0] == '\0')
1207 return; /* nothing to do */
1209 /* Need a modifiable copy of string */
1210 rawstring = pstrdup(libraries);
1212 /* Parse string into list of identifiers */
1213 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1215 /* syntax error in list */
1217 list_free(elemlist);
1219 (errcode(ERRCODE_SYNTAX_ERROR),
1220 errmsg("invalid list syntax in parameter \"%s\"",
1226 * Choose notice level: avoid repeat messages when re-loading a library
1227 * that was preloaded into the postmaster. (Only possible in EXEC_BACKEND
1231 if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1237 foreach(l, elemlist)
1239 char *tok = (char *) lfirst(l);
1242 filename = pstrdup(tok);
1243 canonicalize_path(filename);
1244 /* If restricting, insert $libdir/plugins if not mentioned already */
1245 if (restricted && first_dir_separator(filename) == NULL)
1249 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1250 strcpy(expanded, "$libdir/plugins/");
1251 strcat(expanded, filename);
1253 filename = expanded;
1255 load_file(filename, restricted);
1257 (errmsg("loaded library \"%s\"", filename)));
1262 list_free(elemlist);
1266 * process any libraries that should be preloaded at postmaster start
1269 process_shared_preload_libraries(void)
1271 process_shared_preload_libraries_in_progress = true;
1272 load_libraries(shared_preload_libraries_string,
1273 "shared_preload_libraries",
1275 process_shared_preload_libraries_in_progress = false;
1279 * process any libraries that should be preloaded at backend start
1282 process_local_preload_libraries(void)
1284 load_libraries(local_preload_libraries_string,
1285 "local_preload_libraries",
1290 pg_bindtextdomain(const char *domain)
1293 if (my_exec_path[0] != '\0')
1295 char locale_path[MAXPGPATH];
1297 get_locale_path(my_exec_path, locale_path);
1298 bindtextdomain(domain, locale_path);
1299 pg_bind_textdomain_codeset(domain);