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

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

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(), pmdie(), PostmasterMain(), reaper(), and sigusr1_handler().

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 436 of file miscinit.c.

437 {
438  Assert(DataDir);
439 
440  if (chdir(DataDir) < 0)
441  ereport(FATAL,
443  errmsg("could not change directory to \"%s\": %m",
444  DataDir)));
445 }
#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 323 of file miscinit.c.

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

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

1443 {
1444  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1445 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1137

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

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

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

1453 {
1454  char lockfile[MAXPGPATH];
1455 
1456  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1457  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1458 }

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1014 of file miscinit.c.

1015 {
1016  Size size = 0;
1017 
1018  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1019 
1021  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1022 
1023  return size;
1024 }
size_t Size
Definition: c.h:541
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:997
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
const char * authn_id
Definition: libpq-be.h:113

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

Referenced by InitializeParallelDSM().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 566 of file miscinit.c.

567 {
569  return AuthenticatedUserId;
570 }
#define OidIsValid(objectId)
Definition: c.h:711
static Oid AuthenticatedUserId
Definition: miscinit.c:476

References Assert(), AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

◆ GetBackendTypeDesc()

const char* GetBackendTypeDesc ( BackendType  backendType)

Definition at line 251 of file miscinit.c.

252 {
253  const char *backendDesc = "unknown process type";
254 
255  switch (backendType)
256  {
257  case B_INVALID:
258  backendDesc = "not initialized";
259  break;
260  case B_ARCHIVER:
261  backendDesc = "archiver";
262  break;
263  case B_AUTOVAC_LAUNCHER:
264  backendDesc = "autovacuum launcher";
265  break;
266  case B_AUTOVAC_WORKER:
267  backendDesc = "autovacuum worker";
268  break;
269  case B_BACKEND:
270  backendDesc = "client backend";
271  break;
272  case B_BG_WORKER:
273  backendDesc = "background worker";
274  break;
275  case B_BG_WRITER:
276  backendDesc = "background writer";
277  break;
278  case B_CHECKPOINTER:
279  backendDesc = "checkpointer";
280  break;
281  case B_LOGGER:
282  backendDesc = "logger";
283  break;
285  backendDesc = "standalone backend";
286  break;
287  case B_STARTUP:
288  backendDesc = "startup";
289  break;
290  case B_WAL_RECEIVER:
291  backendDesc = "walreceiver";
292  break;
293  case B_WAL_SENDER:
294  backendDesc = "walsender";
295  break;
296  case B_WAL_WRITER:
297  backendDesc = "walwriter";
298  break;
299  }
300 
301  return backendDesc;
302 }
@ B_WAL_WRITER
Definition: miscadmin.h:331
@ B_WAL_RECEIVER
Definition: miscadmin.h:329
@ B_CHECKPOINTER
Definition: miscadmin.h:325
@ B_WAL_SENDER
Definition: miscadmin.h:330
@ B_LOGGER
Definition: miscadmin.h:326
@ B_STARTUP
Definition: miscadmin.h:328
@ B_BG_WORKER
Definition: miscadmin.h:323
@ B_INVALID
Definition: miscadmin.h:318
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:327
@ B_BG_WRITER
Definition: miscadmin.h:324
@ B_BACKEND
Definition: miscadmin.h:322
@ B_ARCHIVER
Definition: miscadmin.h:319
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:320
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:321

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

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 911 of file miscinit.c.

912 {
913  if (SetRoleIsActive)
914  return OuterUserId;
915  else
916  return InvalidOid;
917 }
static Oid OuterUserId
Definition: miscinit.c:478
static bool SetRoleIsActive
Definition: miscinit.c:489
#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 508 of file miscinit.c.

509 {
511  return OuterUserId;
512 }

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 531 of file miscinit.c.

532 {
534  return SessionUserId;
535 }
static Oid SessionUserId
Definition: miscinit.c:477

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

558 {
559  return SystemUser;
560 }
static const char * SystemUser
Definition: miscinit.c:480

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 497 of file miscinit.c.

498 {
500  return CurrentUserId;
501 }
static Oid CurrentUserId
Definition: miscinit.c:479

References Assert(), CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), 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(), convert_and_check_filename(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTriggerFiringOn(), current_user(), currtid_internal(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), DelRoleMems(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), emit_audit_message(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecBuildGroupingEqual(), ExecBuildParamSetEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckOneRelPerms(), ExecGetResultRelCheckAsUser(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Parameter(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecReindex(), ExecSecLabelStmt(), execute_extension_script(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteGrantStmt(), ExecuteTruncateGuts(), extension_is_trusted(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_explain_guc_options(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), get_tables_to_cluster_partitioned(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionResetString(), GetConfigOptionValues(), gin_clean_pending_list(), 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(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), ShowAllGUCConfig(), 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 667 of file miscinit.c.

668 {
669  *userid = CurrentUserId;
670  *sec_def_context = InLocalUserIdChange();
671 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:636

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 967 of file miscinit.c.

968 {
969  HeapTuple tuple;
970  char *result;
971 
972  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
973  if (!HeapTupleIsValid(tuple))
974  {
975  if (!noerr)
976  ereport(ERROR,
977  (errcode(ERRCODE_UNDEFINED_OBJECT),
978  errmsg("invalid role OID: %u", roleid)));
979  result = NULL;
980  }
981  else
982  {
983  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
984  ReleaseSysCache(tuple);
985  }
986  return result;
987 }
#define NameStr(name)
Definition: c.h:682
#define ERROR
Definition: elog.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
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:600
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ 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_role_grantor(), current_user(), DelRoleMems(), execute_extension_script(), getObjectDescription(), getObjectIdentityParts(), insert_username(), LogicalRepSyncTableStart(), regroleout(), session_user(), and TargetPrivilegesCheck().

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 694 of file miscinit.c.

695 {
696  bool result = false;
697  HeapTuple utup;
698 
699  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
700  if (HeapTupleIsValid(utup))
701  {
702  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
703  ReleaseSysCache(utup);
704  }
705  return result;
706 }
bool rolreplication
Definition: pg_authid.h:40

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

Referenced by CheckSlotPermissions(), and InitPostgres().

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 712 of file miscinit.c.

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

816 {
817  /*
818  * This function should only be called in single-user mode, in autovacuum
819  * workers, and in background workers.
820  */
822 
823  /* call only once */
825 
826  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
828 
829  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
830 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3314
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 838 of file miscinit.c.

839 {
840  char *system_user;
841 
842  /* call only once */
843  Assert(SystemUser == NULL);
844 
845  /*
846  * InitializeSystemUser should be called only when authn_id is not NULL,
847  * meaning that auth_method is valid.
848  */
849  Assert(authn_id != NULL);
850 
851  system_user = psprintf("%s:%s", auth_method, authn_id);
852 
853  /* Store SystemUser in long-lived storage */
856 }
void pfree(void *pointer)
Definition: mcxt.c:1306
MemoryContext TopMemoryContext
Definition: mcxt.c:130
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1470
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:862
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 */
141 
142  /*
143  * If possible, make this process a group leader, so that the postmaster
144  * can signal any child processes too. Not all processes will have
145  * children, but for consistency we make all postmaster child processes do
146  * this.
147  */
148 #ifdef HAVE_SETSID
149  if (setsid() < 0)
150  elog(FATAL, "setsid() failed: %m");
151 #endif
152 
153  /*
154  * Every postmaster child process is expected to respond promptly to
155  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
156  * BlockSig and install a suitable signal handler. (Client-facing
157  * processes may choose to replace this default choice of handler with
158  * quickdie().) All other blockable signals remain blocked for now.
159  */
161 
162  sigdelset(&BlockSig, SIGQUIT);
164 
165  /* Request a signal if the postmaster dies, if possible. */
167 }
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
struct Latch * MyLatch
Definition: globals.c:58
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:77
void on_exit_reset(void)
Definition: ipc.c:412
void InitializeLatchWaitSet(void)
Definition: latch.c:305
void InitializeLatchSupport(void)
Definition: latch.c:207
void InitLatch(Latch *latch)
Definition: latch.c:353
static Latch LocalLatchData
Definition: miscinit.c:68
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:437
pqsigfunc pqsignal(int signo, pqsigfunc func)
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3390
void InitProcessGlobals(void)
Definition: postmaster.c:2672
#define PG_SETMASK(mask)
Definition: pqsignal.h:18
void pgwin32_signal_initialize(void)
Definition: signal.c:79
#define SIGQUIT
Definition: win32_port.h:177

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

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

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 175 of file miscinit.c.

176 {
178 
180 
181  /*
182  * Start our win32 signal implementation
183  */
184 #ifdef WIN32
186 #endif
187 
189 
190  /* Initialize process-local latch support */
195 
196  /*
197  * For consistency with InitPostmasterChild, initialize signal mask here.
198  * But we don't unblock SIGQUIT or provide a default handler for it.
199  */
200  pqinitmask();
202 
203  /* Compute paths, no postmaster to inherit from */
204  if (my_exec_path[0] == '\0')
205  {
206  if (find_my_exec(argv0, my_exec_path) < 0)
207  elog(FATAL, "%s: could not locate my own executable path",
208  argv0);
209  }
210 
211  if (pkglib_path[0] == '\0')
213 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:152
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(), InitLatch(), InitProcessGlobals(), IsPostmasterEnvironment, LocalLatchData, my_exec_path, MyBackendType, MyLatch, PG_SETMASK, pgwin32_signal_initialize(), pkglib_path, and pqinitmask().

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 636 of file miscinit.c.

637 {
639 }
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:304

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_option_ext().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 654 of file miscinit.c.

655 {
657 }
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:306

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

1779 {
1780  char *rawstring;
1781  List *elemlist;
1782  ListCell *l;
1783 
1784  if (libraries == NULL || libraries[0] == '\0')
1785  return; /* nothing to do */
1786 
1787  /* Need a modifiable copy of string */
1788  rawstring = pstrdup(libraries);
1789 
1790  /* Parse string into list of filename paths */
1791  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1792  {
1793  /* syntax error in list */
1794  list_free_deep(elemlist);
1795  pfree(rawstring);
1796  ereport(LOG,
1797  (errcode(ERRCODE_SYNTAX_ERROR),
1798  errmsg("invalid list syntax in parameter \"%s\"",
1799  gucname)));
1800  return;
1801  }
1802 
1803  foreach(l, elemlist)
1804  {
1805  /* Note that filename was already canonicalized */
1806  char *filename = (char *) lfirst(l);
1807  char *expanded = NULL;
1808 
1809  /* If restricting, insert $libdir/plugins if not mentioned already */
1810  if (restricted && first_dir_separator(filename) == NULL)
1811  {
1812  expanded = psprintf("$libdir/plugins/%s", filename);
1813  filename = expanded;
1814  }
1815  load_file(filename, restricted);
1816  ereport(DEBUG1,
1817  (errmsg_internal("loaded library \"%s\"", filename)));
1818  if (expanded)
1819  pfree(expanded);
1820  }
1821 
1822  list_free_deep(elemlist);
1823  pfree(rawstring);
1824 }
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
#define DEBUG1
Definition: elog.h:30
void list_free_deep(List *list)
Definition: list.c:1559
#define lfirst(lc)
Definition: pg_list.h:170
char * first_dir_separator(const char *filename)
Definition: path.c:104
Definition: pg_list.h:52
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3839

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

1868 {
1869 #ifdef ENABLE_NLS
1870  if (my_exec_path[0] != '\0')
1871  {
1872  char locale_path[MAXPGPATH];
1873 
1874  get_locale_path(my_exec_path, locale_path);
1875  bindtextdomain(domain, locale_path);
1876  pg_bind_textdomain_codeset(domain);
1877  }
1878 #endif
1879 }
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 1844 of file miscinit.c.

1845 {
1847  "session_preload_libraries",
1848  false);
1850  "local_preload_libraries",
1851  true);
1852 }
char * session_preload_libraries_string
Definition: miscinit.c:1760
char * local_preload_libraries_string
Definition: miscinit.c:1762
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1778

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

1831 {
1834  "shared_preload_libraries",
1835  false);
1838 }
bool process_shared_preload_libraries_done
Definition: miscinit.c:1766
char * shared_preload_libraries_string
Definition: miscinit.c:1761
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1765

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

1859 {
1861  if (shmem_request_hook)
1864 }
bool process_shmem_requests_in_progress
Definition: miscinit.c:1769
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1768

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1625 of file miscinit.c.

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

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

1063 {
1064  SerializedClientConnectionInfo serialized;
1065 
1066  memcpy(&serialized, conninfo, sizeof(serialized));
1067 
1068  /* Copy the fields back into place */
1071 
1072  if (serialized.authn_id_len >= 0)
1073  {
1074  char *authn_id;
1075 
1076  authn_id = conninfo + sizeof(serialized);
1078  authn_id);
1079  }
1080 }
UserAuth auth_method
Definition: libpq-be.h:119

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

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

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

933 {
934  /*
935  * Get correct info if it's SET ROLE NONE
936  *
937  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
938  * SetSessionUserId call will fix everything. This is needed since we
939  * will get called during GUC initialization.
940  */
941  if (!OidIsValid(roleid))
942  {
944  return;
945 
946  roleid = SessionUserId;
948 
949  SetRoleIsActive = false;
950  }
951  else
952  SetRoleIsActive = true;
953 
954  SetOuterUserId(roleid);
955 
956  SetConfigOption("is_superuser",
957  is_superuser ? "on" : "off",
959 }
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:516
static bool SessionUserIsSuperuser
Definition: miscinit.c:484
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4460

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

311 {
312  /* This should happen only once per process */
315 }
char * DatabasePath
Definition: globals.c:97

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 416 of file miscinit.c.

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

517 {
519  Assert(OidIsValid(userid));
520  OuterUserId = userid;
521 
522  /* We force the effective user ID to match, too */
523  CurrentUserId = userid;
524 }

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

Referenced by SetCurrentRoleId().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 886 of file miscinit.c.

887 {
888  /* Must have authenticated already, else can't make permission check */
890 
891  if (userid != AuthenticatedUserId &&
893  ereport(ERROR,
894  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
895  errmsg("permission denied to set session authorization")));
896 
898 
899  SetConfigOption("is_superuser",
900  is_superuser ? "on" : "off",
902 }

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

540 {
542  Assert(OidIsValid(userid));
543  SessionUserId = userid;
545  SetRoleIsActive = false;
546 
547  /* We force the effective user IDs to match, too */
548  OuterUserId = userid;
549  CurrentUserId = userid;
550 }

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

675 {
676  /* We throw the same error SET ROLE would. */
678  ereport(ERROR,
679  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
680  errmsg("cannot set parameter \"%s\" within security-restricted operation",
681  "role")));
682  CurrentUserId = userid;
683  if (sec_def_context)
685  else
687 }
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:645

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

◆ SetUserIdAndSecContext()

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 236 of file miscinit.c.

237 {
239  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
240 
242 
243  if (FeBeWaitSet)
245  MyLatch);
246 
247  SetLatch(MyLatch);
248 }
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:972
void SetLatch(Latch *latch)
Definition: latch.c:591
#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 216 of file miscinit.c.

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

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

863 {
864  const char *sysuser = GetSystemUser();
865 
866  if (sysuser)
868  else
869  PG_RETURN_NULL();
870 }
#define CStringGetTextDatum(s)
Definition: builtins.h:88
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
const char * GetSystemUser(void)
Definition: miscinit.c:557

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

Referenced by InitializeSystemUser().

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1469 of file miscinit.c.

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

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 1102 of file miscinit.c.

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

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

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

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

◆ 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 478 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 1760 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 477 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 484 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 489 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1761 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

shmem_request_hook_type shmem_request_hook = NULL

Definition at line 1768 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ SystemUser

const char* SystemUser = NULL
static

Definition at line 480 of file miscinit.c.

Referenced by GetSystemUser(), and InitializeSystemUser().