PostgreSQL Source Code  git master
miscinit.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <signal.h>
#include <time.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <utime.h>
#include "access/htup_details.h"
#include "catalog/pg_authid.h"
#include "common/file_perm.h"
#include "libpq/libpq.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/pg_shmem.h"
#include "storage/pmsignal.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/pidfile.h"
#include "utils/syscache.h"
#include "utils/varlena.h"
Include dependency graph for miscinit.c:

Go to the source code of this file.

Macros

#define DIRECTORY_LOCK_FILE   "postmaster.pid"
 

Functions

void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
const char * GetBackendTypeDesc (BackendType backendType)
 
void SetDatabasePath (const char *path)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
static void SetOuterUserId (Oid userid)
 
Oid GetSessionUserId (void)
 
static void SetSessionUserId (Oid userid, bool is_superuser)
 
Oid GetAuthenticatedUserId (void)
 
void GetUserIdAndSecContext (Oid *userid, int *sec_context)
 
void SetUserIdAndSecContext (Oid userid, int sec_context)
 
bool InLocalUserIdChange (void)
 
bool InSecurityRestrictedOperation (void)
 
bool InNoForceRLSOperation (void)
 
void GetUserIdAndContext (Oid *userid, bool *sec_def_context)
 
void SetUserIdAndContext (Oid userid, bool sec_def_context)
 
bool has_rolreplication (Oid roleid)
 
void InitializeSessionUserId (const char *rolename, Oid roleid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
static void UnlinkLockFiles (int status, Datum arg)
 
static void CreateLockFile (const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
 
void CreateDataDirLockFile (bool amPostmaster)
 
void CreateSocketLockFile (const char *socketfile, bool amPostmaster, const char *socketDir)
 
void TouchSocketLockFiles (void)
 
void AddToDataDirLockFile (int target_line, const char *str)
 
bool RecheckDataDirLockFile (void)
 
void ValidatePgVersion (const char *path)
 
static void load_libraries (const char *libraries, const char *gucname, bool restricted)
 
void process_shared_preload_libraries (void)
 
void process_session_preload_libraries (void)
 
void pg_bindtextdomain (const char *domain)
 

Variables

ProcessingMode Mode = InitProcessing
 
BackendType MyBackendType
 
static Listlock_files = NIL
 
static Latch LocalLatchData
 
bool IgnoreSystemIndexes = false
 
static Oid AuthenticatedUserId = InvalidOid
 
static Oid SessionUserId = InvalidOid
 
static Oid OuterUserId = InvalidOid
 
static Oid CurrentUserId = InvalidOid
 
static bool AuthenticatedUserIsSuperuser = false
 
static bool SessionUserIsSuperuser = false
 
static int SecurityRestrictionContext = 0
 
static bool SetRoleIsActive = false
 
char * session_preload_libraries_string = NULL
 
char * shared_preload_libraries_string = NULL
 
char * local_preload_libraries_string = NULL
 
bool process_shared_preload_libraries_in_progress = false
 

Macro Definition Documentation

◆ DIRECTORY_LOCK_FILE

#define DIRECTORY_LOCK_FILE   "postmaster.pid"

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1329 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pg_fsync(), pg_pwrite(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, and WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE.

Referenced by InternalIpcMemoryCreate(), pmdie(), PostmasterMain(), reaper(), and sigusr1_handler().

1330 {
1331  int fd;
1332  int len;
1333  int lineno;
1334  char *srcptr;
1335  char *destptr;
1336  char srcbuffer[BLCKSZ];
1337  char destbuffer[BLCKSZ];
1338 
1339  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1340  if (fd < 0)
1341  {
1342  ereport(LOG,
1344  errmsg("could not open file \"%s\": %m",
1346  return;
1347  }
1349  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1351  if (len < 0)
1352  {
1353  ereport(LOG,
1355  errmsg("could not read from file \"%s\": %m",
1357  close(fd);
1358  return;
1359  }
1360  srcbuffer[len] = '\0';
1361 
1362  /*
1363  * Advance over lines we are not supposed to rewrite, then copy them to
1364  * destbuffer.
1365  */
1366  srcptr = srcbuffer;
1367  for (lineno = 1; lineno < target_line; lineno++)
1368  {
1369  char *eol = strchr(srcptr, '\n');
1370 
1371  if (eol == NULL)
1372  break; /* not enough lines in file yet */
1373  srcptr = eol + 1;
1374  }
1375  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1376  destptr = destbuffer + (srcptr - srcbuffer);
1377 
1378  /*
1379  * Fill in any missing lines before the target line, in case lines are
1380  * added to the file out of order.
1381  */
1382  for (; lineno < target_line; lineno++)
1383  {
1384  if (destptr < destbuffer + sizeof(destbuffer))
1385  *destptr++ = '\n';
1386  }
1387 
1388  /*
1389  * Write or rewrite the target line.
1390  */
1391  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1392  destptr += strlen(destptr);
1393 
1394  /*
1395  * If there are more lines in the old file, append them to destbuffer.
1396  */
1397  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1398  {
1399  srcptr++;
1400  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1401  srcptr);
1402  }
1403 
1404  /*
1405  * And rewrite the data. Since we write in a single kernel call, this
1406  * update should appear atomic to onlookers.
1407  */
1408  len = strlen(destbuffer);
1409  errno = 0;
1411  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1412  {
1414  /* if write didn't set errno, assume problem is no disk space */
1415  if (errno == 0)
1416  errno = ENOSPC;
1417  ereport(LOG,
1419  errmsg("could not write to file \"%s\": %m",
1421  close(fd);
1422  return;
1423  }
1426  if (pg_fsync(fd) != 0)
1427  {
1428  ereport(LOG,
1430  errmsg("could not write to file \"%s\": %m",
1432  }
1434  if (close(fd) != 0)
1435  {
1436  ereport(LOG,
1438  errmsg("could not write to file \"%s\": %m",
1440  }
1441 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1213
ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
Definition: pwrite.c:27
int errcode_for_file_access(void)
Definition: elog.c:633
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1466
#define ereport(elevel,...)
Definition: elog.h:144
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1442
int errmsg(const char *fmt,...)
Definition: elog.c:821
int pg_fsync(int fd)
Definition: fd.c:346
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:215
#define read(a, b, c)
Definition: win32.h:13

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 416 of file miscinit.c.

References AssertState, DataDir, ereport, errcode_for_file_access(), errmsg(), and FATAL.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

417 {
419 
420  if (chdir(DataDir) < 0)
421  ereport(FATAL,
423  errmsg("could not change directory to \"%s\": %m",
424  DataDir)));
425 }
#define AssertState(condition)
Definition: c.h:749
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:633
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821
char * DataDir
Definition: globals.c:62

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 302 of file miscinit.c.

References Assert, data_directory_mode, DataDir, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, pg_dir_create_mode, pg_mode_mask, PG_MODE_MASK_GROUP, S_ISDIR, SetDataDirectoryCreatePerm(), stat::st_mode, stat::st_uid, stat, and ValidatePgVersion().

Referenced by AuxiliaryProcessMain(), BackendRun(), PostgresMain(), and PostmasterMain().

303 {
304  struct stat stat_buf;
305 
306  Assert(DataDir);
307 
308  if (stat(DataDir, &stat_buf) != 0)
309  {
310  if (errno == ENOENT)
311  ereport(FATAL,
313  errmsg("data directory \"%s\" does not exist",
314  DataDir)));
315  else
316  ereport(FATAL,
318  errmsg("could not read permissions of directory \"%s\": %m",
319  DataDir)));
320  }
321 
322  /* eventual chdir would fail anyway, but let's test ... */
323  if (!S_ISDIR(stat_buf.st_mode))
324  ereport(FATAL,
325  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
326  errmsg("specified data directory \"%s\" is not a directory",
327  DataDir)));
328 
329  /*
330  * Check that the directory belongs to my userid; if not, reject.
331  *
332  * This check is an essential part of the interlock that prevents two
333  * postmasters from starting in the same directory (see CreateLockFile()).
334  * Do not remove or weaken it.
335  *
336  * XXX can we safely enable this check on Windows?
337  */
338 #if !defined(WIN32) && !defined(__CYGWIN__)
339  if (stat_buf.st_uid != geteuid())
340  ereport(FATAL,
341  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
342  errmsg("data directory \"%s\" has wrong ownership",
343  DataDir),
344  errhint("The server must be started by the user that owns the data directory.")));
345 #endif
346 
347  /*
348  * Check if the directory has correct permissions. If not, reject.
349  *
350  * Only two possible modes are allowed, 0700 and 0750. The latter mode
351  * indicates that group read/execute should be allowed on all newly
352  * created files and directories.
353  *
354  * XXX temporarily suppress check when on Windows, because there may not
355  * be proper support for Unix-y file permissions. Need to think of a
356  * reasonable check to apply on Windows.
357  */
358 #if !defined(WIN32) && !defined(__CYGWIN__)
360  ereport(FATAL,
361  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
362  errmsg("data directory \"%s\" has invalid permissions",
363  DataDir),
364  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
365 #endif
366 
367  /*
368  * Reset creation modes and mask based on the mode of the data directory.
369  *
370  * The mask was set earlier in startup to disallow group permissions on
371  * newly created files and directories. However, if group read/execute
372  * are present on the data directory then modify the create modes and mask
373  * to allow group read/execute on newly created files and directories and
374  * set the data_directory_mode GUC.
375  *
376  * Suppress when on Windows, because there may not be proper support for
377  * Unix-y file permissions.
378  */
379 #if !defined(WIN32) && !defined(__CYGWIN__)
381 
382  umask(pg_mode_mask);
384 #endif
385 
386  /* Check for PG_VERSION */
388 }
int errhint(const char *fmt,...)
Definition: elog.c:1068
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1528
int errcode(int sqlerrcode)
Definition: elog.c:610
short st_uid
Definition: win32_port.h:262
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
struct stat stat_buf
Definition: pg_standby.c:100
#define FATAL
Definition: elog.h:52
int errdetail(const char *fmt,...)
Definition: elog.c:954
int errcode_for_file_access(void)
Definition: elog.c:633
int pg_dir_create_mode
Definition: file_perm.c:18
unsigned short st_mode
Definition: win32_port.h:260
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
#define S_ISDIR(m)
Definition: win32_port.h:316
int errmsg(const char *fmt,...)
Definition: elog.c:821
int data_directory_mode
Definition: globals.c:68
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
char * DataDir
Definition: globals.c:62
int pg_mode_mask
Definition: file_perm.c:25
#define stat
Definition: win32_port.h:275

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1273 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

1274 {
1275  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1276 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:968
char * DataDir
Definition: globals.c:62

◆ CreateLockFile()

static void CreateLockFile ( const char *  filename,
bool  amPostmaster,
const char *  socketDir,
bool  isDDLock,
const char *  refName 
)
static

Definition at line 968 of file miscinit.c.

References close, DataDir, elog, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), kill, lcons(), LOCK_FILE_LINE_SHMEM_KEY, MAXPGPATH, MyStartTime, NIL, on_proc_exit(), pg_file_create_mode, pg_fsync(), PGSharedMemoryIsInUse(), pgstat_report_wait_end(), pgstat_report_wait_start(), PostPortNumber, pstrdup(), read, snprintf, strlcat(), UnlinkLockFiles(), WAIT_EVENT_LOCK_FILE_CREATE_READ, WAIT_EVENT_LOCK_FILE_CREATE_SYNC, WAIT_EVENT_LOCK_FILE_CREATE_WRITE, and write.

Referenced by CreateDataDirLockFile(), and CreateSocketLockFile().

971 {
972  int fd;
973  char buffer[MAXPGPATH * 2 + 256];
974  int ntries;
975  int len;
976  int encoded_pid;
977  pid_t other_pid;
978  pid_t my_pid,
979  my_p_pid,
980  my_gp_pid;
981  const char *envvar;
982 
983  /*
984  * If the PID in the lockfile is our own PID or our parent's or
985  * grandparent's PID, then the file must be stale (probably left over from
986  * a previous system boot cycle). We need to check this because of the
987  * likelihood that a reboot will assign exactly the same PID as we had in
988  * the previous reboot, or one that's only one or two counts larger and
989  * hence the lockfile's PID now refers to an ancestor shell process. We
990  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
991  * via the environment variable PG_GRANDPARENT_PID; this is so that
992  * launching the postmaster via pg_ctl can be just as reliable as
993  * launching it directly. There is no provision for detecting
994  * further-removed ancestor processes, but if the init script is written
995  * carefully then all but the immediate parent shell will be root-owned
996  * processes and so the kill test will fail with EPERM. Note that we
997  * cannot get a false negative this way, because an existing postmaster
998  * would surely never launch a competing postmaster or pg_ctl process
999  * directly.
1000  */
1001  my_pid = getpid();
1002 
1003 #ifndef WIN32
1004  my_p_pid = getppid();
1005 #else
1006 
1007  /*
1008  * Windows hasn't got getppid(), but doesn't need it since it's not using
1009  * real kill() either...
1010  */
1011  my_p_pid = 0;
1012 #endif
1013 
1014  envvar = getenv("PG_GRANDPARENT_PID");
1015  if (envvar)
1016  my_gp_pid = atoi(envvar);
1017  else
1018  my_gp_pid = 0;
1019 
1020  /*
1021  * We need a loop here because of race conditions. But don't loop forever
1022  * (for example, a non-writable $PGDATA directory might cause a failure
1023  * that won't go away). 100 tries seems like plenty.
1024  */
1025  for (ntries = 0;; ntries++)
1026  {
1027  /*
1028  * Try to create the lock file --- O_EXCL makes this atomic.
1029  *
1030  * Think not to make the file protection weaker than 0600/0640. See
1031  * comments below.
1032  */
1033  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
1034  if (fd >= 0)
1035  break; /* Success; exit the retry loop */
1036 
1037  /*
1038  * Couldn't create the pid file. Probably it already exists.
1039  */
1040  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
1041  ereport(FATAL,
1043  errmsg("could not create lock file \"%s\": %m",
1044  filename)));
1045 
1046  /*
1047  * Read the file to get the old owner's PID. Note race condition
1048  * here: file might have been deleted since we tried to create it.
1049  */
1050  fd = open(filename, O_RDONLY, pg_file_create_mode);
1051  if (fd < 0)
1052  {
1053  if (errno == ENOENT)
1054  continue; /* race condition; try again */
1055  ereport(FATAL,
1057  errmsg("could not open lock file \"%s\": %m",
1058  filename)));
1059  }
1061  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
1062  ereport(FATAL,
1064  errmsg("could not read lock file \"%s\": %m",
1065  filename)));
1067  close(fd);
1068 
1069  if (len == 0)
1070  {
1071  ereport(FATAL,
1072  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1073  errmsg("lock file \"%s\" is empty", filename),
1074  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
1075  }
1076 
1077  buffer[len] = '\0';
1078  encoded_pid = atoi(buffer);
1079 
1080  /* if pid < 0, the pid is for postgres, not postmaster */
1081  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
1082 
1083  if (other_pid <= 0)
1084  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
1085  filename, buffer);
1086 
1087  /*
1088  * Check to see if the other process still exists
1089  *
1090  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
1091  * ignored as false matches.
1092  *
1093  * Normally kill() will fail with ESRCH if the given PID doesn't
1094  * exist.
1095  *
1096  * We can treat the EPERM-error case as okay because that error
1097  * implies that the existing process has a different userid than we
1098  * do, which means it cannot be a competing postmaster. A postmaster
1099  * cannot successfully attach to a data directory owned by a userid
1100  * other than its own, as enforced in checkDataDir(). Also, since we
1101  * create the lockfiles mode 0600/0640, we'd have failed above if the
1102  * lockfile belonged to another userid --- which means that whatever
1103  * process kill() is reporting about isn't the one that made the
1104  * lockfile. (NOTE: this last consideration is the only one that
1105  * keeps us from blowing away a Unix socket file belonging to an
1106  * instance of Postgres being run by someone else, at least on
1107  * machines where /tmp hasn't got a stickybit.)
1108  */
1109  if (other_pid != my_pid && other_pid != my_p_pid &&
1110  other_pid != my_gp_pid)
1111  {
1112  if (kill(other_pid, 0) == 0 ||
1113  (errno != ESRCH && errno != EPERM))
1114  {
1115  /* lockfile belongs to a live process */
1116  ereport(FATAL,
1117  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1118  errmsg("lock file \"%s\" already exists",
1119  filename),
1120  isDDLock ?
1121  (encoded_pid < 0 ?
1122  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
1123  (int) other_pid, refName) :
1124  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
1125  (int) other_pid, refName)) :
1126  (encoded_pid < 0 ?
1127  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
1128  (int) other_pid, refName) :
1129  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
1130  (int) other_pid, refName))));
1131  }
1132  }
1133 
1134  /*
1135  * No, the creating process did not exist. However, it could be that
1136  * the postmaster crashed (or more likely was kill -9'd by a clueless
1137  * admin) but has left orphan backends behind. Check for this by
1138  * looking to see if there is an associated shmem segment that is
1139  * still in use.
1140  *
1141  * Note: because postmaster.pid is written in multiple steps, we might
1142  * not find the shmem ID values in it; we can't treat that as an
1143  * error.
1144  */
1145  if (isDDLock)
1146  {
1147  char *ptr = buffer;
1148  unsigned long id1,
1149  id2;
1150  int lineno;
1151 
1152  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
1153  {
1154  if ((ptr = strchr(ptr, '\n')) == NULL)
1155  break;
1156  ptr++;
1157  }
1158 
1159  if (ptr != NULL &&
1160  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
1161  {
1162  if (PGSharedMemoryIsInUse(id1, id2))
1163  ereport(FATAL,
1164  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1165  errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
1166  id1, id2),
1167  errhint("Terminate any old server processes associated with data directory \"%s\".",
1168  refName)));
1169  }
1170  }
1171 
1172  /*
1173  * Looks like nobody's home. Unlink the file and try again to create
1174  * it. Need a loop because of possible race condition against other
1175  * would-be creators.
1176  */
1177  if (unlink(filename) < 0)
1178  ereport(FATAL,
1180  errmsg("could not remove old lock file \"%s\": %m",
1181  filename),
1182  errhint("The file seems accidentally left over, but "
1183  "it could not be removed. Please remove the file "
1184  "by hand and try again.")));
1185  }
1186 
1187  /*
1188  * Successfully created the file, now fill it. See comment in pidfile.h
1189  * about the contents. Note that we write the same first five lines into
1190  * both datadir and socket lockfiles; although more stuff may get added to
1191  * the datadir lockfile later.
1192  */
1193  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
1194  amPostmaster ? (int) my_pid : -((int) my_pid),
1195  DataDir,
1196  (long) MyStartTime,
1198  socketDir);
1199 
1200  /*
1201  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1202  * will never receive data, so fill it in as empty now.
1203  */
1204  if (isDDLock && !amPostmaster)
1205  strlcat(buffer, "\n", sizeof(buffer));
1206 
1207  errno = 0;
1209  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1210  {
1211  int save_errno = errno;
1212 
1213  close(fd);
1214  unlink(filename);
1215  /* if write didn't set errno, assume problem is no disk space */
1216  errno = save_errno ? save_errno : ENOSPC;
1217  ereport(FATAL,
1219  errmsg("could not write lock file \"%s\": %m", filename)));
1220  }
1222 
1224  if (pg_fsync(fd) != 0)
1225  {
1226  int save_errno = errno;
1227 
1228  close(fd);
1229  unlink(filename);
1230  errno = save_errno;
1231  ereport(FATAL,
1233  errmsg("could not write lock file \"%s\": %m", filename)));
1234  }
1236  if (close(fd) != 0)
1237  {
1238  int save_errno = errno;
1239 
1240  unlink(filename);
1241  errno = save_errno;
1242  ereport(FATAL,
1244  errmsg("could not write lock file \"%s\": %m", filename)));
1245  }
1246 
1247  /*
1248  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1249  * one, set up the on_proc_exit function to do it; then add this lock file
1250  * to the list of files to unlink.
1251  */
1252  if (lock_files == NIL)
1254 
1255  /*
1256  * Use lcons so that the lock files are unlinked in reverse order of
1257  * creation; this is critical!
1258  */
1260 }
#define NIL
Definition: pg_list.h:65
int pg_file_create_mode
Definition: file_perm.c:19
int errhint(const char *fmt,...)
Definition: elog.c:1068
#define write(a, b, c)
Definition: win32.h:14
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
static List * lock_files
Definition: miscinit.c:65
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: pidfile.h:43
char * pstrdup(const char *in)
Definition: mcxt.c:1187
pg_time_t MyStartTime
Definition: globals.c:41
int errcode(int sqlerrcode)
Definition: elog.c:610
#define kill(pid, sig)
Definition: win32_port.h:454
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int PostPortNumber
Definition: postmaster.c:200
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:633
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1466
#define ereport(elevel,...)
Definition: elog.h:144
List * lcons(void *datum, List *list)
Definition: list.c:453
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1442
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:310
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:933
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
char * DataDir
Definition: globals.c:62
int pg_fsync(int fd)
Definition: fd.c:346
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:215
#define read(a, b, c)
Definition: win32.h:13
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33

◆ CreateSocketLockFile()

void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1282 of file miscinit.c.

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by StreamServerPort().

1284 {
1285  char lockfile[MAXPGPATH];
1286 
1287  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1288  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1289 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:968
#define MAXPGPATH
#define snprintf
Definition: port.h:215

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 535 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

536 {
538  return AuthenticatedUserId;
539 }
#define AssertState(condition)
Definition: c.h:749
#define OidIsValid(objectId)
Definition: c.h:652
static Oid AuthenticatedUserId
Definition: miscinit.c:456

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 230 of file miscinit.c.

References B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_INVALID, B_LOGGER, B_STARTUP, B_STATS_COLLECTOR, B_WAL_RECEIVER, B_WAL_SENDER, and B_WAL_WRITER.

Referenced by BackendInitialize(), init_ps_display(), log_line_prefix(), pg_stat_get_activity(), and write_csvlog().

231 {
232  const char *backendDesc = "unknown process type";
233 
234  switch (backendType)
235  {
236  case B_INVALID:
237  backendDesc = "not initialized";
238  break;
239  case B_AUTOVAC_LAUNCHER:
240  backendDesc = "autovacuum launcher";
241  break;
242  case B_AUTOVAC_WORKER:
243  backendDesc = "autovacuum worker";
244  break;
245  case B_BACKEND:
246  backendDesc = "client backend";
247  break;
248  case B_BG_WORKER:
249  backendDesc = "background worker";
250  break;
251  case B_BG_WRITER:
252  backendDesc = "background writer";
253  break;
254  case B_CHECKPOINTER:
255  backendDesc = "checkpointer";
256  break;
257  case B_STARTUP:
258  backendDesc = "startup";
259  break;
260  case B_WAL_RECEIVER:
261  backendDesc = "walreceiver";
262  break;
263  case B_WAL_SENDER:
264  backendDesc = "walsender";
265  break;
266  case B_WAL_WRITER:
267  backendDesc = "walwriter";
268  break;
269  case B_ARCHIVER:
270  backendDesc = "archiver";
271  break;
272  case B_STATS_COLLECTOR:
273  backendDesc = "stats collector";
274  break;
275  case B_LOGGER:
276  backendDesc = "logger";
277  break;
278  }
279 
280  return backendDesc;
281 }

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 835 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

836 {
837  if (SetRoleIsActive)
838  return OuterUserId;
839  else
840  return InvalidOid;
841 }
static Oid OuterUserId
Definition: miscinit.c:458
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:468

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 487 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

488 {
490  return OuterUserId;
491 }
#define AssertState(condition)
Definition: c.h:749
static Oid OuterUserId
Definition: miscinit.c:458
#define OidIsValid(objectId)
Definition: c.h:652

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 510 of file miscinit.c.

References AssertState, OidIsValid, and SessionUserId.

Referenced by check_role(), DropRole(), get_rolespec_oid(), get_rolespec_tuple(), InitPostgres(), is_admin_of_role(), pgstat_bestart(), RenameRole(), and session_user().

511 {
513  return SessionUserId;
514 }
#define AssertState(condition)
Definition: c.h:749
static Oid SessionUserId
Definition: miscinit.c:457
#define OidIsValid(objectId)
Definition: c.h:652

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 476 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), brin_summarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), convert_and_check_filename(), create_foreign_modify(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTrigger(), current_user(), currtid_byrelname(), currtid_byreloid(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), DelRoleMems(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteTruncateGuts(), extension_is_trusted(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_explain_guc_options(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), gin_clean_pending_list(), GrantRole(), HandleFunctionRequest(), has_any_column_privilege_id(), has_any_column_privilege_name(), has_column_privilege_id_attnum(), has_column_privilege_id_name(), has_column_privilege_name_attnum(), has_column_privilege_name_name(), has_database_privilege_id(), has_database_privilege_name(), has_foreign_data_wrapper_privilege_id(), has_foreign_data_wrapper_privilege_name(), has_function_privilege_id(), has_function_privilege_name(), has_language_privilege_id(), has_language_privilege_name(), has_schema_privilege_id(), has_schema_privilege_name(), has_sequence_privilege_id(), has_sequence_privilege_name(), has_server_privilege_id(), has_server_privilege_name(), has_table_privilege_id(), has_table_privilege_name(), has_tablespace_privilege_id(), has_tablespace_privilege_name(), has_type_privilege_id(), has_type_privilege_name(), have_createdb_privilege(), have_createrole_privilege(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), RemoveRoleFromObjectPolicy(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), sanity_check_relation(), select_perl_context(), set_foreign_rel_properties(), ShowAllGUCConfig(), statext_is_compatible_clause(), superuser(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_relation_owner(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

477 {
479  return CurrentUserId;
480 }
#define AssertState(condition)
Definition: c.h:749
#define OidIsValid(objectId)
Definition: c.h:652
static Oid CurrentUserId
Definition: miscinit.c:459

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 630 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

631 {
632  *userid = CurrentUserId;
633  *sec_def_context = InLocalUserIdChange();
634 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:599
static Oid CurrentUserId
Definition: miscinit.c:459

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 891 of file miscinit.c.

References AUTHOID, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, NameStr, ObjectIdGetDatum, pstrdup(), ReleaseSysCache(), rolname, and SearchSysCache1().

Referenced by check_is_member_of_role(), current_user(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), insert_username(), regroleout(), RemoveRoleFromObjectPolicy(), and session_user().

892 {
893  HeapTuple tuple;
894  char *result;
895 
896  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
897  if (!HeapTupleIsValid(tuple))
898  {
899  if (!noerr)
900  ereport(ERROR,
901  (errcode(ERRCODE_UNDEFINED_OBJECT),
902  errmsg("invalid role OID: %u", roleid)));
903  result = NULL;
904  }
905  else
906  {
907  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
908  ReleaseSysCache(tuple);
909  }
910  return result;
911 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData rolname
Definition: pg_authid.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1187
int errcode(int sqlerrcode)
Definition: elog.c:610
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define NameStr(name)
Definition: c.h:623

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 657 of file miscinit.c.

References AUTHOID, GETSTRUCT, HeapTupleIsValid, ObjectIdGetDatum, ReleaseSysCache(), rolreplication, and SearchSysCache1().

Referenced by check_permissions(), and InitPostgres().

658 {
659  bool result = false;
660  HeapTuple utup;
661 
662  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
663  if (HeapTupleIsValid(utup))
664  {
665  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
666  ReleaseSysCache(utup);
667  }
668  return result;
669 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
bool rolreplication
Definition: pg_authid.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 675 of file miscinit.c.

References AcceptInvalidationMessages(), AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, HeapTupleIsValid, IsBootstrapProcessingMode, IsUnderPostmaster, MyProc, NameStr, ObjectIdGetDatum, OidIsValid, PGC_BACKEND, PGC_INTERNAL, PGC_S_OVERRIDE, PointerGetDatum, ReleaseSysCache(), PGPROC::roleId, SearchSysCache1(), SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

676 {
677  HeapTuple roleTup;
678  Form_pg_authid rform;
679  char *rname;
680 
681  /*
682  * Don't do scans if we're bootstrapping, none of the system catalogs
683  * exist yet, and they should be owned by postgres anyway.
684  */
686 
687  /* call only once */
689 
690  /*
691  * Make sure syscache entries are flushed for recent catalog changes. This
692  * allows us to find roles that were created on-the-fly during
693  * authentication.
694  */
696 
697  if (rolename != NULL)
698  {
699  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
700  if (!HeapTupleIsValid(roleTup))
701  ereport(FATAL,
702  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
703  errmsg("role \"%s\" does not exist", rolename)));
704  }
705  else
706  {
707  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
708  if (!HeapTupleIsValid(roleTup))
709  ereport(FATAL,
710  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
711  errmsg("role with OID %u does not exist", roleid)));
712  }
713 
714  rform = (Form_pg_authid) GETSTRUCT(roleTup);
715  roleid = rform->oid;
716  rname = NameStr(rform->rolname);
717 
718  AuthenticatedUserId = roleid;
719  AuthenticatedUserIsSuperuser = rform->rolsuper;
720 
721  /* This sets OuterUserId/CurrentUserId too */
723 
724  /* Also mark our PGPROC entry with the authenticated user id */
725  /* (We assume this is an atomic store so no lock is needed) */
726  MyProc->roleId = roleid;
727 
728  /*
729  * These next checks are not enforced when in standalone mode, so that
730  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
731  * rolcanlogin = false;".
732  */
733  if (IsUnderPostmaster)
734  {
735  /*
736  * Is role allowed to login at all?
737  */
738  if (!rform->rolcanlogin)
739  ereport(FATAL,
740  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
741  errmsg("role \"%s\" is not permitted to log in",
742  rname)));
743 
744  /*
745  * Check connection limit for this role.
746  *
747  * There is a race condition here --- we create our PGPROC before
748  * checking for other PGPROCs. If two backends did this at about the
749  * same time, they might both think they were over the limit, while
750  * ideally one should succeed and one fail. Getting that to work
751  * exactly seems more trouble than it is worth, however; instead we
752  * just document that the connection limit is approximate.
753  */
754  if (rform->rolconnlimit >= 0 &&
756  CountUserBackends(roleid) > rform->rolconnlimit)
757  ereport(FATAL,
758  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
759  errmsg("too many connections for role \"%s\"",
760  rname)));
761  }
762 
763  /* Record username and superuser status as GUC settings too */
764  SetConfigOption("session_authorization", rname,
766  SetConfigOption("is_superuser",
767  AuthenticatedUserIsSuperuser ? "on" : "off",
769 
770  ReleaseSysCache(roleTup);
771 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
#define AssertState(condition)
Definition: c.h:749
void AcceptInvalidationMessages(void)
Definition: inval.c:684
PGPROC * MyProc
Definition: proc.c:67
#define PointerGetDatum(X)
Definition: postgres.h:556
Oid roleId
Definition: proc.h:146
int errcode(int sqlerrcode)
Definition: elog.c:610
#define OidIsValid(objectId)
Definition: c.h:652
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define FATAL
Definition: elog.h:52
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7742
bool IsUnderPostmaster
Definition: globals.c:109
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:462
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int CountUserBackends(Oid roleid)
Definition: procarray.c:3524
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:393
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define NameStr(name)
Definition: c.h:623
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:518
static Oid AuthenticatedUserId
Definition: miscinit.c:456

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 778 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsUnderPostmaster, OidIsValid, and SetSessionUserId().

Referenced by InitPostgres().

779 {
780  /*
781  * This function should only be called in single-user mode, in autovacuum
782  * workers, and in background workers.
783  */
785 
786  /* call only once */
788 
789  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
791 
792  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
793 }
#define AssertState(condition)
Definition: c.h:749
#define OidIsValid(objectId)
Definition: c.h:652
bool IsBackgroundWorker
Definition: globals.c:111
bool IsUnderPostmaster
Definition: globals.c:109
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:462
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3325
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:518
static Oid AuthenticatedUserId
Definition: miscinit.c:456

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 93 of file miscinit.c.

References BlockSig, elog, FATAL, InitializeLatchSupport(), InitializeLatchWaitSet(), InitLatch(), InitProcessGlobals(), IsUnderPostmaster, LocalLatchData, MyLatch, on_exit_reset(), PG_SETMASK, PostmasterDeathSignalInit(), pqinitmask(), pqsignal(), set_stack_base(), SignalHandlerForCrashExit(), and SIGQUIT.

Referenced by BackendRun(), BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

94 {
95  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
96 
97  /*
98  * Set reference point for stack-depth checking. We re-do that even in the
99  * !EXEC_BACKEND case, because there are some edge cases where processes
100  * are started with an alternative stack (e.g. starting bgworkers when
101  * running postgres using the rr debugger, as bgworkers are launched from
102  * signal handlers).
103  */
104  set_stack_base();
105 
107 
108  /*
109  * make sure stderr is in binary mode before anything can possibly be
110  * written to it, in case it's actually the syslogger pipe, so the pipe
111  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
112  * redirection (e.g. via pg_ctl -l) anyway.
113  */
114 #ifdef WIN32
115  _setmode(fileno(stderr), _O_BINARY);
116 #endif
117 
118  /* We don't want the postmaster's proc_exit() handlers */
119  on_exit_reset();
120 
121  /* Initialize process-local latch support */
126 
127  /*
128  * If possible, make this process a group leader, so that the postmaster
129  * can signal any child processes too. Not all processes will have
130  * children, but for consistency we make all postmaster child processes do
131  * this.
132  */
133 #ifdef HAVE_SETSID
134  if (setsid() < 0)
135  elog(FATAL, "setsid() failed: %m");
136 #endif
137 
138  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
139 #ifdef EXEC_BACKEND
140  pqinitmask();
141 #endif
142 
143  /*
144  * Every postmaster child process is expected to respond promptly to
145  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
146  * BlockSig and install a suitable signal handler. (Client-facing
147  * processes may choose to replace this default choice of handler with
148  * quickdie().) All other blockable signals remain blocked for now.
149  */
151 
152  sigdelset(&BlockSig, SIGQUIT);
154 
155  /* Request a signal if the postmaster dies, if possible. */
157 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3259
#define SIGQUIT
Definition: win32_port.h:160
void InitLatch(Latch *latch)
Definition: latch.c:274
void InitProcessGlobals(void)
Definition: postmaster.c:2645
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pqinitmask(void)
Definition: pqsignal.c:41
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:72
void on_exit_reset(void)
Definition: ipc.c:412
static Latch LocalLatchData
Definition: miscinit.c:67
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:109
sigset_t BlockSig
Definition: pqsignal.c:22
void InitializeLatchSupport(void)
Definition: latch.c:175
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
void InitializeLatchWaitSet(void)
Definition: latch.c:253
#define elog(elevel,...)
Definition: elog.h:214
struct Latch * MyLatch
Definition: globals.c:54
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:370

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 165 of file miscinit.c.

References Assert, BlockSig, elog, FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitLatch(), InitProcessGlobals(), IsPostmasterEnvironment, LocalLatchData, my_exec_path, MyLatch, PG_SETMASK, pkglib_path, and pqinitmask().

Referenced by AuxiliaryProcessMain(), and PostgresMain().

166 {
168 
170 
171  /* Initialize process-local latch support */
176 
177  /*
178  * For consistency with InitPostmasterChild, initialize signal mask here.
179  * But we don't unblock SIGQUIT or provide a default handler for it.
180  */
181  pqinitmask();
183 
184  /* Compute paths, no postmaster to inherit from */
185  if (my_exec_path[0] == '\0')
186  {
187  if (find_my_exec(argv0, my_exec_path) < 0)
188  elog(FATAL, "%s: could not locate my own executable path",
189  argv0);
190  }
191 
192  if (pkglib_path[0] == '\0')
194 }
bool IsPostmasterEnvironment
Definition: globals.c:108
static char * argv0
Definition: pg_ctl.c:97
void InitLatch(Latch *latch)
Definition: latch.c:274
void InitProcessGlobals(void)
Definition: postmaster.c:2645
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void pqinitmask(void)
Definition: pqsignal.c:41
static Latch LocalLatchData
Definition: miscinit.c:67
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
sigset_t BlockSig
Definition: pqsignal.c:22
void InitializeLatchSupport(void)
Definition: latch.c:175
#define Assert(condition)
Definition: c.h:746
void InitializeLatchWaitSet(void)
Definition: latch.c:253
#define elog(elevel,...)
Definition: elog.h:214
struct Latch * MyLatch
Definition: globals.c:54
char pkglib_path[MAXPGPATH]
Definition: globals.c:73

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 599 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), is_admin_of_role(), and set_config_option().

600 {
602 }
static int SecurityRestrictionContext
Definition: miscinit.c:465
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:298

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 617 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

618 {
620 }
static int SecurityRestrictionContext
Definition: miscinit.c:465
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:300

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

Definition at line 608 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

Referenced by CheckRestrictedOperation(), DefineRelation(), is_admin_of_role(), set_config_option(), and SetUserIdAndContext().

609 {
611 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:299
static int SecurityRestrictionContext
Definition: miscinit.c:465

◆ load_libraries()

static void load_libraries ( const char *  libraries,
const char *  gucname,
bool  restricted 
)
static

Definition at line 1605 of file miscinit.c.

References DEBUG1, ereport, errcode(), errmsg(), filename, first_dir_separator(), lfirst, list_free_deep(), load_file(), LOG, pfree(), psprintf(), pstrdup(), and SplitDirectoriesString().

Referenced by process_session_preload_libraries(), and process_shared_preload_libraries().

1606 {
1607  char *rawstring;
1608  List *elemlist;
1609  ListCell *l;
1610 
1611  if (libraries == NULL || libraries[0] == '\0')
1612  return; /* nothing to do */
1613 
1614  /* Need a modifiable copy of string */
1615  rawstring = pstrdup(libraries);
1616 
1617  /* Parse string into list of filename paths */
1618  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1619  {
1620  /* syntax error in list */
1621  list_free_deep(elemlist);
1622  pfree(rawstring);
1623  ereport(LOG,
1624  (errcode(ERRCODE_SYNTAX_ERROR),
1625  errmsg("invalid list syntax in parameter \"%s\"",
1626  gucname)));
1627  return;
1628  }
1629 
1630  foreach(l, elemlist)
1631  {
1632  /* Note that filename was already canonicalized */
1633  char *filename = (char *) lfirst(l);
1634  char *expanded = NULL;
1635 
1636  /* If restricting, insert $libdir/plugins if not mentioned already */
1637  if (restricted && first_dir_separator(filename) == NULL)
1638  {
1639  expanded = psprintf("$libdir/plugins/%s", filename);
1640  filename = expanded;
1641  }
1642  load_file(filename, restricted);
1643  ereport(DEBUG1,
1644  (errmsg("loaded library \"%s\"", filename)));
1645  if (expanded)
1646  pfree(expanded);
1647  }
1648 
1649  list_free_deep(elemlist);
1650  pfree(rawstring);
1651 }
#define DEBUG1
Definition: elog.h:25
char * pstrdup(const char *in)
Definition: mcxt.c:1187
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LOG
Definition: elog.h:26
void list_free_deep(List *list)
Definition: list.c:1390
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3829
void pfree(void *pointer)
Definition: mcxt.c:1057
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:169
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:821
Definition: pg_list.h:50

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1681 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1682 {
1683 #ifdef ENABLE_NLS
1684  if (my_exec_path[0] != '\0')
1685  {
1686  char locale_path[MAXPGPATH];
1687 
1688  get_locale_path(my_exec_path, locale_path);
1689  bindtextdomain(domain, locale_path);
1690  pg_bind_textdomain_codeset(domain);
1691  }
1692 #endif
1693 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1670 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1671 {
1673  "session_preload_libraries",
1674  false);
1676  "local_preload_libraries",
1677  true);
1678 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1605
char * local_preload_libraries_string
Definition: miscinit.c:1593
char * session_preload_libraries_string
Definition: miscinit.c:1591

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1657 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1658 {
1661  "shared_preload_libraries",
1662  false);
1664 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1596
char * shared_preload_libraries_string
Definition: miscinit.c:1592
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1605

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1456 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pgstat_report_wait_end(), pgstat_report_wait_start(), read, and WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ.

Referenced by ServerLoop().

1457 {
1458  int fd;
1459  int len;
1460  long file_pid;
1461  char buffer[BLCKSZ];
1462 
1463  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1464  if (fd < 0)
1465  {
1466  /*
1467  * There are many foreseeable false-positive error conditions. For
1468  * safety, fail only on enumerated clearly-something-is-wrong
1469  * conditions.
1470  */
1471  switch (errno)
1472  {
1473  case ENOENT:
1474  case ENOTDIR:
1475  /* disaster */
1476  ereport(LOG,
1478  errmsg("could not open file \"%s\": %m",
1480  return false;
1481  default:
1482  /* non-fatal, at least for now */
1483  ereport(LOG,
1485  errmsg("could not open file \"%s\": %m; continuing anyway",
1487  return true;
1488  }
1489  }
1491  len = read(fd, buffer, sizeof(buffer) - 1);
1493  if (len < 0)
1494  {
1495  ereport(LOG,
1497  errmsg("could not read from file \"%s\": %m",
1499  close(fd);
1500  return true; /* treat read failure as nonfatal */
1501  }
1502  buffer[len] = '\0';
1503  close(fd);
1504  file_pid = atol(buffer);
1505  if (file_pid == getpid())
1506  return true; /* all is well */
1507 
1508  /* Trouble: someone's overwritten the lock file */
1509  ereport(LOG,
1510  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1511  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1512  return false;
1513 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1213
int errcode_for_file_access(void)
Definition: elog.c:633
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1466
#define ereport(elevel,...)
Definition: elog.h:144
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1442
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 856 of file miscinit.c.

References OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SessionUserId, SessionUserIsSuperuser, SetConfigOption(), SetOuterUserId(), and SetRoleIsActive.

Referenced by assign_role(), and ParallelWorkerMain().

857 {
858  /*
859  * Get correct info if it's SET ROLE NONE
860  *
861  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
862  * SetSessionUserId call will fix everything. This is needed since we
863  * will get called during GUC initialization.
864  */
865  if (!OidIsValid(roleid))
866  {
868  return;
869 
870  roleid = SessionUserId;
872 
873  SetRoleIsActive = false;
874  }
875  else
876  SetRoleIsActive = true;
877 
878  SetOuterUserId(roleid);
879 
880  SetConfigOption("is_superuser",
881  is_superuser ? "on" : "off",
883 }
static Oid SessionUserId
Definition: miscinit.c:457
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:495
#define OidIsValid(objectId)
Definition: c.h:652
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7742
static bool SetRoleIsActive
Definition: miscinit.c:468
static bool SessionUserIsSuperuser
Definition: miscinit.c:463
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4189

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 289 of file miscinit.c.

References Assert, DatabasePath, MemoryContextStrdup(), and TopMemoryContext.

Referenced by InitPostgres().

290 {
291  /* This should happen only once per process */
294 }
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * DatabasePath
Definition: globals.c:93
#define Assert(condition)
Definition: c.h:746
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 395 of file miscinit.c.

References AssertArg, DataDir, free, and make_absolute_path().

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

396 {
397  char *new;
398 
399  AssertArg(dir);
400 
401  /* If presented path is relative, convert to absolute */
402  new = make_absolute_path(dir);
403 
404  if (DataDir)
405  free(DataDir);
406  DataDir = new;
407 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:748
#define free(a)
Definition: header.h:65
char * DataDir
Definition: globals.c:62

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 495 of file miscinit.c.

References AssertArg, AssertState, CurrentUserId, OidIsValid, OuterUserId, and SecurityRestrictionContext.

Referenced by SetCurrentRoleId().

496 {
498  AssertArg(OidIsValid(userid));
499  OuterUserId = userid;
500 
501  /* We force the effective user ID to match, too */
502  CurrentUserId = userid;
503 }
#define AssertState(condition)
Definition: c.h:749
static Oid OuterUserId
Definition: miscinit.c:458
#define OidIsValid(objectId)
Definition: c.h:652
static int SecurityRestrictionContext
Definition: miscinit.c:465
#define AssertArg(condition)
Definition: c.h:748
static Oid CurrentUserId
Definition: miscinit.c:459

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 810 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), ERRCODE_INSUFFICIENT_PRIVILEGE, errmsg(), ERROR, OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

811 {
812  /* Must have authenticated already, else can't make permission check */
814 
815  if (userid != AuthenticatedUserId &&
817  ereport(ERROR,
819  errmsg("permission denied to set session authorization")));
820 
822 
823  SetConfigOption("is_superuser",
824  is_superuser ? "on" : "off",
826 }
#define AssertState(condition)
Definition: c.h:749
int errcode(int sqlerrcode)
Definition: elog.c:610
#define OidIsValid(objectId)
Definition: c.h:652
#define ERRCODE_INSUFFICIENT_PRIVILEGE
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7742
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:462
#define ereport(elevel,...)
Definition: elog.h:144
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4189
int errmsg(const char *fmt,...)
Definition: elog.c:821
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:518
static Oid AuthenticatedUserId
Definition: miscinit.c:456

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 518 of file miscinit.c.

References AssertArg, AssertState, CurrentUserId, is_superuser(), OidIsValid, OuterUserId, SecurityRestrictionContext, SessionUserId, SessionUserIsSuperuser, and SetRoleIsActive.

Referenced by InitializeSessionUserId(), InitializeSessionUserIdStandalone(), and SetSessionAuthorization().

519 {
521  AssertArg(OidIsValid(userid));
522  SessionUserId = userid;
524  SetRoleIsActive = false;
525 
526  /* We force the effective user IDs to match, too */
527  OuterUserId = userid;
528  CurrentUserId = userid;
529 }
#define AssertState(condition)
Definition: c.h:749
static Oid SessionUserId
Definition: miscinit.c:457
static Oid OuterUserId
Definition: miscinit.c:458
#define OidIsValid(objectId)
Definition: c.h:652
static int SecurityRestrictionContext
Definition: miscinit.c:465
#define AssertArg(condition)
Definition: c.h:748
static bool SetRoleIsActive
Definition: miscinit.c:468
static bool SessionUserIsSuperuser
Definition: miscinit.c:463
static Oid CurrentUserId
Definition: miscinit.c:459
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4189

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 637 of file miscinit.c.

References CurrentUserId, ereport, errcode(), ERRCODE_INSUFFICIENT_PRIVILEGE, errmsg(), ERROR, InSecurityRestrictedOperation(), SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

638 {
639  /* We throw the same error SET ROLE would. */
641  ereport(ERROR,
643  errmsg("cannot set parameter \"%s\" within security-restricted operation",
644  "role")));
645  CurrentUserId = userid;
646  if (sec_def_context)
648  else
650 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERRCODE_INSUFFICIENT_PRIVILEGE
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:465
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:298
#define ereport(elevel,...)
Definition: elog.h:144
static Oid CurrentUserId
Definition: miscinit.c:459
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:608
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 216 of file miscinit.c.

References Assert, FeBeWaitSet, LocalLatchData, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by AuxiliaryProcKill(), and ProcKill().

217 {
219  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
220 
222 
223  if (FeBeWaitSet)
225 
226  SetLatch(MyLatch);
227 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:887
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:184
void SetLatch(Latch *latch)
Definition: latch.c:505
Latch procLatch
Definition: proc.h:121
static Latch LocalLatchData
Definition: miscinit.c:67
#define Assert(condition)
Definition: c.h:746
struct Latch * MyLatch
Definition: globals.c:54
#define WL_LATCH_SET
Definition: latch.h:124

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 197 of file miscinit.c.

References Assert, FeBeWaitSet, ModifyWaitEvent(), MyLatch, MyProc, PGPROC::procLatch, SetLatch(), and WL_LATCH_SET.

Referenced by InitAuxiliaryProcess(), and InitProcess().

198 {
200  Assert(MyProc != NULL);
201 
203 
204  if (FeBeWaitSet)
206 
207  /*
208  * Set the shared latch as the local one might have been set. This
209  * shouldn't normally be necessary as code is supposed to check the
210  * condition before waiting for the latch, but a bit care can't hurt.
211  */
212  SetLatch(MyLatch);
213 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:887
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:184
void SetLatch(Latch *latch)
Definition: latch.c:505
Latch procLatch
Definition: proc.h:121
static Latch LocalLatchData
Definition: miscinit.c:67
#define Assert(condition)
Definition: c.h:746
struct Latch * MyLatch
Definition: globals.c:54
#define WL_LATCH_SET
Definition: latch.h:124

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1300 of file miscinit.c.

References DIRECTORY_LOCK_FILE, and lfirst.

Referenced by ServerLoop().

1301 {
1302  ListCell *l;
1303 
1304  foreach(l, lock_files)
1305  {
1306  char *socketLockFile = (char *) lfirst(l);
1307 
1308  /* No need to touch the data directory lock file, we trust */
1309  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1310  continue;
1311 
1312  /* we just ignore any error here */
1313  (void) utime(socketLockFile, NULL);
1314  }
1315 }
static List * lock_files
Definition: miscinit.c:65
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#define lfirst(lc)
Definition: pg_list.h:169

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 933 of file miscinit.c.

References ereport, errmsg(), IsPostmasterEnvironment, lfirst, LOG, NIL, and NOTICE.

Referenced by CreateLockFile().

934 {
935  ListCell *l;
936 
937  foreach(l, lock_files)
938  {
939  char *curfile = (char *) lfirst(l);
940 
941  unlink(curfile);
942  /* Should we complain if the unlink fails? */
943  }
944  /* Since we're about to exit, no need to reclaim storage */
945  lock_files = NIL;
946 
947  /*
948  * Lock file removal should always be the last externally visible action
949  * of a postmaster or standalone backend, while we won't come here at all
950  * when exiting postmaster child processes. Therefore, this is a good
951  * place to log completion of shutdown. We could alternatively teach
952  * proc_exit() to do it, but that seems uglier. In a standalone backend,
953  * use NOTICE elevel to be less chatty.
954  */
956  (errmsg("database system is shut down")));
957 }
#define NIL
Definition: pg_list.h:65
bool IsPostmasterEnvironment
Definition: globals.c:108
static List * lock_files
Definition: miscinit.c:65
#define LOG
Definition: elog.h:26
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define lfirst(lc)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1528 of file miscinit.c.

References AllocateFile(), ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, FreeFile(), MAXPGPATH, and snprintf.

Referenced by checkDataDir(), and InitPostgres().

1529 {
1530  char full_path[MAXPGPATH];
1531  FILE *file;
1532  int ret;
1533  long file_major;
1534  long my_major;
1535  char *endptr;
1536  char file_version_string[64];
1537  const char *my_version_string = PG_VERSION;
1538 
1539  my_major = strtol(my_version_string, &endptr, 10);
1540 
1541  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1542 
1543  file = AllocateFile(full_path, "r");
1544  if (!file)
1545  {
1546  if (errno == ENOENT)
1547  ereport(FATAL,
1548  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1549  errmsg("\"%s\" is not a valid data directory",
1550  path),
1551  errdetail("File \"%s\" is missing.", full_path)));
1552  else
1553  ereport(FATAL,
1555  errmsg("could not open file \"%s\": %m", full_path)));
1556  }
1557 
1558  file_version_string[0] = '\0';
1559  ret = fscanf(file, "%63s", file_version_string);
1560  file_major = strtol(file_version_string, &endptr, 10);
1561 
1562  if (ret != 1 || endptr == file_version_string)
1563  ereport(FATAL,
1564  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1565  errmsg("\"%s\" is not a valid data directory",
1566  path),
1567  errdetail("File \"%s\" does not contain valid data.",
1568  full_path),
1569  errhint("You might need to initdb.")));
1570 
1571  FreeFile(file);
1572 
1573  if (my_major != file_major)
1574  ereport(FATAL,
1575  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1576  errmsg("database files are incompatible with server"),
1577  errdetail("The data directory was initialized by PostgreSQL version %s, "
1578  "which is not compatible with this version %s.",
1579  file_version_string, my_version_string)));
1580 }
int errhint(const char *fmt,...)
Definition: elog.c:1068
int errcode(int sqlerrcode)
Definition: elog.c:610
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:954
int errcode_for_file_access(void)
Definition: elog.c:633
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
#define ereport(elevel,...)
Definition: elog.h:144
int FreeFile(FILE *file)
Definition: fd.c:2521
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define snprintf
Definition: port.h:215

Variable Documentation

◆ AuthenticatedUserId

◆ AuthenticatedUserIsSuperuser

bool AuthenticatedUserIsSuperuser = false
static

◆ CurrentUserId

◆ IgnoreSystemIndexes

bool IgnoreSystemIndexes = false

◆ local_preload_libraries_string

char* local_preload_libraries_string = NULL

Definition at line 1593 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

Definition at line 67 of file miscinit.c.

Referenced by InitPostmasterChild(), InitStandaloneProcess(), and SwitchBackToLocalLatch().

◆ lock_files

List* lock_files = NIL
static

Definition at line 65 of file miscinit.c.

◆ Mode

Definition at line 60 of file miscinit.c.

◆ MyBackendType

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 458 of file miscinit.c.

Referenced by GetCurrentRoleId(), GetOuterUserId(), SetOuterUserId(), and SetSessionUserId().

◆ process_shared_preload_libraries_in_progress

bool process_shared_preload_libraries_in_progress = false

◆ SecurityRestrictionContext

◆ session_preload_libraries_string

char* session_preload_libraries_string = NULL

Definition at line 1591 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 457 of file miscinit.c.

Referenced by GetSessionUserId(), SetCurrentRoleId(), and SetSessionUserId().

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 463 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 468 of file miscinit.c.

Referenced by GetCurrentRoleId(), SetCurrentRoleId(), and SetSessionUserId().

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1592 of file miscinit.c.

Referenced by process_shared_preload_libraries().