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.185 2010/08/16 17:32:46 tgl 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;
68 /* ----------------------------------------------------------------
69 * database path / name support stuff
70 * ----------------------------------------------------------------
74 SetDatabasePath(const char *path)
76 /* This should happen only once per process */
77 Assert(!DatabasePath);
78 DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
82 * Set data directory, but make sure it's an absolute path. Use this,
83 * never set DataDir directly.
86 SetDataDir(const char *dir)
92 /* If presented path is relative, convert to absolute */
93 new = make_absolute_path(dir);
101 * Change working directory to DataDir. Most of the postmaster and backend
102 * code assumes that we are in DataDir so it can use relative paths to access
103 * stuff in and under the data directory. For convenience during path
104 * setup, however, we don't force the chdir to occur during SetDataDir.
107 ChangeToDataDir(void)
109 AssertState(DataDir);
111 if (chdir(DataDir) < 0)
113 (errcode_for_file_access(),
114 errmsg("could not change directory to \"%s\": %m",
119 * If the given pathname isn't already absolute, make it so, interpreting
120 * it relative to the current working directory.
122 * Also canonicalizes the path. The result is always a malloc'd copy.
124 * Note: interpretation of relative-path arguments during postmaster startup
125 * should happen before doing ChangeToDataDir(), else the user will probably
126 * not like the results.
129 make_absolute_path(const char *path)
133 /* Returning null for null input is convenient for some callers */
137 if (!is_absolute_path(path))
145 buf = malloc(buflen);
148 (errcode(ERRCODE_OUT_OF_MEMORY),
149 errmsg("out of memory")));
151 if (getcwd(buf, buflen))
153 else if (errno == ERANGE)
162 elog(FATAL, "could not get current working directory: %m");
166 new = malloc(strlen(buf) + strlen(path) + 2);
169 (errcode(ERRCODE_OUT_OF_MEMORY),
170 errmsg("out of memory")));
171 sprintf(new, "%s/%s", buf, path);
179 (errcode(ERRCODE_OUT_OF_MEMORY),
180 errmsg("out of memory")));
183 /* Make sure punctuation is canonical, too */
184 canonicalize_path(new);
190 /* ----------------------------------------------------------------
193 * We have to track several different values associated with the concept
196 * AuthenticatedUserId is determined at connection start and never changes.
198 * SessionUserId is initially the same as AuthenticatedUserId, but can be
199 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
200 * This is the ID reported by the SESSION_USER SQL function.
202 * OuterUserId is the current user ID in effect at the "outer level" (outside
203 * any transaction or function). This is initially the same as SessionUserId,
204 * but can be changed by SET ROLE to any role that SessionUserId is a
205 * member of. (XXX rename to something like CurrentRoleId?)
207 * CurrentUserId is the current effective user ID; this is the one to use
208 * for all normal permissions-checking purposes. At outer level this will
209 * be the same as OuterUserId, but it changes during calls to SECURITY
210 * DEFINER functions, as well as locally in some specialized commands.
212 * SecurityRestrictionContext holds flags indicating reason(s) for changing
213 * CurrentUserId. In some cases we need to lock down operations that are
214 * not directly controlled by privilege settings, and this provides a
215 * convenient way to do it.
216 * ----------------------------------------------------------------
218 static Oid AuthenticatedUserId = InvalidOid;
219 static Oid SessionUserId = InvalidOid;
220 static Oid OuterUserId = InvalidOid;
221 static Oid CurrentUserId = InvalidOid;
223 /* We also have to remember the superuser state of some of these levels */
224 static bool AuthenticatedUserIsSuperuser = false;
225 static bool SessionUserIsSuperuser = false;
227 static int SecurityRestrictionContext = 0;
229 /* We also remember if a SET ROLE is currently active */
230 static bool SetRoleIsActive = false;
234 * GetUserId - get the current effective user ID.
236 * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
241 AssertState(OidIsValid(CurrentUserId));
242 return CurrentUserId;
247 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
252 AssertState(OidIsValid(OuterUserId));
258 SetOuterUserId(Oid userid)
260 AssertState(SecurityRestrictionContext == 0);
261 AssertArg(OidIsValid(userid));
262 OuterUserId = userid;
264 /* We force the effective user ID to match, too */
265 CurrentUserId = userid;
270 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
273 GetSessionUserId(void)
275 AssertState(OidIsValid(SessionUserId));
276 return SessionUserId;
281 SetSessionUserId(Oid userid, bool is_superuser)
283 AssertState(SecurityRestrictionContext == 0);
284 AssertArg(OidIsValid(userid));
285 SessionUserId = userid;
286 SessionUserIsSuperuser = is_superuser;
287 SetRoleIsActive = false;
289 /* We force the effective user IDs to match, too */
290 OuterUserId = userid;
291 CurrentUserId = userid;
296 * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
297 * and the SecurityRestrictionContext flags.
299 * Currently there are two valid bits in SecurityRestrictionContext:
301 * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
302 * that is temporarily changing CurrentUserId via these functions. This is
303 * needed to indicate that the actual value of CurrentUserId is not in sync
304 * with guc.c's internal state, so SET ROLE has to be disallowed.
306 * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
307 * that does not wish to trust called user-defined functions at all. This
308 * bit prevents not only SET ROLE, but various other changes of session state
309 * that normally is unprotected but might possibly be used to subvert the
310 * calling session later. An example is replacing an existing prepared
311 * statement with new code, which will then be executed with the outer
312 * session's permissions when the prepared statement is next used. Since
313 * these restrictions are fairly draconian, we apply them only in contexts
314 * where the called functions are really supposed to be side-effect-free
315 * anyway, such as VACUUM/ANALYZE/REINDEX.
317 * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
318 * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
319 * the new value to be valid. In fact, these routines had better not
320 * ever throw any kind of error. This is because they are used by
321 * StartTransaction and AbortTransaction to save/restore the settings,
322 * and during the first transaction within a backend, the value to be saved
323 * and perhaps restored is indeed invalid. We have to be able to get
324 * through AbortTransaction without asserting in case InitPostgres fails.
327 GetUserIdAndSecContext(Oid *userid, int *sec_context)
329 *userid = CurrentUserId;
330 *sec_context = SecurityRestrictionContext;
334 SetUserIdAndSecContext(Oid userid, int sec_context)
336 CurrentUserId = userid;
337 SecurityRestrictionContext = sec_context;
342 * InLocalUserIdChange - are we inside a local change of CurrentUserId?
345 InLocalUserIdChange(void)
347 return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
351 * InSecurityRestrictedOperation - are we inside a security-restricted command?
354 InSecurityRestrictedOperation(void)
356 return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
361 * These are obsolete versions of Get/SetUserIdAndSecContext that are
362 * only provided for bug-compatibility with some rather dubious code in
363 * pljava. We allow the userid to be set, but only when not inside a
364 * security restriction context.
367 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
369 *userid = CurrentUserId;
370 *sec_def_context = InLocalUserIdChange();
374 SetUserIdAndContext(Oid userid, bool sec_def_context)
376 /* We throw the same error SET ROLE would. */
377 if (InSecurityRestrictedOperation())
379 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
380 errmsg("cannot set parameter \"%s\" within security-restricted operation",
382 CurrentUserId = userid;
384 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
386 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
391 * Initialize user identity during normal backend startup
394 InitializeSessionUserId(const char *rolename)
397 Form_pg_authid rform;
401 * Don't do scans if we're bootstrapping, none of the system catalogs
402 * exist yet, and they should be owned by postgres anyway.
404 AssertState(!IsBootstrapProcessingMode());
407 AssertState(!OidIsValid(AuthenticatedUserId));
409 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
410 if (!HeapTupleIsValid(roleTup))
412 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
413 errmsg("role \"%s\" does not exist", rolename)));
415 rform = (Form_pg_authid) GETSTRUCT(roleTup);
416 roleid = HeapTupleGetOid(roleTup);
418 AuthenticatedUserId = roleid;
419 AuthenticatedUserIsSuperuser = rform->rolsuper;
421 /* This sets OuterUserId/CurrentUserId too */
422 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
424 /* Also mark our PGPROC entry with the authenticated user id */
425 /* (We assume this is an atomic store so no lock is needed) */
426 MyProc->roleId = roleid;
429 * These next checks are not enforced when in standalone mode, so that
430 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
431 * rolcanlogin = false;".
433 if (IsUnderPostmaster)
436 * Is role allowed to login at all?
438 if (!rform->rolcanlogin)
440 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
441 errmsg("role \"%s\" is not permitted to log in",
445 * Check connection limit for this role.
447 * There is a race condition here --- we create our PGPROC before
448 * checking for other PGPROCs. If two backends did this at about the
449 * same time, they might both think they were over the limit, while
450 * ideally one should succeed and one fail. Getting that to work
451 * exactly seems more trouble than it is worth, however; instead we
452 * just document that the connection limit is approximate.
454 if (rform->rolconnlimit >= 0 &&
455 !AuthenticatedUserIsSuperuser &&
456 CountUserBackends(roleid) > rform->rolconnlimit)
458 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
459 errmsg("too many connections for role \"%s\"",
463 /* Record username and superuser status as GUC settings too */
464 SetConfigOption("session_authorization", rolename,
465 PGC_BACKEND, PGC_S_OVERRIDE);
466 SetConfigOption("is_superuser",
467 AuthenticatedUserIsSuperuser ? "on" : "off",
468 PGC_INTERNAL, PGC_S_OVERRIDE);
470 ReleaseSysCache(roleTup);
475 * Initialize user identity during special backend startup
478 InitializeSessionUserIdStandalone(void)
481 * This function should only be called in single-user mode and in
482 * autovacuum workers.
484 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
487 AssertState(!OidIsValid(AuthenticatedUserId));
489 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
490 AuthenticatedUserIsSuperuser = true;
492 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
497 * Change session auth ID while running
499 * Only a superuser may set auth ID to something other than himself. Note
500 * that in case of multiple SETs in a single session, the original userid's
501 * superuserness is what matters. But we set the GUC variable is_superuser
502 * to indicate whether the *current* session userid is a superuser.
504 * Note: this is not an especially clean place to do the permission check.
505 * It's OK because the check does not require catalog access and can't
506 * fail during an end-of-transaction GUC reversion, but we may someday
507 * have to push it up into assign_session_authorization.
510 SetSessionAuthorization(Oid userid, bool is_superuser)
512 /* Must have authenticated already, else can't make permission check */
513 AssertState(OidIsValid(AuthenticatedUserId));
515 if (userid != AuthenticatedUserId &&
516 !AuthenticatedUserIsSuperuser)
518 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
519 errmsg("permission denied to set session authorization")));
521 SetSessionUserId(userid, is_superuser);
523 SetConfigOption("is_superuser",
524 is_superuser ? "on" : "off",
525 PGC_INTERNAL, PGC_S_OVERRIDE);
529 * Report current role id
530 * This follows the semantics of SET ROLE, ie return the outer-level ID
531 * not the current effective ID, and return InvalidOid when the setting
532 * is logically SET ROLE NONE.
535 GetCurrentRoleId(void)
544 * Change Role ID while running (SET ROLE)
546 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
547 * session user authorization. In this case the is_superuser argument
550 * When roleid is not InvalidOid, the caller must have checked whether
551 * the session user has permission to become that role. (We cannot check
552 * here because this routine must be able to execute in a failed transaction
553 * to restore a prior value of the ROLE GUC variable.)
556 SetCurrentRoleId(Oid roleid, bool is_superuser)
559 * Get correct info if it's SET ROLE NONE
561 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
562 * SetSessionUserId call will fix everything. This is needed since we
563 * will get called during GUC initialization.
565 if (!OidIsValid(roleid))
567 if (!OidIsValid(SessionUserId))
570 roleid = SessionUserId;
571 is_superuser = SessionUserIsSuperuser;
573 SetRoleIsActive = false;
576 SetRoleIsActive = true;
578 SetOuterUserId(roleid);
580 SetConfigOption("is_superuser",
581 is_superuser ? "on" : "off",
582 PGC_INTERNAL, PGC_S_OVERRIDE);
587 * Get user name from user oid
590 GetUserNameFromId(Oid roleid)
595 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
596 if (!HeapTupleIsValid(tuple))
598 (errcode(ERRCODE_UNDEFINED_OBJECT),
599 errmsg("invalid role OID: %u", roleid)));
601 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
603 ReleaseSysCache(tuple);
608 /*-------------------------------------------------------------------------
609 * Interlock-file support
611 * These routines are used to create both a data-directory lockfile
612 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
613 * Both kinds of files contain the same info:
615 * Owning process' PID
616 * Data directory path
618 * By convention, the owning process' PID is negated if it is a standalone
619 * backend rather than a postmaster. This is just for informational purposes.
620 * The path is also just for informational purposes (so that a socket lockfile
621 * can be more easily traced to the associated postmaster).
623 * A data-directory lockfile can optionally contain a third line, containing
624 * the key and ID for the shared memory block used by this postmaster.
626 * On successful lockfile creation, a proc_exit callback to remove the
627 * lockfile is automatically created.
628 *-------------------------------------------------------------------------
632 * proc_exit callback to remove a lockfile.
635 UnlinkLockFile(int status, Datum filename)
637 char *fname = (char *) DatumGetPointer(filename);
641 if (unlink(fname) != 0)
643 /* Should we complain if the unlink fails? */
652 * filename is the name of the lockfile to create.
653 * amPostmaster is used to determine how to encode the output PID.
654 * isDDLock and refName are used to determine what error message to produce.
657 CreateLockFile(const char *filename, bool amPostmaster,
658 bool isDDLock, const char *refName)
661 char buffer[MAXPGPATH + 100];
672 * If the PID in the lockfile is our own PID or our parent's or
673 * grandparent's PID, then the file must be stale (probably left over from
674 * a previous system boot cycle). We need to check this because of the
675 * likelihood that a reboot will assign exactly the same PID as we had in
676 * the previous reboot, or one that's only one or two counts larger and
677 * hence the lockfile's PID now refers to an ancestor shell process. We
678 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
679 * via the environment variable PG_GRANDPARENT_PID; this is so that
680 * launching the postmaster via pg_ctl can be just as reliable as
681 * launching it directly. There is no provision for detecting
682 * further-removed ancestor processes, but if the init script is written
683 * carefully then all but the immediate parent shell will be root-owned
684 * processes and so the kill test will fail with EPERM. Note that we
685 * cannot get a false negative this way, because an existing postmaster
686 * would surely never launch a competing postmaster or pg_ctl process
692 my_p_pid = getppid();
696 * Windows hasn't got getppid(), but doesn't need it since it's not using
697 * real kill() either...
702 envvar = getenv("PG_GRANDPARENT_PID");
704 my_gp_pid = atoi(envvar);
709 * We need a loop here because of race conditions. But don't loop forever
710 * (for example, a non-writable $PGDATA directory might cause a failure
711 * that won't go away). 100 tries seems like plenty.
713 for (ntries = 0;; ntries++)
716 * Try to create the lock file --- O_EXCL makes this atomic.
718 * Think not to make the file protection weaker than 0600. See
721 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
723 break; /* Success; exit the retry loop */
726 * Couldn't create the pid file. Probably it already exists.
728 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
730 (errcode_for_file_access(),
731 errmsg("could not create lock file \"%s\": %m",
735 * Read the file to get the old owner's PID. Note race condition
736 * here: file might have been deleted since we tried to create it.
738 fd = open(filename, O_RDONLY, 0600);
742 continue; /* race condition; try again */
744 (errcode_for_file_access(),
745 errmsg("could not open lock file \"%s\": %m",
748 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
750 (errcode_for_file_access(),
751 errmsg("could not read lock file \"%s\": %m",
756 encoded_pid = atoi(buffer);
758 /* if pid < 0, the pid is for postgres, not postmaster */
759 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
762 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
766 * Check to see if the other process still exists
768 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
769 * ignored as false matches.
771 * Normally kill() will fail with ESRCH if the given PID doesn't
774 * We can treat the EPERM-error case as okay because that error
775 * implies that the existing process has a different userid than we
776 * do, which means it cannot be a competing postmaster. A postmaster
777 * cannot successfully attach to a data directory owned by a userid
778 * other than its own. (This is now checked directly in
779 * checkDataDir(), but has been true for a long time because of the
780 * restriction that the data directory isn't group- or
781 * world-accessible.) Also, since we create the lockfiles mode 600,
782 * we'd have failed above if the lockfile belonged to another userid
783 * --- which means that whatever process kill() is reporting about
784 * isn't the one that made the lockfile. (NOTE: this last
785 * consideration is the only one that keeps us from blowing away a
786 * Unix socket file belonging to an instance of Postgres being run by
787 * someone else, at least on machines where /tmp hasn't got a
790 if (other_pid != my_pid && other_pid != my_p_pid &&
791 other_pid != my_gp_pid)
793 if (kill(other_pid, 0) == 0 ||
794 (errno != ESRCH && errno != EPERM))
796 /* lockfile belongs to a live process */
798 (errcode(ERRCODE_LOCK_FILE_EXISTS),
799 errmsg("lock file \"%s\" already exists",
803 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
804 (int) other_pid, refName) :
805 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
806 (int) other_pid, refName)) :
808 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
809 (int) other_pid, refName) :
810 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
811 (int) other_pid, refName))));
816 * No, the creating process did not exist. However, it could be that
817 * the postmaster crashed (or more likely was kill -9'd by a clueless
818 * admin) but has left orphan backends behind. Check for this by
819 * looking to see if there is an associated shmem segment that is
822 * Note: because postmaster.pid is written in two steps, we might not
823 * find the shmem ID values in it; we can't treat that as an error.
831 ptr = strchr(buffer, '\n');
833 (ptr = strchr(ptr + 1, '\n')) != NULL)
836 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
838 if (PGSharedMemoryIsInUse(id1, id2))
840 (errcode(ERRCODE_LOCK_FILE_EXISTS),
841 errmsg("pre-existing shared memory block "
842 "(key %lu, ID %lu) is still in use",
844 errhint("If you're sure there are no old "
845 "server processes still running, remove "
846 "the shared memory block "
847 "or just delete the file \"%s\".",
854 * Looks like nobody's home. Unlink the file and try again to create
855 * it. Need a loop because of possible race condition against other
858 if (unlink(filename) < 0)
860 (errcode_for_file_access(),
861 errmsg("could not remove old lock file \"%s\": %m",
863 errhint("The file seems accidentally left over, but "
864 "it could not be removed. Please remove the file "
865 "by hand and try again.")));
869 * Successfully created the file, now fill it.
871 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
872 amPostmaster ? (int) my_pid : -((int) my_pid),
875 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
877 int save_errno = errno;
881 /* if write didn't set errno, assume problem is no disk space */
882 errno = save_errno ? save_errno : ENOSPC;
884 (errcode_for_file_access(),
885 errmsg("could not write lock file \"%s\": %m", filename)));
887 if (pg_fsync(fd) != 0)
889 int save_errno = errno;
895 (errcode_for_file_access(),
896 errmsg("could not write lock file \"%s\": %m", filename)));
900 int save_errno = errno;
905 (errcode_for_file_access(),
906 errmsg("could not write lock file \"%s\": %m", filename)));
910 * Arrange for automatic removal of lockfile at proc_exit.
912 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
916 * Create the data directory lockfile.
918 * When this is called, we must have already switched the working
919 * directory to DataDir, so we can just use a relative path. This
920 * helps ensure that we are locking the directory we should be.
923 CreateDataDirLockFile(bool amPostmaster)
925 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
929 * Create a lockfile for the specified Unix socket file.
932 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
934 char lockfile[MAXPGPATH];
936 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
937 CreateLockFile(lockfile, amPostmaster, false, socketfile);
938 /* Save name of lockfile for TouchSocketLockFile */
939 strcpy(socketLockFile, lockfile);
943 * TouchSocketLockFile -- mark socket lock file as recently accessed
945 * This routine should be called every so often to ensure that the lock file
946 * has a recent mod or access date. That saves it
947 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
948 * (Another reason we should never have put the socket file in /tmp...)
951 TouchSocketLockFile(void)
953 /* Do nothing if we did not create a socket... */
954 if (socketLockFile[0] != '\0')
957 * utime() is POSIX standard, utimes() is a common alternative; if we
958 * have neither, fall back to actually reading the file (which only
959 * sets the access time not mod time, but that should be enough in
960 * most cases). In all paths, we ignore errors.
963 utime(socketLockFile, NULL);
964 #else /* !HAVE_UTIME */
966 utimes(socketLockFile, NULL);
967 #else /* !HAVE_UTIMES */
971 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
974 read(fd, buffer, sizeof(buffer));
977 #endif /* HAVE_UTIMES */
978 #endif /* HAVE_UTIME */
983 * Append information about a shared memory segment to the data directory
986 * This may be called multiple times in the life of a postmaster, if we
987 * delete and recreate shmem due to backend crash. Therefore, be prepared
988 * to overwrite existing information. (As of 7.1, a postmaster only creates
989 * one shm seg at a time; but for the purposes here, if we did have more than
990 * one then any one of them would do anyway.)
993 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
1000 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1004 (errcode_for_file_access(),
1005 errmsg("could not open file \"%s\": %m",
1006 DIRECTORY_LOCK_FILE)));
1009 len = read(fd, buffer, sizeof(buffer) - 100);
1013 (errcode_for_file_access(),
1014 errmsg("could not read from file \"%s\": %m",
1015 DIRECTORY_LOCK_FILE)));
1022 * Skip over first two lines (PID and path).
1024 ptr = strchr(buffer, '\n');
1026 (ptr = strchr(ptr + 1, '\n')) == NULL)
1028 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1035 * Append key information. Format to try to keep it the same length
1036 * always (trailing junk won't hurt, but might confuse humans).
1038 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1041 * And rewrite the data. Since we write in a single kernel call, this
1042 * update should appear atomic to onlookers.
1044 len = strlen(buffer);
1046 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1047 (int) write(fd, buffer, len) != len)
1049 /* if write didn't set errno, assume problem is no disk space */
1053 (errcode_for_file_access(),
1054 errmsg("could not write to file \"%s\": %m",
1055 DIRECTORY_LOCK_FILE)));
1059 if (pg_fsync(fd) != 0)
1062 (errcode_for_file_access(),
1063 errmsg("could not write to file \"%s\": %m",
1064 DIRECTORY_LOCK_FILE)));
1069 (errcode_for_file_access(),
1070 errmsg("could not write to file \"%s\": %m",
1071 DIRECTORY_LOCK_FILE)));
1076 /*-------------------------------------------------------------------------
1077 * Version checking support
1078 *-------------------------------------------------------------------------
1082 * Determine whether the PG_VERSION file in directory `path' indicates
1083 * a data version compatible with the version of this program.
1085 * If compatible, return. Otherwise, ereport(FATAL).
1088 ValidatePgVersion(const char *path)
1090 char full_path[MAXPGPATH];
1098 const char *version_string = PG_VERSION;
1100 my_major = strtol(version_string, &endptr, 10);
1102 my_minor = strtol(endptr + 1, NULL, 10);
1104 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1106 file = AllocateFile(full_path, "r");
1109 if (errno == ENOENT)
1111 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1112 errmsg("\"%s\" is not a valid data directory",
1114 errdetail("File \"%s\" is missing.", full_path)));
1117 (errcode_for_file_access(),
1118 errmsg("could not open file \"%s\": %m", full_path)));
1121 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1124 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1125 errmsg("\"%s\" is not a valid data directory",
1127 errdetail("File \"%s\" does not contain valid data.",
1129 errhint("You might need to initdb.")));
1133 if (my_major != file_major || my_minor != file_minor)
1135 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1136 errmsg("database files are incompatible with server"),
1137 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1138 "which is not compatible with this version %s.",
1139 file_major, file_minor, version_string)));
1142 /*-------------------------------------------------------------------------
1143 * Library preload support
1144 *-------------------------------------------------------------------------
1148 * GUC variables: lists of library names to be preloaded at postmaster
1149 * start and at backend start
1151 char *shared_preload_libraries_string = NULL;
1152 char *local_preload_libraries_string = NULL;
1154 /* Flag telling that we are loading shared_preload_libraries */
1155 bool process_shared_preload_libraries_in_progress = false;
1158 * load the shared libraries listed in 'libraries'
1160 * 'gucname': name of GUC variable, for error reports
1161 * 'restricted': if true, force libraries to be in $libdir/plugins/
1164 load_libraries(const char *libraries, const char *gucname, bool restricted)
1171 if (libraries == NULL || libraries[0] == '\0')
1172 return; /* nothing to do */
1174 /* Need a modifiable copy of string */
1175 rawstring = pstrdup(libraries);
1177 /* Parse string into list of identifiers */
1178 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1180 /* syntax error in list */
1182 list_free(elemlist);
1184 (errcode(ERRCODE_SYNTAX_ERROR),
1185 errmsg("invalid list syntax in parameter \"%s\"",
1191 * Choose notice level: avoid repeat messages when re-loading a library
1192 * that was preloaded into the postmaster. (Only possible in EXEC_BACKEND
1196 if (IsUnderPostmaster && process_shared_preload_libraries_in_progress)
1202 foreach(l, elemlist)
1204 char *tok = (char *) lfirst(l);
1207 filename = pstrdup(tok);
1208 canonicalize_path(filename);
1209 /* If restricting, insert $libdir/plugins if not mentioned already */
1210 if (restricted && first_dir_separator(filename) == NULL)
1214 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1215 strcpy(expanded, "$libdir/plugins/");
1216 strcat(expanded, filename);
1218 filename = expanded;
1220 load_file(filename, restricted);
1222 (errmsg("loaded library \"%s\"", filename)));
1227 list_free(elemlist);
1231 * process any libraries that should be preloaded at postmaster start
1234 process_shared_preload_libraries(void)
1236 process_shared_preload_libraries_in_progress = true;
1237 load_libraries(shared_preload_libraries_string,
1238 "shared_preload_libraries",
1240 process_shared_preload_libraries_in_progress = false;
1244 * process any libraries that should be preloaded at backend start
1247 process_local_preload_libraries(void)
1249 load_libraries(local_preload_libraries_string,
1250 "local_preload_libraries",
1255 pg_bindtextdomain(const char *domain)
1258 if (my_exec_path[0] != '\0')
1260 char locale_path[MAXPGPATH];
1262 get_locale_path(my_exec_path, locale_path);
1263 bindtextdomain(domain, locale_path);
1264 pg_bind_textdomain_codeset(domain);