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/pgarch.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.

Data Structures

struct  SerializedClientConnectionInfo
 

Macros

#define DIRECTORY_LOCK_FILE   "postmaster.pid"
 

Typedefs

typedef struct SerializedClientConnectionInfo SerializedClientConnectionInfo
 

Functions

void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SwitchToSharedLatch (void)
 
void InitProcessLocalLatch (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)
 
const char * GetSystemUser (void)
 
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 InitializeSystemUser (const char *authn_id, const char *auth_method)
 
Datum system_user (PG_FUNCTION_ARGS)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
Size EstimateClientConnectionInfoSpace (void)
 
void SerializeClientConnectionInfo (Size maxsize, char *start_address)
 
void RestoreClientConnectionInfo (char *conninfo)
 
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 process_shmem_requests (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 const char * SystemUser = NULL
 
static bool AuthenticatedUserIsSuperuser = false
 
static bool SessionUserIsSuperuser = false
 
static int SecurityRestrictionContext = 0
 
static bool SetRoleIsActive = false
 
ClientConnectionInfo MyClientConnectionInfo
 
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
 
bool process_shared_preload_libraries_done = false
 
shmem_request_hook_type shmem_request_hook = NULL
 
bool process_shmem_requests_in_progress = false
 

Macro Definition Documentation

◆ DIRECTORY_LOCK_FILE

#define DIRECTORY_LOCK_FILE   "postmaster.pid"

Definition at line 59 of file miscinit.c.

Typedef Documentation

◆ SerializedClientConnectionInfo

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1515 of file miscinit.c.

1516 {
1517  int fd;
1518  int len;
1519  int lineno;
1520  char *srcptr;
1521  char *destptr;
1522  char srcbuffer[BLCKSZ];
1523  char destbuffer[BLCKSZ];
1524 
1525  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1526  if (fd < 0)
1527  {
1528  ereport(LOG,
1530  errmsg("could not open file \"%s\": %m",
1532  return;
1533  }
1535  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1537  if (len < 0)
1538  {
1539  ereport(LOG,
1541  errmsg("could not read from file \"%s\": %m",
1543  close(fd);
1544  return;
1545  }
1546  srcbuffer[len] = '\0';
1547 
1548  /*
1549  * Advance over lines we are not supposed to rewrite, then copy them to
1550  * destbuffer.
1551  */
1552  srcptr = srcbuffer;
1553  for (lineno = 1; lineno < target_line; lineno++)
1554  {
1555  char *eol = strchr(srcptr, '\n');
1556 
1557  if (eol == NULL)
1558  break; /* not enough lines in file yet */
1559  srcptr = eol + 1;
1560  }
1561  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1562  destptr = destbuffer + (srcptr - srcbuffer);
1563 
1564  /*
1565  * Fill in any missing lines before the target line, in case lines are
1566  * added to the file out of order.
1567  */
1568  for (; lineno < target_line; lineno++)
1569  {
1570  if (destptr < destbuffer + sizeof(destbuffer))
1571  *destptr++ = '\n';
1572  }
1573 
1574  /*
1575  * Write or rewrite the target line.
1576  */
1577  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1578  destptr += strlen(destptr);
1579 
1580  /*
1581  * If there are more lines in the old file, append them to destbuffer.
1582  */
1583  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1584  {
1585  srcptr++;
1586  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1587  srcptr);
1588  }
1589 
1590  /*
1591  * And rewrite the data. Since we write in a single kernel call, this
1592  * update should appear atomic to onlookers.
1593  */
1594  len = strlen(destbuffer);
1595  errno = 0;
1597  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1598  {
1600  /* if write didn't set errno, assume problem is no disk space */
1601  if (errno == 0)
1602  errno = ENOSPC;
1603  ereport(LOG,
1605  errmsg("could not write to file \"%s\": %m",
1607  close(fd);
1608  return;
1609  }
1612  if (pg_fsync(fd) != 0)
1613  {
1614  ereport(LOG,
1616  errmsg("could not write to file \"%s\": %m",
1618  }
1620  if (close(fd) != 0)
1621  {
1622  ereport(LOG,
1624  errmsg("could not write to file \"%s\": %m",
1626  }
1627 }
#define PG_BINARY
Definition: c.h:1278
int errcode_for_file_access(void)
Definition: elog.c:881
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int pg_fsync(int fd)
Definition: fd.c:361
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:59
const void size_t len
#define pg_pwrite
Definition: port.h:226
#define snprintf
Definition: port.h:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE
Definition: wait_event.h:189
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ
Definition: wait_event.h:187
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC
Definition: wait_event.h:188
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:271
static void pgstat_report_wait_end(void)
Definition: wait_event.h:287

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

Referenced by InternalIpcMemoryCreate(), PostmasterMain(), process_pm_child_exit(), process_pm_pmsignal(), and process_pm_shutdown_request().

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 449 of file miscinit.c.

450 {
451  Assert(DataDir);
452 
453  if (chdir(DataDir) < 0)
454  ereport(FATAL,
456  errmsg("could not change directory to \"%s\": %m",
457  DataDir)));
458 }
#define FATAL
Definition: elog.h:41
char * DataDir
Definition: globals.c:66
Assert(fmt[strlen(fmt) - 1] !='\n')

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

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

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 336 of file miscinit.c.

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

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 BootstrapModeMain(), PostgresSingleUserMain(), and PostmasterMain().

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1459 of file miscinit.c.

1460 {
1461  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1462 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1154

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

◆ CreateLockFile()

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

Definition at line 1154 of file miscinit.c.

1157 {
1158  int fd;
1159  char buffer[MAXPGPATH * 2 + 256];
1160  int ntries;
1161  int len;
1162  int encoded_pid;
1163  pid_t other_pid;
1164  pid_t my_pid,
1165  my_p_pid,
1166  my_gp_pid;
1167  const char *envvar;
1168 
1169  /*
1170  * If the PID in the lockfile is our own PID or our parent's or
1171  * grandparent's PID, then the file must be stale (probably left over from
1172  * a previous system boot cycle). We need to check this because of the
1173  * likelihood that a reboot will assign exactly the same PID as we had in
1174  * the previous reboot, or one that's only one or two counts larger and
1175  * hence the lockfile's PID now refers to an ancestor shell process. We
1176  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
1177  * via the environment variable PG_GRANDPARENT_PID; this is so that
1178  * launching the postmaster via pg_ctl can be just as reliable as
1179  * launching it directly. There is no provision for detecting
1180  * further-removed ancestor processes, but if the init script is written
1181  * carefully then all but the immediate parent shell will be root-owned
1182  * processes and so the kill test will fail with EPERM. Note that we
1183  * cannot get a false negative this way, because an existing postmaster
1184  * would surely never launch a competing postmaster or pg_ctl process
1185  * directly.
1186  */
1187  my_pid = getpid();
1188 
1189 #ifndef WIN32
1190  my_p_pid = getppid();
1191 #else
1192 
1193  /*
1194  * Windows hasn't got getppid(), but doesn't need it since it's not using
1195  * real kill() either...
1196  */
1197  my_p_pid = 0;
1198 #endif
1199 
1200  envvar = getenv("PG_GRANDPARENT_PID");
1201  if (envvar)
1202  my_gp_pid = atoi(envvar);
1203  else
1204  my_gp_pid = 0;
1205 
1206  /*
1207  * We need a loop here because of race conditions. But don't loop forever
1208  * (for example, a non-writable $PGDATA directory might cause a failure
1209  * that won't go away). 100 tries seems like plenty.
1210  */
1211  for (ntries = 0;; ntries++)
1212  {
1213  /*
1214  * Try to create the lock file --- O_EXCL makes this atomic.
1215  *
1216  * Think not to make the file protection weaker than 0600/0640. See
1217  * comments below.
1218  */
1219  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
1220  if (fd >= 0)
1221  break; /* Success; exit the retry loop */
1222 
1223  /*
1224  * Couldn't create the pid file. Probably it already exists.
1225  */
1226  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
1227  ereport(FATAL,
1229  errmsg("could not create lock file \"%s\": %m",
1230  filename)));
1231 
1232  /*
1233  * Read the file to get the old owner's PID. Note race condition
1234  * here: file might have been deleted since we tried to create it.
1235  */
1236  fd = open(filename, O_RDONLY, pg_file_create_mode);
1237  if (fd < 0)
1238  {
1239  if (errno == ENOENT)
1240  continue; /* race condition; try again */
1241  ereport(FATAL,
1243  errmsg("could not open lock file \"%s\": %m",
1244  filename)));
1245  }
1247  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
1248  ereport(FATAL,
1250  errmsg("could not read lock file \"%s\": %m",
1251  filename)));
1253  close(fd);
1254 
1255  if (len == 0)
1256  {
1257  ereport(FATAL,
1258  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1259  errmsg("lock file \"%s\" is empty", filename),
1260  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
1261  }
1262 
1263  buffer[len] = '\0';
1264  encoded_pid = atoi(buffer);
1265 
1266  /* if pid < 0, the pid is for postgres, not postmaster */
1267  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
1268 
1269  if (other_pid <= 0)
1270  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
1271  filename, buffer);
1272 
1273  /*
1274  * Check to see if the other process still exists
1275  *
1276  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
1277  * ignored as false matches.
1278  *
1279  * Normally kill() will fail with ESRCH if the given PID doesn't
1280  * exist.
1281  *
1282  * We can treat the EPERM-error case as okay because that error
1283  * implies that the existing process has a different userid than we
1284  * do, which means it cannot be a competing postmaster. A postmaster
1285  * cannot successfully attach to a data directory owned by a userid
1286  * other than its own, as enforced in checkDataDir(). Also, since we
1287  * create the lockfiles mode 0600/0640, we'd have failed above if the
1288  * lockfile belonged to another userid --- which means that whatever
1289  * process kill() is reporting about isn't the one that made the
1290  * lockfile. (NOTE: this last consideration is the only one that
1291  * keeps us from blowing away a Unix socket file belonging to an
1292  * instance of Postgres being run by someone else, at least on
1293  * machines where /tmp hasn't got a stickybit.)
1294  */
1295  if (other_pid != my_pid && other_pid != my_p_pid &&
1296  other_pid != my_gp_pid)
1297  {
1298  if (kill(other_pid, 0) == 0 ||
1299  (errno != ESRCH && errno != EPERM))
1300  {
1301  /* lockfile belongs to a live process */
1302  ereport(FATAL,
1303  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1304  errmsg("lock file \"%s\" already exists",
1305  filename),
1306  isDDLock ?
1307  (encoded_pid < 0 ?
1308  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
1309  (int) other_pid, refName) :
1310  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
1311  (int) other_pid, refName)) :
1312  (encoded_pid < 0 ?
1313  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
1314  (int) other_pid, refName) :
1315  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
1316  (int) other_pid, refName))));
1317  }
1318  }
1319 
1320  /*
1321  * No, the creating process did not exist. However, it could be that
1322  * the postmaster crashed (or more likely was kill -9'd by a clueless
1323  * admin) but has left orphan backends behind. Check for this by
1324  * looking to see if there is an associated shmem segment that is
1325  * still in use.
1326  *
1327  * Note: because postmaster.pid is written in multiple steps, we might
1328  * not find the shmem ID values in it; we can't treat that as an
1329  * error.
1330  */
1331  if (isDDLock)
1332  {
1333  char *ptr = buffer;
1334  unsigned long id1,
1335  id2;
1336  int lineno;
1337 
1338  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
1339  {
1340  if ((ptr = strchr(ptr, '\n')) == NULL)
1341  break;
1342  ptr++;
1343  }
1344 
1345  if (ptr != NULL &&
1346  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
1347  {
1348  if (PGSharedMemoryIsInUse(id1, id2))
1349  ereport(FATAL,
1350  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1351  errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
1352  id1, id2),
1353  errhint("Terminate any old server processes associated with data directory \"%s\".",
1354  refName)));
1355  }
1356  }
1357 
1358  /*
1359  * Looks like nobody's home. Unlink the file and try again to create
1360  * it. Need a loop because of possible race condition against other
1361  * would-be creators.
1362  */
1363  if (unlink(filename) < 0)
1364  ereport(FATAL,
1366  errmsg("could not remove old lock file \"%s\": %m",
1367  filename),
1368  errhint("The file seems accidentally left over, but "
1369  "it could not be removed. Please remove the file "
1370  "by hand and try again.")));
1371  }
1372 
1373  /*
1374  * Successfully created the file, now fill it. See comment in pidfile.h
1375  * about the contents. Note that we write the same first five lines into
1376  * both datadir and socket lockfiles; although more stuff may get added to
1377  * the datadir lockfile later.
1378  */
1379  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
1380  amPostmaster ? (int) my_pid : -((int) my_pid),
1381  DataDir,
1382  (long) MyStartTime,
1384  socketDir);
1385 
1386  /*
1387  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1388  * will never receive data, so fill it in as empty now.
1389  */
1390  if (isDDLock && !amPostmaster)
1391  strlcat(buffer, "\n", sizeof(buffer));
1392 
1393  errno = 0;
1395  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1396  {
1397  int save_errno = errno;
1398 
1399  close(fd);
1400  unlink(filename);
1401  /* if write didn't set errno, assume problem is no disk space */
1402  errno = save_errno ? save_errno : ENOSPC;
1403  ereport(FATAL,
1405  errmsg("could not write lock file \"%s\": %m", filename)));
1406  }
1408 
1410  if (pg_fsync(fd) != 0)
1411  {
1412  int save_errno = errno;
1413 
1414  close(fd);
1415  unlink(filename);
1416  errno = save_errno;
1417  ereport(FATAL,
1419  errmsg("could not write lock file \"%s\": %m", filename)));
1420  }
1422  if (close(fd) != 0)
1423  {
1424  int save_errno = errno;
1425 
1426  unlink(filename);
1427  errno = save_errno;
1428  ereport(FATAL,
1430  errmsg("could not write lock file \"%s\": %m", filename)));
1431  }
1432 
1433  /*
1434  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1435  * one, set up the on_proc_exit function to do it; then add this lock file
1436  * to the list of files to unlink.
1437  */
1438  if (lock_files == NIL)
1440 
1441  /*
1442  * Use lcons so that the lock files are unlinked in reverse order of
1443  * creation; this is critical!
1444  */
1446 }
int pg_file_create_mode
Definition: file_perm.c:19
pg_time_t MyStartTime
Definition: globals.c:45
#define write(a, b, c)
Definition: win32.h:14
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
List * lcons(void *datum, List *list)
Definition: list.c:494
char * pstrdup(const char *in)
Definition: mcxt.c:1644
static List * lock_files
Definition: miscinit.c:66
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:1119
#define MAXPGPATH
static char * filename
Definition: pg_dumpall.c:119
#define NIL
Definition: pg_list.h:68
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: pidfile.h:43
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
int PostPortNumber
Definition: postmaster.c:198
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:316
@ WAIT_EVENT_LOCK_FILE_CREATE_SYNC
Definition: wait_event.h:191
@ WAIT_EVENT_LOCK_FILE_CREATE_READ
Definition: wait_event.h:190
@ WAIT_EVENT_LOCK_FILE_CREATE_WRITE
Definition: wait_event.h:192
#define kill(pid, sig)
Definition: win32_port.h:495

References close, DataDir, elog(), ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), filename, kill, lcons(), len, LOCK_FILE_LINE_SHMEM_KEY, lock_files, 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().

◆ CreateSocketLockFile()

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

Definition at line 1468 of file miscinit.c.

1470 {
1471  char lockfile[MAXPGPATH];
1472 
1473  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1474  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1475 }

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1031 of file miscinit.c.

1032 {
1033  Size size = 0;
1034 
1035  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1036 
1038  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1039 
1040  return size;
1041 }
size_t Size
Definition: c.h:589
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1014
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
const char * authn_id
Definition: libpq-be.h:114

References add_size(), ClientConnectionInfo::authn_id, and MyClientConnectionInfo.

Referenced by InitializeParallelDSM().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 579 of file miscinit.c.

580 {
582  return AuthenticatedUserId;
583 }
#define OidIsValid(objectId)
Definition: c.h:759
static Oid AuthenticatedUserId
Definition: miscinit.c:489

References Assert(), AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 264 of file miscinit.c.

265 {
266  const char *backendDesc = "unknown process type";
267 
268  switch (backendType)
269  {
270  case B_INVALID:
271  backendDesc = "not initialized";
272  break;
273  case B_ARCHIVER:
274  backendDesc = "archiver";
275  break;
276  case B_AUTOVAC_LAUNCHER:
277  backendDesc = "autovacuum launcher";
278  break;
279  case B_AUTOVAC_WORKER:
280  backendDesc = "autovacuum worker";
281  break;
282  case B_BACKEND:
283  backendDesc = "client backend";
284  break;
285  case B_BG_WORKER:
286  backendDesc = "background worker";
287  break;
288  case B_BG_WRITER:
289  backendDesc = "background writer";
290  break;
291  case B_CHECKPOINTER:
292  backendDesc = "checkpointer";
293  break;
294  case B_LOGGER:
295  backendDesc = "logger";
296  break;
298  backendDesc = "standalone backend";
299  break;
300  case B_STARTUP:
301  backendDesc = "startup";
302  break;
303  case B_WAL_RECEIVER:
304  backendDesc = "walreceiver";
305  break;
306  case B_WAL_SENDER:
307  backendDesc = "walsender";
308  break;
309  case B_WAL_WRITER:
310  backendDesc = "walwriter";
311  break;
312  }
313 
314  return backendDesc;
315 }
@ B_WAL_WRITER
Definition: miscadmin.h:341
@ B_WAL_RECEIVER
Definition: miscadmin.h:339
@ B_CHECKPOINTER
Definition: miscadmin.h:335
@ B_WAL_SENDER
Definition: miscadmin.h:340
@ B_LOGGER
Definition: miscadmin.h:336
@ B_STARTUP
Definition: miscadmin.h:338
@ B_BG_WORKER
Definition: miscadmin.h:333
@ B_INVALID
Definition: miscadmin.h:328
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:337
@ B_BG_WRITER
Definition: miscadmin.h:334
@ B_BACKEND
Definition: miscadmin.h:332
@ B_ARCHIVER
Definition: miscadmin.h:329
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:330
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:331

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

Referenced by BackendInitialize(), get_backend_type_for_log(), init_ps_display(), pg_stat_get_activity(), and pg_stat_get_io().

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 928 of file miscinit.c.

929 {
930  if (SetRoleIsActive)
931  return OuterUserId;
932  else
933  return InvalidOid;
934 }
static Oid OuterUserId
Definition: miscinit.c:491
static bool SetRoleIsActive
Definition: miscinit.c:502
#define InvalidOid
Definition: postgres_ext.h:36

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 521 of file miscinit.c.

522 {
524  return OuterUserId;
525 }

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 544 of file miscinit.c.

545 {
547  return SessionUserId;
548 }
static Oid SessionUserId
Definition: miscinit.c:490

References Assert(), OidIsValid, and SessionUserId.

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

◆ GetSystemUser()

const char* GetSystemUser ( void  )

Definition at line 570 of file miscinit.c.

571 {
572  return SystemUser;
573 }
static const char * SystemUser
Definition: miscinit.c:493

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 510 of file miscinit.c.

511 {
513  return CurrentUserId;
514 }
static Oid CurrentUserId
Definition: miscinit.c:492

References Assert(), CurrentUserId, and OidIsValid.

Referenced by AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), 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(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_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(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), ConfigOptionIsVisible(), convert_and_check_filename(), 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(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), emit_audit_message(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildParamSetEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckOneRelPerms(), ExecGetResultRelCheckAsUser(), ExecGrant_Attribute(), ExecGrant_common(), ExecGrant_Largeobject(), ExecGrant_Parameter(), ExecGrant_Relation(), 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_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOptionValues(), 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_parameter_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(), LockViewRecurse(), LogicalRepSyncTableStart(), 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(), RangeVarCallbackMaintainsTable(), RangeVarCallbackOwnsRelation(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameRole(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), standard_ProcessUtility(), statext_is_compatible_clause(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_permitted_for_relation(), validate_option_array_item(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 680 of file miscinit.c.

681 {
682  *userid = CurrentUserId;
683  *sec_def_context = InLocalUserIdChange();
684 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:649

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 984 of file miscinit.c.

985 {
986  HeapTuple tuple;
987  char *result;
988 
989  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
990  if (!HeapTupleIsValid(tuple))
991  {
992  if (!noerr)
993  ereport(ERROR,
994  (errcode(ERRCODE_UNDEFINED_OBJECT),
995  errmsg("invalid role OID: %u", roleid)));
996  result = NULL;
997  }
998  else
999  {
1000  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
1001  ReleaseSysCache(tuple);
1002  }
1003  return result;
1004 }
#define NameStr(name)
Definition: c.h:730
#define ERROR
Definition: elog.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
NameData rolname
Definition: pg_authid.h:34
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:866
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:818
@ AUTHOID
Definition: syscache.h:45

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

Referenced by AddRoleMems(), check_can_set_role(), check_object_ownership(), check_role_grantor(), check_role_membership_authorization(), current_user(), DelRoleMems(), DropOwnedObjects(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), insert_username(), LogicalRepSyncTableStart(), ReassignOwnedObjects(), regroleout(), session_user(), SwitchToUntrustedUser(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 707 of file miscinit.c.

708 {
709  bool result = false;
710  HeapTuple utup;
711 
712  /* Superusers bypass all permission checking. */
713  if (superuser_arg(roleid))
714  return true;
715 
716  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
717  if (HeapTupleIsValid(utup))
718  {
719  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
720  ReleaseSysCache(utup);
721  }
722  return result;
723 }
bool rolreplication
Definition: pg_authid.h:40
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

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

Referenced by AlterRole(), CheckSlotPermissions(), CreateRole(), and InitPostgres().

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 729 of file miscinit.c.

730 {
731  HeapTuple roleTup;
732  Form_pg_authid rform;
733  char *rname;
734 
735  /*
736  * Don't do scans if we're bootstrapping, none of the system catalogs
737  * exist yet, and they should be owned by postgres anyway.
738  */
740 
741  /* call only once */
743 
744  /*
745  * Make sure syscache entries are flushed for recent catalog changes. This
746  * allows us to find roles that were created on-the-fly during
747  * authentication.
748  */
750 
751  if (rolename != NULL)
752  {
753  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
754  if (!HeapTupleIsValid(roleTup))
755  ereport(FATAL,
756  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
757  errmsg("role \"%s\" does not exist", rolename)));
758  }
759  else
760  {
761  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
762  if (!HeapTupleIsValid(roleTup))
763  ereport(FATAL,
764  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
765  errmsg("role with OID %u does not exist", roleid)));
766  }
767 
768  rform = (Form_pg_authid) GETSTRUCT(roleTup);
769  roleid = rform->oid;
770  rname = NameStr(rform->rolname);
771 
772  AuthenticatedUserId = roleid;
773  AuthenticatedUserIsSuperuser = rform->rolsuper;
774 
775  /* This sets OuterUserId/CurrentUserId too */
777 
778  /* Also mark our PGPROC entry with the authenticated user id */
779  /* (We assume this is an atomic store so no lock is needed) */
780  MyProc->roleId = roleid;
781 
782  /*
783  * These next checks are not enforced when in standalone mode, so that
784  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
785  * rolcanlogin = false;".
786  */
787  if (IsUnderPostmaster)
788  {
789  /*
790  * Is role allowed to login at all?
791  */
792  if (!rform->rolcanlogin)
793  ereport(FATAL,
794  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
795  errmsg("role \"%s\" is not permitted to log in",
796  rname)));
797 
798  /*
799  * Check connection limit for this role.
800  *
801  * There is a race condition here --- we create our PGPROC before
802  * checking for other PGPROCs. If two backends did this at about the
803  * same time, they might both think they were over the limit, while
804  * ideally one should succeed and one fail. Getting that to work
805  * exactly seems more trouble than it is worth, however; instead we
806  * just document that the connection limit is approximate.
807  */
808  if (rform->rolconnlimit >= 0 &&
810  CountUserBackends(roleid) > rform->rolconnlimit)
811  ereport(FATAL,
812  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
813  errmsg("too many connections for role \"%s\"",
814  rname)));
815  }
816 
817  /* Record username and superuser status as GUC settings too */
818  SetConfigOption("session_authorization", rname,
820  SetConfigOption("is_superuser",
821  AuthenticatedUserIsSuperuser ? "on" : "off",
823 
824  ReleaseSysCache(roleTup);
825 }
bool IsUnderPostmaster
Definition: globals.c:113
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4176
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_INTERNAL
Definition: guc.h:69
@ PGC_BACKEND
Definition: guc.h:73
void AcceptInvalidationMessages(void)
Definition: inval.c:746
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:414
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:496
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:552
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
int CountUserBackends(Oid roleid)
Definition: procarray.c:3638
PGPROC * MyProc
Definition: proc.c:66
Oid roleId
Definition: proc.h:199
@ AUTHNAME
Definition: syscache.h:44

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

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 832 of file miscinit.c.

833 {
834  /*
835  * This function should only be called in single-user mode, in autovacuum
836  * workers, and in background workers.
837  */
839 
840  /* call only once */
842 
843  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
845 
846  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
847 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3385
bool IsBackgroundWorker
Definition: globals.c:115

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

Referenced by InitPostgres().

◆ InitializeSystemUser()

void InitializeSystemUser ( const char *  authn_id,
const char *  auth_method 
)

Definition at line 855 of file miscinit.c.

856 {
857  char *system_user;
858 
859  /* call only once */
860  Assert(SystemUser == NULL);
861 
862  /*
863  * InitializeSystemUser should be called only when authn_id is not NULL,
864  * meaning that auth_method is valid.
865  */
866  Assert(authn_id != NULL);
867 
868  system_user = psprintf("%s:%s", auth_method, authn_id);
869 
870  /* Store SystemUser in long-lived storage */
873 }
void pfree(void *pointer)
Definition: mcxt.c:1456
MemoryContext TopMemoryContext
Definition: mcxt.c:141
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1631
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:879
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46

References Assert(), MemoryContextStrdup(), pfree(), psprintf(), system_user(), SystemUser, and TopMemoryContext.

Referenced by InitPostgres(), and ParallelWorkerMain().

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 95 of file miscinit.c.

96 {
97  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
98 
99  /*
100  * Start our win32 signal implementation. This has to be done after we
101  * read the backend variables, because we need to pick up the signal pipe
102  * from the parent process.
103  */
104 #ifdef WIN32
106 #endif
107 
108  /*
109  * Set reference point for stack-depth checking. This might seem
110  * redundant in !EXEC_BACKEND builds; but it's not because the postmaster
111  * launches its children from signal handlers, so we might be running on
112  * an alternative stack.
113  */
114  (void) 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 */
140 
141  /*
142  * If possible, make this process a group leader, so that the postmaster
143  * can signal any child processes too. Not all processes will have
144  * children, but for consistency we make all postmaster child processes do
145  * this.
146  */
147 #ifdef HAVE_SETSID
148  if (setsid() < 0)
149  elog(FATAL, "setsid() failed: %m");
150 #endif
151 
152  /*
153  * Every postmaster child process is expected to respond promptly to
154  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
155  * BlockSig and install a suitable signal handler. (Client-facing
156  * processes may choose to replace this default choice of handler with
157  * quickdie().) All other blockable signals remain blocked for now.
158  */
160 
161  sigdelset(&BlockSig, SIGQUIT);
162  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
163 
164  /* Request a signal if the postmaster dies, if possible. */
166 
167  /* Don't give the pipe to subprograms that we execute. */
168 #ifndef WIN32
169  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
170  ereport(FATAL,
172  errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
173 #endif
174 }
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
int errcode_for_socket_access(void)
Definition: elog.c:952
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:77
void on_exit_reset(void)
Definition: ipc.c:412
void InitializeLatchWaitSet(void)
Definition: latch.c:321
void InitializeLatchSupport(void)
Definition: latch.c:207
void InitProcessLocalLatch(void)
Definition: miscinit.c:242
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:437
pqsigfunc pqsignal(int signo, pqsigfunc func)
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3458
void InitProcessGlobals(void)
Definition: postmaster.c:2645
int postmaster_alive_fds[2]
Definition: postmaster.c:576
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46
void pgwin32_signal_initialize(void)
Definition: signal.c:79
#define SIGQUIT
Definition: win32_port.h:177

References BlockSig, elog(), ereport, errcode_for_socket_access(), errmsg_internal(), FATAL, InitializeLatchSupport(), InitializeLatchWaitSet(), InitProcessGlobals(), InitProcessLocalLatch(), IsUnderPostmaster, on_exit_reset(), pgwin32_signal_initialize(), postmaster_alive_fds, POSTMASTER_FD_WATCH, PostmasterDeathSignalInit(), pqinitmask(), pqsignal(), set_stack_base(), SignalHandlerForCrashExit(), and SIGQUIT.

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

◆ InitProcessLocalLatch()

void InitProcessLocalLatch ( void  )

Definition at line 242 of file miscinit.c.

243 {
246 }
struct Latch * MyLatch
Definition: globals.c:58
void InitLatch(Latch *latch)
Definition: latch.c:369
static Latch LocalLatchData
Definition: miscinit.c:68

References InitLatch(), LocalLatchData, and MyLatch.

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

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 182 of file miscinit.c.

183 {
185 
187 
188  /*
189  * Start our win32 signal implementation
190  */
191 #ifdef WIN32
193 #endif
194 
196 
197  /* Initialize process-local latch support */
201 
202  /*
203  * For consistency with InitPostmasterChild, initialize signal mask here.
204  * But we don't unblock SIGQUIT or provide a default handler for it.
205  */
206  pqinitmask();
207  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
208 
209  /* Compute paths, no postmaster to inherit from */
210  if (my_exec_path[0] == '\0')
211  {
212  if (find_my_exec(argv0, my_exec_path) < 0)
213  elog(FATAL, "%s: could not locate my own executable path",
214  argv0);
215  }
216 
217  if (pkglib_path[0] == '\0')
219 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:158
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
bool IsPostmasterEnvironment
Definition: globals.c:112
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
BackendType MyBackendType
Definition: miscinit.c:63
static char * argv0
Definition: pg_ctl.c:92
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879

References argv0, Assert(), B_STANDALONE_BACKEND, BlockSig, elog(), FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitializeLatchWaitSet(), InitProcessGlobals(), InitProcessLocalLatch(), IsPostmasterEnvironment, my_exec_path, MyBackendType, pgwin32_signal_initialize(), pkglib_path, and pqinitmask().

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 649 of file miscinit.c.

650 {
652 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:313

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option_ext().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 667 of file miscinit.c.

668 {
670 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:315

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

◆ load_libraries()

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

Definition at line 1795 of file miscinit.c.

1796 {
1797  char *rawstring;
1798  List *elemlist;
1799  ListCell *l;
1800 
1801  if (libraries == NULL || libraries[0] == '\0')
1802  return; /* nothing to do */
1803 
1804  /* Need a modifiable copy of string */
1805  rawstring = pstrdup(libraries);
1806 
1807  /* Parse string into list of filename paths */
1808  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1809  {
1810  /* syntax error in list */
1811  list_free_deep(elemlist);
1812  pfree(rawstring);
1813  ereport(LOG,
1814  (errcode(ERRCODE_SYNTAX_ERROR),
1815  errmsg("invalid list syntax in parameter \"%s\"",
1816  gucname)));
1817  return;
1818  }
1819 
1820  foreach(l, elemlist)
1821  {
1822  /* Note that filename was already canonicalized */
1823  char *filename = (char *) lfirst(l);
1824  char *expanded = NULL;
1825 
1826  /* If restricting, insert $libdir/plugins if not mentioned already */
1827  if (restricted && first_dir_separator(filename) == NULL)
1828  {
1829  expanded = psprintf("$libdir/plugins/%s", filename);
1830  filename = expanded;
1831  }
1832  load_file(filename, restricted);
1833  ereport(DEBUG1,
1834  (errmsg_internal("loaded library \"%s\"", filename)));
1835  if (expanded)
1836  pfree(expanded);
1837  }
1838 
1839  list_free_deep(elemlist);
1840  pfree(rawstring);
1841 }
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
#define DEBUG1
Definition: elog.h:30
void list_free_deep(List *list)
Definition: list.c:1559
#define lfirst(lc)
Definition: pg_list.h:172
char * first_dir_separator(const char *filename)
Definition: path.c:104
Definition: pg_list.h:54
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3581

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

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1884 of file miscinit.c.

1885 {
1886 #ifdef ENABLE_NLS
1887  if (my_exec_path[0] != '\0')
1888  {
1889  char locale_path[MAXPGPATH];
1890 
1891  get_locale_path(my_exec_path, locale_path);
1892  bindtextdomain(domain, locale_path);
1893  pg_bind_textdomain_codeset(domain);
1894  }
1895 #endif
1896 }
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:888

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1861 of file miscinit.c.

1862 {
1864  "session_preload_libraries",
1865  false);
1867  "local_preload_libraries",
1868  true);
1869 }
char * session_preload_libraries_string
Definition: miscinit.c:1777
char * local_preload_libraries_string
Definition: miscinit.c:1779
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1795

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by InitPostgres().

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1847 of file miscinit.c.

1848 {
1851  "shared_preload_libraries",
1852  false);
1855 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1783
char * shared_preload_libraries_string
Definition: miscinit.c:1778
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1782

References load_libraries(), process_shared_preload_libraries_done, process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ process_shmem_requests()

void process_shmem_requests ( void  )

Definition at line 1875 of file miscinit.c.

1876 {
1878  if (shmem_request_hook)
1881 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1786
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1785

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1642 of file miscinit.c.

1643 {
1644  int fd;
1645  int len;
1646  long file_pid;
1647  char buffer[BLCKSZ];
1648 
1649  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1650  if (fd < 0)
1651  {
1652  /*
1653  * There are many foreseeable false-positive error conditions. For
1654  * safety, fail only on enumerated clearly-something-is-wrong
1655  * conditions.
1656  */
1657  switch (errno)
1658  {
1659  case ENOENT:
1660  case ENOTDIR:
1661  /* disaster */
1662  ereport(LOG,
1664  errmsg("could not open file \"%s\": %m",
1666  return false;
1667  default:
1668  /* non-fatal, at least for now */
1669  ereport(LOG,
1671  errmsg("could not open file \"%s\": %m; continuing anyway",
1673  return true;
1674  }
1675  }
1677  len = read(fd, buffer, sizeof(buffer) - 1);
1679  if (len < 0)
1680  {
1681  ereport(LOG,
1683  errmsg("could not read from file \"%s\": %m",
1685  close(fd);
1686  return true; /* treat read failure as nonfatal */
1687  }
1688  buffer[len] = '\0';
1689  close(fd);
1690  file_pid = atol(buffer);
1691  if (file_pid == getpid())
1692  return true; /* all is well */
1693 
1694  /* Trouble: someone's overwritten the lock file */
1695  ereport(LOG,
1696  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1697  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1698  return false;
1699 }
@ WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ
Definition: wait_event.h:193

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

Referenced by ServerLoop().

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char *  conninfo)

Definition at line 1079 of file miscinit.c.

1080 {
1081  SerializedClientConnectionInfo serialized;
1082 
1083  memcpy(&serialized, conninfo, sizeof(serialized));
1084 
1085  /* Copy the fields back into place */
1088 
1089  if (serialized.authn_id_len >= 0)
1090  {
1091  char *authn_id;
1092 
1093  authn_id = conninfo + sizeof(serialized);
1095  authn_id);
1096  }
1097 }
UserAuth auth_method
Definition: libpq-be.h:120

References SerializedClientConnectionInfo::auth_method, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, SerializedClientConnectionInfo::authn_id_len, MemoryContextStrdup(), MyClientConnectionInfo, and TopMemoryContext.

Referenced by ParallelWorkerMain().

◆ SerializeClientConnectionInfo()

void SerializeClientConnectionInfo ( Size  maxsize,
char *  start_address 
)

Definition at line 1047 of file miscinit.c.

1048 {
1049  SerializedClientConnectionInfo serialized = {0};
1050 
1051  serialized.authn_id_len = -1;
1053 
1055  serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1056 
1057  /* Copy serialized representation to buffer */
1058  Assert(maxsize >= sizeof(serialized));
1059  memcpy(start_address, &serialized, sizeof(serialized));
1060 
1061  maxsize -= sizeof(serialized);
1062  start_address += sizeof(serialized);
1063 
1064  /* Copy authn_id into the space after the struct */
1065  if (serialized.authn_id_len >= 0)
1066  {
1067  Assert(maxsize >= (serialized.authn_id_len + 1));
1068  memcpy(start_address,
1070  /* include the NULL terminator to ease deserialization */
1071  serialized.authn_id_len + 1);
1072  }
1073 }

References Assert(), SerializedClientConnectionInfo::auth_method, ClientConnectionInfo::auth_method, ClientConnectionInfo::authn_id, SerializedClientConnectionInfo::authn_id_len, and MyClientConnectionInfo.

Referenced by InitializeParallelDSM().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 949 of file miscinit.c.

950 {
951  /*
952  * Get correct info if it's SET ROLE NONE
953  *
954  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
955  * SetSessionUserId call will fix everything. This is needed since we
956  * will get called during GUC initialization.
957  */
958  if (!OidIsValid(roleid))
959  {
961  return;
962 
963  roleid = SessionUserId;
965 
966  SetRoleIsActive = false;
967  }
968  else
969  SetRoleIsActive = true;
970 
971  SetOuterUserId(roleid);
972 
973  SetConfigOption("is_superuser",
974  is_superuser ? "on" : "off",
976 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:529
static bool SessionUserIsSuperuser
Definition: miscinit.c:497
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4558

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

Referenced by assign_role(), and ParallelWorkerMain().

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 323 of file miscinit.c.

324 {
325  /* This should happen only once per process */
328 }
char * DatabasePath
Definition: globals.c:97

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 429 of file miscinit.c.

430 {
431  char *new;
432 
433  Assert(dir);
434 
435  /* If presented path is relative, convert to absolute */
436  new = make_absolute_path(dir);
437 
438  free(DataDir);
439  DataDir = new;
440 }
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:729

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

Referenced by SelectConfigFiles().

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 529 of file miscinit.c.

530 {
532  Assert(OidIsValid(userid));
533  OuterUserId = userid;
534 
535  /* We force the effective user ID to match, too */
536  CurrentUserId = userid;
537 }

References Assert(), CurrentUserId, OidIsValid, OuterUserId, and SecurityRestrictionContext.

Referenced by SetCurrentRoleId().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 903 of file miscinit.c.

904 {
905  /* Must have authenticated already, else can't make permission check */
907 
908  if (userid != AuthenticatedUserId &&
910  ereport(ERROR,
911  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
912  errmsg("permission denied to set session authorization")));
913 
915 
916  SetConfigOption("is_superuser",
917  is_superuser ? "on" : "off",
919 }

References Assert(), AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), errmsg(), ERROR, is_superuser(), OidIsValid, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 552 of file miscinit.c.

553 {
555  Assert(OidIsValid(userid));
556  SessionUserId = userid;
558  SetRoleIsActive = false;
559 
560  /* We force the effective user IDs to match, too */
561  OuterUserId = userid;
562  CurrentUserId = userid;
563 }

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

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

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 687 of file miscinit.c.

688 {
689  /* We throw the same error SET ROLE would. */
691  ereport(ERROR,
692  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
693  errmsg("cannot set parameter \"%s\" within security-restricted operation",
694  "role")));
695  CurrentUserId = userid;
696  if (sec_def_context)
698  else
700 }
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:658

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

◆ SetUserIdAndSecContext()

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 249 of file miscinit.c.

250 {
252  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
253 
255 
256  if (FeBeWaitSet)
258  MyLatch);
259 
260  SetLatch(MyLatch);
261 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1008
void SetLatch(Latch *latch)
Definition: latch.c:607
#define WL_LATCH_SET
Definition: latch.h:125
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:164
Latch procLatch
Definition: proc.h:170

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

Referenced by AuxiliaryProcKill(), and ProcKill().

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 222 of file miscinit.c.

223 {
225  Assert(MyProc != NULL);
226 
228 
229  if (FeBeWaitSet)
231  MyLatch);
232 
233  /*
234  * Set the shared latch as the local one might have been set. This
235  * shouldn't normally be necessary as code is supposed to check the
236  * condition before waiting for the latch, but a bit care can't hurt.
237  */
238  SetLatch(MyLatch);
239 }

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

◆ system_user()

Datum system_user ( PG_FUNCTION_ARGS  )

Definition at line 879 of file miscinit.c.

880 {
881  const char *sysuser = GetSystemUser();
882 
883  if (sysuser)
885  else
886  PG_RETURN_NULL();
887 }
#define CStringGetTextDatum(s)
Definition: builtins.h:94
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
const char * GetSystemUser(void)
Definition: miscinit.c:570

References CStringGetTextDatum, GetSystemUser(), PG_RETURN_DATUM, and PG_RETURN_NULL.

Referenced by check_ident_usermap(), check_usermap(), and InitializeSystemUser().

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1486 of file miscinit.c.

1487 {
1488  ListCell *l;
1489 
1490  foreach(l, lock_files)
1491  {
1492  char *socketLockFile = (char *) lfirst(l);
1493 
1494  /* No need to touch the data directory lock file, we trust */
1495  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1496  continue;
1497 
1498  /* we just ignore any error here */
1499  (void) utime(socketLockFile, NULL);
1500  }
1501 }

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 1119 of file miscinit.c.

1120 {
1121  ListCell *l;
1122 
1123  foreach(l, lock_files)
1124  {
1125  char *curfile = (char *) lfirst(l);
1126 
1127  unlink(curfile);
1128  /* Should we complain if the unlink fails? */
1129  }
1130  /* Since we're about to exit, no need to reclaim storage */
1131  lock_files = NIL;
1132 
1133  /*
1134  * Lock file removal should always be the last externally visible action
1135  * of a postmaster or standalone backend, while we won't come here at all
1136  * when exiting postmaster child processes. Therefore, this is a good
1137  * place to log completion of shutdown. We could alternatively teach
1138  * proc_exit() to do it, but that seems uglier. In a standalone backend,
1139  * use NOTICE elevel to be less chatty.
1140  */
1142  (errmsg("database system is shut down")));
1143 }
#define NOTICE
Definition: elog.h:35

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

Referenced by CreateLockFile().

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1714 of file miscinit.c.

1715 {
1716  char full_path[MAXPGPATH];
1717  FILE *file;
1718  int ret;
1719  long file_major;
1720  long my_major;
1721  char *endptr;
1722  char file_version_string[64];
1723  const char *my_version_string = PG_VERSION;
1724 
1725  my_major = strtol(my_version_string, &endptr, 10);
1726 
1727  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1728 
1729  file = AllocateFile(full_path, "r");
1730  if (!file)
1731  {
1732  if (errno == ENOENT)
1733  ereport(FATAL,
1734  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1735  errmsg("\"%s\" is not a valid data directory",
1736  path),
1737  errdetail("File \"%s\" is missing.", full_path)));
1738  else
1739  ereport(FATAL,
1741  errmsg("could not open file \"%s\": %m", full_path)));
1742  }
1743 
1744  file_version_string[0] = '\0';
1745  ret = fscanf(file, "%63s", file_version_string);
1746  file_major = strtol(file_version_string, &endptr, 10);
1747 
1748  if (ret != 1 || endptr == file_version_string)
1749  ereport(FATAL,
1750  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1751  errmsg("\"%s\" is not a valid data directory",
1752  path),
1753  errdetail("File \"%s\" does not contain valid data.",
1754  full_path),
1755  errhint("You might need to initdb.")));
1756 
1757  FreeFile(file);
1758 
1759  if (my_major != file_major)
1760  ereport(FATAL,
1761  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1762  errmsg("database files are incompatible with server"),
1763  errdetail("The data directory was initialized by PostgreSQL version %s, "
1764  "which is not compatible with this version %s.",
1765  file_version_string, my_version_string)));
1766 }
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2480
int FreeFile(FILE *file)
Definition: fd.c:2678

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

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ AuthenticatedUserId

◆ AuthenticatedUserIsSuperuser

bool AuthenticatedUserIsSuperuser = false
static

◆ CurrentUserId

◆ IgnoreSystemIndexes

◆ local_preload_libraries_string

char* local_preload_libraries_string = NULL

Definition at line 1779 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

Definition at line 68 of file miscinit.c.

Referenced by InitProcessLocalLatch(), SwitchBackToLocalLatch(), and SwitchToSharedLatch().

◆ lock_files

List* lock_files = NIL
static

Definition at line 66 of file miscinit.c.

Referenced by CreateLockFile(), TouchSocketLockFiles(), and UnlinkLockFiles().

◆ Mode

Definition at line 61 of file miscinit.c.

◆ MyBackendType

◆ MyClientConnectionInfo

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 491 of file miscinit.c.

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

◆ process_shared_preload_libraries_done

bool process_shared_preload_libraries_done = false

◆ process_shared_preload_libraries_in_progress

bool process_shared_preload_libraries_in_progress = false

◆ process_shmem_requests_in_progress

bool process_shmem_requests_in_progress = false

◆ SecurityRestrictionContext

◆ session_preload_libraries_string

char* session_preload_libraries_string = NULL

Definition at line 1777 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 490 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 497 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 502 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1778 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

shmem_request_hook_type shmem_request_hook = NULL

Definition at line 1785 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ SystemUser

const char* SystemUser = NULL
static

Definition at line 493 of file miscinit.c.

Referenced by GetSystemUser(), and InitializeSystemUser().