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

Generated by: LCOV version 2.4-beta