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

1349 {
1350  int fd;
1351  int len;
1352  int lineno;
1353  char *srcptr;
1354  char *destptr;
1355  char srcbuffer[BLCKSZ];
1356  char destbuffer[BLCKSZ];
1357 
1358  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1359  if (fd < 0)
1360  {
1361  ereport(LOG,
1363  errmsg("could not open file \"%s\": %m",
1365  return;
1366  }
1368  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1370  if (len < 0)
1371  {
1372  ereport(LOG,
1374  errmsg("could not read from file \"%s\": %m",
1376  close(fd);
1377  return;
1378  }
1379  srcbuffer[len] = '\0';
1380 
1381  /*
1382  * Advance over lines we are not supposed to rewrite, then copy them to
1383  * destbuffer.
1384  */
1385  srcptr = srcbuffer;
1386  for (lineno = 1; lineno < target_line; lineno++)
1387  {
1388  char *eol = strchr(srcptr, '\n');
1389 
1390  if (eol == NULL)
1391  break; /* not enough lines in file yet */
1392  srcptr = eol + 1;
1393  }
1394  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1395  destptr = destbuffer + (srcptr - srcbuffer);
1396 
1397  /*
1398  * Fill in any missing lines before the target line, in case lines are
1399  * added to the file out of order.
1400  */
1401  for (; lineno < target_line; lineno++)
1402  {
1403  if (destptr < destbuffer + sizeof(destbuffer))
1404  *destptr++ = '\n';
1405  }
1406 
1407  /*
1408  * Write or rewrite the target line.
1409  */
1410  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1411  destptr += strlen(destptr);
1412 
1413  /*
1414  * If there are more lines in the old file, append them to destbuffer.
1415  */
1416  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1417  {
1418  srcptr++;
1419  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1420  srcptr);
1421  }
1422 
1423  /*
1424  * And rewrite the data. Since we write in a single kernel call, this
1425  * update should appear atomic to onlookers.
1426  */
1427  len = strlen(destbuffer);
1428  errno = 0;
1430  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1431  {
1433  /* if write didn't set errno, assume problem is no disk space */
1434  if (errno == 0)
1435  errno = ENOSPC;
1436  ereport(LOG,
1438  errmsg("could not write to file \"%s\": %m",
1440  close(fd);
1441  return;
1442  }
1445  if (pg_fsync(fd) != 0)
1446  {
1447  ereport(LOG,
1449  errmsg("could not write to file \"%s\": %m",
1451  }
1453  if (close(fd) != 0)
1454  {
1455  ereport(LOG,
1457  errmsg("could not write to file \"%s\": %m",
1459  }
1460 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274
#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:258
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909
int pg_fsync(int fd)
Definition: fd.c:358
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:217
#define read(a, b, c)
Definition: win32.h:13

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 435 of file miscinit.c.

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

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

436 {
438 
439  if (chdir(DataDir) < 0)
440  ereport(FATAL,
442  errmsg("could not change directory to \"%s\": %m",
443  DataDir)));
444 }
#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 321 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 BackendRun(), BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

322 {
323  struct stat stat_buf;
324 
325  Assert(DataDir);
326 
327  if (stat(DataDir, &stat_buf) != 0)
328  {
329  if (errno == ENOENT)
330  ereport(FATAL,
332  errmsg("data directory \"%s\" does not exist",
333  DataDir)));
334  else
335  ereport(FATAL,
337  errmsg("could not read permissions of directory \"%s\": %m",
338  DataDir)));
339  }
340 
341  /* eventual chdir would fail anyway, but let's test ... */
342  if (!S_ISDIR(stat_buf.st_mode))
343  ereport(FATAL,
344  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
345  errmsg("specified data directory \"%s\" is not a directory",
346  DataDir)));
347 
348  /*
349  * Check that the directory belongs to my userid; if not, reject.
350  *
351  * This check is an essential part of the interlock that prevents two
352  * postmasters from starting in the same directory (see CreateLockFile()).
353  * Do not remove or weaken it.
354  *
355  * XXX can we safely enable this check on Windows?
356  */
357 #if !defined(WIN32) && !defined(__CYGWIN__)
358  if (stat_buf.st_uid != geteuid())
359  ereport(FATAL,
360  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
361  errmsg("data directory \"%s\" has wrong ownership",
362  DataDir),
363  errhint("The server must be started by the user that owns the data directory.")));
364 #endif
365 
366  /*
367  * Check if the directory has correct permissions. If not, reject.
368  *
369  * Only two possible modes are allowed, 0700 and 0750. The latter mode
370  * indicates that group read/execute should be allowed on all newly
371  * created files and directories.
372  *
373  * XXX temporarily suppress check when on Windows, because there may not
374  * be proper support for Unix-y file permissions. Need to think of a
375  * reasonable check to apply on Windows.
376  */
377 #if !defined(WIN32) && !defined(__CYGWIN__)
378  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
379  ereport(FATAL,
380  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
381  errmsg("data directory \"%s\" has invalid permissions",
382  DataDir),
383  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
384 #endif
385 
386  /*
387  * Reset creation modes and mask based on the mode of the data directory.
388  *
389  * The mask was set earlier in startup to disallow group permissions on
390  * newly created files and directories. However, if group read/execute
391  * are present on the data directory then modify the create modes and mask
392  * to allow group read/execute on newly created files and directories and
393  * set the data_directory_mode GUC.
394  *
395  * Suppress when on Windows, because there may not be proper support for
396  * Unix-y file permissions.
397  */
398 #if !defined(WIN32) && !defined(__CYGWIN__)
399  SetDataDirectoryCreatePerm(stat_buf.st_mode);
400 
401  umask(pg_mode_mask);
403 #endif
404 
405  /* Check for PG_VERSION */
407 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1547
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:324
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:283

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1292 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

Referenced by BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

1293 {
1294  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1295 }
#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:987
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 987 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().

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

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by StreamServerPort().

1303 {
1304  char lockfile[MAXPGPATH];
1305 
1306  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1307  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1308 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:987
#define MAXPGPATH
#define snprintf
Definition: port.h:217

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 554 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

555 {
557  return AuthenticatedUserId;
558 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

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

250 {
251  const char *backendDesc = "unknown process type";
252 
253  switch (backendType)
254  {
255  case B_INVALID:
256  backendDesc = "not initialized";
257  break;
258  case B_AUTOVAC_LAUNCHER:
259  backendDesc = "autovacuum launcher";
260  break;
261  case B_AUTOVAC_WORKER:
262  backendDesc = "autovacuum worker";
263  break;
264  case B_BACKEND:
265  backendDesc = "client backend";
266  break;
267  case B_BG_WORKER:
268  backendDesc = "background worker";
269  break;
270  case B_BG_WRITER:
271  backendDesc = "background writer";
272  break;
273  case B_CHECKPOINTER:
274  backendDesc = "checkpointer";
275  break;
276  case B_STARTUP:
277  backendDesc = "startup";
278  break;
279  case B_WAL_RECEIVER:
280  backendDesc = "walreceiver";
281  break;
282  case B_WAL_SENDER:
283  backendDesc = "walsender";
284  break;
285  case B_WAL_WRITER:
286  backendDesc = "walwriter";
287  break;
288  case B_ARCHIVER:
289  backendDesc = "archiver";
290  break;
291  case B_STATS_COLLECTOR:
292  backendDesc = "stats collector";
293  break;
294  case B_LOGGER:
295  backendDesc = "logger";
296  break;
297  }
298 
299  return backendDesc;
300 }

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 854 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

855 {
856  if (SetRoleIsActive)
857  return OuterUserId;
858  else
859  return InvalidOid;
860 }
static Oid OuterUserId
Definition: miscinit.c:477
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:487

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 506 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

507 {
509  return OuterUserId;
510 }
#define AssertState(condition)
Definition: c.h:807
static Oid OuterUserId
Definition: miscinit.c:477
#define OidIsValid(objectId)
Definition: c.h:710

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

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

530 {
532  return SessionUserId;
533 }
#define AssertState(condition)
Definition: c.h:807
static Oid SessionUserId
Definition: miscinit.c:476
#define OidIsValid(objectId)
Definition: c.h:710

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 495 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_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), CheckSlotPermissions(), 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().

496 {
498  return CurrentUserId;
499 }
#define AssertState(condition)
Definition: c.h:807
#define OidIsValid(objectId)
Definition: c.h:710
static Oid CurrentUserId
Definition: miscinit.c:478

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 649 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

650 {
651  *userid = CurrentUserId;
652  *sec_def_context = InLocalUserIdChange();
653 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:618
static Oid CurrentUserId
Definition: miscinit.c:478

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

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

911 {
912  HeapTuple tuple;
913  char *result;
914 
915  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
916  if (!HeapTupleIsValid(tuple))
917  {
918  if (!noerr)
919  ereport(ERROR,
920  (errcode(ERRCODE_UNDEFINED_OBJECT),
921  errmsg("invalid role OID: %u", roleid)));
922  result = NULL;
923  }
924  else
925  {
926  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
927  ReleaseSysCache(tuple);
928  }
929  return result;
930 }
#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 676 of file miscinit.c.

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

Referenced by CheckSlotPermissions(), and InitPostgres().

677 {
678  bool result = false;
679  HeapTuple utup;
680 
681  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
682  if (HeapTupleIsValid(utup))
683  {
684  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
685  ReleaseSysCache(utup);
686  }
687  return result;
688 }
#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 694 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().

695 {
696  HeapTuple roleTup;
697  Form_pg_authid rform;
698  char *rname;
699 
700  /*
701  * Don't do scans if we're bootstrapping, none of the system catalogs
702  * exist yet, and they should be owned by postgres anyway.
703  */
705 
706  /* call only once */
708 
709  /*
710  * Make sure syscache entries are flushed for recent catalog changes. This
711  * allows us to find roles that were created on-the-fly during
712  * authentication.
713  */
715 
716  if (rolename != NULL)
717  {
718  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
719  if (!HeapTupleIsValid(roleTup))
720  ereport(FATAL,
721  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
722  errmsg("role \"%s\" does not exist", rolename)));
723  }
724  else
725  {
726  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
727  if (!HeapTupleIsValid(roleTup))
728  ereport(FATAL,
729  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
730  errmsg("role with OID %u does not exist", roleid)));
731  }
732 
733  rform = (Form_pg_authid) GETSTRUCT(roleTup);
734  roleid = rform->oid;
735  rname = NameStr(rform->rolname);
736 
737  AuthenticatedUserId = roleid;
738  AuthenticatedUserIsSuperuser = rform->rolsuper;
739 
740  /* This sets OuterUserId/CurrentUserId too */
742 
743  /* Also mark our PGPROC entry with the authenticated user id */
744  /* (We assume this is an atomic store so no lock is needed) */
745  MyProc->roleId = roleid;
746 
747  /*
748  * These next checks are not enforced when in standalone mode, so that
749  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
750  * rolcanlogin = false;".
751  */
752  if (IsUnderPostmaster)
753  {
754  /*
755  * Is role allowed to login at all?
756  */
757  if (!rform->rolcanlogin)
758  ereport(FATAL,
759  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
760  errmsg("role \"%s\" is not permitted to log in",
761  rname)));
762 
763  /*
764  * Check connection limit for this role.
765  *
766  * There is a race condition here --- we create our PGPROC before
767  * checking for other PGPROCs. If two backends did this at about the
768  * same time, they might both think they were over the limit, while
769  * ideally one should succeed and one fail. Getting that to work
770  * exactly seems more trouble than it is worth, however; instead we
771  * just document that the connection limit is approximate.
772  */
773  if (rform->rolconnlimit >= 0 &&
775  CountUserBackends(roleid) > rform->rolconnlimit)
776  ereport(FATAL,
777  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
778  errmsg("too many connections for role \"%s\"",
779  rname)));
780  }
781 
782  /* Record username and superuser status as GUC settings too */
783  SetConfigOption("session_authorization", rname,
785  SetConfigOption("is_superuser",
786  AuthenticatedUserIsSuperuser ? "on" : "off",
788 
789  ReleaseSysCache(roleTup);
790 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define AssertState(condition)
Definition: c.h:807
void AcceptInvalidationMessages(void)
Definition: inval.c:745
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:8123
bool IsUnderPostmaster
Definition: globals.c:112
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:481
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:537
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 797 of file miscinit.c.

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

Referenced by InitPostgres().

798 {
799  /*
800  * This function should only be called in single-user mode, in autovacuum
801  * workers, and in background workers.
802  */
804 
805  /* call only once */
807 
808  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
810 
811  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
812 }
#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:481
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3410
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:537
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 94 of file miscinit.c.

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

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

95 {
96  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
97 
98  /*
99  * Start our win32 signal implementation. This has to be done after we
100  * read the backend variables, because we need to pick up the signal pipe
101  * from the parent process.
102  */
103 #ifdef WIN32
105 #endif
106 
107  /*
108  * Set reference point for stack-depth checking. We re-do that even in the
109  * !EXEC_BACKEND case, because there are some edge cases where processes
110  * are started with an alternative stack (e.g. starting bgworkers when
111  * running postgres using the rr debugger, as bgworkers are launched from
112  * signal handlers).
113  */
114  set_stack_base();
115 
117 
118  /*
119  * make sure stderr is in binary mode before anything can possibly be
120  * written to it, in case it's actually the syslogger pipe, so the pipe
121  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
122  * redirection (e.g. via pg_ctl -l) anyway.
123  */
124 #ifdef WIN32
125  _setmode(fileno(stderr), _O_BINARY);
126 #endif
127 
128  /* We don't want the postmaster's proc_exit() handlers */
129  on_exit_reset();
130 
131  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
132 #ifdef EXEC_BACKEND
133  pqinitmask();
134 #endif
135 
136  /* Initialize process-local latch support */
141 
142  /*
143  * If possible, make this process a group leader, so that the postmaster
144  * can signal any child processes too. Not all processes will have
145  * children, but for consistency we make all postmaster child processes do
146  * this.
147  */
148 #ifdef HAVE_SETSID
149  if (setsid() < 0)
150  elog(FATAL, "setsid() failed: %m");
151 #endif
152 
153  /*
154  * Every postmaster child process is expected to respond promptly to
155  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
156  * BlockSig and install a suitable signal handler. (Client-facing
157  * processes may choose to replace this default choice of handler with
158  * quickdie().) All other blockable signals remain blocked for now.
159  */
161 
162  sigdelset(&BlockSig, SIGQUIT);
164 
165  /* Request a signal if the postmaster dies, if possible. */
167 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3416
#define SIGQUIT
Definition: win32_port.h:168
void pgwin32_signal_initialize(void)
Definition: signal.c:69
void InitLatch(Latch *latch)
Definition: latch.c:338
void InitProcessGlobals(void)
Definition: postmaster.c:2676
#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 175 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, pgwin32_signal_initialize(), pkglib_path, and pqinitmask().

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

176 {
178 
179  /*
180  * Start our win32 signal implementation
181  */
182 #ifdef WIN32
184 #endif
185 
187 
188  /* Initialize process-local latch support */
193 
194  /*
195  * For consistency with InitPostmasterChild, initialize signal mask here.
196  * But we don't unblock SIGQUIT or provide a default handler for it.
197  */
198  pqinitmask();
200 
201  /* Compute paths, no postmaster to inherit from */
202  if (my_exec_path[0] == '\0')
203  {
204  if (find_my_exec(argv0, my_exec_path) < 0)
205  elog(FATAL, "%s: could not locate my own executable path",
206  argv0);
207  }
208 
209  if (pkglib_path[0] == '\0')
211 }
bool IsPostmasterEnvironment
Definition: globals.c:111
static char * argv0
Definition: pg_ctl.c:97
void pgwin32_signal_initialize(void)
Definition: signal.c:69
void InitLatch(Latch *latch)
Definition: latch.c:338
void InitProcessGlobals(void)
Definition: postmaster.c:2676
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 618 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

619 {
621 }
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 636 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

637 {
639 }
static int SecurityRestrictionContext
Definition: miscinit.c:484
#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 1624 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().

1625 {
1626  char *rawstring;
1627  List *elemlist;
1628  ListCell *l;
1629 
1630  if (libraries == NULL || libraries[0] == '\0')
1631  return; /* nothing to do */
1632 
1633  /* Need a modifiable copy of string */
1634  rawstring = pstrdup(libraries);
1635 
1636  /* Parse string into list of filename paths */
1637  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1638  {
1639  /* syntax error in list */
1640  list_free_deep(elemlist);
1641  pfree(rawstring);
1642  ereport(LOG,
1643  (errcode(ERRCODE_SYNTAX_ERROR),
1644  errmsg("invalid list syntax in parameter \"%s\"",
1645  gucname)));
1646  return;
1647  }
1648 
1649  foreach(l, elemlist)
1650  {
1651  /* Note that filename was already canonicalized */
1652  char *filename = (char *) lfirst(l);
1653  char *expanded = NULL;
1654 
1655  /* If restricting, insert $libdir/plugins if not mentioned already */
1656  if (restricted && first_dir_separator(filename) == NULL)
1657  {
1658  expanded = psprintf("$libdir/plugins/%s", filename);
1659  filename = expanded;
1660  }
1661  load_file(filename, restricted);
1662  ereport(DEBUG1,
1663  (errmsg_internal("loaded library \"%s\"", filename)));
1664  if (expanded)
1665  pfree(expanded);
1666  }
1667 
1668  list_free_deep(elemlist);
1669  pfree(rawstring);
1670 }
#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:3873
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 1700 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1701 {
1702 #ifdef ENABLE_NLS
1703  if (my_exec_path[0] != '\0')
1704  {
1705  char locale_path[MAXPGPATH];
1706 
1707  get_locale_path(my_exec_path, locale_path);
1708  bindtextdomain(domain, locale_path);
1709  pg_bind_textdomain_codeset(domain);
1710  }
1711 #endif
1712 }
#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 1689 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1690 {
1692  "session_preload_libraries",
1693  false);
1695  "local_preload_libraries",
1696  true);
1697 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1624
char * local_preload_libraries_string
Definition: miscinit.c:1612
char * session_preload_libraries_string
Definition: miscinit.c:1610

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1676 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1677 {
1680  "shared_preload_libraries",
1681  false);
1683 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1615
char * shared_preload_libraries_string
Definition: miscinit.c:1611
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1624

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

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

1476 {
1477  int fd;
1478  int len;
1479  long file_pid;
1480  char buffer[BLCKSZ];
1481 
1482  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1483  if (fd < 0)
1484  {
1485  /*
1486  * There are many foreseeable false-positive error conditions. For
1487  * safety, fail only on enumerated clearly-something-is-wrong
1488  * conditions.
1489  */
1490  switch (errno)
1491  {
1492  case ENOENT:
1493  case ENOTDIR:
1494  /* disaster */
1495  ereport(LOG,
1497  errmsg("could not open file \"%s\": %m",
1499  return false;
1500  default:
1501  /* non-fatal, at least for now */
1502  ereport(LOG,
1504  errmsg("could not open file \"%s\": %m; continuing anyway",
1506  return true;
1507  }
1508  }
1510  len = read(fd, buffer, sizeof(buffer) - 1);
1512  if (len < 0)
1513  {
1514  ereport(LOG,
1516  errmsg("could not read from file \"%s\": %m",
1518  close(fd);
1519  return true; /* treat read failure as nonfatal */
1520  }
1521  buffer[len] = '\0';
1522  close(fd);
1523  file_pid = atol(buffer);
1524  if (file_pid == getpid())
1525  return true; /* all is well */
1526 
1527  /* Trouble: someone's overwritten the lock file */
1528  ereport(LOG,
1529  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1530  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1531  return false;
1532 }
static void pgstat_report_wait_end(void)
Definition: wait_event.h:274
#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:258
#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 875 of file miscinit.c.

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

Referenced by assign_role(), and ParallelWorkerMain().

876 {
877  /*
878  * Get correct info if it's SET ROLE NONE
879  *
880  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
881  * SetSessionUserId call will fix everything. This is needed since we
882  * will get called during GUC initialization.
883  */
884  if (!OidIsValid(roleid))
885  {
887  return;
888 
889  roleid = SessionUserId;
891 
892  SetRoleIsActive = false;
893  }
894  else
895  SetRoleIsActive = true;
896 
897  SetOuterUserId(roleid);
898 
899  SetConfigOption("is_superuser",
900  is_superuser ? "on" : "off",
902 }
static Oid SessionUserId
Definition: miscinit.c:476
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:514
#define OidIsValid(objectId)
Definition: c.h:710
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:8123
static bool SetRoleIsActive
Definition: miscinit.c:487
static bool SessionUserIsSuperuser
Definition: miscinit.c:482
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4263

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 308 of file miscinit.c.

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

Referenced by InitPostgres().

309 {
310  /* This should happen only once per process */
313 }
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 414 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

415 {
416  char *new;
417 
418  AssertArg(dir);
419 
420  /* If presented path is relative, convert to absolute */
421  new = make_absolute_path(dir);
422 
423  if (DataDir)
424  free(DataDir);
425  DataDir = new;
426 }
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 514 of file miscinit.c.

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

Referenced by SetCurrentRoleId().

515 {
517  AssertArg(OidIsValid(userid));
518  OuterUserId = userid;
519 
520  /* We force the effective user ID to match, too */
521  CurrentUserId = userid;
522 }
#define AssertState(condition)
Definition: c.h:807
static Oid OuterUserId
Definition: miscinit.c:477
#define OidIsValid(objectId)
Definition: c.h:710
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define AssertArg(condition)
Definition: c.h:806
static Oid CurrentUserId
Definition: miscinit.c:478

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

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

830 {
831  /* Must have authenticated already, else can't make permission check */
833 
834  if (userid != AuthenticatedUserId &&
836  ereport(ERROR,
837  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
838  errmsg("permission denied to set session authorization")));
839 
841 
842  SetConfigOption("is_superuser",
843  is_superuser ? "on" : "off",
845 }
#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:8123
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:481
#define ereport(elevel,...)
Definition: elog.h:157
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4263
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:537
static Oid AuthenticatedUserId
Definition: miscinit.c:475

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 537 of file miscinit.c.

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

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

538 {
540  AssertArg(OidIsValid(userid));
541  SessionUserId = userid;
543  SetRoleIsActive = false;
544 
545  /* We force the effective user IDs to match, too */
546  OuterUserId = userid;
547  CurrentUserId = userid;
548 }
#define AssertState(condition)
Definition: c.h:807
static Oid SessionUserId
Definition: miscinit.c:476
static Oid OuterUserId
Definition: miscinit.c:477
#define OidIsValid(objectId)
Definition: c.h:710
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define AssertArg(condition)
Definition: c.h:806
static bool SetRoleIsActive
Definition: miscinit.c:487
static bool SessionUserIsSuperuser
Definition: miscinit.c:482
static Oid CurrentUserId
Definition: miscinit.c:478
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4263

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 656 of file miscinit.c.

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

657 {
658  /* We throw the same error SET ROLE would. */
660  ereport(ERROR,
661  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
662  errmsg("cannot set parameter \"%s\" within security-restricted operation",
663  "role")));
664  CurrentUserId = userid;
665  if (sec_def_context)
667  else
669 }
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
static int SecurityRestrictionContext
Definition: miscinit.c:484
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:311
#define ereport(elevel,...)
Definition: elog.h:157
static Oid CurrentUserId
Definition: miscinit.c:478
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:627
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 234 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

235 {
237  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
238 
240 
241  if (FeBeWaitSet)
243  MyLatch);
244 
245  SetLatch(MyLatch);
246 }
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 214 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

215 {
217  Assert(MyProc != NULL);
218 
220 
221  if (FeBeWaitSet)
223  MyLatch);
224 
225  /*
226  * Set the shared latch as the local one might have been set. This
227  * shouldn't normally be necessary as code is supposed to check the
228  * condition before waiting for the latch, but a bit care can't hurt.
229  */
230  SetLatch(MyLatch);
231 }
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 1319 of file miscinit.c.

References DIRECTORY_LOCK_FILE, and lfirst.

Referenced by ServerLoop().

1320 {
1321  ListCell *l;
1322 
1323  foreach(l, lock_files)
1324  {
1325  char *socketLockFile = (char *) lfirst(l);
1326 
1327  /* No need to touch the data directory lock file, we trust */
1328  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1329  continue;
1330 
1331  /* we just ignore any error here */
1332  (void) utime(socketLockFile, NULL);
1333  }
1334 }
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 952 of file miscinit.c.

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

Referenced by CreateLockFile().

953 {
954  ListCell *l;
955 
956  foreach(l, lock_files)
957  {
958  char *curfile = (char *) lfirst(l);
959 
960  unlink(curfile);
961  /* Should we complain if the unlink fails? */
962  }
963  /* Since we're about to exit, no need to reclaim storage */
964  lock_files = NIL;
965 
966  /*
967  * Lock file removal should always be the last externally visible action
968  * of a postmaster or standalone backend, while we won't come here at all
969  * when exiting postmaster child processes. Therefore, this is a good
970  * place to log completion of shutdown. We could alternatively teach
971  * proc_exit() to do it, but that seems uglier. In a standalone backend,
972  * use NOTICE elevel to be less chatty.
973  */
975  (errmsg("database system is shut down")));
976 }
#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 1547 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().

1548 {
1549  char full_path[MAXPGPATH];
1550  FILE *file;
1551  int ret;
1552  long file_major;
1553  long my_major;
1554  char *endptr;
1555  char file_version_string[64];
1556  const char *my_version_string = PG_VERSION;
1557 
1558  my_major = strtol(my_version_string, &endptr, 10);
1559 
1560  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1561 
1562  file = AllocateFile(full_path, "r");
1563  if (!file)
1564  {
1565  if (errno == ENOENT)
1566  ereport(FATAL,
1567  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1568  errmsg("\"%s\" is not a valid data directory",
1569  path),
1570  errdetail("File \"%s\" is missing.", full_path)));
1571  else
1572  ereport(FATAL,
1574  errmsg("could not open file \"%s\": %m", full_path)));
1575  }
1576 
1577  file_version_string[0] = '\0';
1578  ret = fscanf(file, "%63s", file_version_string);
1579  file_major = strtol(file_version_string, &endptr, 10);
1580 
1581  if (ret != 1 || endptr == file_version_string)
1582  ereport(FATAL,
1583  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1584  errmsg("\"%s\" is not a valid data directory",
1585  path),
1586  errdetail("File \"%s\" does not contain valid data.",
1587  full_path),
1588  errhint("You might need to initdb.")));
1589 
1590  FreeFile(file);
1591 
1592  if (my_major != file_major)
1593  ereport(FATAL,
1594  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1595  errmsg("database files are incompatible with server"),
1596  errdetail("The data directory was initialized by PostgreSQL version %s, "
1597  "which is not compatible with this version %s.",
1598  file_version_string, my_version_string)));
1599 }
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:2460
#define ereport(elevel,...)
Definition: elog.h:157
int FreeFile(FILE *file)
Definition: fd.c:2659
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define snprintf
Definition: port.h:217

Variable Documentation

◆ AuthenticatedUserId

◆ AuthenticatedUserIsSuperuser

bool AuthenticatedUserIsSuperuser = false
static

◆ CurrentUserId

◆ IgnoreSystemIndexes

◆ local_preload_libraries_string

char* local_preload_libraries_string = NULL

Definition at line 1612 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 477 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 1610 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 476 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 482 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 487 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1611 of file miscinit.c.

Referenced by process_shared_preload_libraries().