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 "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.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 1301 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().

1302 {
1303  int fd;
1304  int len;
1305  int lineno;
1306  char *srcptr;
1307  char *destptr;
1308  char srcbuffer[BLCKSZ];
1309  char destbuffer[BLCKSZ];
1310 
1311  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1312  if (fd < 0)
1313  {
1314  ereport(LOG,
1316  errmsg("could not open file \"%s\": %m",
1318  return;
1319  }
1321  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1323  if (len < 0)
1324  {
1325  ereport(LOG,
1327  errmsg("could not read from file \"%s\": %m",
1329  close(fd);
1330  return;
1331  }
1332  srcbuffer[len] = '\0';
1333 
1334  /*
1335  * Advance over lines we are not supposed to rewrite, then copy them to
1336  * destbuffer.
1337  */
1338  srcptr = srcbuffer;
1339  for (lineno = 1; lineno < target_line; lineno++)
1340  {
1341  char *eol = strchr(srcptr, '\n');
1342 
1343  if (eol == NULL)
1344  break; /* not enough lines in file yet */
1345  srcptr = eol + 1;
1346  }
1347  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1348  destptr = destbuffer + (srcptr - srcbuffer);
1349 
1350  /*
1351  * Fill in any missing lines before the target line, in case lines are
1352  * added to the file out of order.
1353  */
1354  for (; lineno < target_line; lineno++)
1355  {
1356  if (destptr < destbuffer + sizeof(destbuffer))
1357  *destptr++ = '\n';
1358  }
1359 
1360  /*
1361  * Write or rewrite the target line.
1362  */
1363  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1364  destptr += strlen(destptr);
1365 
1366  /*
1367  * If there are more lines in the old file, append them to destbuffer.
1368  */
1369  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1370  {
1371  srcptr++;
1372  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1373  srcptr);
1374  }
1375 
1376  /*
1377  * And rewrite the data. Since we write in a single kernel call, this
1378  * update should appear atomic to onlookers.
1379  */
1380  len = strlen(destbuffer);
1381  errno = 0;
1383  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1384  {
1386  /* if write didn't set errno, assume problem is no disk space */
1387  if (errno == 0)
1388  errno = ENOSPC;
1389  ereport(LOG,
1391  errmsg("could not write to file \"%s\": %m",
1393  close(fd);
1394  return;
1395  }
1398  if (pg_fsync(fd) != 0)
1399  {
1400  ereport(LOG,
1402  errmsg("could not write to file \"%s\": %m",
1404  }
1406  if (close(fd) != 0)
1407  {
1408  ereport(LOG,
1410  errmsg("could not write to file \"%s\": %m",
1412  }
1413 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
#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:1233
ssize_t pg_pwrite(int fd, const void *buf, size_t nbyte, off_t offset)
Definition: pwrite.c:27
int errcode_for_file_access(void)
Definition: elog.c:633
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1381
#define ereport(elevel,...)
Definition: elog.h:144
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1357
int errmsg(const char *fmt,...)
Definition: elog.c:824
int pg_fsync(int fd)
Definition: fd.c:345
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:193
#define read(a, b, c)
Definition: win32.h:13

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 388 of file miscinit.c.

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

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

389 {
391 
392  if (chdir(DataDir) < 0)
393  ereport(FATAL,
395  errmsg("could not change directory to \"%s\": %m",
396  DataDir)));
397 }
#define AssertState(condition)
Definition: c.h:741
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:633
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
char * DataDir
Definition: globals.c:62

◆ checkDataDir()

void checkDataDir ( void  )

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

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

275 {
276  struct stat stat_buf;
277 
278  Assert(DataDir);
279 
280  if (stat(DataDir, &stat_buf) != 0)
281  {
282  if (errno == ENOENT)
283  ereport(FATAL,
285  errmsg("data directory \"%s\" does not exist",
286  DataDir)));
287  else
288  ereport(FATAL,
290  errmsg("could not read permissions of directory \"%s\": %m",
291  DataDir)));
292  }
293 
294  /* eventual chdir would fail anyway, but let's test ... */
295  if (!S_ISDIR(stat_buf.st_mode))
296  ereport(FATAL,
297  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
298  errmsg("specified data directory \"%s\" is not a directory",
299  DataDir)));
300 
301  /*
302  * Check that the directory belongs to my userid; if not, reject.
303  *
304  * This check is an essential part of the interlock that prevents two
305  * postmasters from starting in the same directory (see CreateLockFile()).
306  * Do not remove or weaken it.
307  *
308  * XXX can we safely enable this check on Windows?
309  */
310 #if !defined(WIN32) && !defined(__CYGWIN__)
311  if (stat_buf.st_uid != geteuid())
312  ereport(FATAL,
313  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
314  errmsg("data directory \"%s\" has wrong ownership",
315  DataDir),
316  errhint("The server must be started by the user that owns the data directory.")));
317 #endif
318 
319  /*
320  * Check if the directory has correct permissions. If not, reject.
321  *
322  * Only two possible modes are allowed, 0700 and 0750. The latter mode
323  * indicates that group read/execute should be allowed on all newly
324  * created files and directories.
325  *
326  * XXX temporarily suppress check when on Windows, because there may not
327  * be proper support for Unix-y file permissions. Need to think of a
328  * reasonable check to apply on Windows.
329  */
330 #if !defined(WIN32) && !defined(__CYGWIN__)
331  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
332  ereport(FATAL,
333  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
334  errmsg("data directory \"%s\" has invalid permissions",
335  DataDir),
336  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
337 #endif
338 
339  /*
340  * Reset creation modes and mask based on the mode of the data directory.
341  *
342  * The mask was set earlier in startup to disallow group permissions on
343  * newly created files and directories. However, if group read/execute
344  * are present on the data directory then modify the create modes and mask
345  * to allow group read/execute on newly created files and directories and
346  * set the data_directory_mode GUC.
347  *
348  * Suppress when on Windows, because there may not be proper support for
349  * Unix-y file permissions.
350  */
351 #if !defined(WIN32) && !defined(__CYGWIN__)
353 
354  umask(pg_mode_mask);
356 #endif
357 
358  /* Check for PG_VERSION */
360 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1500
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
struct stat stat_buf
Definition: pg_standby.c:100
#define FATAL
Definition: elog.h:52
int errdetail(const char *fmt,...)
Definition: elog.c:957
int errcode_for_file_access(void)
Definition: elog.c:633
#define stat(a, b)
Definition: win32_port.h:255
int pg_dir_create_mode
Definition: file_perm.c:18
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:738
#define S_ISDIR(m)
Definition: win32_port.h:296
int errmsg(const char *fmt,...)
Definition: elog.c:824
int data_directory_mode
Definition: globals.c:68
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
char * DataDir
Definition: globals.c:62
int pg_mode_mask
Definition: file_perm.c:25

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1245 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1246 {
1247  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1248 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:940
char * DataDir
Definition: globals.c:62

◆ CreateLockFile()

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

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

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

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by StreamServerPort().

1256 {
1257  char lockfile[MAXPGPATH];
1258 
1259  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1260  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1261 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:940
#define MAXPGPATH
#define snprintf
Definition: port.h:193

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 507 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

508 {
510  return AuthenticatedUserId;
511 }
#define AssertState(condition)
Definition: c.h:741
#define OidIsValid(objectId)
Definition: c.h:644
static Oid AuthenticatedUserId
Definition: miscinit.c:428

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

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

203 {
204  const char *backendDesc = "unknown process type";
205 
206  switch (backendType)
207  {
208  case B_INVALID:
209  backendDesc = "not initialized";
210  break;
211  case B_AUTOVAC_LAUNCHER:
212  backendDesc = "autovacuum launcher";
213  break;
214  case B_AUTOVAC_WORKER:
215  backendDesc = "autovacuum worker";
216  break;
217  case B_BACKEND:
218  backendDesc = "client backend";
219  break;
220  case B_BG_WORKER:
221  backendDesc = "background worker";
222  break;
223  case B_BG_WRITER:
224  backendDesc = "background writer";
225  break;
226  case B_CHECKPOINTER:
227  backendDesc = "checkpointer";
228  break;
229  case B_STARTUP:
230  backendDesc = "startup";
231  break;
232  case B_WAL_RECEIVER:
233  backendDesc = "walreceiver";
234  break;
235  case B_WAL_SENDER:
236  backendDesc = "walsender";
237  break;
238  case B_WAL_WRITER:
239  backendDesc = "walwriter";
240  break;
241  case B_ARCHIVER:
242  backendDesc = "archiver";
243  break;
244  case B_STATS_COLLECTOR:
245  backendDesc = "stats collector";
246  break;
247  case B_LOGGER:
248  backendDesc = "logger";
249  break;
250  }
251 
252  return backendDesc;
253 }

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 807 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

808 {
809  if (SetRoleIsActive)
810  return OuterUserId;
811  else
812  return InvalidOid;
813 }
static Oid OuterUserId
Definition: miscinit.c:430
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:440

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 459 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

460 {
462  return OuterUserId;
463 }
#define AssertState(condition)
Definition: c.h:741
static Oid OuterUserId
Definition: miscinit.c:430
#define OidIsValid(objectId)
Definition: c.h:644

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

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

483 {
485  return SessionUserId;
486 }
#define AssertState(condition)
Definition: c.h:741
static Oid SessionUserId
Definition: miscinit.c:429
#define OidIsValid(objectId)
Definition: c.h:644

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 448 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

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

449 {
451  return CurrentUserId;
452 }
#define AssertState(condition)
Definition: c.h:741
#define OidIsValid(objectId)
Definition: c.h:644
static Oid CurrentUserId
Definition: miscinit.c:431

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 602 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

603 {
604  *userid = CurrentUserId;
605  *sec_def_context = InLocalUserIdChange();
606 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:571
static Oid CurrentUserId
Definition: miscinit.c:431

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 863 of file miscinit.c.

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

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

864 {
865  HeapTuple tuple;
866  char *result;
867 
868  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
869  if (!HeapTupleIsValid(tuple))
870  {
871  if (!noerr)
872  ereport(ERROR,
873  (errcode(ERRCODE_UNDEFINED_OBJECT),
874  errmsg("invalid role OID: %u", roleid)));
875  result = NULL;
876  }
877  else
878  {
879  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
880  ReleaseSysCache(tuple);
881  }
882  return result;
883 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData rolname
Definition: pg_authid.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1186
int errcode(int sqlerrcode)
Definition: elog.c:610
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define NameStr(name)
Definition: c.h:615

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 629 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

630 {
631  bool result = false;
632  HeapTuple utup;
633 
634  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
635  if (HeapTupleIsValid(utup))
636  {
637  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
638  ReleaseSysCache(utup);
639  }
640  return result;
641 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
bool rolreplication
Definition: pg_authid.h:40
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

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

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

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 750 of file miscinit.c.

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

Referenced by InitPostgres().

751 {
752  /*
753  * This function should only be called in single-user mode, in autovacuum
754  * workers, and in background workers.
755  */
757 
758  /* call only once */
760 
761  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
763 
764  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
765 }
#define AssertState(condition)
Definition: c.h:741
#define OidIsValid(objectId)
Definition: c.h:644
bool IsBackgroundWorker
Definition: globals.c:111
bool IsUnderPostmaster
Definition: globals.c:109
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:434
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3301
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:490
static Oid AuthenticatedUserId
Definition: miscinit.c:428

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 91 of file miscinit.c.

References elog, FATAL, InitializeLatchSupport(), InitLatch(), InitProcessGlobals(), IsUnderPostmaster, LocalLatchData, MyLatch, on_exit_reset(), PostmasterDeathSignalInit(), and set_stack_base().

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

92 {
93  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
94 
95  /*
96  * Set reference point for stack-depth checking. We re-do that even in the
97  * !EXEC_BACKEND case, because there are some edge cases where processes
98  * are started with an alternative stack (e.g. starting bgworkers when
99  * running postgres using the rr debugger, as bgworkers are launched from
100  * signal handlers).
101  */
102  set_stack_base();
103 
105 
106  /*
107  * make sure stderr is in binary mode before anything can possibly be
108  * written to it, in case it's actually the syslogger pipe, so the pipe
109  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
110  * redirection (e.g. via pg_ctl -l) anyway.
111  */
112 #ifdef WIN32
113  _setmode(fileno(stderr), _O_BINARY);
114 #endif
115 
116  /* We don't want the postmaster's proc_exit() handlers */
117  on_exit_reset();
118 
119  /* Initialize process-local latch support */
123 
124  /*
125  * If possible, make this process a group leader, so that the postmaster
126  * can signal any child processes too. Not all processes will have
127  * children, but for consistency we make all postmaster child processes do
128  * this.
129  */
130 #ifdef HAVE_SETSID
131  if (setsid() < 0)
132  elog(FATAL, "setsid() failed: %m");
133 #endif
134 
135  /* Request a signal if the postmaster dies, if possible. */
137 }
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3259
void InitLatch(Latch *latch)
Definition: latch.c:249
void InitProcessGlobals(void)
Definition: postmaster.c:2623
void on_exit_reset(void)
Definition: ipc.c:409
static Latch LocalLatchData
Definition: miscinit.c:65
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:109
void InitializeLatchSupport(void)
Definition: latch.c:168
#define elog(elevel,...)
Definition: elog.h:214
struct Latch * MyLatch
Definition: globals.c:54
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:370

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 145 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), and PostgresMain().

146 {
148 
150 
151  /* Initialize process-local latch support */
155 
156  /* Compute paths, no postmaster to inherit from */
157  if (my_exec_path[0] == '\0')
158  {
159  if (find_my_exec(argv0, my_exec_path) < 0)
160  elog(FATAL, "%s: could not locate my own executable path",
161  argv0);
162  }
163 
164  if (pkglib_path[0] == '\0')
166 }
bool IsPostmasterEnvironment
Definition: globals.c:108
static char * argv0
Definition: pg_ctl.c:97
void InitLatch(Latch *latch)
Definition: latch.c:249
void InitProcessGlobals(void)
Definition: postmaster.c:2623
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:65
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:128
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
void InitializeLatchSupport(void)
Definition: latch.c:168
#define Assert(condition)
Definition: c.h:738
#define elog(elevel,...)
Definition: elog.h:214
struct Latch * MyLatch
Definition: globals.c:54
char pkglib_path[MAXPGPATH]
Definition: globals.c:73

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 571 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

572 {
574 }
static int SecurityRestrictionContext
Definition: miscinit.c:437
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 589 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

590 {
592 }
static int SecurityRestrictionContext
Definition: miscinit.c:437
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:299

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

Definition at line 580 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

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

581 {
583 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
static int SecurityRestrictionContext
Definition: miscinit.c:437

◆ load_libraries()

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

Definition at line 1577 of file miscinit.c.

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

Referenced by process_session_preload_libraries(), and process_shared_preload_libraries().

1578 {
1579  char *rawstring;
1580  List *elemlist;
1581  ListCell *l;
1582 
1583  if (libraries == NULL || libraries[0] == '\0')
1584  return; /* nothing to do */
1585 
1586  /* Need a modifiable copy of string */
1587  rawstring = pstrdup(libraries);
1588 
1589  /* Parse string into list of filename paths */
1590  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1591  {
1592  /* syntax error in list */
1593  list_free_deep(elemlist);
1594  pfree(rawstring);
1595  ereport(LOG,
1596  (errcode(ERRCODE_SYNTAX_ERROR),
1597  errmsg("invalid list syntax in parameter \"%s\"",
1598  gucname)));
1599  return;
1600  }
1601 
1602  foreach(l, elemlist)
1603  {
1604  /* Note that filename was already canonicalized */
1605  char *filename = (char *) lfirst(l);
1606  char *expanded = NULL;
1607 
1608  /* If restricting, insert $libdir/plugins if not mentioned already */
1609  if (restricted && first_dir_separator(filename) == NULL)
1610  {
1611  expanded = psprintf("$libdir/plugins/%s", filename);
1612  filename = expanded;
1613  }
1614  load_file(filename, restricted);
1615  ereport(DEBUG1,
1616  (errmsg("loaded library \"%s\"", filename)));
1617  if (expanded)
1618  pfree(expanded);
1619  }
1620 
1621  list_free_deep(elemlist);
1622  pfree(rawstring);
1623 }
#define DEBUG1
Definition: elog.h:25
char * pstrdup(const char *in)
Definition: mcxt.c:1186
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LOG
Definition: elog.h:26
void list_free_deep(List *list)
Definition: list.c:1390
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3813
void pfree(void *pointer)
Definition: mcxt.c:1056
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:824
Definition: pg_list.h:50

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1653 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1654 {
1655 #ifdef ENABLE_NLS
1656  if (my_exec_path[0] != '\0')
1657  {
1658  char locale_path[MAXPGPATH];
1659 
1660  get_locale_path(my_exec_path, locale_path);
1661  bindtextdomain(domain, locale_path);
1662  pg_bind_textdomain_codeset(domain);
1663  }
1664 #endif
1665 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1642 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1643 {
1645  "session_preload_libraries",
1646  false);
1648  "local_preload_libraries",
1649  true);
1650 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1577
char * local_preload_libraries_string
Definition: miscinit.c:1565
char * session_preload_libraries_string
Definition: miscinit.c:1563

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1629 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1630 {
1633  "shared_preload_libraries",
1634  false);
1636 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1568
char * shared_preload_libraries_string
Definition: miscinit.c:1564
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1577

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

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

1429 {
1430  int fd;
1431  int len;
1432  long file_pid;
1433  char buffer[BLCKSZ];
1434 
1435  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1436  if (fd < 0)
1437  {
1438  /*
1439  * There are many foreseeable false-positive error conditions. For
1440  * safety, fail only on enumerated clearly-something-is-wrong
1441  * conditions.
1442  */
1443  switch (errno)
1444  {
1445  case ENOENT:
1446  case ENOTDIR:
1447  /* disaster */
1448  ereport(LOG,
1450  errmsg("could not open file \"%s\": %m",
1452  return false;
1453  default:
1454  /* non-fatal, at least for now */
1455  ereport(LOG,
1457  errmsg("could not open file \"%s\": %m; continuing anyway",
1459  return true;
1460  }
1461  }
1463  len = read(fd, buffer, sizeof(buffer) - 1);
1465  if (len < 0)
1466  {
1467  ereport(LOG,
1469  errmsg("could not read from file \"%s\": %m",
1471  close(fd);
1472  return true; /* treat read failure as nonfatal */
1473  }
1474  buffer[len] = '\0';
1475  close(fd);
1476  file_pid = atol(buffer);
1477  if (file_pid == getpid())
1478  return true; /* all is well */
1479 
1480  /* Trouble: someone's overwritten the lock file */
1481  ereport(LOG,
1482  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1483  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1484  return false;
1485 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
#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:1233
int errcode_for_file_access(void)
Definition: elog.c:633
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1381
#define ereport(elevel,...)
Definition: elog.h:144
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1357
int errmsg(const char *fmt,...)
Definition: elog.c:824
#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 828 of file miscinit.c.

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

Referenced by assign_role(), and ParallelWorkerMain().

829 {
830  /*
831  * Get correct info if it's SET ROLE NONE
832  *
833  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
834  * SetSessionUserId call will fix everything. This is needed since we
835  * will get called during GUC initialization.
836  */
837  if (!OidIsValid(roleid))
838  {
840  return;
841 
842  roleid = SessionUserId;
844 
845  SetRoleIsActive = false;
846  }
847  else
848  SetRoleIsActive = true;
849 
850  SetOuterUserId(roleid);
851 
852  SetConfigOption("is_superuser",
853  is_superuser ? "on" : "off",
855 }
static Oid SessionUserId
Definition: miscinit.c:429
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:467
#define OidIsValid(objectId)
Definition: c.h:644
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7685
static bool SetRoleIsActive
Definition: miscinit.c:440
static bool SessionUserIsSuperuser
Definition: miscinit.c:435
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4176

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 261 of file miscinit.c.

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

Referenced by InitPostgres().

262 {
263  /* This should happen only once per process */
266 }
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * DatabasePath
Definition: globals.c:93
#define Assert(condition)
Definition: c.h:738
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1173

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 367 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

368 {
369  char *new;
370 
371  AssertArg(dir);
372 
373  /* If presented path is relative, convert to absolute */
374  new = make_absolute_path(dir);
375 
376  if (DataDir)
377  free(DataDir);
378  DataDir = new;
379 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:740
#define free(a)
Definition: header.h:65
char * DataDir
Definition: globals.c:62

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 467 of file miscinit.c.

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

Referenced by SetCurrentRoleId().

468 {
470  AssertArg(OidIsValid(userid));
471  OuterUserId = userid;
472 
473  /* We force the effective user ID to match, too */
474  CurrentUserId = userid;
475 }
#define AssertState(condition)
Definition: c.h:741
static Oid OuterUserId
Definition: miscinit.c:430
#define OidIsValid(objectId)
Definition: c.h:644
static int SecurityRestrictionContext
Definition: miscinit.c:437
#define AssertArg(condition)
Definition: c.h:740
static Oid CurrentUserId
Definition: miscinit.c:431

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

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

783 {
784  /* Must have authenticated already, else can't make permission check */
786 
787  if (userid != AuthenticatedUserId &&
789  ereport(ERROR,
790  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
791  errmsg("permission denied to set session authorization")));
792 
794 
795  SetConfigOption("is_superuser",
796  is_superuser ? "on" : "off",
798 }
#define AssertState(condition)
Definition: c.h:741
int errcode(int sqlerrcode)
Definition: elog.c:610
#define OidIsValid(objectId)
Definition: c.h:644
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7685
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:434
#define ereport(elevel,...)
Definition: elog.h:144
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4176
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:490
static Oid AuthenticatedUserId
Definition: miscinit.c:428

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 490 of file miscinit.c.

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

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

491 {
493  AssertArg(OidIsValid(userid));
494  SessionUserId = userid;
496  SetRoleIsActive = false;
497 
498  /* We force the effective user IDs to match, too */
499  OuterUserId = userid;
500  CurrentUserId = userid;
501 }
#define AssertState(condition)
Definition: c.h:741
static Oid SessionUserId
Definition: miscinit.c:429
static Oid OuterUserId
Definition: miscinit.c:430
#define OidIsValid(objectId)
Definition: c.h:644
static int SecurityRestrictionContext
Definition: miscinit.c:437
#define AssertArg(condition)
Definition: c.h:740
static bool SetRoleIsActive
Definition: miscinit.c:440
static bool SessionUserIsSuperuser
Definition: miscinit.c:435
static Oid CurrentUserId
Definition: miscinit.c:431
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4176

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 609 of file miscinit.c.

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

610 {
611  /* We throw the same error SET ROLE would. */
613  ereport(ERROR,
614  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
615  errmsg("cannot set parameter \"%s\" within security-restricted operation",
616  "role")));
617  CurrentUserId = userid;
618  if (sec_def_context)
620  else
622 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:437
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
#define ereport(elevel,...)
Definition: elog.h:144
static Oid CurrentUserId
Definition: miscinit.c:431
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:580
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 188 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

189 {
191  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
192 
194 
195  if (FeBeWaitSet)
197 
198  SetLatch(MyLatch);
199 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:838
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:184
void SetLatch(Latch *latch)
Definition: latch.c:457
Latch procLatch
Definition: proc.h:111
static Latch LocalLatchData
Definition: miscinit.c:65
#define Assert(condition)
Definition: c.h:738
struct Latch * MyLatch
Definition: globals.c:54
#define WL_LATCH_SET
Definition: latch.h:124

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 169 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

170 {
172  Assert(MyProc != NULL);
173 
175 
176  if (FeBeWaitSet)
178 
179  /*
180  * Set the shared latch as the local one might have been set. This
181  * shouldn't normally be necessary as code is supposed to check the
182  * condition before waiting for the latch, but a bit care can't hurt.
183  */
184  SetLatch(MyLatch);
185 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:838
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:184
void SetLatch(Latch *latch)
Definition: latch.c:457
Latch procLatch
Definition: proc.h:111
static Latch LocalLatchData
Definition: miscinit.c:65
#define Assert(condition)
Definition: c.h:738
struct Latch * MyLatch
Definition: globals.c:54
#define WL_LATCH_SET
Definition: latch.h:124

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1272 of file miscinit.c.

References DIRECTORY_LOCK_FILE, and lfirst.

Referenced by ServerLoop().

1273 {
1274  ListCell *l;
1275 
1276  foreach(l, lock_files)
1277  {
1278  char *socketLockFile = (char *) lfirst(l);
1279 
1280  /* No need to touch the data directory lock file, we trust */
1281  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1282  continue;
1283 
1284  /* we just ignore any error here */
1285  (void) utime(socketLockFile, NULL);
1286  }
1287 }
static List * lock_files
Definition: miscinit.c:63
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
#define lfirst(lc)
Definition: pg_list.h:190

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 905 of file miscinit.c.

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

Referenced by CreateLockFile().

906 {
907  ListCell *l;
908 
909  foreach(l, lock_files)
910  {
911  char *curfile = (char *) lfirst(l);
912 
913  unlink(curfile);
914  /* Should we complain if the unlink fails? */
915  }
916  /* Since we're about to exit, no need to reclaim storage */
917  lock_files = NIL;
918 
919  /*
920  * Lock file removal should always be the last externally visible action
921  * of a postmaster or standalone backend, while we won't come here at all
922  * when exiting postmaster child processes. Therefore, this is a good
923  * place to log completion of shutdown. We could alternatively teach
924  * proc_exit() to do it, but that seems uglier. In a standalone backend,
925  * use NOTICE elevel to be less chatty.
926  */
928  (errmsg("database system is shut down")));
929 }
#define NIL
Definition: pg_list.h:65
bool IsPostmasterEnvironment
Definition: globals.c:108
static List * lock_files
Definition: miscinit.c:63
#define LOG
Definition: elog.h:26
#define ereport(elevel,...)
Definition: elog.h:144
#define NOTICE
Definition: elog.h:37
#define lfirst(lc)
Definition: pg_list.h:190
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

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

1501 {
1502  char full_path[MAXPGPATH];
1503  FILE *file;
1504  int ret;
1505  long file_major;
1506  long my_major;
1507  char *endptr;
1508  char file_version_string[64];
1509  const char *my_version_string = PG_VERSION;
1510 
1511  my_major = strtol(my_version_string, &endptr, 10);
1512 
1513  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1514 
1515  file = AllocateFile(full_path, "r");
1516  if (!file)
1517  {
1518  if (errno == ENOENT)
1519  ereport(FATAL,
1520  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1521  errmsg("\"%s\" is not a valid data directory",
1522  path),
1523  errdetail("File \"%s\" is missing.", full_path)));
1524  else
1525  ereport(FATAL,
1527  errmsg("could not open file \"%s\": %m", full_path)));
1528  }
1529 
1530  file_version_string[0] = '\0';
1531  ret = fscanf(file, "%63s", file_version_string);
1532  file_major = strtol(file_version_string, &endptr, 10);
1533 
1534  if (ret != 1 || endptr == file_version_string)
1535  ereport(FATAL,
1536  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1537  errmsg("\"%s\" is not a valid data directory",
1538  path),
1539  errdetail("File \"%s\" does not contain valid data.",
1540  full_path),
1541  errhint("You might need to initdb.")));
1542 
1543  FreeFile(file);
1544 
1545  if (my_major != file_major)
1546  ereport(FATAL,
1547  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1548  errmsg("database files are incompatible with server"),
1549  errdetail("The data directory was initialized by PostgreSQL version %s, "
1550  "which is not compatible with this version %s.",
1551  file_version_string, my_version_string)));
1552 }
int errhint(const char *fmt,...)
Definition: elog.c:1071
int errcode(int sqlerrcode)
Definition: elog.c:610
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:957
int errcode_for_file_access(void)
Definition: elog.c:633
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
#define ereport(elevel,...)
Definition: elog.h:144
int FreeFile(FILE *file)
Definition: fd.c:2521
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define snprintf
Definition: port.h:193

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 1565 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

Definition at line 65 of file miscinit.c.

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

◆ lock_files

List* lock_files = NIL
static

Definition at line 63 of file miscinit.c.

◆ Mode

Definition at line 58 of file miscinit.c.

◆ MyBackendType

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 430 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 1563 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 429 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 435 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 440 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1564 of file miscinit.c.

Referenced by process_shared_preload_libraries().