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, bool bypass_login_check)
 
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 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 1504 of file miscinit.c.

1505 {
1506  int fd;
1507  int len;
1508  int lineno;
1509  char *srcptr;
1510  char *destptr;
1511  char srcbuffer[BLCKSZ];
1512  char destbuffer[BLCKSZ];
1513 
1514  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1515  if (fd < 0)
1516  {
1517  ereport(LOG,
1519  errmsg("could not open file \"%s\": %m",
1521  return;
1522  }
1523  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
1524  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1526  if (len < 0)
1527  {
1528  ereport(LOG,
1530  errmsg("could not read from file \"%s\": %m",
1532  close(fd);
1533  return;
1534  }
1535  srcbuffer[len] = '\0';
1536 
1537  /*
1538  * Advance over lines we are not supposed to rewrite, then copy them to
1539  * destbuffer.
1540  */
1541  srcptr = srcbuffer;
1542  for (lineno = 1; lineno < target_line; lineno++)
1543  {
1544  char *eol = strchr(srcptr, '\n');
1545 
1546  if (eol == NULL)
1547  break; /* not enough lines in file yet */
1548  srcptr = eol + 1;
1549  }
1550  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1551  destptr = destbuffer + (srcptr - srcbuffer);
1552 
1553  /*
1554  * Fill in any missing lines before the target line, in case lines are
1555  * added to the file out of order.
1556  */
1557  for (; lineno < target_line; lineno++)
1558  {
1559  if (destptr < destbuffer + sizeof(destbuffer))
1560  *destptr++ = '\n';
1561  }
1562 
1563  /*
1564  * Write or rewrite the target line.
1565  */
1566  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1567  destptr += strlen(destptr);
1568 
1569  /*
1570  * If there are more lines in the old file, append them to destbuffer.
1571  */
1572  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1573  {
1574  srcptr++;
1575  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1576  srcptr);
1577  }
1578 
1579  /*
1580  * And rewrite the data. Since we write in a single kernel call, this
1581  * update should appear atomic to onlookers.
1582  */
1583  len = strlen(destbuffer);
1584  errno = 0;
1585  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
1586  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1587  {
1589  /* if write didn't set errno, assume problem is no disk space */
1590  if (errno == 0)
1591  errno = ENOSPC;
1592  ereport(LOG,
1594  errmsg("could not write to file \"%s\": %m",
1596  close(fd);
1597  return;
1598  }
1600  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
1601  if (pg_fsync(fd) != 0)
1602  {
1603  ereport(LOG,
1605  errmsg("could not write to file \"%s\": %m",
1607  }
1609  if (close(fd) != 0)
1610  {
1611  ereport(LOG,
1613  errmsg("could not write to file \"%s\": %m",
1615  }
1616 }
#define PG_BINARY
Definition: c.h:1283
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:386
#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
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104

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, and generate_unaccent_rules::str.

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

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 448 of file miscinit.c.

449 {
450  Assert(DataDir);
451 
452  if (chdir(DataDir) < 0)
453  ereport(FATAL,
455  errmsg("could not change directory to \"%s\": %m",
456  DataDir)));
457 }
#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 335 of file miscinit.c.

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

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

1449 {
1450  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1451 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1143

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

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

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(), and write.

Referenced by CreateDataDirLockFile(), and CreateSocketLockFile().

◆ CreateSocketLockFile()

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

Definition at line 1457 of file miscinit.c.

1459 {
1460  char lockfile[MAXPGPATH];
1461 
1462  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1463  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1464 }

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1020 of file miscinit.c.

1021 {
1022  Size size = 0;
1023 
1024  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1025 
1027  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1028 
1029  return size;
1030 }
size_t Size
Definition: c.h:594
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1003
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 577 of file miscinit.c.

578 {
580  return AuthenticatedUserId;
581 }
#define OidIsValid(objectId)
Definition: c.h:764
static Oid AuthenticatedUserId
Definition: miscinit.c:488

References Assert(), AuthenticatedUserId, and OidIsValid.

Referenced by check_session_authorization(), and InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 263 of file miscinit.c.

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

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

918 {
919  if (SetRoleIsActive)
920  return OuterUserId;
921  else
922  return InvalidOid;
923 }
static Oid OuterUserId
Definition: miscinit.c:490
static bool SetRoleIsActive
Definition: miscinit.c:500
#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 519 of file miscinit.c.

520 {
522  return OuterUserId;
523 }

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 542 of file miscinit.c.

543 {
545  return SessionUserId;
546 }
static Oid SessionUserId
Definition: miscinit.c:489

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

569 {
570  return SystemUser;
571 }
static const char * SystemUser
Definition: miscinit.c:492

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 508 of file miscinit.c.

509 {
511  return CurrentUserId;
512 }
static Oid CurrentUserId
Definition: miscinit.c:491

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_search_path(), 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(), get_tables_to_cluster_partitioned(), 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(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), 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_relation_owner(), validate_option_array_item(), ValidateJoinEstimator(), ValidateOperatorReference(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 678 of file miscinit.c.

679 {
680  *userid = CurrentUserId;
681  *sec_def_context = InLocalUserIdChange();
682 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:647

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 973 of file miscinit.c.

974 {
975  HeapTuple tuple;
976  char *result;
977 
978  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
979  if (!HeapTupleIsValid(tuple))
980  {
981  if (!noerr)
982  ereport(ERROR,
983  (errcode(ERRCODE_UNDEFINED_OBJECT),
984  errmsg("invalid role OID: %u", roleid)));
985  result = NULL;
986  }
987  else
988  {
989  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
990  ReleaseSysCache(tuple);
991  }
992  return result;
993 }
#define NameStr(name)
Definition: c.h:735
#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:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ 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 705 of file miscinit.c.

706 {
707  bool result = false;
708  HeapTuple utup;
709 
710  /* Superusers bypass all permission checking. */
711  if (superuser_arg(roleid))
712  return true;
713 
714  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
715  if (HeapTupleIsValid(utup))
716  {
717  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
718  ReleaseSysCache(utup);
719  }
720  return result;
721 }
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,
bool  bypass_login_check 
)

Definition at line 727 of file miscinit.c.

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

References AcceptInvalidationMessages(), Assert(), AuthenticatedUserId, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, HeapTupleIsValid, is_superuser(), 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 831 of file miscinit.c.

832 {
833  /*
834  * This function should only be called in single-user mode, in autovacuum
835  * workers, and in background workers.
836  */
838 
839  /* call only once */
841 
842  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
843  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
844 
845  /*
846  * XXX This should set SetConfigOption("session_authorization"), too.
847  * Since we don't, C code will get NULL, and current_setting() will get an
848  * empty string.
849  */
850  SetConfigOption("is_superuser", "on",
852 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3388
bool IsBackgroundWorker
Definition: globals.c:117

References Assert(), AuthenticatedUserId, IsAutoVacuumWorkerProcess(), IsBackgroundWorker, IsUnderPostmaster, OidIsValid, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SetConfigOption(), and SetSessionUserId().

Referenced by InitPostgres().

◆ InitializeSystemUser()

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

Definition at line 860 of file miscinit.c.

861 {
862  char *system_user;
863 
864  /* call only once */
865  Assert(SystemUser == NULL);
866 
867  /*
868  * InitializeSystemUser should be called only when authn_id is not NULL,
869  * meaning that auth_method is valid.
870  */
871  Assert(authn_id != NULL);
872 
873  system_user = psprintf("%s:%s", auth_method, authn_id);
874 
875  /* Store SystemUser in long-lived storage */
878 }
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:884
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 better to keep the depth
111  * logic the same with and without that build option.
112  */
113  (void) set_stack_base();
114 
116 
117  /*
118  * make sure stderr is in binary mode before anything can possibly be
119  * written to it, in case it's actually the syslogger pipe, so the pipe
120  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
121  * redirection (e.g. via pg_ctl -l) anyway.
122  */
123 #ifdef WIN32
124  _setmode(fileno(stderr), _O_BINARY);
125 #endif
126 
127  /* We don't want the postmaster's proc_exit() handlers */
128  on_exit_reset();
129 
130  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
131 #ifdef EXEC_BACKEND
132  pqinitmask();
133 #endif
134 
135  /* Initialize process-local latch support */
139 
140  /*
141  * If possible, make this process a group leader, so that the postmaster
142  * can signal any child processes too. Not all processes will have
143  * children, but for consistency we make all postmaster child processes do
144  * this.
145  */
146 #ifdef HAVE_SETSID
147  if (setsid() < 0)
148  elog(FATAL, "setsid() failed: %m");
149 #endif
150 
151  /*
152  * Every postmaster child process is expected to respond promptly to
153  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
154  * BlockSig and install a suitable signal handler. (Client-facing
155  * processes may choose to replace this default choice of handler with
156  * quickdie().) All other blockable signals remain blocked for now.
157  */
159 
160  sigdelset(&BlockSig, SIGQUIT);
161  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
162 
163  /* Request a signal if the postmaster dies, if possible. */
165 
166  /* Don't give the pipe to subprograms that we execute. */
167 #ifndef WIN32
168  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
169  ereport(FATAL,
171  errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
172 #endif
173 }
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:416
void InitializeLatchWaitSet(void)
Definition: latch.c:347
void InitializeLatchSupport(void)
Definition: latch.c:233
void InitProcessLocalLatch(void)
Definition: miscinit.c:241
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:437
pqsigfunc pqsignal(int signo, pqsigfunc func)
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3470
void InitProcessGlobals(void)
Definition: postmaster.c:2571
int postmaster_alive_fds[2]
Definition: postmaster.c:581
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46
void pgwin32_signal_initialize(void)
Definition: signal.c:79
#define SIGQUIT
Definition: win32_port.h:169

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

242 {
245 }
struct Latch * MyLatch
Definition: globals.c:58
void InitLatch(Latch *latch)
Definition: latch.c:395
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 181 of file miscinit.c.

182 {
184 
186 
187  /*
188  * Start our win32 signal implementation
189  */
190 #ifdef WIN32
192 #endif
193 
195 
196  /* Initialize process-local latch support */
200 
201  /*
202  * For consistency with InitPostmasterChild, initialize signal mask here.
203  * But we don't unblock SIGQUIT or provide a default handler for it.
204  */
205  pqinitmask();
206  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
207 
208  /* Compute paths, no postmaster to inherit from */
209  if (my_exec_path[0] == '\0')
210  {
211  if (find_my_exec(argv0, my_exec_path) < 0)
212  elog(FATAL, "%s: could not locate my own executable path",
213  argv0);
214  }
215 
216  if (pkglib_path[0] == '\0')
218 }
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:114
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 647 of file miscinit.c.

648 {
650 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:315

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option_ext().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 665 of file miscinit.c.

666 {
668 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:317

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

1785 {
1786  char *rawstring;
1787  List *elemlist;
1788  ListCell *l;
1789 
1790  if (libraries == NULL || libraries[0] == '\0')
1791  return; /* nothing to do */
1792 
1793  /* Need a modifiable copy of string */
1794  rawstring = pstrdup(libraries);
1795 
1796  /* Parse string into list of filename paths */
1797  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1798  {
1799  /* syntax error in list */
1800  list_free_deep(elemlist);
1801  pfree(rawstring);
1802  ereport(LOG,
1803  (errcode(ERRCODE_SYNTAX_ERROR),
1804  errmsg("invalid list syntax in parameter \"%s\"",
1805  gucname)));
1806  return;
1807  }
1808 
1809  foreach(l, elemlist)
1810  {
1811  /* Note that filename was already canonicalized */
1812  char *filename = (char *) lfirst(l);
1813  char *expanded = NULL;
1814 
1815  /* If restricting, insert $libdir/plugins if not mentioned already */
1816  if (restricted && first_dir_separator(filename) == NULL)
1817  {
1818  expanded = psprintf("$libdir/plugins/%s", filename);
1819  filename = expanded;
1820  }
1821  load_file(filename, restricted);
1822  ereport(DEBUG1,
1823  (errmsg_internal("loaded library \"%s\"", filename)));
1824  if (expanded)
1825  pfree(expanded);
1826  }
1827 
1828  list_free_deep(elemlist);
1829  pfree(rawstring);
1830 }
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:3583

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

1874 {
1875 #ifdef ENABLE_NLS
1876  if (my_exec_path[0] != '\0')
1877  {
1878  char locale_path[MAXPGPATH];
1879 
1880  get_locale_path(my_exec_path, locale_path);
1881  bindtextdomain(domain, locale_path);
1882  pg_bind_textdomain_codeset(domain);
1883  }
1884 #endif
1885 }
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 1850 of file miscinit.c.

1851 {
1853  "session_preload_libraries",
1854  false);
1856  "local_preload_libraries",
1857  true);
1858 }
char * session_preload_libraries_string
Definition: miscinit.c:1766
char * local_preload_libraries_string
Definition: miscinit.c:1768
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1784

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

1837 {
1840  "shared_preload_libraries",
1841  false);
1844 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1772
char * shared_preload_libraries_string
Definition: miscinit.c:1767
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1771

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

1865 {
1867  if (shmem_request_hook)
1870 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1775
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1774

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1631 of file miscinit.c.

1632 {
1633  int fd;
1634  int len;
1635  long file_pid;
1636  char buffer[BLCKSZ];
1637 
1638  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1639  if (fd < 0)
1640  {
1641  /*
1642  * There are many foreseeable false-positive error conditions. For
1643  * safety, fail only on enumerated clearly-something-is-wrong
1644  * conditions.
1645  */
1646  switch (errno)
1647  {
1648  case ENOENT:
1649  case ENOTDIR:
1650  /* disaster */
1651  ereport(LOG,
1653  errmsg("could not open file \"%s\": %m",
1655  return false;
1656  default:
1657  /* non-fatal, at least for now */
1658  ereport(LOG,
1660  errmsg("could not open file \"%s\": %m; continuing anyway",
1662  return true;
1663  }
1664  }
1665  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ);
1666  len = read(fd, buffer, sizeof(buffer) - 1);
1668  if (len < 0)
1669  {
1670  ereport(LOG,
1672  errmsg("could not read from file \"%s\": %m",
1674  close(fd);
1675  return true; /* treat read failure as nonfatal */
1676  }
1677  buffer[len] = '\0';
1678  close(fd);
1679  file_pid = atol(buffer);
1680  if (file_pid == getpid())
1681  return true; /* all is well */
1682 
1683  /* Trouble: someone's overwritten the lock file */
1684  ereport(LOG,
1685  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1686  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1687  return false;
1688 }

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

Referenced by ServerLoop().

◆ RestoreClientConnectionInfo()

void RestoreClientConnectionInfo ( char *  conninfo)

Definition at line 1068 of file miscinit.c.

1069 {
1070  SerializedClientConnectionInfo serialized;
1071 
1072  memcpy(&serialized, conninfo, sizeof(serialized));
1073 
1074  /* Copy the fields back into place */
1077 
1078  if (serialized.authn_id_len >= 0)
1079  {
1080  char *authn_id;
1081 
1082  authn_id = conninfo + sizeof(serialized);
1084  authn_id);
1085  }
1086 }
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 1036 of file miscinit.c.

1037 {
1038  SerializedClientConnectionInfo serialized = {0};
1039 
1040  serialized.authn_id_len = -1;
1042 
1044  serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1045 
1046  /* Copy serialized representation to buffer */
1047  Assert(maxsize >= sizeof(serialized));
1048  memcpy(start_address, &serialized, sizeof(serialized));
1049 
1050  maxsize -= sizeof(serialized);
1051  start_address += sizeof(serialized);
1052 
1053  /* Copy authn_id into the space after the struct */
1054  if (serialized.authn_id_len >= 0)
1055  {
1056  Assert(maxsize >= (serialized.authn_id_len + 1));
1057  memcpy(start_address,
1059  /* include the NULL terminator to ease deserialization */
1060  serialized.authn_id_len + 1);
1061  }
1062 }

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

939 {
940  /*
941  * Get correct info if it's SET ROLE NONE
942  *
943  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
944  * SetSessionUserId call will fix everything. This is needed since we
945  * will get called during GUC initialization.
946  */
947  if (!OidIsValid(roleid))
948  {
950  return;
951 
952  roleid = SessionUserId;
954 
955  SetRoleIsActive = false;
956  }
957  else
958  SetRoleIsActive = true;
959 
960  SetOuterUserId(roleid);
961 
962  SetConfigOption("is_superuser",
963  is_superuser ? "on" : "off",
965 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:527
static bool SessionUserIsSuperuser
Definition: miscinit.c:495

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

323 {
324  /* This should happen only once per process */
327 }
char * DatabasePath
Definition: globals.c:99

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 428 of file miscinit.c.

429 {
430  char *new;
431 
432  Assert(dir);
433 
434  /* If presented path is relative, convert to absolute */
435  new = make_absolute_path(dir);
436 
437  free(DataDir);
438  DataDir = new;
439 }
#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 527 of file miscinit.c.

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

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

Referenced by SetCurrentRoleId().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 901 of file miscinit.c.

902 {
904 
905  SetConfigOption("is_superuser",
906  is_superuser ? "on" : "off",
908 }

References is_superuser(), 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 550 of file miscinit.c.

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

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

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

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

◆ SetUserIdAndSecContext()

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 248 of file miscinit.c.

249 {
251  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
252 
254 
255  if (FeBeWaitSet)
257  MyLatch);
258 
259  SetLatch(MyLatch);
260 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1050
void SetLatch(Latch *latch)
Definition: latch.c:633
#define WL_LATCH_SET
Definition: latch.h:127
#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 221 of file miscinit.c.

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

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

885 {
886  const char *sysuser = GetSystemUser();
887 
888  if (sysuser)
890  else
891  PG_RETURN_NULL();
892 }
#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:568

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

1476 {
1477  ListCell *l;
1478 
1479  foreach(l, lock_files)
1480  {
1481  char *socketLockFile = (char *) lfirst(l);
1482 
1483  /* No need to touch the data directory lock file, we trust */
1484  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1485  continue;
1486 
1487  /* we just ignore any error here */
1488  (void) utime(socketLockFile, NULL);
1489  }
1490 }

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 1108 of file miscinit.c.

1109 {
1110  ListCell *l;
1111 
1112  foreach(l, lock_files)
1113  {
1114  char *curfile = (char *) lfirst(l);
1115 
1116  unlink(curfile);
1117  /* Should we complain if the unlink fails? */
1118  }
1119  /* Since we're about to exit, no need to reclaim storage */
1120  lock_files = NIL;
1121 
1122  /*
1123  * Lock file removal should always be the last externally visible action
1124  * of a postmaster or standalone backend, while we won't come here at all
1125  * when exiting postmaster child processes. Therefore, this is a good
1126  * place to log completion of shutdown. We could alternatively teach
1127  * proc_exit() to do it, but that seems uglier. In a standalone backend,
1128  * use NOTICE elevel to be less chatty.
1129  */
1131  (errmsg("database system is shut down")));
1132 }
#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 1703 of file miscinit.c.

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

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

Referenced by checkDataDir(), and InitPostgres().

Variable Documentation

◆ AuthenticatedUserId

Oid AuthenticatedUserId = InvalidOid
static

◆ CurrentUserId

◆ IgnoreSystemIndexes

◆ local_preload_libraries_string

char* local_preload_libraries_string = NULL

Definition at line 1768 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 490 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 1766 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 489 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 495 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 500 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1767 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

shmem_request_hook_type shmem_request_hook = NULL

Definition at line 1774 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ SystemUser

const char* SystemUser = NULL
static

Definition at line 492 of file miscinit.c.

Referenced by GetSystemUser(), and InitializeSystemUser().