LCOV - code coverage report
Current view: top level - src/backend/utils/init - miscinit.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 413 512 80.7 %
Date: 2025-01-18 05:15:39 Functions: 48 51 94.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * miscinit.c
       4             :  *    miscellaneous initialization support stuff
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/utils/init/miscinit.c
      12             :  *
      13             :  *-------------------------------------------------------------------------
      14             :  */
      15             : #include "postgres.h"
      16             : 
      17             : #include <sys/param.h>
      18             : #include <signal.h>
      19             : #include <time.h>
      20             : #include <sys/file.h>
      21             : #include <sys/stat.h>
      22             : #include <sys/time.h>
      23             : #include <fcntl.h>
      24             : #include <unistd.h>
      25             : #include <grp.h>
      26             : #include <pwd.h>
      27             : #include <netinet/in.h>
      28             : #include <arpa/inet.h>
      29             : #include <utime.h>
      30             : 
      31             : #include "access/htup_details.h"
      32             : #include "access/parallel.h"
      33             : #include "catalog/pg_authid.h"
      34             : #include "common/file_perm.h"
      35             : #include "libpq/libpq.h"
      36             : #include "libpq/pqsignal.h"
      37             : #include "mb/pg_wchar.h"
      38             : #include "miscadmin.h"
      39             : #include "pgstat.h"
      40             : #include "postmaster/autovacuum.h"
      41             : #include "postmaster/interrupt.h"
      42             : #include "postmaster/postmaster.h"
      43             : #include "replication/slotsync.h"
      44             : #include "storage/fd.h"
      45             : #include "storage/ipc.h"
      46             : #include "storage/latch.h"
      47             : #include "storage/pg_shmem.h"
      48             : #include "storage/pmsignal.h"
      49             : #include "storage/proc.h"
      50             : #include "storage/procarray.h"
      51             : #include "utils/builtins.h"
      52             : #include "utils/guc.h"
      53             : #include "utils/inval.h"
      54             : #include "utils/memutils.h"
      55             : #include "utils/pidfile.h"
      56             : #include "utils/syscache.h"
      57             : #include "utils/varlena.h"
      58             : 
      59             : 
      60             : #define DIRECTORY_LOCK_FILE     "postmaster.pid"
      61             : 
      62             : ProcessingMode Mode = InitProcessing;
      63             : 
      64             : BackendType MyBackendType;
      65             : 
      66             : /* List of lock files to be removed at proc exit */
      67             : static List *lock_files = NIL;
      68             : 
      69             : static Latch LocalLatchData;
      70             : 
      71             : /* ----------------------------------------------------------------
      72             :  *      ignoring system indexes support stuff
      73             :  *
      74             :  * NOTE: "ignoring system indexes" means we do not use the system indexes
      75             :  * for lookups (either in hardwired catalog accesses or in planner-generated
      76             :  * plans).  We do, however, still update the indexes when a catalog
      77             :  * modification is made.
      78             :  * ----------------------------------------------------------------
      79             :  */
      80             : 
      81             : bool        IgnoreSystemIndexes = false;
      82             : 
      83             : 
      84             : /* ----------------------------------------------------------------
      85             :  *  common process startup code
      86             :  * ----------------------------------------------------------------
      87             :  */
      88             : 
      89             : /*
      90             :  * Initialize the basic environment for a postmaster child
      91             :  *
      92             :  * Should be called as early as possible after the child's startup. However,
      93             :  * on EXEC_BACKEND builds it does need to be after read_backend_variables().
      94             :  */
      95             : void
      96       37668 : InitPostmasterChild(void)
      97             : {
      98       37668 :     IsUnderPostmaster = true;   /* we are a postmaster subprocess now */
      99             : 
     100             :     /*
     101             :      * Start our win32 signal implementation. This has to be done after we
     102             :      * read the backend variables, because we need to pick up the signal pipe
     103             :      * from the parent process.
     104             :      */
     105             : #ifdef WIN32
     106             :     pgwin32_signal_initialize();
     107             : #endif
     108             : 
     109       37668 :     InitProcessGlobals();
     110             : 
     111             :     /*
     112             :      * make sure stderr is in binary mode before anything can possibly be
     113             :      * written to it, in case it's actually the syslogger pipe, so the pipe
     114             :      * chunking protocol isn't disturbed. Non-logpipe data gets translated on
     115             :      * redirection (e.g. via pg_ctl -l) anyway.
     116             :      */
     117             : #ifdef WIN32
     118             :     _setmode(fileno(stderr), _O_BINARY);
     119             : #endif
     120             : 
     121             :     /* We don't want the postmaster's proc_exit() handlers */
     122       37668 :     on_exit_reset();
     123             : 
     124             :     /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
     125             : #ifdef EXEC_BACKEND
     126             :     pqinitmask();
     127             : #endif
     128             : 
     129             :     /* Initialize process-local latch support */
     130       37668 :     InitializeLatchSupport();
     131       37668 :     InitProcessLocalLatch();
     132       37668 :     InitializeLatchWaitSet();
     133             : 
     134             :     /*
     135             :      * If possible, make this process a group leader, so that the postmaster
     136             :      * can signal any child processes too. Not all processes will have
     137             :      * children, but for consistency we make all postmaster child processes do
     138             :      * this.
     139             :      */
     140             : #ifdef HAVE_SETSID
     141       37668 :     if (setsid() < 0)
     142           0 :         elog(FATAL, "setsid() failed: %m");
     143             : #endif
     144             : 
     145             :     /*
     146             :      * Every postmaster child process is expected to respond promptly to
     147             :      * SIGQUIT at all times.  Therefore we centrally remove SIGQUIT from
     148             :      * BlockSig and install a suitable signal handler.  (Client-facing
     149             :      * processes may choose to replace this default choice of handler with
     150             :      * quickdie().)  All other blockable signals remain blocked for now.
     151             :      */
     152       37668 :     pqsignal(SIGQUIT, SignalHandlerForCrashExit);
     153             : 
     154       37668 :     sigdelset(&BlockSig, SIGQUIT);
     155       37668 :     sigprocmask(SIG_SETMASK, &BlockSig, NULL);
     156             : 
     157             :     /* Request a signal if the postmaster dies, if possible. */
     158       37668 :     PostmasterDeathSignalInit();
     159             : 
     160             :     /* Don't give the pipe to subprograms that we execute. */
     161             : #ifndef WIN32
     162       37668 :     if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
     163           0 :         ereport(FATAL,
     164             :                 (errcode_for_socket_access(),
     165             :                  errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
     166             : #endif
     167       37668 : }
     168             : 
     169             : /*
     170             :  * Initialize the basic environment for a standalone process.
     171             :  *
     172             :  * argv0 has to be suitable to find the program's executable.
     173             :  */
     174             : void
     175         432 : InitStandaloneProcess(const char *argv0)
     176             : {
     177             :     Assert(!IsPostmasterEnvironment);
     178             : 
     179         432 :     MyBackendType = B_STANDALONE_BACKEND;
     180             : 
     181             :     /*
     182             :      * Start our win32 signal implementation
     183             :      */
     184             : #ifdef WIN32
     185             :     pgwin32_signal_initialize();
     186             : #endif
     187             : 
     188         432 :     InitProcessGlobals();
     189             : 
     190             :     /* Initialize process-local latch support */
     191         432 :     InitializeLatchSupport();
     192         432 :     InitProcessLocalLatch();
     193         432 :     InitializeLatchWaitSet();
     194             : 
     195             :     /*
     196             :      * For consistency with InitPostmasterChild, initialize signal mask here.
     197             :      * But we don't unblock SIGQUIT or provide a default handler for it.
     198             :      */
     199         432 :     pqinitmask();
     200         432 :     sigprocmask(SIG_SETMASK, &BlockSig, NULL);
     201             : 
     202             :     /* Compute paths, no postmaster to inherit from */
     203         432 :     if (my_exec_path[0] == '\0')
     204             :     {
     205         432 :         if (find_my_exec(argv0, my_exec_path) < 0)
     206           0 :             elog(FATAL, "%s: could not locate my own executable path",
     207             :                  argv0);
     208             :     }
     209             : 
     210         432 :     if (pkglib_path[0] == '\0')
     211         432 :         get_pkglib_path(my_exec_path, pkglib_path);
     212         432 : }
     213             : 
     214             : void
     215       37506 : SwitchToSharedLatch(void)
     216             : {
     217             :     Assert(MyLatch == &LocalLatchData);
     218             :     Assert(MyProc != NULL);
     219             : 
     220       37506 :     MyLatch = &MyProc->procLatch;
     221             : 
     222       37506 :     if (FeBeWaitSet)
     223       25580 :         ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetLatchPos, WL_LATCH_SET,
     224             :                         MyLatch);
     225             : 
     226             :     /*
     227             :      * Set the shared latch as the local one might have been set. This
     228             :      * shouldn't normally be necessary as code is supposed to check the
     229             :      * condition before waiting for the latch, but a bit care can't hurt.
     230             :      */
     231       37506 :     SetLatch(MyLatch);
     232       37506 : }
     233             : 
     234             : void
     235       39650 : InitProcessLocalLatch(void)
     236             : {
     237       39650 :     MyLatch = &LocalLatchData;
     238       39650 :     InitLatch(MyLatch);
     239       39650 : }
     240             : 
     241             : void
     242       37506 : SwitchBackToLocalLatch(void)
     243             : {
     244             :     Assert(MyLatch != &LocalLatchData);
     245             :     Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
     246             : 
     247       37506 :     MyLatch = &LocalLatchData;
     248             : 
     249       37506 :     if (FeBeWaitSet)
     250       25580 :         ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetLatchPos, WL_LATCH_SET,
     251             :                         MyLatch);
     252             : 
     253       37506 :     SetLatch(MyLatch);
     254       37506 : }
     255             : 
     256             : /*
     257             :  * Return a human-readable string representation of a BackendType.
     258             :  *
     259             :  * The string is not localized here, but we mark the strings for translation
     260             :  * so that callers can invoke _() on the result.
     261             :  */
     262             : const char *
     263       95172 : GetBackendTypeDesc(BackendType backendType)
     264             : {
     265       95172 :     const char *backendDesc = gettext_noop("unknown process type");
     266             : 
     267       95172 :     switch (backendType)
     268             :     {
     269           0 :         case B_INVALID:
     270           0 :             backendDesc = gettext_noop("not initialized");
     271           0 :             break;
     272          94 :         case B_ARCHIVER:
     273          94 :             backendDesc = gettext_noop("archiver");
     274          94 :             break;
     275        2066 :         case B_AUTOVAC_LAUNCHER:
     276        2066 :             backendDesc = gettext_noop("autovacuum launcher");
     277        2066 :             break;
     278        4950 :         case B_AUTOVAC_WORKER:
     279        4950 :             backendDesc = gettext_noop("autovacuum worker");
     280        4950 :             break;
     281       73634 :         case B_BACKEND:
     282       73634 :             backendDesc = gettext_noop("client backend");
     283       73634 :             break;
     284         296 :         case B_DEAD_END_BACKEND:
     285         296 :             backendDesc = gettext_noop("dead-end client backend");
     286         296 :             break;
     287         112 :         case B_BG_WORKER:
     288         112 :             backendDesc = gettext_noop("background worker");
     289         112 :             break;
     290        2398 :         case B_BG_WRITER:
     291        2398 :             backendDesc = gettext_noop("background writer");
     292        2398 :             break;
     293        3092 :         case B_CHECKPOINTER:
     294        3092 :             backendDesc = gettext_noop("checkpointer");
     295        3092 :             break;
     296           2 :         case B_LOGGER:
     297           2 :             backendDesc = gettext_noop("logger");
     298           2 :             break;
     299         120 :         case B_SLOTSYNC_WORKER:
     300         120 :             backendDesc = gettext_noop("slotsync worker");
     301         120 :             break;
     302         112 :         case B_STANDALONE_BACKEND:
     303         112 :             backendDesc = gettext_noop("standalone backend");
     304         112 :             break;
     305        1770 :         case B_STARTUP:
     306        1770 :             backendDesc = gettext_noop("startup");
     307        1770 :             break;
     308         432 :         case B_WAL_RECEIVER:
     309         432 :             backendDesc = gettext_noop("walreceiver");
     310         432 :             break;
     311        3934 :         case B_WAL_SENDER:
     312        3934 :             backendDesc = gettext_noop("walsender");
     313        3934 :             break;
     314           2 :         case B_WAL_SUMMARIZER:
     315           2 :             backendDesc = gettext_noop("walsummarizer");
     316           2 :             break;
     317        2158 :         case B_WAL_WRITER:
     318        2158 :             backendDesc = gettext_noop("walwriter");
     319        2158 :             break;
     320             :     }
     321             : 
     322       95172 :     return backendDesc;
     323             : }
     324             : 
     325             : /* ----------------------------------------------------------------
     326             :  *              database path / name support stuff
     327             :  * ----------------------------------------------------------------
     328             :  */
     329             : 
     330             : void
     331       30492 : SetDatabasePath(const char *path)
     332             : {
     333             :     /* This should happen only once per process */
     334             :     Assert(!DatabasePath);
     335       30492 :     DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
     336       30492 : }
     337             : 
     338             : /*
     339             :  * Validate the proposed data directory.
     340             :  *
     341             :  * Also initialize file and directory create modes and mode mask.
     342             :  */
     343             : void
     344        1928 : checkDataDir(void)
     345             : {
     346             :     struct stat stat_buf;
     347             : 
     348             :     Assert(DataDir);
     349             : 
     350        1928 :     if (stat(DataDir, &stat_buf) != 0)
     351             :     {
     352           0 :         if (errno == ENOENT)
     353           0 :             ereport(FATAL,
     354             :                     (errcode_for_file_access(),
     355             :                      errmsg("data directory \"%s\" does not exist",
     356             :                             DataDir)));
     357             :         else
     358           0 :             ereport(FATAL,
     359             :                     (errcode_for_file_access(),
     360             :                      errmsg("could not read permissions of directory \"%s\": %m",
     361             :                             DataDir)));
     362             :     }
     363             : 
     364             :     /* eventual chdir would fail anyway, but let's test ... */
     365        1928 :     if (!S_ISDIR(stat_buf.st_mode))
     366           0 :         ereport(FATAL,
     367             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     368             :                  errmsg("specified data directory \"%s\" is not a directory",
     369             :                         DataDir)));
     370             : 
     371             :     /*
     372             :      * Check that the directory belongs to my userid; if not, reject.
     373             :      *
     374             :      * This check is an essential part of the interlock that prevents two
     375             :      * postmasters from starting in the same directory (see CreateLockFile()).
     376             :      * Do not remove or weaken it.
     377             :      *
     378             :      * XXX can we safely enable this check on Windows?
     379             :      */
     380             : #if !defined(WIN32) && !defined(__CYGWIN__)
     381        1928 :     if (stat_buf.st_uid != geteuid())
     382           0 :         ereport(FATAL,
     383             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     384             :                  errmsg("data directory \"%s\" has wrong ownership",
     385             :                         DataDir),
     386             :                  errhint("The server must be started by the user that owns the data directory.")));
     387             : #endif
     388             : 
     389             :     /*
     390             :      * Check if the directory has correct permissions.  If not, reject.
     391             :      *
     392             :      * Only two possible modes are allowed, 0700 and 0750.  The latter mode
     393             :      * indicates that group read/execute should be allowed on all newly
     394             :      * created files and directories.
     395             :      *
     396             :      * XXX temporarily suppress check when on Windows, because there may not
     397             :      * be proper support for Unix-y file permissions.  Need to think of a
     398             :      * reasonable check to apply on Windows.
     399             :      */
     400             : #if !defined(WIN32) && !defined(__CYGWIN__)
     401        1928 :     if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
     402           0 :         ereport(FATAL,
     403             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     404             :                  errmsg("data directory \"%s\" has invalid permissions",
     405             :                         DataDir),
     406             :                  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
     407             : #endif
     408             : 
     409             :     /*
     410             :      * Reset creation modes and mask based on the mode of the data directory.
     411             :      *
     412             :      * The mask was set earlier in startup to disallow group permissions on
     413             :      * newly created files and directories.  However, if group read/execute
     414             :      * are present on the data directory then modify the create modes and mask
     415             :      * to allow group read/execute on newly created files and directories and
     416             :      * set the data_directory_mode GUC.
     417             :      *
     418             :      * Suppress when on Windows, because there may not be proper support for
     419             :      * Unix-y file permissions.
     420             :      */
     421             : #if !defined(WIN32) && !defined(__CYGWIN__)
     422        1928 :     SetDataDirectoryCreatePerm(stat_buf.st_mode);
     423             : 
     424        1928 :     umask(pg_mode_mask);
     425        1928 :     data_directory_mode = pg_dir_create_mode;
     426             : #endif
     427             : 
     428             :     /* Check for PG_VERSION */
     429        1928 :     ValidatePgVersion(DataDir);
     430        1928 : }
     431             : 
     432             : /*
     433             :  * Set data directory, but make sure it's an absolute path.  Use this,
     434             :  * never set DataDir directly.
     435             :  */
     436             : void
     437        1934 : SetDataDir(const char *dir)
     438             : {
     439             :     char       *new;
     440             : 
     441             :     Assert(dir);
     442             : 
     443             :     /* If presented path is relative, convert to absolute */
     444        1934 :     new = make_absolute_path(dir);
     445             : 
     446        1934 :     free(DataDir);
     447        1934 :     DataDir = new;
     448        1934 : }
     449             : 
     450             : /*
     451             :  * Change working directory to DataDir.  Most of the postmaster and backend
     452             :  * code assumes that we are in DataDir so it can use relative paths to access
     453             :  * stuff in and under the data directory.  For convenience during path
     454             :  * setup, however, we don't force the chdir to occur during SetDataDir.
     455             :  */
     456             : void
     457        1928 : ChangeToDataDir(void)
     458             : {
     459             :     Assert(DataDir);
     460             : 
     461        1928 :     if (chdir(DataDir) < 0)
     462           0 :         ereport(FATAL,
     463             :                 (errcode_for_file_access(),
     464             :                  errmsg("could not change directory to \"%s\": %m",
     465             :                         DataDir)));
     466        1928 : }
     467             : 
     468             : 
     469             : /* ----------------------------------------------------------------
     470             :  *  User ID state
     471             :  *
     472             :  * We have to track several different values associated with the concept
     473             :  * of "user ID".
     474             :  *
     475             :  * AuthenticatedUserId is determined at connection start and never changes.
     476             :  *
     477             :  * SessionUserId is initially the same as AuthenticatedUserId, but can be
     478             :  * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserId is a
     479             :  * superuser).  This is the ID reported by the SESSION_USER SQL function.
     480             :  *
     481             :  * OuterUserId is the current user ID in effect at the "outer level" (outside
     482             :  * any transaction or function).  This is initially the same as SessionUserId,
     483             :  * but can be changed by SET ROLE to any role that SessionUserId is a
     484             :  * member of.  (XXX rename to something like CurrentRoleId?)
     485             :  *
     486             :  * CurrentUserId is the current effective user ID; this is the one to use
     487             :  * for all normal permissions-checking purposes.  At outer level this will
     488             :  * be the same as OuterUserId, but it changes during calls to SECURITY
     489             :  * DEFINER functions, as well as locally in some specialized commands.
     490             :  *
     491             :  * SecurityRestrictionContext holds flags indicating reason(s) for changing
     492             :  * CurrentUserId.  In some cases we need to lock down operations that are
     493             :  * not directly controlled by privilege settings, and this provides a
     494             :  * convenient way to do it.
     495             :  * ----------------------------------------------------------------
     496             :  */
     497             : static Oid  AuthenticatedUserId = InvalidOid;
     498             : static Oid  SessionUserId = InvalidOid;
     499             : static Oid  OuterUserId = InvalidOid;
     500             : static Oid  CurrentUserId = InvalidOid;
     501             : static const char *SystemUser = NULL;
     502             : 
     503             : /* We also have to remember the superuser state of the session user */
     504             : static bool SessionUserIsSuperuser = false;
     505             : 
     506             : static int  SecurityRestrictionContext = 0;
     507             : 
     508             : /* We also remember if a SET ROLE is currently active */
     509             : static bool SetRoleIsActive = false;
     510             : 
     511             : /*
     512             :  * GetUserId - get the current effective user ID.
     513             :  *
     514             :  * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
     515             :  */
     516             : Oid
     517    12253156 : GetUserId(void)
     518             : {
     519             :     Assert(OidIsValid(CurrentUserId));
     520    12253156 :     return CurrentUserId;
     521             : }
     522             : 
     523             : 
     524             : /*
     525             :  * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
     526             :  */
     527             : Oid
     528        1510 : GetOuterUserId(void)
     529             : {
     530             :     Assert(OidIsValid(OuterUserId));
     531        1510 :     return OuterUserId;
     532             : }
     533             : 
     534             : 
     535             : static void
     536       78208 : SetOuterUserId(Oid userid, bool is_superuser)
     537             : {
     538             :     Assert(SecurityRestrictionContext == 0);
     539             :     Assert(OidIsValid(userid));
     540       78208 :     OuterUserId = userid;
     541             : 
     542             :     /* We force the effective user ID to match, too */
     543       78208 :     CurrentUserId = userid;
     544             : 
     545             :     /* Also update the is_superuser GUC to match OuterUserId's property */
     546       78208 :     SetConfigOption("is_superuser",
     547             :                     is_superuser ? "on" : "off",
     548             :                     PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
     549       78208 : }
     550             : 
     551             : 
     552             : /*
     553             :  * GetSessionUserId/SetSessionUserId - get/set the session user ID.
     554             :  */
     555             : Oid
     556       66854 : GetSessionUserId(void)
     557             : {
     558             :     Assert(OidIsValid(SessionUserId));
     559       66854 :     return SessionUserId;
     560             : }
     561             : 
     562             : bool
     563        3606 : GetSessionUserIsSuperuser(void)
     564             : {
     565             :     Assert(OidIsValid(SessionUserId));
     566        3606 :     return SessionUserIsSuperuser;
     567             : }
     568             : 
     569             : static void
     570       38328 : SetSessionUserId(Oid userid, bool is_superuser)
     571             : {
     572             :     Assert(SecurityRestrictionContext == 0);
     573             :     Assert(OidIsValid(userid));
     574       38328 :     SessionUserId = userid;
     575       38328 :     SessionUserIsSuperuser = is_superuser;
     576       38328 : }
     577             : 
     578             : /*
     579             :  * Return the system user representing the authenticated identity.
     580             :  * It is defined in InitializeSystemUser() as auth_method:authn_id.
     581             :  */
     582             : const char *
     583          44 : GetSystemUser(void)
     584             : {
     585          44 :     return SystemUser;
     586             : }
     587             : 
     588             : /*
     589             :  * GetAuthenticatedUserId/SetAuthenticatedUserId - get/set the authenticated
     590             :  * user ID
     591             :  */
     592             : Oid
     593       32248 : GetAuthenticatedUserId(void)
     594             : {
     595             :     Assert(OidIsValid(AuthenticatedUserId));
     596       32248 :     return AuthenticatedUserId;
     597             : }
     598             : 
     599             : void
     600       28962 : SetAuthenticatedUserId(Oid userid)
     601             : {
     602             :     Assert(OidIsValid(userid));
     603             : 
     604             :     /* call only once */
     605             :     Assert(!OidIsValid(AuthenticatedUserId));
     606             : 
     607       28962 :     AuthenticatedUserId = userid;
     608             : 
     609             :     /* Also mark our PGPROC entry with the authenticated user id */
     610             :     /* (We assume this is an atomic store so no lock is needed) */
     611       28962 :     MyProc->roleId = userid;
     612       28962 : }
     613             : 
     614             : 
     615             : /*
     616             :  * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
     617             :  * and the SecurityRestrictionContext flags.
     618             :  *
     619             :  * Currently there are three valid bits in SecurityRestrictionContext:
     620             :  *
     621             :  * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
     622             :  * that is temporarily changing CurrentUserId via these functions.  This is
     623             :  * needed to indicate that the actual value of CurrentUserId is not in sync
     624             :  * with guc.c's internal state, so SET ROLE has to be disallowed.
     625             :  *
     626             :  * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
     627             :  * that does not wish to trust called user-defined functions at all.  The
     628             :  * policy is to use this before operations, e.g. autovacuum and REINDEX, that
     629             :  * enumerate relations of a database or schema and run functions associated
     630             :  * with each found relation.  The relation owner is the new user ID.  Set this
     631             :  * as soon as possible after locking the relation.  Restore the old user ID as
     632             :  * late as possible before closing the relation; restoring it shortly after
     633             :  * close is also tolerable.  If a command has both relation-enumerating and
     634             :  * non-enumerating modes, e.g. ANALYZE, both modes set this bit.  This bit
     635             :  * prevents not only SET ROLE, but various other changes of session state that
     636             :  * normally is unprotected but might possibly be used to subvert the calling
     637             :  * session later.  An example is replacing an existing prepared statement with
     638             :  * new code, which will then be executed with the outer session's permissions
     639             :  * when the prepared statement is next used.  These restrictions are fairly
     640             :  * draconian, but the functions called in relation-enumerating operations are
     641             :  * really supposed to be side-effect-free anyway.
     642             :  *
     643             :  * SECURITY_NOFORCE_RLS indicates that we are inside an operation which should
     644             :  * ignore the FORCE ROW LEVEL SECURITY per-table indication.  This is used to
     645             :  * ensure that FORCE RLS does not mistakenly break referential integrity
     646             :  * checks.  Note that this is intentionally only checked when running as the
     647             :  * owner of the table (which should always be the case for referential
     648             :  * integrity checks).
     649             :  *
     650             :  * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
     651             :  * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
     652             :  * the new value to be valid.  In fact, these routines had better not
     653             :  * ever throw any kind of error.  This is because they are used by
     654             :  * StartTransaction and AbortTransaction to save/restore the settings,
     655             :  * and during the first transaction within a backend, the value to be saved
     656             :  * and perhaps restored is indeed invalid.  We have to be able to get
     657             :  * through AbortTransaction without asserting in case InitPostgres fails.
     658             :  */
     659             : void
     660     1377552 : GetUserIdAndSecContext(Oid *userid, int *sec_context)
     661             : {
     662     1377552 :     *userid = CurrentUserId;
     663     1377552 :     *sec_context = SecurityRestrictionContext;
     664     1377552 : }
     665             : 
     666             : void
     667     1211244 : SetUserIdAndSecContext(Oid userid, int sec_context)
     668             : {
     669     1211244 :     CurrentUserId = userid;
     670     1211244 :     SecurityRestrictionContext = sec_context;
     671     1211244 : }
     672             : 
     673             : 
     674             : /*
     675             :  * InLocalUserIdChange - are we inside a local change of CurrentUserId?
     676             :  */
     677             : bool
     678       66138 : InLocalUserIdChange(void)
     679             : {
     680       66138 :     return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
     681             : }
     682             : 
     683             : /*
     684             :  * InSecurityRestrictedOperation - are we inside a security-restricted command?
     685             :  */
     686             : bool
     687       77840 : InSecurityRestrictedOperation(void)
     688             : {
     689       77840 :     return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
     690             : }
     691             : 
     692             : /*
     693             :  * InNoForceRLSOperation - are we ignoring FORCE ROW LEVEL SECURITY ?
     694             :  */
     695             : bool
     696         216 : InNoForceRLSOperation(void)
     697             : {
     698         216 :     return (SecurityRestrictionContext & SECURITY_NOFORCE_RLS) != 0;
     699             : }
     700             : 
     701             : 
     702             : /*
     703             :  * These are obsolete versions of Get/SetUserIdAndSecContext that are
     704             :  * only provided for bug-compatibility with some rather dubious code in
     705             :  * pljava.  We allow the userid to be set, but only when not inside a
     706             :  * security restriction context.
     707             :  */
     708             : void
     709           0 : GetUserIdAndContext(Oid *userid, bool *sec_def_context)
     710             : {
     711           0 :     *userid = CurrentUserId;
     712           0 :     *sec_def_context = InLocalUserIdChange();
     713           0 : }
     714             : 
     715             : void
     716           0 : SetUserIdAndContext(Oid userid, bool sec_def_context)
     717             : {
     718             :     /* We throw the same error SET ROLE would. */
     719           0 :     if (InSecurityRestrictedOperation())
     720           0 :         ereport(ERROR,
     721             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     722             :                  errmsg("cannot set parameter \"%s\" within security-restricted operation",
     723             :                         "role")));
     724           0 :     CurrentUserId = userid;
     725           0 :     if (sec_def_context)
     726           0 :         SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
     727             :     else
     728           0 :         SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
     729           0 : }
     730             : 
     731             : 
     732             : /*
     733             :  * Check whether specified role has explicit REPLICATION privilege
     734             :  */
     735             : bool
     736        3212 : has_rolreplication(Oid roleid)
     737             : {
     738        3212 :     bool        result = false;
     739             :     HeapTuple   utup;
     740             : 
     741             :     /* Superusers bypass all permission checking. */
     742        3212 :     if (superuser_arg(roleid))
     743        3104 :         return true;
     744             : 
     745         108 :     utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
     746         108 :     if (HeapTupleIsValid(utup))
     747             :     {
     748         108 :         result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
     749         108 :         ReleaseSysCache(utup);
     750             :     }
     751         108 :     return result;
     752             : }
     753             : 
     754             : /*
     755             :  * Initialize user identity during normal backend startup
     756             :  */
     757             : void
     758       28968 : InitializeSessionUserId(const char *rolename, Oid roleid,
     759             :                         bool bypass_login_check)
     760             : {
     761             :     HeapTuple   roleTup;
     762             :     Form_pg_authid rform;
     763             :     char       *rname;
     764             :     bool        is_superuser;
     765             : 
     766             :     /*
     767             :      * In a parallel worker, we don't have to do anything here.
     768             :      * ParallelWorkerMain already set our output variables, and we aren't
     769             :      * going to enforce either rolcanlogin or rolconnlimit.  Furthermore, we
     770             :      * don't really want to perform a catalog lookup for the role: we don't
     771             :      * want to fail if it's been dropped.
     772             :      */
     773       28968 :     if (InitializingParallelWorker)
     774             :     {
     775             :         Assert(bypass_login_check);
     776        2714 :         return;
     777             :     }
     778             : 
     779             :     /*
     780             :      * Don't do scans if we're bootstrapping, none of the system catalogs
     781             :      * exist yet, and they should be owned by postgres anyway.
     782             :      */
     783             :     Assert(!IsBootstrapProcessingMode());
     784             : 
     785             :     /*
     786             :      * Make sure syscache entries are flushed for recent catalog changes. This
     787             :      * allows us to find roles that were created on-the-fly during
     788             :      * authentication.
     789             :      */
     790       26254 :     AcceptInvalidationMessages();
     791             : 
     792             :     /*
     793             :      * Look up the role, either by name if that's given or by OID if not.
     794             :      */
     795       26254 :     if (rolename != NULL)
     796             :     {
     797       25450 :         roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
     798       25450 :         if (!HeapTupleIsValid(roleTup))
     799           4 :             ereport(FATAL,
     800             :                     (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     801             :                      errmsg("role \"%s\" does not exist", rolename)));
     802             :     }
     803             :     else
     804             :     {
     805         804 :         roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
     806         802 :         if (!HeapTupleIsValid(roleTup))
     807           0 :             ereport(FATAL,
     808             :                     (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     809             :                      errmsg("role with OID %u does not exist", roleid)));
     810             :     }
     811             : 
     812       26248 :     rform = (Form_pg_authid) GETSTRUCT(roleTup);
     813       26248 :     roleid = rform->oid;
     814       26248 :     rname = NameStr(rform->rolname);
     815       26248 :     is_superuser = rform->rolsuper;
     816             : 
     817       26248 :     SetAuthenticatedUserId(roleid);
     818             : 
     819             :     /*
     820             :      * Set SessionUserId and related variables, including "role", via the GUC
     821             :      * mechanisms.
     822             :      *
     823             :      * Note: ideally we would use PGC_S_DYNAMIC_DEFAULT here, so that
     824             :      * session_authorization could subsequently be changed from
     825             :      * pg_db_role_setting entries.  Instead, session_authorization in
     826             :      * pg_db_role_setting has no effect.  Changing that would require solving
     827             :      * two problems:
     828             :      *
     829             :      * 1. If pg_db_role_setting has values for both session_authorization and
     830             :      * role, we could not be sure which order those would be applied in, and
     831             :      * it would matter.
     832             :      *
     833             :      * 2. Sites may have years-old session_authorization entries.  There's not
     834             :      * been any particular reason to remove them.  Ending the dormancy of
     835             :      * those entries could seriously change application behavior, so only a
     836             :      * major release should do that.
     837             :      */
     838       26248 :     SetConfigOption("session_authorization", rname,
     839             :                     PGC_BACKEND, PGC_S_OVERRIDE);
     840             : 
     841             :     /*
     842             :      * These next checks are not enforced when in standalone mode, so that
     843             :      * there is a way to recover from sillinesses like "UPDATE pg_authid SET
     844             :      * rolcanlogin = false;".
     845             :      */
     846       26248 :     if (IsUnderPostmaster)
     847             :     {
     848             :         /*
     849             :          * Is role allowed to login at all?  (But background workers can
     850             :          * override this by setting bypass_login_check.)
     851             :          */
     852       26248 :         if (!bypass_login_check && !rform->rolcanlogin)
     853           6 :             ereport(FATAL,
     854             :                     (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
     855             :                      errmsg("role \"%s\" is not permitted to log in",
     856             :                             rname)));
     857             : 
     858             :         /*
     859             :          * Check connection limit for this role.  We enforce the limit only
     860             :          * for regular backends, since other process types have their own
     861             :          * PGPROC pools.
     862             :          *
     863             :          * There is a race condition here --- we create our PGPROC before
     864             :          * checking for other PGPROCs.  If two backends did this at about the
     865             :          * same time, they might both think they were over the limit, while
     866             :          * ideally one should succeed and one fail.  Getting that to work
     867             :          * exactly seems more trouble than it is worth, however; instead we
     868             :          * just document that the connection limit is approximate.
     869             :          */
     870       26242 :         if (rform->rolconnlimit >= 0 &&
     871           0 :             AmRegularBackendProcess() &&
     872           0 :             !is_superuser &&
     873           0 :             CountUserBackends(roleid) > rform->rolconnlimit)
     874           0 :             ereport(FATAL,
     875             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     876             :                      errmsg("too many connections for role \"%s\"",
     877             :                             rname)));
     878             :     }
     879             : 
     880       26242 :     ReleaseSysCache(roleTup);
     881             : }
     882             : 
     883             : 
     884             : /*
     885             :  * Initialize user identity during special backend startup
     886             :  */
     887             : void
     888        3204 : InitializeSessionUserIdStandalone(void)
     889             : {
     890             :     /*
     891             :      * This function should only be called in single-user mode, in autovacuum
     892             :      * workers, in slot sync worker and in background workers.
     893             :      */
     894             :     Assert(!IsUnderPostmaster || AmAutoVacuumWorkerProcess() ||
     895             :            AmLogicalSlotSyncWorkerProcess() || AmBackgroundWorkerProcess());
     896             : 
     897             :     /* call only once */
     898             :     Assert(!OidIsValid(AuthenticatedUserId));
     899             : 
     900        3204 :     AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
     901             : 
     902             :     /*
     903             :      * XXX Ideally we'd do this via SetConfigOption("session_authorization"),
     904             :      * but we lack the role name needed to do that, and we can't fetch it
     905             :      * because one reason for this special case is to be able to start up even
     906             :      * if something's happened to the BOOTSTRAP_SUPERUSERID's pg_authid row.
     907             :      * Since we don't set the GUC itself, C code will see the value as NULL,
     908             :      * and current_setting() will report an empty string within this session.
     909             :      */
     910        3204 :     SetSessionAuthorization(BOOTSTRAP_SUPERUSERID, true);
     911             : 
     912             :     /* We could do SetConfigOption("role"), but let's be consistent */
     913        3204 :     SetCurrentRoleId(InvalidOid, false);
     914        3204 : }
     915             : 
     916             : /*
     917             :  * Initialize the system user.
     918             :  *
     919             :  * This is built as auth_method:authn_id.
     920             :  */
     921             : void
     922         230 : InitializeSystemUser(const char *authn_id, const char *auth_method)
     923             : {
     924             :     char       *system_user;
     925             : 
     926             :     /* call only once */
     927             :     Assert(SystemUser == NULL);
     928             : 
     929             :     /*
     930             :      * InitializeSystemUser should be called only when authn_id is not NULL,
     931             :      * meaning that auth_method is valid.
     932             :      */
     933             :     Assert(authn_id != NULL);
     934             : 
     935         230 :     system_user = psprintf("%s:%s", auth_method, authn_id);
     936             : 
     937             :     /* Store SystemUser in long-lived storage */
     938         230 :     SystemUser = MemoryContextStrdup(TopMemoryContext, system_user);
     939         230 :     pfree(system_user);
     940         230 : }
     941             : 
     942             : /*
     943             :  * SQL-function SYSTEM_USER
     944             :  */
     945             : Datum
     946          44 : system_user(PG_FUNCTION_ARGS)
     947             : {
     948          44 :     const char *sysuser = GetSystemUser();
     949             : 
     950          44 :     if (sysuser)
     951          22 :         PG_RETURN_DATUM(CStringGetTextDatum(sysuser));
     952             :     else
     953          22 :         PG_RETURN_NULL();
     954             : }
     955             : 
     956             : /*
     957             :  * Change session auth ID while running
     958             :  *
     959             :  * The SQL standard says that SET SESSION AUTHORIZATION implies SET ROLE NONE.
     960             :  * We mechanize that at higher levels not here, because this is the GUC
     961             :  * assign hook for "session_authorization", and it must be commutative with
     962             :  * SetCurrentRoleId (the hook for "role") because guc.c provides no guarantees
     963             :  * which will run first during cases such as transaction rollback.  Therefore,
     964             :  * we update derived state (OuterUserId/CurrentUserId/is_superuser) only if
     965             :  * !SetRoleIsActive.
     966             :  */
     967             : void
     968       38328 : SetSessionAuthorization(Oid userid, bool is_superuser)
     969             : {
     970       38328 :     SetSessionUserId(userid, is_superuser);
     971             : 
     972       38328 :     if (!SetRoleIsActive)
     973       38260 :         SetOuterUserId(userid, is_superuser);
     974       38328 : }
     975             : 
     976             : /*
     977             :  * Report current role id
     978             :  *      This follows the semantics of SET ROLE, ie return the outer-level ID
     979             :  *      not the current effective ID, and return InvalidOid when the setting
     980             :  *      is logically SET ROLE NONE.
     981             :  */
     982             : Oid
     983         964 : GetCurrentRoleId(void)
     984             : {
     985         964 :     if (SetRoleIsActive)
     986          60 :         return OuterUserId;
     987             :     else
     988         904 :         return InvalidOid;
     989             : }
     990             : 
     991             : /*
     992             :  * Change Role ID while running (SET ROLE)
     993             :  *
     994             :  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
     995             :  * session user authorization.  In this case the is_superuser argument
     996             :  * is ignored.
     997             :  *
     998             :  * When roleid is not InvalidOid, the caller must have checked whether
     999             :  * the session user has permission to become that role.  (We cannot check
    1000             :  * here because this routine must be able to execute in a failed transaction
    1001             :  * to restore a prior value of the ROLE GUC variable.)
    1002             :  */
    1003             : void
    1004       41930 : SetCurrentRoleId(Oid roleid, bool is_superuser)
    1005             : {
    1006             :     /*
    1007             :      * Get correct info if it's SET ROLE NONE
    1008             :      *
    1009             :      * If SessionUserId hasn't been set yet, do nothing beyond updating
    1010             :      * SetRoleIsActive --- the eventual SetSessionAuthorization call will
    1011             :      * update the derived state.  This is needed since we will get called
    1012             :      * during GUC initialization.
    1013             :      */
    1014       41930 :     if (!OidIsValid(roleid))
    1015             :     {
    1016       40952 :         SetRoleIsActive = false;
    1017             : 
    1018       40952 :         if (!OidIsValid(SessionUserId))
    1019        1982 :             return;
    1020             : 
    1021       38970 :         roleid = SessionUserId;
    1022       38970 :         is_superuser = SessionUserIsSuperuser;
    1023             :     }
    1024             :     else
    1025         978 :         SetRoleIsActive = true;
    1026             : 
    1027       39948 :     SetOuterUserId(roleid, is_superuser);
    1028             : }
    1029             : 
    1030             : 
    1031             : /*
    1032             :  * Get user name from user oid, returns NULL for nonexistent roleid if noerr
    1033             :  * is true.
    1034             :  */
    1035             : char *
    1036       21224 : GetUserNameFromId(Oid roleid, bool noerr)
    1037             : {
    1038             :     HeapTuple   tuple;
    1039             :     char       *result;
    1040             : 
    1041       21224 :     tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
    1042       21224 :     if (!HeapTupleIsValid(tuple))
    1043             :     {
    1044          18 :         if (!noerr)
    1045           0 :             ereport(ERROR,
    1046             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1047             :                      errmsg("invalid role OID: %u", roleid)));
    1048          18 :         result = NULL;
    1049             :     }
    1050             :     else
    1051             :     {
    1052       21206 :         result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
    1053       21206 :         ReleaseSysCache(tuple);
    1054             :     }
    1055       21224 :     return result;
    1056             : }
    1057             : 
    1058             : /* ------------------------------------------------------------------------
    1059             :  *              Client connection state shared with parallel workers
    1060             :  *
    1061             :  * ClientConnectionInfo contains pieces of information about the client that
    1062             :  * need to be synced to parallel workers when they initialize.
    1063             :  *-------------------------------------------------------------------------
    1064             :  */
    1065             : 
    1066             : ClientConnectionInfo MyClientConnectionInfo;
    1067             : 
    1068             : /*
    1069             :  * Intermediate representation of ClientConnectionInfo for easier
    1070             :  * serialization.  Variable-length fields are allocated right after this
    1071             :  * header.
    1072             :  */
    1073             : typedef struct SerializedClientConnectionInfo
    1074             : {
    1075             :     int32       authn_id_len;   /* strlen(authn_id), or -1 if NULL */
    1076             :     UserAuth    auth_method;
    1077             : } SerializedClientConnectionInfo;
    1078             : 
    1079             : /*
    1080             :  * Calculate the space needed to serialize MyClientConnectionInfo.
    1081             :  */
    1082             : Size
    1083         892 : EstimateClientConnectionInfoSpace(void)
    1084             : {
    1085         892 :     Size        size = 0;
    1086             : 
    1087         892 :     size = add_size(size, sizeof(SerializedClientConnectionInfo));
    1088             : 
    1089         892 :     if (MyClientConnectionInfo.authn_id)
    1090           2 :         size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
    1091             : 
    1092         892 :     return size;
    1093             : }
    1094             : 
    1095             : /*
    1096             :  * Serialize MyClientConnectionInfo for use by parallel workers.
    1097             :  */
    1098             : void
    1099         892 : SerializeClientConnectionInfo(Size maxsize, char *start_address)
    1100             : {
    1101         892 :     SerializedClientConnectionInfo serialized = {0};
    1102             : 
    1103         892 :     serialized.authn_id_len = -1;
    1104         892 :     serialized.auth_method = MyClientConnectionInfo.auth_method;
    1105             : 
    1106         892 :     if (MyClientConnectionInfo.authn_id)
    1107           2 :         serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
    1108             : 
    1109             :     /* Copy serialized representation to buffer */
    1110             :     Assert(maxsize >= sizeof(serialized));
    1111         892 :     memcpy(start_address, &serialized, sizeof(serialized));
    1112             : 
    1113         892 :     maxsize -= sizeof(serialized);
    1114         892 :     start_address += sizeof(serialized);
    1115             : 
    1116             :     /* Copy authn_id into the space after the struct */
    1117         892 :     if (serialized.authn_id_len >= 0)
    1118             :     {
    1119             :         Assert(maxsize >= (serialized.authn_id_len + 1));
    1120           2 :         memcpy(start_address,
    1121           2 :                MyClientConnectionInfo.authn_id,
    1122             :         /* include the NULL terminator to ease deserialization */
    1123           2 :                serialized.authn_id_len + 1);
    1124             :     }
    1125         892 : }
    1126             : 
    1127             : /*
    1128             :  * Restore MyClientConnectionInfo from its serialized representation.
    1129             :  */
    1130             : void
    1131        2714 : RestoreClientConnectionInfo(char *conninfo)
    1132             : {
    1133             :     SerializedClientConnectionInfo serialized;
    1134             : 
    1135        2714 :     memcpy(&serialized, conninfo, sizeof(serialized));
    1136             : 
    1137             :     /* Copy the fields back into place */
    1138        2714 :     MyClientConnectionInfo.authn_id = NULL;
    1139        2714 :     MyClientConnectionInfo.auth_method = serialized.auth_method;
    1140             : 
    1141        2714 :     if (serialized.authn_id_len >= 0)
    1142             :     {
    1143             :         char       *authn_id;
    1144             : 
    1145           4 :         authn_id = conninfo + sizeof(serialized);
    1146           4 :         MyClientConnectionInfo.authn_id = MemoryContextStrdup(TopMemoryContext,
    1147             :                                                               authn_id);
    1148             :     }
    1149        2714 : }
    1150             : 
    1151             : 
    1152             : /*-------------------------------------------------------------------------
    1153             :  *              Interlock-file support
    1154             :  *
    1155             :  * These routines are used to create both a data-directory lockfile
    1156             :  * ($DATADIR/postmaster.pid) and Unix-socket-file lockfiles ($SOCKFILE.lock).
    1157             :  * Both kinds of files contain the same info initially, although we can add
    1158             :  * more information to a data-directory lockfile after it's created, using
    1159             :  * AddToDataDirLockFile().  See pidfile.h for documentation of the contents
    1160             :  * of these lockfiles.
    1161             :  *
    1162             :  * On successful lockfile creation, a proc_exit callback to remove the
    1163             :  * lockfile is automatically created.
    1164             :  *-------------------------------------------------------------------------
    1165             :  */
    1166             : 
    1167             : /*
    1168             :  * proc_exit callback to remove lockfiles.
    1169             :  */
    1170             : static void
    1171        1918 : UnlinkLockFiles(int status, Datum arg)
    1172             : {
    1173             :     ListCell   *l;
    1174             : 
    1175        5358 :     foreach(l, lock_files)
    1176             :     {
    1177        3440 :         char       *curfile = (char *) lfirst(l);
    1178             : 
    1179        3440 :         unlink(curfile);
    1180             :         /* Should we complain if the unlink fails? */
    1181             :     }
    1182             :     /* Since we're about to exit, no need to reclaim storage */
    1183        1918 :     lock_files = NIL;
    1184             : 
    1185             :     /*
    1186             :      * Lock file removal should always be the last externally visible action
    1187             :      * of a postmaster or standalone backend, while we won't come here at all
    1188             :      * when exiting postmaster child processes.  Therefore, this is a good
    1189             :      * place to log completion of shutdown.  We could alternatively teach
    1190             :      * proc_exit() to do it, but that seems uglier.  In a standalone backend,
    1191             :      * use NOTICE elevel to be less chatty.
    1192             :      */
    1193        1918 :     ereport(IsPostmasterEnvironment ? LOG : NOTICE,
    1194             :             (errmsg("database system is shut down")));
    1195        1918 : }
    1196             : 
    1197             : /*
    1198             :  * Create a lockfile.
    1199             :  *
    1200             :  * filename is the path name of the lockfile to create.
    1201             :  * amPostmaster is used to determine how to encode the output PID.
    1202             :  * socketDir is the Unix socket directory path to include (possibly empty).
    1203             :  * isDDLock and refName are used to determine what error message to produce.
    1204             :  */
    1205             : static void
    1206        3456 : CreateLockFile(const char *filename, bool amPostmaster,
    1207             :                const char *socketDir,
    1208             :                bool isDDLock, const char *refName)
    1209             : {
    1210             :     int         fd;
    1211             :     char        buffer[MAXPGPATH * 2 + 256];
    1212             :     int         ntries;
    1213             :     int         len;
    1214             :     int         encoded_pid;
    1215             :     pid_t       other_pid;
    1216             :     pid_t       my_pid,
    1217             :                 my_p_pid,
    1218             :                 my_gp_pid;
    1219             :     const char *envvar;
    1220             : 
    1221             :     /*
    1222             :      * If the PID in the lockfile is our own PID or our parent's or
    1223             :      * grandparent's PID, then the file must be stale (probably left over from
    1224             :      * a previous system boot cycle).  We need to check this because of the
    1225             :      * likelihood that a reboot will assign exactly the same PID as we had in
    1226             :      * the previous reboot, or one that's only one or two counts larger and
    1227             :      * hence the lockfile's PID now refers to an ancestor shell process.  We
    1228             :      * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
    1229             :      * via the environment variable PG_GRANDPARENT_PID; this is so that
    1230             :      * launching the postmaster via pg_ctl can be just as reliable as
    1231             :      * launching it directly.  There is no provision for detecting
    1232             :      * further-removed ancestor processes, but if the init script is written
    1233             :      * carefully then all but the immediate parent shell will be root-owned
    1234             :      * processes and so the kill test will fail with EPERM.  Note that we
    1235             :      * cannot get a false negative this way, because an existing postmaster
    1236             :      * would surely never launch a competing postmaster or pg_ctl process
    1237             :      * directly.
    1238             :      */
    1239        3456 :     my_pid = getpid();
    1240             : 
    1241             : #ifndef WIN32
    1242        3456 :     my_p_pid = getppid();
    1243             : #else
    1244             : 
    1245             :     /*
    1246             :      * Windows hasn't got getppid(), but doesn't need it since it's not using
    1247             :      * real kill() either...
    1248             :      */
    1249             :     my_p_pid = 0;
    1250             : #endif
    1251             : 
    1252        3456 :     envvar = getenv("PG_GRANDPARENT_PID");
    1253        3456 :     if (envvar)
    1254        2724 :         my_gp_pid = atoi(envvar);
    1255             :     else
    1256         732 :         my_gp_pid = 0;
    1257             : 
    1258             :     /*
    1259             :      * We need a loop here because of race conditions.  But don't loop forever
    1260             :      * (for example, a non-writable $PGDATA directory might cause a failure
    1261             :      * that won't go away).  100 tries seems like plenty.
    1262             :      */
    1263        3456 :     for (ntries = 0;; ntries++)
    1264             :     {
    1265             :         /*
    1266             :          * Try to create the lock file --- O_EXCL makes this atomic.
    1267             :          *
    1268             :          * Think not to make the file protection weaker than 0600/0640.  See
    1269             :          * comments below.
    1270             :          */
    1271        3466 :         fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
    1272        3466 :         if (fd >= 0)
    1273        3452 :             break;              /* Success; exit the retry loop */
    1274             : 
    1275             :         /*
    1276             :          * Couldn't create the pid file. Probably it already exists.
    1277             :          */
    1278          14 :         if ((errno != EEXIST && errno != EACCES) || ntries > 100)
    1279           0 :             ereport(FATAL,
    1280             :                     (errcode_for_file_access(),
    1281             :                      errmsg("could not create lock file \"%s\": %m",
    1282             :                             filename)));
    1283             : 
    1284             :         /*
    1285             :          * Read the file to get the old owner's PID.  Note race condition
    1286             :          * here: file might have been deleted since we tried to create it.
    1287             :          */
    1288          14 :         fd = open(filename, O_RDONLY, pg_file_create_mode);
    1289          14 :         if (fd < 0)
    1290             :         {
    1291           0 :             if (errno == ENOENT)
    1292           0 :                 continue;       /* race condition; try again */
    1293           0 :             ereport(FATAL,
    1294             :                     (errcode_for_file_access(),
    1295             :                      errmsg("could not open lock file \"%s\": %m",
    1296             :                             filename)));
    1297             :         }
    1298          14 :         pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_CREATE_READ);
    1299          14 :         if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
    1300           0 :             ereport(FATAL,
    1301             :                     (errcode_for_file_access(),
    1302             :                      errmsg("could not read lock file \"%s\": %m",
    1303             :                             filename)));
    1304          14 :         pgstat_report_wait_end();
    1305          14 :         close(fd);
    1306             : 
    1307          14 :         if (len == 0)
    1308             :         {
    1309           0 :             ereport(FATAL,
    1310             :                     (errcode(ERRCODE_LOCK_FILE_EXISTS),
    1311             :                      errmsg("lock file \"%s\" is empty", filename),
    1312             :                      errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
    1313             :         }
    1314             : 
    1315          14 :         buffer[len] = '\0';
    1316          14 :         encoded_pid = atoi(buffer);
    1317             : 
    1318             :         /* if pid < 0, the pid is for postgres, not postmaster */
    1319          14 :         other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
    1320             : 
    1321          14 :         if (other_pid <= 0)
    1322           0 :             elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
    1323             :                  filename, buffer);
    1324             : 
    1325             :         /*
    1326             :          * Check to see if the other process still exists
    1327             :          *
    1328             :          * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
    1329             :          * ignored as false matches.
    1330             :          *
    1331             :          * Normally kill() will fail with ESRCH if the given PID doesn't
    1332             :          * exist.
    1333             :          *
    1334             :          * We can treat the EPERM-error case as okay because that error
    1335             :          * implies that the existing process has a different userid than we
    1336             :          * do, which means it cannot be a competing postmaster.  A postmaster
    1337             :          * cannot successfully attach to a data directory owned by a userid
    1338             :          * other than its own, as enforced in checkDataDir(). Also, since we
    1339             :          * create the lockfiles mode 0600/0640, we'd have failed above if the
    1340             :          * lockfile belonged to another userid --- which means that whatever
    1341             :          * process kill() is reporting about isn't the one that made the
    1342             :          * lockfile.  (NOTE: this last consideration is the only one that
    1343             :          * keeps us from blowing away a Unix socket file belonging to an
    1344             :          * instance of Postgres being run by someone else, at least on
    1345             :          * machines where /tmp hasn't got a stickybit.)
    1346             :          */
    1347          14 :         if (other_pid != my_pid && other_pid != my_p_pid &&
    1348             :             other_pid != my_gp_pid)
    1349             :         {
    1350          14 :             if (kill(other_pid, 0) == 0 ||
    1351          10 :                 (errno != ESRCH && errno != EPERM))
    1352             :             {
    1353             :                 /* lockfile belongs to a live process */
    1354           4 :                 ereport(FATAL,
    1355             :                         (errcode(ERRCODE_LOCK_FILE_EXISTS),
    1356             :                          errmsg("lock file \"%s\" already exists",
    1357             :                                 filename),
    1358             :                          isDDLock ?
    1359             :                          (encoded_pid < 0 ?
    1360             :                           errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
    1361             :                                   (int) other_pid, refName) :
    1362             :                           errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
    1363             :                                   (int) other_pid, refName)) :
    1364             :                          (encoded_pid < 0 ?
    1365             :                           errhint("Is another postgres (PID %d) using socket file \"%s\"?",
    1366             :                                   (int) other_pid, refName) :
    1367             :                           errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
    1368             :                                   (int) other_pid, refName))));
    1369             :             }
    1370             :         }
    1371             : 
    1372             :         /*
    1373             :          * No, the creating process did not exist.  However, it could be that
    1374             :          * the postmaster crashed (or more likely was kill -9'd by a clueless
    1375             :          * admin) but has left orphan backends behind.  Check for this by
    1376             :          * looking to see if there is an associated shmem segment that is
    1377             :          * still in use.
    1378             :          *
    1379             :          * Note: because postmaster.pid is written in multiple steps, we might
    1380             :          * not find the shmem ID values in it; we can't treat that as an
    1381             :          * error.
    1382             :          */
    1383          10 :         if (isDDLock)
    1384             :         {
    1385           4 :             char       *ptr = buffer;
    1386             :             unsigned long id1,
    1387             :                         id2;
    1388             :             int         lineno;
    1389             : 
    1390          28 :             for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
    1391             :             {
    1392          24 :                 if ((ptr = strchr(ptr, '\n')) == NULL)
    1393           0 :                     break;
    1394          24 :                 ptr++;
    1395             :             }
    1396             : 
    1397           4 :             if (ptr != NULL &&
    1398           4 :                 sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
    1399             :             {
    1400           4 :                 if (PGSharedMemoryIsInUse(id1, id2))
    1401           0 :                     ereport(FATAL,
    1402             :                             (errcode(ERRCODE_LOCK_FILE_EXISTS),
    1403             :                              errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
    1404             :                                     id1, id2),
    1405             :                              errhint("Terminate any old server processes associated with data directory \"%s\".",
    1406             :                                      refName)));
    1407             :             }
    1408             :         }
    1409             : 
    1410             :         /*
    1411             :          * Looks like nobody's home.  Unlink the file and try again to create
    1412             :          * it.  Need a loop because of possible race condition against other
    1413             :          * would-be creators.
    1414             :          */
    1415          10 :         if (unlink(filename) < 0)
    1416           0 :             ereport(FATAL,
    1417             :                     (errcode_for_file_access(),
    1418             :                      errmsg("could not remove old lock file \"%s\": %m",
    1419             :                             filename),
    1420             :                      errhint("The file seems accidentally left over, but "
    1421             :                              "it could not be removed. Please remove the file "
    1422             :                              "by hand and try again.")));
    1423             :     }
    1424             : 
    1425             :     /*
    1426             :      * Successfully created the file, now fill it.  See comment in pidfile.h
    1427             :      * about the contents.  Note that we write the same first five lines into
    1428             :      * both datadir and socket lockfiles; although more stuff may get added to
    1429             :      * the datadir lockfile later.
    1430             :      */
    1431        3452 :     snprintf(buffer, sizeof(buffer), "%d\n%s\n" INT64_FORMAT "\n%d\n%s\n",
    1432             :              amPostmaster ? (int) my_pid : -((int) my_pid),
    1433             :              DataDir,
    1434             :              MyStartTime,
    1435             :              PostPortNumber,
    1436             :              socketDir);
    1437             : 
    1438             :     /*
    1439             :      * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
    1440             :      * will never receive data, so fill it in as empty now.
    1441             :      */
    1442        3452 :     if (isDDLock && !amPostmaster)
    1443         380 :         strlcat(buffer, "\n", sizeof(buffer));
    1444             : 
    1445        3452 :     errno = 0;
    1446        3452 :     pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_CREATE_WRITE);
    1447        3452 :     if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
    1448             :     {
    1449           0 :         int         save_errno = errno;
    1450             : 
    1451           0 :         close(fd);
    1452           0 :         unlink(filename);
    1453             :         /* if write didn't set errno, assume problem is no disk space */
    1454           0 :         errno = save_errno ? save_errno : ENOSPC;
    1455           0 :         ereport(FATAL,
    1456             :                 (errcode_for_file_access(),
    1457             :                  errmsg("could not write lock file \"%s\": %m", filename)));
    1458             :     }
    1459        3452 :     pgstat_report_wait_end();
    1460             : 
    1461        3452 :     pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_CREATE_SYNC);
    1462        3452 :     if (pg_fsync(fd) != 0)
    1463             :     {
    1464           0 :         int         save_errno = errno;
    1465             : 
    1466           0 :         close(fd);
    1467           0 :         unlink(filename);
    1468           0 :         errno = save_errno;
    1469           0 :         ereport(FATAL,
    1470             :                 (errcode_for_file_access(),
    1471             :                  errmsg("could not write lock file \"%s\": %m", filename)));
    1472             :     }
    1473        3452 :     pgstat_report_wait_end();
    1474        3452 :     if (close(fd) != 0)
    1475             :     {
    1476           0 :         int         save_errno = errno;
    1477             : 
    1478           0 :         unlink(filename);
    1479           0 :         errno = save_errno;
    1480           0 :         ereport(FATAL,
    1481             :                 (errcode_for_file_access(),
    1482             :                  errmsg("could not write lock file \"%s\": %m", filename)));
    1483             :     }
    1484             : 
    1485             :     /*
    1486             :      * Arrange to unlink the lock file(s) at proc_exit.  If this is the first
    1487             :      * one, set up the on_proc_exit function to do it; then add this lock file
    1488             :      * to the list of files to unlink.
    1489             :      */
    1490        3452 :     if (lock_files == NIL)
    1491        1924 :         on_proc_exit(UnlinkLockFiles, 0);
    1492             : 
    1493             :     /*
    1494             :      * Use lcons so that the lock files are unlinked in reverse order of
    1495             :      * creation; this is critical!
    1496             :      */
    1497        3452 :     lock_files = lcons(pstrdup(filename), lock_files);
    1498        3452 : }
    1499             : 
    1500             : /*
    1501             :  * Create the data directory lockfile.
    1502             :  *
    1503             :  * When this is called, we must have already switched the working
    1504             :  * directory to DataDir, so we can just use a relative path.  This
    1505             :  * helps ensure that we are locking the directory we should be.
    1506             :  *
    1507             :  * Note that the socket directory path line is initially written as empty.
    1508             :  * postmaster.c will rewrite it upon creating the first Unix socket.
    1509             :  */
    1510             : void
    1511        1928 : CreateDataDirLockFile(bool amPostmaster)
    1512             : {
    1513        1928 :     CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
    1514        1924 : }
    1515             : 
    1516             : /*
    1517             :  * Create a lockfile for the specified Unix socket file.
    1518             :  */
    1519             : void
    1520        1528 : CreateSocketLockFile(const char *socketfile, bool amPostmaster,
    1521             :                      const char *socketDir)
    1522             : {
    1523             :     char        lockfile[MAXPGPATH];
    1524             : 
    1525        1528 :     snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
    1526        1528 :     CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
    1527        1528 : }
    1528             : 
    1529             : /*
    1530             :  * TouchSocketLockFiles -- mark socket lock files as recently accessed
    1531             :  *
    1532             :  * This routine should be called every so often to ensure that the socket
    1533             :  * lock files have a recent mod or access date.  That saves them
    1534             :  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
    1535             :  * (Another reason we should never have put the socket file in /tmp...)
    1536             :  */
    1537             : void
    1538           0 : TouchSocketLockFiles(void)
    1539             : {
    1540             :     ListCell   *l;
    1541             : 
    1542           0 :     foreach(l, lock_files)
    1543             :     {
    1544           0 :         char       *socketLockFile = (char *) lfirst(l);
    1545             : 
    1546             :         /* No need to touch the data directory lock file, we trust */
    1547           0 :         if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
    1548           0 :             continue;
    1549             : 
    1550             :         /* we just ignore any error here */
    1551           0 :         (void) utime(socketLockFile, NULL);
    1552             :     }
    1553           0 : }
    1554             : 
    1555             : 
    1556             : /*
    1557             :  * Add (or replace) a line in the data directory lock file.
    1558             :  * The given string should not include a trailing newline.
    1559             :  *
    1560             :  * Note: because we don't truncate the file, if we were to rewrite a line
    1561             :  * with less data than it had before, there would be garbage after the last
    1562             :  * line.  While we could fix that by adding a truncate call, that would make
    1563             :  * the file update non-atomic, which we'd rather avoid.  Therefore, callers
    1564             :  * should endeavor never to shorten a line once it's been written.
    1565             :  */
    1566             : void
    1567        9658 : AddToDataDirLockFile(int target_line, const char *str)
    1568             : {
    1569             :     int         fd;
    1570             :     int         len;
    1571             :     int         lineno;
    1572             :     char       *srcptr;
    1573             :     char       *destptr;
    1574             :     char        srcbuffer[BLCKSZ];
    1575             :     char        destbuffer[BLCKSZ];
    1576             : 
    1577        9658 :     fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
    1578        9658 :     if (fd < 0)
    1579             :     {
    1580           0 :         ereport(LOG,
    1581             :                 (errcode_for_file_access(),
    1582             :                  errmsg("could not open file \"%s\": %m",
    1583             :                         DIRECTORY_LOCK_FILE)));
    1584           0 :         return;
    1585             :     }
    1586        9658 :     pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
    1587        9658 :     len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
    1588        9658 :     pgstat_report_wait_end();
    1589        9658 :     if (len < 0)
    1590             :     {
    1591           0 :         ereport(LOG,
    1592             :                 (errcode_for_file_access(),
    1593             :                  errmsg("could not read from file \"%s\": %m",
    1594             :                         DIRECTORY_LOCK_FILE)));
    1595           0 :         close(fd);
    1596           0 :         return;
    1597             :     }
    1598        9658 :     srcbuffer[len] = '\0';
    1599             : 
    1600             :     /*
    1601             :      * Advance over lines we are not supposed to rewrite, then copy them to
    1602             :      * destbuffer.
    1603             :      */
    1604        9658 :     srcptr = srcbuffer;
    1605       66172 :     for (lineno = 1; lineno < target_line; lineno++)
    1606             :     {
    1607       58044 :         char       *eol = strchr(srcptr, '\n');
    1608             : 
    1609       58044 :         if (eol == NULL)
    1610        1530 :             break;              /* not enough lines in file yet */
    1611       56514 :         srcptr = eol + 1;
    1612             :     }
    1613        9658 :     memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
    1614        9658 :     destptr = destbuffer + (srcptr - srcbuffer);
    1615             : 
    1616             :     /*
    1617             :      * Fill in any missing lines before the target line, in case lines are
    1618             :      * added to the file out of order.
    1619             :      */
    1620       11188 :     for (; lineno < target_line; lineno++)
    1621             :     {
    1622        1530 :         if (destptr < destbuffer + sizeof(destbuffer))
    1623        1530 :             *destptr++ = '\n';
    1624             :     }
    1625             : 
    1626             :     /*
    1627             :      * Write or rewrite the target line.
    1628             :      */
    1629        9658 :     snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
    1630        9658 :     destptr += strlen(destptr);
    1631             : 
    1632             :     /*
    1633             :      * If there are more lines in the old file, append them to destbuffer.
    1634             :      */
    1635        9658 :     if ((srcptr = strchr(srcptr, '\n')) != NULL)
    1636             :     {
    1637        6220 :         srcptr++;
    1638        6220 :         snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
    1639             :                  srcptr);
    1640             :     }
    1641             : 
    1642             :     /*
    1643             :      * And rewrite the data.  Since we write in a single kernel call, this
    1644             :      * update should appear atomic to onlookers.
    1645             :      */
    1646        9658 :     len = strlen(destbuffer);
    1647        9658 :     errno = 0;
    1648        9658 :     pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
    1649        9658 :     if (pg_pwrite(fd, destbuffer, len, 0) != len)
    1650             :     {
    1651           0 :         pgstat_report_wait_end();
    1652             :         /* if write didn't set errno, assume problem is no disk space */
    1653           0 :         if (errno == 0)
    1654           0 :             errno = ENOSPC;
    1655           0 :         ereport(LOG,
    1656             :                 (errcode_for_file_access(),
    1657             :                  errmsg("could not write to file \"%s\": %m",
    1658             :                         DIRECTORY_LOCK_FILE)));
    1659           0 :         close(fd);
    1660           0 :         return;
    1661             :     }
    1662        9658 :     pgstat_report_wait_end();
    1663        9658 :     pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
    1664        9658 :     if (pg_fsync(fd) != 0)
    1665             :     {
    1666           0 :         ereport(LOG,
    1667             :                 (errcode_for_file_access(),
    1668             :                  errmsg("could not write to file \"%s\": %m",
    1669             :                         DIRECTORY_LOCK_FILE)));
    1670             :     }
    1671        9658 :     pgstat_report_wait_end();
    1672        9658 :     if (close(fd) != 0)
    1673             :     {
    1674           0 :         ereport(LOG,
    1675             :                 (errcode_for_file_access(),
    1676             :                  errmsg("could not write to file \"%s\": %m",
    1677             :                         DIRECTORY_LOCK_FILE)));
    1678             :     }
    1679             : }
    1680             : 
    1681             : 
    1682             : /*
    1683             :  * Recheck that the data directory lock file still exists with expected
    1684             :  * content.  Return true if the lock file appears OK, false if it isn't.
    1685             :  *
    1686             :  * We call this periodically in the postmaster.  The idea is that if the
    1687             :  * lock file has been removed or replaced by another postmaster, we should
    1688             :  * do a panic database shutdown.  Therefore, we should return true if there
    1689             :  * is any doubt: we do not want to cause a panic shutdown unnecessarily.
    1690             :  * Transient failures like EINTR or ENFILE should not cause us to fail.
    1691             :  * (If there really is something wrong, we'll detect it on a future recheck.)
    1692             :  */
    1693             : bool
    1694          40 : RecheckDataDirLockFile(void)
    1695             : {
    1696             :     int         fd;
    1697             :     int         len;
    1698             :     long        file_pid;
    1699             :     char        buffer[BLCKSZ];
    1700             : 
    1701          40 :     fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
    1702          40 :     if (fd < 0)
    1703             :     {
    1704             :         /*
    1705             :          * There are many foreseeable false-positive error conditions.  For
    1706             :          * safety, fail only on enumerated clearly-something-is-wrong
    1707             :          * conditions.
    1708             :          */
    1709           0 :         switch (errno)
    1710             :         {
    1711           0 :             case ENOENT:
    1712             :             case ENOTDIR:
    1713             :                 /* disaster */
    1714           0 :                 ereport(LOG,
    1715             :                         (errcode_for_file_access(),
    1716             :                          errmsg("could not open file \"%s\": %m",
    1717             :                                 DIRECTORY_LOCK_FILE)));
    1718           0 :                 return false;
    1719           0 :             default:
    1720             :                 /* non-fatal, at least for now */
    1721           0 :                 ereport(LOG,
    1722             :                         (errcode_for_file_access(),
    1723             :                          errmsg("could not open file \"%s\": %m; continuing anyway",
    1724             :                                 DIRECTORY_LOCK_FILE)));
    1725           0 :                 return true;
    1726             :         }
    1727             :     }
    1728          40 :     pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ);
    1729          40 :     len = read(fd, buffer, sizeof(buffer) - 1);
    1730          40 :     pgstat_report_wait_end();
    1731          40 :     if (len < 0)
    1732             :     {
    1733           0 :         ereport(LOG,
    1734             :                 (errcode_for_file_access(),
    1735             :                  errmsg("could not read from file \"%s\": %m",
    1736             :                         DIRECTORY_LOCK_FILE)));
    1737           0 :         close(fd);
    1738           0 :         return true;            /* treat read failure as nonfatal */
    1739             :     }
    1740          40 :     buffer[len] = '\0';
    1741          40 :     close(fd);
    1742          40 :     file_pid = atol(buffer);
    1743          40 :     if (file_pid == getpid())
    1744          40 :         return true;            /* all is well */
    1745             : 
    1746             :     /* Trouble: someone's overwritten the lock file */
    1747           0 :     ereport(LOG,
    1748             :             (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
    1749             :                     DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
    1750           0 :     return false;
    1751             : }
    1752             : 
    1753             : 
    1754             : /*-------------------------------------------------------------------------
    1755             :  *              Version checking support
    1756             :  *-------------------------------------------------------------------------
    1757             :  */
    1758             : 
    1759             : /*
    1760             :  * Determine whether the PG_VERSION file in directory `path' indicates
    1761             :  * a data version compatible with the version of this program.
    1762             :  *
    1763             :  * If compatible, return. Otherwise, ereport(FATAL).
    1764             :  */
    1765             : void
    1766       32330 : ValidatePgVersion(const char *path)
    1767             : {
    1768             :     char        full_path[MAXPGPATH];
    1769             :     FILE       *file;
    1770             :     int         ret;
    1771             :     long        file_major;
    1772             :     long        my_major;
    1773             :     char       *endptr;
    1774             :     char        file_version_string[64];
    1775       32330 :     const char *my_version_string = PG_VERSION;
    1776             : 
    1777       32330 :     my_major = strtol(my_version_string, &endptr, 10);
    1778             : 
    1779       32330 :     snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
    1780             : 
    1781       32330 :     file = AllocateFile(full_path, "r");
    1782       32330 :     if (!file)
    1783             :     {
    1784           0 :         if (errno == ENOENT)
    1785           0 :             ereport(FATAL,
    1786             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1787             :                      errmsg("\"%s\" is not a valid data directory",
    1788             :                             path),
    1789             :                      errdetail("File \"%s\" is missing.", full_path)));
    1790             :         else
    1791           0 :             ereport(FATAL,
    1792             :                     (errcode_for_file_access(),
    1793             :                      errmsg("could not open file \"%s\": %m", full_path)));
    1794             :     }
    1795             : 
    1796       32330 :     file_version_string[0] = '\0';
    1797       32330 :     ret = fscanf(file, "%63s", file_version_string);
    1798       32330 :     file_major = strtol(file_version_string, &endptr, 10);
    1799             : 
    1800       32330 :     if (ret != 1 || endptr == file_version_string)
    1801           0 :         ereport(FATAL,
    1802             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1803             :                  errmsg("\"%s\" is not a valid data directory",
    1804             :                         path),
    1805             :                  errdetail("File \"%s\" does not contain valid data.",
    1806             :                            full_path),
    1807             :                  errhint("You might need to initdb.")));
    1808             : 
    1809       32330 :     FreeFile(file);
    1810             : 
    1811       32330 :     if (my_major != file_major)
    1812           0 :         ereport(FATAL,
    1813             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1814             :                  errmsg("database files are incompatible with server"),
    1815             :                  errdetail("The data directory was initialized by PostgreSQL version %s, "
    1816             :                            "which is not compatible with this version %s.",
    1817             :                            file_version_string, my_version_string)));
    1818       32330 : }
    1819             : 
    1820             : /*-------------------------------------------------------------------------
    1821             :  *              Library preload support
    1822             :  *-------------------------------------------------------------------------
    1823             :  */
    1824             : 
    1825             : /*
    1826             :  * GUC variables: lists of library names to be preloaded at postmaster
    1827             :  * start and at backend start
    1828             :  */
    1829             : char       *session_preload_libraries_string = NULL;
    1830             : char       *shared_preload_libraries_string = NULL;
    1831             : char       *local_preload_libraries_string = NULL;
    1832             : 
    1833             : /* Flag telling that we are loading shared_preload_libraries */
    1834             : bool        process_shared_preload_libraries_in_progress = false;
    1835             : bool        process_shared_preload_libraries_done = false;
    1836             : 
    1837             : shmem_request_hook_type shmem_request_hook = NULL;
    1838             : bool        process_shmem_requests_in_progress = false;
    1839             : 
    1840             : /*
    1841             :  * load the shared libraries listed in 'libraries'
    1842             :  *
    1843             :  * 'gucname': name of GUC variable, for error reports
    1844             :  * 'restricted': if true, force libraries to be in $libdir/plugins/
    1845             :  */
    1846             : static void
    1847       48426 : load_libraries(const char *libraries, const char *gucname, bool restricted)
    1848             : {
    1849             :     char       *rawstring;
    1850             :     List       *elemlist;
    1851             :     ListCell   *l;
    1852             : 
    1853       48426 :     if (libraries == NULL || libraries[0] == '\0')
    1854       48354 :         return;                 /* nothing to do */
    1855             : 
    1856             :     /* Need a modifiable copy of string */
    1857          72 :     rawstring = pstrdup(libraries);
    1858             : 
    1859             :     /* Parse string into list of filename paths */
    1860          72 :     if (!SplitDirectoriesString(rawstring, ',', &elemlist))
    1861             :     {
    1862             :         /* syntax error in list */
    1863           0 :         list_free_deep(elemlist);
    1864           0 :         pfree(rawstring);
    1865           0 :         ereport(LOG,
    1866             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    1867             :                  errmsg("invalid list syntax in parameter \"%s\"",
    1868             :                         gucname)));
    1869           0 :         return;
    1870             :     }
    1871             : 
    1872         146 :     foreach(l, elemlist)
    1873             :     {
    1874             :         /* Note that filename was already canonicalized */
    1875          74 :         char       *filename = (char *) lfirst(l);
    1876          74 :         char       *expanded = NULL;
    1877             : 
    1878             :         /* If restricting, insert $libdir/plugins if not mentioned already */
    1879          74 :         if (restricted && first_dir_separator(filename) == NULL)
    1880             :         {
    1881           0 :             expanded = psprintf("$libdir/plugins/%s", filename);
    1882           0 :             filename = expanded;
    1883             :         }
    1884          74 :         load_file(filename, restricted);
    1885          74 :         ereport(DEBUG1,
    1886             :                 (errmsg_internal("loaded library \"%s\"", filename)));
    1887          74 :         if (expanded)
    1888           0 :             pfree(expanded);
    1889             :     }
    1890             : 
    1891          72 :     list_free_deep(elemlist);
    1892          72 :     pfree(rawstring);
    1893             : }
    1894             : 
    1895             : /*
    1896             :  * process any libraries that should be preloaded at postmaster start
    1897             :  */
    1898             : void
    1899        1654 : process_shared_preload_libraries(void)
    1900             : {
    1901        1654 :     process_shared_preload_libraries_in_progress = true;
    1902        1654 :     load_libraries(shared_preload_libraries_string,
    1903             :                    "shared_preload_libraries",
    1904             :                    false);
    1905        1654 :     process_shared_preload_libraries_in_progress = false;
    1906        1654 :     process_shared_preload_libraries_done = true;
    1907        1654 : }
    1908             : 
    1909             : /*
    1910             :  * process any libraries that should be preloaded at backend start
    1911             :  */
    1912             : void
    1913       23386 : process_session_preload_libraries(void)
    1914             : {
    1915       23386 :     load_libraries(session_preload_libraries_string,
    1916             :                    "session_preload_libraries",
    1917             :                    false);
    1918       23386 :     load_libraries(local_preload_libraries_string,
    1919             :                    "local_preload_libraries",
    1920             :                    true);
    1921       23386 : }
    1922             : 
    1923             : /*
    1924             :  * process any shared memory requests from preloaded libraries
    1925             :  */
    1926             : void
    1927        1644 : process_shmem_requests(void)
    1928             : {
    1929        1644 :     process_shmem_requests_in_progress = true;
    1930        1644 :     if (shmem_request_hook)
    1931          24 :         shmem_request_hook();
    1932        1644 :     process_shmem_requests_in_progress = false;
    1933        1644 : }
    1934             : 
    1935             : void
    1936        3622 : pg_bindtextdomain(const char *domain)
    1937             : {
    1938             : #ifdef ENABLE_NLS
    1939        3622 :     if (my_exec_path[0] != '\0')
    1940             :     {
    1941             :         char        locale_path[MAXPGPATH];
    1942             : 
    1943        3622 :         get_locale_path(my_exec_path, locale_path);
    1944        3622 :         bindtextdomain(domain, locale_path);
    1945        3622 :         pg_bind_textdomain_codeset(domain);
    1946             :     }
    1947             : #endif
    1948        3622 : }

Generated by: LCOV version 1.14