LCOV - differential code coverage report
Current view: top level - src/backend/utils/init - miscinit.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 80.4 % 491 395 96 1 5 389 3
Current Date: 2026-11-28 16:48:44 +0900 Functions: 94.1 % 51 48 3 4 44
Baseline: lcov-20261128-baseline Branches: 49.6 % 399 198 1 1 2 197 3 4 1 190
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
[..1] days: 100.0 % 1 1 1
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 3 3 3
(360..) days: 80.2 % 486 390 96 1 389
Function coverage date bins:
(360..) days: 94.1 % 51 48 3 4 44
Branch coverage date bins:
(30,360] days: 50.0 % 2 1 1 1
(360..) days: 49.6 % 397 197 1 2 197 3 4 190

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

Generated by: LCOV version 2.0-1