1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2012, 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 /* List of lock files to be removed at proc exit */
53 static List *lock_files = NIL;
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 Unix-socket-file lockfiles ($SOCKFILE.lock).
632 * Both kinds of files contain the same info initially, although we can add
633 * more information to a data-directory lockfile after it's created, using
634 * AddToDataDirLockFile(). See miscadmin.h for documentation of the contents
635 * of these lockfiles.
637 * On successful lockfile creation, a proc_exit callback to remove the
638 * lockfile is automatically created.
639 *-------------------------------------------------------------------------
643 * proc_exit callback to remove lockfiles.
646 UnlinkLockFiles(int status, Datum arg)
650 foreach(l, lock_files)
652 char *curfile = (char *) lfirst(l);
655 /* Should we complain if the unlink fails? */
657 /* Since we're about to exit, no need to reclaim storage */
664 * filename is the path name of the lockfile to create.
665 * amPostmaster is used to determine how to encode the output PID.
666 * socketDir is the Unix socket directory path to include (possibly empty).
667 * isDDLock and refName are used to determine what error message to produce.
670 CreateLockFile(const char *filename, bool amPostmaster,
671 const char *socketDir,
672 bool isDDLock, const char *refName)
675 char buffer[MAXPGPATH * 2 + 256];
686 * If the PID in the lockfile is our own PID or our parent's or
687 * grandparent's PID, then the file must be stale (probably left over from
688 * a previous system boot cycle). We need to check this because of the
689 * likelihood that a reboot will assign exactly the same PID as we had in
690 * the previous reboot, or one that's only one or two counts larger and
691 * hence the lockfile's PID now refers to an ancestor shell process. We
692 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
693 * via the environment variable PG_GRANDPARENT_PID; this is so that
694 * launching the postmaster via pg_ctl can be just as reliable as
695 * launching it directly. There is no provision for detecting
696 * further-removed ancestor processes, but if the init script is written
697 * carefully then all but the immediate parent shell will be root-owned
698 * processes and so the kill test will fail with EPERM. Note that we
699 * cannot get a false negative this way, because an existing postmaster
700 * would surely never launch a competing postmaster or pg_ctl process
706 my_p_pid = getppid();
710 * Windows hasn't got getppid(), but doesn't need it since it's not using
711 * real kill() either...
716 envvar = getenv("PG_GRANDPARENT_PID");
718 my_gp_pid = atoi(envvar);
723 * We need a loop here because of race conditions. But don't loop forever
724 * (for example, a non-writable $PGDATA directory might cause a failure
725 * that won't go away). 100 tries seems like plenty.
727 for (ntries = 0;; ntries++)
730 * Try to create the lock file --- O_EXCL makes this atomic.
732 * Think not to make the file protection weaker than 0600. See
735 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
737 break; /* Success; exit the retry loop */
740 * Couldn't create the pid file. Probably it already exists.
742 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
744 (errcode_for_file_access(),
745 errmsg("could not create lock file \"%s\": %m",
749 * Read the file to get the old owner's PID. Note race condition
750 * here: file might have been deleted since we tried to create it.
752 fd = open(filename, O_RDONLY, 0600);
756 continue; /* race condition; try again */
758 (errcode_for_file_access(),
759 errmsg("could not open lock file \"%s\": %m",
762 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
764 (errcode_for_file_access(),
765 errmsg("could not read lock file \"%s\": %m",
772 (errcode(ERRCODE_LOCK_FILE_EXISTS),
773 errmsg("lock file \"%s\" is empty", filename),
774 errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
778 encoded_pid = atoi(buffer);
780 /* if pid < 0, the pid is for postgres, not postmaster */
781 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
784 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
788 * Check to see if the other process still exists
790 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
791 * ignored as false matches.
793 * Normally kill() will fail with ESRCH if the given PID doesn't
796 * We can treat the EPERM-error case as okay because that error
797 * implies that the existing process has a different userid than we
798 * do, which means it cannot be a competing postmaster. A postmaster
799 * cannot successfully attach to a data directory owned by a userid
800 * other than its own. (This is now checked directly in
801 * checkDataDir(), but has been true for a long time because of the
802 * restriction that the data directory isn't group- or
803 * world-accessible.) Also, since we create the lockfiles mode 600,
804 * we'd have failed above if the lockfile belonged to another userid
805 * --- which means that whatever process kill() is reporting about
806 * isn't the one that made the lockfile. (NOTE: this last
807 * consideration is the only one that keeps us from blowing away a
808 * Unix socket file belonging to an instance of Postgres being run by
809 * someone else, at least on machines where /tmp hasn't got a
812 if (other_pid != my_pid && other_pid != my_p_pid &&
813 other_pid != my_gp_pid)
815 if (kill(other_pid, 0) == 0 ||
816 (errno != ESRCH && errno != EPERM))
818 /* lockfile belongs to a live process */
820 (errcode(ERRCODE_LOCK_FILE_EXISTS),
821 errmsg("lock file \"%s\" already exists",
825 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
826 (int) other_pid, refName) :
827 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
828 (int) other_pid, refName)) :
830 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
831 (int) other_pid, refName) :
832 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
833 (int) other_pid, refName))));
838 * No, the creating process did not exist. However, it could be that
839 * the postmaster crashed (or more likely was kill -9'd by a clueless
840 * admin) but has left orphan backends behind. Check for this by
841 * looking to see if there is an associated shmem segment that is
844 * Note: because postmaster.pid is written in multiple steps, we might
845 * not find the shmem ID values in it; we can't treat that as an
855 for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
857 if ((ptr = strchr(ptr, '\n')) == NULL)
863 sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
865 if (PGSharedMemoryIsInUse(id1, id2))
867 (errcode(ERRCODE_LOCK_FILE_EXISTS),
868 errmsg("pre-existing shared memory block "
869 "(key %lu, ID %lu) is still in use",
871 errhint("If you're sure there are no old "
872 "server processes still running, remove "
873 "the shared memory block "
874 "or just delete the file \"%s\".",
880 * Looks like nobody's home. Unlink the file and try again to create
881 * it. Need a loop because of possible race condition against other
884 if (unlink(filename) < 0)
886 (errcode_for_file_access(),
887 errmsg("could not remove old lock file \"%s\": %m",
889 errhint("The file seems accidentally left over, but "
890 "it could not be removed. Please remove the file "
891 "by hand and try again.")));
895 * Successfully created the file, now fill it. See comment in miscadmin.h
896 * about the contents. Note that we write the same info into both datadir
897 * and socket lockfiles; although more stuff may get added to the datadir
900 snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
901 amPostmaster ? (int) my_pid : -((int) my_pid),
908 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
910 int save_errno = errno;
914 /* if write didn't set errno, assume problem is no disk space */
915 errno = save_errno ? save_errno : ENOSPC;
917 (errcode_for_file_access(),
918 errmsg("could not write lock file \"%s\": %m", filename)));
920 if (pg_fsync(fd) != 0)
922 int save_errno = errno;
928 (errcode_for_file_access(),
929 errmsg("could not write lock file \"%s\": %m", filename)));
933 int save_errno = errno;
938 (errcode_for_file_access(),
939 errmsg("could not write lock file \"%s\": %m", filename)));
943 * Arrange to unlink the lock file(s) at proc_exit. If this is the
944 * first one, set up the on_proc_exit function to do it; then add this
945 * lock file to the list of files to unlink.
947 if (lock_files == NIL)
948 on_proc_exit(UnlinkLockFiles, 0);
950 lock_files = lappend(lock_files, pstrdup(filename));
954 * Create the data directory lockfile.
956 * When this is called, we must have already switched the working
957 * directory to DataDir, so we can just use a relative path. This
958 * helps ensure that we are locking the directory we should be.
960 * Note that the socket directory path line is initially written as empty.
961 * postmaster.c will rewrite it upon creating the first Unix socket.
964 CreateDataDirLockFile(bool amPostmaster)
966 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
970 * Create a lockfile for the specified Unix socket file.
973 CreateSocketLockFile(const char *socketfile, bool amPostmaster,
974 const char *socketDir)
976 char lockfile[MAXPGPATH];
978 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
979 CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
983 * TouchSocketLockFiles -- mark socket lock files as recently accessed
985 * This routine should be called every so often to ensure that the socket
986 * lock files have a recent mod or access date. That saves them
987 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
988 * (Another reason we should never have put the socket file in /tmp...)
991 TouchSocketLockFiles(void)
995 foreach(l, lock_files)
997 char *socketLockFile = (char *) lfirst(l);
999 /* No need to touch the data directory lock file, we trust */
1000 if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1004 * utime() is POSIX standard, utimes() is a common alternative; if we
1005 * have neither, fall back to actually reading the file (which only
1006 * sets the access time not mod time, but that should be enough in
1007 * most cases). In all paths, we ignore errors.
1010 utime(socketLockFile, NULL);
1011 #else /* !HAVE_UTIME */
1013 utimes(socketLockFile, NULL);
1014 #else /* !HAVE_UTIMES */
1018 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1021 read(fd, buffer, sizeof(buffer));
1024 #endif /* HAVE_UTIMES */
1025 #endif /* HAVE_UTIME */
1031 * Add (or replace) a line in the data directory lock file.
1032 * The given string should not include a trailing newline.
1034 * Note: because we don't truncate the file, if we were to rewrite a line
1035 * with less data than it had before, there would be garbage after the last
1036 * line. We don't ever actually do that, so not worth adding another kernel
1037 * call to cover the possibility.
1040 AddToDataDirLockFile(int target_line, const char *str)
1047 char srcbuffer[BLCKSZ];
1048 char destbuffer[BLCKSZ];
1050 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1054 (errcode_for_file_access(),
1055 errmsg("could not open file \"%s\": %m",
1056 DIRECTORY_LOCK_FILE)));
1059 len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1063 (errcode_for_file_access(),
1064 errmsg("could not read from file \"%s\": %m",
1065 DIRECTORY_LOCK_FILE)));
1069 srcbuffer[len] = '\0';
1072 * Advance over lines we are not supposed to rewrite, then copy them
1076 for (lineno = 1; lineno < target_line; lineno++)
1078 if ((srcptr = strchr(srcptr, '\n')) == NULL)
1080 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1086 memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1087 destptr = destbuffer + (srcptr - srcbuffer);
1090 * Write or rewrite the target line.
1092 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1093 destptr += strlen(destptr);
1096 * If there are more lines in the old file, append them to destbuffer.
1098 if ((srcptr = strchr(srcptr, '\n')) != NULL)
1101 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1106 * And rewrite the data. Since we write in a single kernel call, this
1107 * update should appear atomic to onlookers.
1109 len = strlen(destbuffer);
1111 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1112 (int) write(fd, destbuffer, len) != len)
1114 /* if write didn't set errno, assume problem is no disk space */
1118 (errcode_for_file_access(),
1119 errmsg("could not write to file \"%s\": %m",
1120 DIRECTORY_LOCK_FILE)));
1124 if (pg_fsync(fd) != 0)
1127 (errcode_for_file_access(),
1128 errmsg("could not write to file \"%s\": %m",
1129 DIRECTORY_LOCK_FILE)));
1134 (errcode_for_file_access(),
1135 errmsg("could not write to file \"%s\": %m",
1136 DIRECTORY_LOCK_FILE)));
1141 /*-------------------------------------------------------------------------
1142 * Version checking support
1143 *-------------------------------------------------------------------------
1147 * Determine whether the PG_VERSION file in directory `path' indicates
1148 * a data version compatible with the version of this program.
1150 * If compatible, return. Otherwise, ereport(FATAL).
1153 ValidatePgVersion(const char *path)
1155 char full_path[MAXPGPATH];
1163 const char *version_string = PG_VERSION;
1165 my_major = strtol(version_string, &endptr, 10);
1167 my_minor = strtol(endptr + 1, NULL, 10);
1169 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1171 file = AllocateFile(full_path, "r");
1174 if (errno == ENOENT)
1176 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1177 errmsg("\"%s\" is not a valid data directory",
1179 errdetail("File \"%s\" is missing.", full_path)));
1182 (errcode_for_file_access(),
1183 errmsg("could not open file \"%s\": %m", full_path)));
1186 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1189 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1190 errmsg("\"%s\" is not a valid data directory",
1192 errdetail("File \"%s\" does not contain valid data.",
1194 errhint("You might need to initdb.")));
1198 if (my_major != file_major || my_minor != file_minor)
1200 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1201 errmsg("database files are incompatible with server"),
1202 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1203 "which is not compatible with this version %s.",
1204 file_major, file_minor, version_string)));
1207 /*-------------------------------------------------------------------------
1208 * Library preload support
1209 *-------------------------------------------------------------------------
1213 * GUC variables: lists of library names to be preloaded at postmaster
1214 * start and at backend start
1216 char *shared_preload_libraries_string = NULL;
1217 char *local_preload_libraries_string = NULL;
1219 /* Flag telling that we are loading shared_preload_libraries */
1220 bool process_shared_preload_libraries_in_progress = false;
1223 * load the shared libraries listed in 'libraries'
1225 * 'gucname': name of GUC variable, for error reports
1226 * 'restricted': if true, force libraries to be in $libdir/plugins/
1229 load_libraries(const char *libraries, const char *gucname, bool restricted)
1236 if (libraries == NULL || libraries[0] == '\0')
1237 return; /* nothing to do */
1239 /* Need a modifiable copy of string */
1240 rawstring = pstrdup(libraries);
1242 /* Parse string into list of identifiers */
1243 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1245 /* syntax error in list */
1247 list_free(elemlist);
1249 (errcode(ERRCODE_SYNTAX_ERROR),
1250 errmsg("invalid list syntax in parameter \"%s\"",
1256 * Choose notice level: avoid repeat messages when re-loading a library
1257 * that was preloaded into the postmaster. (Only possible in EXEC_BACKEND
1261 if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1267 foreach(l, elemlist)
1269 char *tok = (char *) lfirst(l);
1272 filename = pstrdup(tok);
1273 canonicalize_path(filename);
1274 /* If restricting, insert $libdir/plugins if not mentioned already */
1275 if (restricted && first_dir_separator(filename) == NULL)
1279 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1280 strcpy(expanded, "$libdir/plugins/");
1281 strcat(expanded, filename);
1283 filename = expanded;
1285 load_file(filename, restricted);
1287 (errmsg("loaded library \"%s\"", filename)));
1292 list_free(elemlist);
1296 * process any libraries that should be preloaded at postmaster start
1299 process_shared_preload_libraries(void)
1301 process_shared_preload_libraries_in_progress = true;
1302 load_libraries(shared_preload_libraries_string,
1303 "shared_preload_libraries",
1305 process_shared_preload_libraries_in_progress = false;
1309 * process any libraries that should be preloaded at backend start
1312 process_local_preload_libraries(void)
1314 load_libraries(local_preload_libraries_string,
1315 "local_preload_libraries",
1320 pg_bindtextdomain(const char *domain)
1323 if (my_exec_path[0] != '\0')
1325 char locale_path[MAXPGPATH];
1327 get_locale_path(my_exec_path, locale_path);
1328 bindtextdomain(domain, locale_path);
1329 pg_bind_textdomain_codeset(domain);