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 1331 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().

1332 {
1333  int fd;
1334  int len;
1335  int lineno;
1336  char *srcptr;
1337  char *destptr;
1338  char srcbuffer[BLCKSZ];
1339  char destbuffer[BLCKSZ];
1340 
1341  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1342  if (fd < 0)
1343  {
1344  ereport(LOG,
1346  errmsg("could not open file \"%s\": %m",
1348  return;
1349  }
1351  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1353  if (len < 0)
1354  {
1355  ereport(LOG,
1357  errmsg("could not read from file \"%s\": %m",
1359  close(fd);
1360  return;
1361  }
1362  srcbuffer[len] = '\0';
1363 
1364  /*
1365  * Advance over lines we are not supposed to rewrite, then copy them to
1366  * destbuffer.
1367  */
1368  srcptr = srcbuffer;
1369  for (lineno = 1; lineno < target_line; lineno++)
1370  {
1371  char *eol = strchr(srcptr, '\n');
1372 
1373  if (eol == NULL)
1374  break; /* not enough lines in file yet */
1375  srcptr = eol + 1;
1376  }
1377  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1378  destptr = destbuffer + (srcptr - srcbuffer);
1379 
1380  /*
1381  * Fill in any missing lines before the target line, in case lines are
1382  * added to the file out of order.
1383  */
1384  for (; lineno < target_line; lineno++)
1385  {
1386  if (destptr < destbuffer + sizeof(destbuffer))
1387  *destptr++ = '\n';
1388  }
1389 
1390  /*
1391  * Write or rewrite the target line.
1392  */
1393  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1394  destptr += strlen(destptr);
1395 
1396  /*
1397  * If there are more lines in the old file, append them to destbuffer.
1398  */
1399  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1400  {
1401  srcptr++;
1402  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1403  srcptr);
1404  }
1405 
1406  /*
1407  * And rewrite the data. Since we write in a single kernel call, this
1408  * update should appear atomic to onlookers.
1409  */
1410  len = strlen(destbuffer);
1411  errno = 0;
1413  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1414  {
1416  /* if write didn't set errno, assume problem is no disk space */
1417  if (errno == 0)
1418  errno = ENOSPC;
1419  ereport(LOG,
1421  errmsg("could not write to file \"%s\": %m",
1423  close(fd);
1424  return;
1425  }
1428  if (pg_fsync(fd) != 0)
1429  {
1430  ereport(LOG,
1432  errmsg("could not write to file \"%s\": %m",
1434  }
1436  if (close(fd) != 0)
1437  {
1438  ereport(LOG,
1440  errmsg("could not write to file \"%s\": %m",
1442  }
1443 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#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:1271
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:721
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int pg_fsync(int fd)
Definition: fd.c:352
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:216
#define read(a, b, c)
Definition: win32.h:13

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 418 of file miscinit.c.

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

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

419 {
421 
422  if (chdir(DataDir) < 0)
423  ereport(FATAL,
425  errmsg("could not change directory to \"%s\": %m",
426  DataDir)));
427 }
#define AssertState(condition)
Definition: c.h:807
#define FATAL
Definition: elog.h:49
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * DataDir
Definition: globals.c:65

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 304 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().

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

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1275 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1276 {
1277  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1278 }
#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:970
char * DataDir
Definition: globals.c:65

◆ CreateLockFile()

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

Definition at line 970 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().

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

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by StreamServerPort().

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

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 537 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

538 {
540  return AuthenticatedUserId;
541 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
static Oid AuthenticatedUserId
Definition: miscinit.c:458

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 232 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().

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

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 837 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

838 {
839  if (SetRoleIsActive)
840  return OuterUserId;
841  else
842  return InvalidOid;
843 }
static Oid OuterUserId
Definition: miscinit.c:460
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:470

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 489 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

490 {
492  return OuterUserId;
493 }
#define AssertState(condition)
Definition: c.h:807
static Oid OuterUserId
Definition: miscinit.c:460
#define OidIsValid(objectId)
Definition: c.h:710

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 512 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().

513 {
515  return SessionUserId;
516 }
#define AssertState(condition)
Definition: c.h:807
static Oid SessionUserId
Definition: miscinit.c:459
#define OidIsValid(objectId)
Definition: c.h:710

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 478 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(), CreateTriggerFiringOn(), current_user(), currtid_internal(), 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(), ExecBuildParamSetEqual(), 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(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteGrantStmt(), 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(), heap_force_common(), 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(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), 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().

479 {
481  return CurrentUserId;
482 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
static Oid CurrentUserId
Definition: miscinit.c:461

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 632 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

633 {
634  *userid = CurrentUserId;
635  *sec_def_context = InLocalUserIdChange();
636 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:601
static Oid CurrentUserId
Definition: miscinit.c:461

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 893 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(), and session_user().

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

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 659 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

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

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 677 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().

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

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 780 of file miscinit.c.

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

Referenced by InitPostgres().

781 {
782  /*
783  * This function should only be called in single-user mode, in autovacuum
784  * workers, and in background workers.
785  */
787 
788  /* call only once */
790 
791  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
793 
794  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
795 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
bool IsBackgroundWorker
Definition: globals.c:114
bool IsUnderPostmaster
Definition: globals.c:112
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:464
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3454
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:520
static Oid AuthenticatedUserId
Definition: miscinit.c:458

◆ 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(), 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  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
122 #ifdef EXEC_BACKEND
123  pqinitmask();
124 #endif
125 
126  /* Initialize process-local latch support */
131 
132  /*
133  * If possible, make this process a group leader, so that the postmaster
134  * can signal any child processes too. Not all processes will have
135  * children, but for consistency we make all postmaster child processes do
136  * this.
137  */
138 #ifdef HAVE_SETSID
139  if (setsid() < 0)
140  elog(FATAL, "setsid() failed: %m");
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:3416
#define SIGQUIT
Definition: win32_port.h:160
void InitLatch(Latch *latch)
Definition: latch.c:338
void InitProcessGlobals(void)
Definition: postmaster.c:2626
#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:49
bool IsUnderPostmaster
Definition: globals.c:112
sigset_t BlockSig
Definition: pqsignal.c:22
void InitializeLatchSupport(void)
Definition: latch.c:192
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
void InitializeLatchWaitSet(void)
Definition: latch.c:290
#define elog(elevel,...)
Definition: elog.h:232
struct Latch * MyLatch
Definition: globals.c:57
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:405

◆ 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:111
static char * argv0
Definition: pg_ctl.c:97
void InitLatch(Latch *latch)
Definition: latch.c:338
void InitProcessGlobals(void)
Definition: postmaster.c:2626
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:49
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:127
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
sigset_t BlockSig
Definition: pqsignal.c:22
void InitializeLatchSupport(void)
Definition: latch.c:192
#define Assert(condition)
Definition: c.h:804
void InitializeLatchWaitSet(void)
Definition: latch.c:290
#define elog(elevel,...)
Definition: elog.h:232
struct Latch * MyLatch
Definition: globals.c:57
char pkglib_path[MAXPGPATH]
Definition: globals.c:76

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 601 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

602 {
604 }
static int SecurityRestrictionContext
Definition: miscinit.c:467
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 619 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

620 {
622 }
static int SecurityRestrictionContext
Definition: miscinit.c:467
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:313

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ load_libraries()

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

Definition at line 1607 of file miscinit.c.

References DEBUG1, ereport, errcode(), errmsg(), errmsg_internal(), 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().

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

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1683 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1684 {
1685 #ifdef ENABLE_NLS
1686  if (my_exec_path[0] != '\0')
1687  {
1688  char locale_path[MAXPGPATH];
1689 
1690  get_locale_path(my_exec_path, locale_path);
1691  bindtextdomain(domain, locale_path);
1692  pg_bind_textdomain_codeset(domain);
1693  }
1694 #endif
1695 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:75
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 1672 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1673 {
1675  "session_preload_libraries",
1676  false);
1678  "local_preload_libraries",
1679  true);
1680 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1607
char * local_preload_libraries_string
Definition: miscinit.c:1595
char * session_preload_libraries_string
Definition: miscinit.c:1593

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1659 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1660 {
1663  "shared_preload_libraries",
1664  false);
1666 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1598
char * shared_preload_libraries_string
Definition: miscinit.c:1594
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1607

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1458 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().

1459 {
1460  int fd;
1461  int len;
1462  long file_pid;
1463  char buffer[BLCKSZ];
1464 
1465  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1466  if (fd < 0)
1467  {
1468  /*
1469  * There are many foreseeable false-positive error conditions. For
1470  * safety, fail only on enumerated clearly-something-is-wrong
1471  * conditions.
1472  */
1473  switch (errno)
1474  {
1475  case ENOENT:
1476  case ENOTDIR:
1477  /* disaster */
1478  ereport(LOG,
1480  errmsg("could not open file \"%s\": %m",
1482  return false;
1483  default:
1484  /* non-fatal, at least for now */
1485  ereport(LOG,
1487  errmsg("could not open file \"%s\": %m; continuing anyway",
1489  return true;
1490  }
1491  }
1493  len = read(fd, buffer, sizeof(buffer) - 1);
1495  if (len < 0)
1496  {
1497  ereport(LOG,
1499  errmsg("could not read from file \"%s\": %m",
1501  close(fd);
1502  return true; /* treat read failure as nonfatal */
1503  }
1504  buffer[len] = '\0';
1505  close(fd);
1506  file_pid = atol(buffer);
1507  if (file_pid == getpid())
1508  return true; /* all is well */
1509 
1510  /* Trouble: someone's overwritten the lock file */
1511  ereport(LOG,
1512  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1513  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1514  return false;
1515 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#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:1271
int errcode_for_file_access(void)
Definition: elog.c:721
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
#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 858 of file miscinit.c.

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

Referenced by assign_role(), and ParallelWorkerMain().

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

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 291 of file miscinit.c.

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

Referenced by InitPostgres().

292 {
293  /* This should happen only once per process */
296 }
MemoryContext TopMemoryContext
Definition: mcxt.c:48
char * DatabasePath
Definition: globals.c:96
#define Assert(condition)
Definition: c.h:804
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1286

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 397 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

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

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 497 of file miscinit.c.

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

Referenced by SetCurrentRoleId().

498 {
500  AssertArg(OidIsValid(userid));
501  OuterUserId = userid;
502 
503  /* We force the effective user ID to match, too */
504  CurrentUserId = userid;
505 }
#define AssertState(condition)
Definition: c.h:807
static Oid OuterUserId
Definition: miscinit.c:460
#define OidIsValid(objectId)
Definition: c.h:710
static int SecurityRestrictionContext
Definition: miscinit.c:467
#define AssertArg(condition)
Definition: c.h:806
static Oid CurrentUserId
Definition: miscinit.c:461

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 812 of file miscinit.c.

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

Referenced by assign_session_authorization().

813 {
814  /* Must have authenticated already, else can't make permission check */
816 
817  if (userid != AuthenticatedUserId &&
819  ereport(ERROR,
820  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
821  errmsg("permission denied to set session authorization")));
822 
824 
825  SetConfigOption("is_superuser",
826  is_superuser ? "on" : "off",
828 }
#define AssertState(condition)
Definition: c.h:807
int errcode(int sqlerrcode)
Definition: elog.c:698
#define OidIsValid(objectId)
Definition: c.h:710
#define ERROR
Definition: elog.h:46
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8086
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:464
#define ereport(elevel,...)
Definition: elog.h:157
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4270
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:520
static Oid AuthenticatedUserId
Definition: miscinit.c:458

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 520 of file miscinit.c.

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

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

521 {
523  AssertArg(OidIsValid(userid));
524  SessionUserId = userid;
526  SetRoleIsActive = false;
527 
528  /* We force the effective user IDs to match, too */
529  OuterUserId = userid;
530  CurrentUserId = userid;
531 }
#define AssertState(condition)
Definition: c.h:807
static Oid SessionUserId
Definition: miscinit.c:459
static Oid OuterUserId
Definition: miscinit.c:460
#define OidIsValid(objectId)
Definition: c.h:710
static int SecurityRestrictionContext
Definition: miscinit.c:467
#define AssertArg(condition)
Definition: c.h:806
static bool SetRoleIsActive
Definition: miscinit.c:470
static bool SessionUserIsSuperuser
Definition: miscinit.c:465
static Oid CurrentUserId
Definition: miscinit.c:461
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4270

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 639 of file miscinit.c.

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

640 {
641  /* We throw the same error SET ROLE would. */
643  ereport(ERROR,
644  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
645  errmsg("cannot set parameter \"%s\" within security-restricted operation",
646  "role")));
647  CurrentUserId = userid;
648  if (sec_def_context)
650  else
652 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static int SecurityRestrictionContext
Definition: miscinit.c:467
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311
#define ereport(elevel,...)
Definition: elog.h:157
static Oid CurrentUserId
Definition: miscinit.c:461
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:610
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 217 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

218 {
220  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
221 
223 
224  if (FeBeWaitSet)
226  MyLatch);
227 
228  SetLatch(MyLatch);
229 }
PGPROC * MyProc
Definition: proc.c:68
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:948
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
void SetLatch(Latch *latch)
Definition: latch.c:567
Latch procLatch
Definition: proc.h:130
static Latch LocalLatchData
Definition: miscinit.c:67
#define Assert(condition)
Definition: c.h:804
struct Latch * MyLatch
Definition: globals.c:57
#define WL_LATCH_SET
Definition: latch.h:125

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 197 of file miscinit.c.

References Assert, FeBeWaitSet, FeBeWaitSetLatchPos, 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  MyLatch);
207 
208  /*
209  * Set the shared latch as the local one might have been set. This
210  * shouldn't normally be necessary as code is supposed to check the
211  * condition before waiting for the latch, but a bit care can't hurt.
212  */
213  SetLatch(MyLatch);
214 }
PGPROC * MyProc
Definition: proc.c:68
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:948
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:168
void SetLatch(Latch *latch)
Definition: latch.c:567
Latch procLatch
Definition: proc.h:130
static Latch LocalLatchData
Definition: miscinit.c:67
#define Assert(condition)
Definition: c.h:804
struct Latch * MyLatch
Definition: globals.c:57
#define WL_LATCH_SET
Definition: latch.h:125

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1302 of file miscinit.c.

References DIRECTORY_LOCK_FILE, and lfirst.

Referenced by ServerLoop().

1303 {
1304  ListCell *l;
1305 
1306  foreach(l, lock_files)
1307  {
1308  char *socketLockFile = (char *) lfirst(l);
1309 
1310  /* No need to touch the data directory lock file, we trust */
1311  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1312  continue;
1313 
1314  /* we just ignore any error here */
1315  (void) utime(socketLockFile, NULL);
1316  }
1317 }
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 935 of file miscinit.c.

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

Referenced by CreateLockFile().

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

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1530 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().

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

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 1595 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 460 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 1593 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 459 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 465 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 470 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1594 of file miscinit.c.

Referenced by process_shared_preload_libraries().