PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 "access/parallel.h"
#include "catalog/pg_authid.h"
#include "common/file_perm.h"
#include "libpq/libpq.h"
#include "libpq/pqsignal.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/interrupt.h"
#include "postmaster/postmaster.h"
#include "replication/slotsync.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, bool is_superuser)
 
Oid GetSessionUserId (void)
 
bool GetSessionUserIsSuperuser (void)
 
static void SetSessionUserId (Oid userid, bool is_superuser)
 
const char * GetSystemUser (void)
 
Oid GetAuthenticatedUserId (void)
 
void SetAuthenticatedUserId (Oid userid)
 
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 60 of file miscinit.c.

Typedef Documentation

◆ SerializedClientConnectionInfo

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1570 of file miscinit.c.

1571{
1572 int fd;
1573 int len;
1574 int lineno;
1575 char *srcptr;
1576 char *destptr;
1577 char srcbuffer[BLCKSZ];
1578 char destbuffer[BLCKSZ];
1579
1580 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1581 if (fd < 0)
1582 {
1583 ereport(LOG,
1585 errmsg("could not open file \"%s\": %m",
1587 return;
1588 }
1589 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
1590 len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1592 if (len < 0)
1593 {
1594 ereport(LOG,
1596 errmsg("could not read from file \"%s\": %m",
1598 close(fd);
1599 return;
1600 }
1601 srcbuffer[len] = '\0';
1602
1603 /*
1604 * Advance over lines we are not supposed to rewrite, then copy them to
1605 * destbuffer.
1606 */
1607 srcptr = srcbuffer;
1608 for (lineno = 1; lineno < target_line; lineno++)
1609 {
1610 char *eol = strchr(srcptr, '\n');
1611
1612 if (eol == NULL)
1613 break; /* not enough lines in file yet */
1614 srcptr = eol + 1;
1615 }
1616 memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1617 destptr = destbuffer + (srcptr - srcbuffer);
1618
1619 /*
1620 * Fill in any missing lines before the target line, in case lines are
1621 * added to the file out of order.
1622 */
1623 for (; lineno < target_line; lineno++)
1624 {
1625 if (destptr < destbuffer + sizeof(destbuffer))
1626 *destptr++ = '\n';
1627 }
1628
1629 /*
1630 * Write or rewrite the target line.
1631 */
1632 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1633 destptr += strlen(destptr);
1634
1635 /*
1636 * If there are more lines in the old file, append them to destbuffer.
1637 */
1638 if ((srcptr = strchr(srcptr, '\n')) != NULL)
1639 {
1640 srcptr++;
1641 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1642 srcptr);
1643 }
1644
1645 /*
1646 * And rewrite the data. Since we write in a single kernel call, this
1647 * update should appear atomic to onlookers.
1648 */
1649 len = strlen(destbuffer);
1650 errno = 0;
1651 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
1652 if (pg_pwrite(fd, destbuffer, len, 0) != len)
1653 {
1655 /* if write didn't set errno, assume problem is no disk space */
1656 if (errno == 0)
1657 errno = ENOSPC;
1658 ereport(LOG,
1660 errmsg("could not write to file \"%s\": %m",
1662 close(fd);
1663 return;
1664 }
1666 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
1667 if (pg_fsync(fd) != 0)
1668 {
1669 ereport(LOG,
1671 errmsg("could not write to file \"%s\": %m",
1673 }
1675 if (close(fd) != 0)
1676 {
1677 ereport(LOG,
1679 errmsg("could not write to file \"%s\": %m",
1681 }
1682}
#define PG_BINARY
Definition: c.h:1244
int errcode_for_file_access(void)
Definition: elog.c:877
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int pg_fsync(int fd)
Definition: fd.c:386
const char * str
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:60
const void size_t len
#define pg_pwrite
Definition: port.h:227
#define snprintf
Definition: port.h:239
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:85
static void pgstat_report_wait_end(void)
Definition: wait_event.h:101

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 str.

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

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 460 of file miscinit.c.

461{
463
464 if (chdir(DataDir) < 0)
467 errmsg("could not change directory to \"%s\": %m",
468 DataDir)));
469}
#define FATAL
Definition: elog.h:41
char * DataDir
Definition: globals.c:71
Assert(PointerIsAligned(start, uint64))

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

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

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 347 of file miscinit.c.

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

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

1515{
1516 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1517}
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1209

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

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

References close, DataDir, elog, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), filename, INT64_FORMAT, 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 1523 of file miscinit.c.

1525{
1526 char lockfile[MAXPGPATH];
1527
1528 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1529 CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1530}

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1086 of file miscinit.c.

1087{
1088 Size size = 0;
1089
1090 size = add_size(size, sizeof(SerializedClientConnectionInfo));
1091
1093 size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1094
1095 return size;
1096}
size_t Size
Definition: c.h:576
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1069
Size add_size(Size s1, Size s2)
Definition: shmem.c:491
const char * authn_id
Definition: libpq-be.h:99

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

Referenced by InitializeParallelDSM().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 596 of file miscinit.c.

597{
599 return AuthenticatedUserId;
600}
#define OidIsValid(objectId)
Definition: c.h:746
static Oid AuthenticatedUserId
Definition: miscinit.c:500

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 = gettext_noop("unknown process type");
266
267 switch (backendType)
268 {
269 case B_INVALID:
270 backendDesc = gettext_noop("not initialized");
271 break;
272 case B_ARCHIVER:
273 backendDesc = gettext_noop("archiver");
274 break;
276 backendDesc = gettext_noop("autovacuum launcher");
277 break;
278 case B_AUTOVAC_WORKER:
279 backendDesc = gettext_noop("autovacuum worker");
280 break;
281 case B_BACKEND:
282 backendDesc = gettext_noop("client backend");
283 break;
285 backendDesc = gettext_noop("dead-end client backend");
286 break;
287 case B_BG_WORKER:
288 backendDesc = gettext_noop("background worker");
289 break;
290 case B_BG_WRITER:
291 backendDesc = gettext_noop("background writer");
292 break;
293 case B_CHECKPOINTER:
294 backendDesc = gettext_noop("checkpointer");
295 break;
296 case B_IO_WORKER:
297 backendDesc = gettext_noop("io worker");
298 break;
299 case B_LOGGER:
300 backendDesc = gettext_noop("logger");
301 break;
303 backendDesc = gettext_noop("slotsync worker");
304 break;
306 backendDesc = gettext_noop("standalone backend");
307 break;
308 case B_STARTUP:
309 backendDesc = gettext_noop("startup");
310 break;
311 case B_WAL_RECEIVER:
312 backendDesc = gettext_noop("walreceiver");
313 break;
314 case B_WAL_SENDER:
315 backendDesc = gettext_noop("walsender");
316 break;
317 case B_WAL_SUMMARIZER:
318 backendDesc = gettext_noop("walsummarizer");
319 break;
320 case B_WAL_WRITER:
321 backendDesc = gettext_noop("walwriter");
322 break;
323 }
324
325 return backendDesc;
326}
#define gettext_noop(x)
Definition: c.h:1167
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:366
@ B_WAL_WRITER
Definition: miscadmin.h:367
@ B_WAL_RECEIVER
Definition: miscadmin.h:365
@ B_CHECKPOINTER
Definition: miscadmin.h:362
@ B_WAL_SENDER
Definition: miscadmin.h:346
@ B_IO_WORKER
Definition: miscadmin.h:363
@ B_LOGGER
Definition: miscadmin.h:373
@ B_STARTUP
Definition: miscadmin.h:364
@ B_BG_WORKER
Definition: miscadmin.h:345
@ B_INVALID
Definition: miscadmin.h:338
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:349
@ B_BG_WRITER
Definition: miscadmin.h:361
@ B_BACKEND
Definition: miscadmin.h:341
@ B_ARCHIVER
Definition: miscadmin.h:360
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:343
@ B_SLOTSYNC_WORKER
Definition: miscadmin.h:347
@ B_DEAD_END_BACKEND
Definition: miscadmin.h:342
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:344

References B_ARCHIVER, B_AUTOVAC_LAUNCHER, B_AUTOVAC_WORKER, B_BACKEND, B_BG_WORKER, B_BG_WRITER, B_CHECKPOINTER, B_DEAD_END_BACKEND, B_INVALID, B_IO_WORKER, B_LOGGER, B_SLOTSYNC_WORKER, B_STANDALONE_BACKEND, B_STARTUP, B_WAL_RECEIVER, B_WAL_SENDER, B_WAL_SUMMARIZER, B_WAL_WRITER, and gettext_noop.

Referenced by BackendInitialize(), BackendStartup(), CleanupBackend(), CountChildren(), get_backend_type_for_log(), init_ps_display(), pg_stat_get_activity(), pg_stat_io_build_tuples(), and signal_child().

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 986 of file miscinit.c.

987{
988 if (SetRoleIsActive)
989 return OuterUserId;
990 else
991 return InvalidOid;
992}
static Oid OuterUserId
Definition: miscinit.c:502
static bool SetRoleIsActive
Definition: miscinit.c:512
#define InvalidOid
Definition: postgres_ext.h:35

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by check_role(), InitializeParallelDSM(), and show_role().

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 531 of file miscinit.c.

532{
534 return OuterUserId;
535}

References Assert(), OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

◆ GetSessionUserIsSuperuser()

bool GetSessionUserIsSuperuser ( void  )

Definition at line 566 of file miscinit.c.

567{
570}
static bool SessionUserIsSuperuser
Definition: miscinit.c:507

References Assert(), OidIsValid, SessionUserId, and SessionUserIsSuperuser.

Referenced by check_session_authorization(), and InitializeParallelDSM().

◆ GetSystemUser()

const char * GetSystemUser ( void  )

Definition at line 586 of file miscinit.c.

587{
588 return SystemUser;
589}
static const char * SystemUser
Definition: miscinit.c:504

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 520 of file miscinit.c.

521{
523 return CurrentUserId;
524}
static Oid CurrentUserId
Definition: miscinit.c:503

References Assert(), CurrentUserId, and OidIsValid.

Referenced by AfterTriggerSaveEvent(), 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(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetTableSpace(), ATSimplePermissions(), bbsink_server_new(), be_lo_unlink(), binary_upgrade_create_empty_extension(), binary_upgrade_logical_slot_has_caught_up(), 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(), fmgr_security_definer(), 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_largeobject_privilege_id(), 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_get_sequence_data(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_wal_receiver(), pg_stat_get_wal_senders(), pg_stat_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignScan(), postgresExecForeignTruncate(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackMaintainsTable(), RangeVarCallbackOwnsRelation(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), REGRESS_exec_check_perms(), REGRESS_object_access_hook(), REGRESS_object_access_hook_str(), REGRESS_utility_command(), ReindexMultipleInternal(), ReindexMultipleTables(), RemoveObjects(), renameatt_check(), RenameDatabase(), RenameRole(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_config_option(), set_foreign_rel_properties(), shell_check_detail(), standard_ProcessUtility(), statext_is_compatible_clause(), stats_lock_check_privileges(), superuser(), TargetPrivilegesCheck(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_perms(), user_mapping_ddl_aclcheck(), vacuum_is_permitted_for_relation(), validate_option_array_item(), ValidateJoinEstimator(), ValidateOperatorReference(), and ValidateRestrictionEstimator().

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool *  sec_def_context 
)

Definition at line 712 of file miscinit.c.

713{
714 *userid = CurrentUserId;
715 *sec_def_context = InLocalUserIdChange();
716}
bool InLocalUserIdChange(void)
Definition: miscinit.c:681

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char * GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 1039 of file miscinit.c.

1040{
1041 HeapTuple tuple;
1042 char *result;
1043
1044 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
1045 if (!HeapTupleIsValid(tuple))
1046 {
1047 if (!noerr)
1048 ereport(ERROR,
1049 (errcode(ERRCODE_UNDEFINED_OBJECT),
1050 errmsg("invalid role OID: %u", roleid)));
1051 result = NULL;
1052 }
1053 else
1054 {
1055 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
1056 ReleaseSysCache(tuple);
1057 }
1058 return result;
1059}
#define NameStr(name)
Definition: c.h:717
#define ERROR
Definition: elog.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
Definition: htup_details.h:728
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:257
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221

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

740{
741 bool result = false;
742 HeapTuple utup;
743
744 /* Superusers bypass all permission checking. */
745 if (superuser_arg(roleid))
746 return true;
747
748 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
749 if (HeapTupleIsValid(utup))
750 {
751 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
752 ReleaseSysCache(utup);
753 }
754 return result;
755}
bool rolreplication
Definition: pg_authid.h:40
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

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

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

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid,
bool  bypass_login_check 
)

Definition at line 761 of file miscinit.c.

763{
764 HeapTuple roleTup;
765 Form_pg_authid rform;
766 char *rname;
767 bool is_superuser;
768
769 /*
770 * In a parallel worker, we don't have to do anything here.
771 * ParallelWorkerMain already set our output variables, and we aren't
772 * going to enforce either rolcanlogin or rolconnlimit. Furthermore, we
773 * don't really want to perform a catalog lookup for the role: we don't
774 * want to fail if it's been dropped.
775 */
777 {
778 Assert(bypass_login_check);
779 return;
780 }
781
782 /*
783 * Don't do scans if we're bootstrapping, none of the system catalogs
784 * exist yet, and they should be owned by postgres anyway.
785 */
787
788 /*
789 * Make sure syscache entries are flushed for recent catalog changes. This
790 * allows us to find roles that were created on-the-fly during
791 * authentication.
792 */
794
795 /*
796 * Look up the role, either by name if that's given or by OID if not.
797 */
798 if (rolename != NULL)
799 {
800 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
801 if (!HeapTupleIsValid(roleTup))
803 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
804 errmsg("role \"%s\" does not exist", rolename)));
805 }
806 else
807 {
808 roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
809 if (!HeapTupleIsValid(roleTup))
811 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
812 errmsg("role with OID %u does not exist", roleid)));
813 }
814
815 rform = (Form_pg_authid) GETSTRUCT(roleTup);
816 roleid = rform->oid;
817 rname = NameStr(rform->rolname);
818 is_superuser = rform->rolsuper;
819
821
822 /*
823 * Set SessionUserId and related variables, including "role", via the GUC
824 * mechanisms.
825 *
826 * Note: ideally we would use PGC_S_DYNAMIC_DEFAULT here, so that
827 * session_authorization could subsequently be changed from
828 * pg_db_role_setting entries. Instead, session_authorization in
829 * pg_db_role_setting has no effect. Changing that would require solving
830 * two problems:
831 *
832 * 1. If pg_db_role_setting has values for both session_authorization and
833 * role, we could not be sure which order those would be applied in, and
834 * it would matter.
835 *
836 * 2. Sites may have years-old session_authorization entries. There's not
837 * been any particular reason to remove them. Ending the dormancy of
838 * those entries could seriously change application behavior, so only a
839 * major release should do that.
840 */
841 SetConfigOption("session_authorization", rname,
843
844 /*
845 * These next checks are not enforced when in standalone mode, so that
846 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
847 * rolcanlogin = false;".
848 */
850 {
851 /*
852 * Is role allowed to login at all? (But background workers can
853 * override this by setting bypass_login_check.)
854 */
855 if (!bypass_login_check && !rform->rolcanlogin)
857 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
858 errmsg("role \"%s\" is not permitted to log in",
859 rname)));
860
861 /*
862 * Check connection limit for this role. We enforce the limit only
863 * for regular backends, since other process types have their own
864 * PGPROC pools.
865 *
866 * There is a race condition here --- we create our PGPROC before
867 * checking for other PGPROCs. If two backends did this at about the
868 * same time, they might both think they were over the limit, while
869 * ideally one should succeed and one fail. Getting that to work
870 * exactly seems more trouble than it is worth, however; instead we
871 * just document that the connection limit is approximate.
872 */
873 if (rform->rolconnlimit >= 0 &&
875 !is_superuser &&
876 CountUserBackends(roleid) > rform->rolconnlimit)
878 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
879 errmsg("too many connections for role \"%s\"",
880 rname)));
881 }
882
883 ReleaseSysCache(roleTup);
884}
bool InitializingParallelWorker
Definition: parallel.c:121
bool IsUnderPostmaster
Definition: globals.c:120
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4332
@ PGC_S_OVERRIDE
Definition: guc.h:123
@ PGC_BACKEND
Definition: guc.h:77
void AcceptInvalidationMessages(void)
Definition: inval.c:929
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:476
#define AmRegularBackendProcess()
Definition: miscadmin.h:380
void SetAuthenticatedUserId(Oid userid)
Definition: miscinit.c:603
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4899
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:327
int CountUserBackends(Oid roleid)
Definition: procarray.c:3700

References AcceptInvalidationMessages(), AmRegularBackendProcess, Assert(), CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT(), HeapTupleIsValid, InitializingParallelWorker, is_superuser(), IsBootstrapProcessingMode, IsUnderPostmaster, NameStr, ObjectIdGetDatum(), PGC_BACKEND, PGC_S_OVERRIDE, PointerGetDatum(), ReleaseSysCache(), SearchSysCache1(), SetAuthenticatedUserId(), and SetConfigOption().

Referenced by InitPostgres().

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 891 of file miscinit.c.

892{
893 /*
894 * This function should only be called in single-user mode, in autovacuum
895 * workers, in slot sync worker and in background workers.
896 */
899
900 /* call only once */
902
903 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
904
905 /*
906 * XXX Ideally we'd do this via SetConfigOption("session_authorization"),
907 * but we lack the role name needed to do that, and we can't fetch it
908 * because one reason for this special case is to be able to start up even
909 * if something's happened to the BOOTSTRAP_SUPERUSERID's pg_authid row.
910 * Since we don't set the GUC itself, C code will see the value as NULL,
911 * and current_setting() will report an empty string within this session.
912 */
913 SetSessionAuthorization(BOOTSTRAP_SUPERUSERID, true);
914
915 /* We could do SetConfigOption("role"), but let's be consistent */
917}
#define AmAutoVacuumWorkerProcess()
Definition: miscadmin.h:382
#define AmBackgroundWorkerProcess()
Definition: miscadmin.h:383
#define AmLogicalSlotSyncWorkerProcess()
Definition: miscadmin.h:385
void SetSessionAuthorization(Oid userid, bool is_superuser)
Definition: miscinit.c:971
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:1007

References AmAutoVacuumWorkerProcess, AmBackgroundWorkerProcess, AmLogicalSlotSyncWorkerProcess, Assert(), AuthenticatedUserId, InvalidOid, IsUnderPostmaster, OidIsValid, SetCurrentRoleId(), and SetSessionAuthorization().

Referenced by InitPostgres().

◆ InitializeSystemUser()

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

Definition at line 925 of file miscinit.c.

926{
927 char *system_user;
928
929 /* call only once */
930 Assert(SystemUser == NULL);
931
932 /*
933 * InitializeSystemUser should be called only when authn_id is not NULL,
934 * meaning that auth_method is valid.
935 */
936 Assert(authn_id != NULL);
937
938 system_user = psprintf("%s:%s", auth_method, authn_id);
939
940 /* Store SystemUser in long-lived storage */
943}
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1686
void pfree(void *pointer)
Definition: mcxt.c:1524
MemoryContext TopMemoryContext
Definition: mcxt.c:149
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:949
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
static char * authn_id
Definition: validator.c:41

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

Referenced by InitPostgres(), and ParallelWorkerMain().

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 96 of file miscinit.c.

97{
98 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
99
100 /*
101 * Start our win32 signal implementation. This has to be done after we
102 * read the backend variables, because we need to pick up the signal pipe
103 * from the parent process.
104 */
105#ifdef WIN32
107#endif
108
110
111 /*
112 * make sure stderr is in binary mode before anything can possibly be
113 * written to it, in case it's actually the syslogger pipe, so the pipe
114 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
115 * redirection (e.g. via pg_ctl -l) anyway.
116 */
117#ifdef WIN32
118 _setmode(fileno(stderr), _O_BINARY);
119#endif
120
121 /* We don't want the postmaster's proc_exit() handlers */
123
124 /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
125#ifdef EXEC_BACKEND
126 pqinitmask();
127#endif
128
129 /* Initialize process-local latch support */
133
134 /*
135 * If possible, make this process a group leader, so that the postmaster
136 * can signal any child processes too. Not all processes will have
137 * children, but for consistency we make all postmaster child processes do
138 * this.
139 */
140#ifdef HAVE_SETSID
141 if (setsid() < 0)
142 elog(FATAL, "setsid() failed: %m");
143#endif
144
145 /*
146 * Every postmaster child process is expected to respond promptly to
147 * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
148 * BlockSig and install a suitable signal handler. (Client-facing
149 * processes may choose to replace this default choice of handler with
150 * quickdie().) All other blockable signals remain blocked for now.
151 */
153
154 sigdelset(&BlockSig, SIGQUIT);
155 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
156
157 /* Request a signal if the postmaster dies, if possible. */
159
160 /* Don't give the pipe to subprograms that we execute. */
161#ifndef WIN32
162 if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
165 errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
166#endif
167}
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
int errcode_for_socket_access(void)
Definition: elog.c:954
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:73
void on_exit_reset(void)
Definition: ipc.c:416
void InitializeLatchWaitSet(void)
Definition: latch.c:35
void InitProcessLocalLatch(void)
Definition: miscinit.c:235
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:407
#define pqsignal
Definition: port.h:531
void InitProcessGlobals(void)
Definition: postmaster.c:1932
int postmaster_alive_fds[2]
Definition: postmaster.c:483
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:83
void pgwin32_signal_initialize(void)
Definition: signal.c:79
void InitializeWaitEventSupport(void)
Definition: waiteventset.c:240
#define SIGQUIT
Definition: win32_port.h:159

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

Referenced by postmaster_child_launch().

◆ InitProcessLocalLatch()

void InitProcessLocalLatch ( void  )

Definition at line 235 of file miscinit.c.

236{
239}
struct Latch * MyLatch
Definition: globals.c:63
void InitLatch(Latch *latch)
Definition: latch.c:63
static Latch LocalLatchData
Definition: miscinit.c:69

References InitLatch(), LocalLatchData, and MyLatch.

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

◆ 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 */
194
195 /*
196 * For consistency with InitPostmasterChild, initialize signal mask here.
197 * But we don't unblock SIGQUIT or provide a default handler for it.
198 */
199 pqinitmask();
200 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
201
202 /* Compute paths, no postmaster to inherit from */
203 if (my_exec_path[0] == '\0')
204 {
206 elog(FATAL, "%s: could not locate my own executable path",
207 argv0);
208 }
209
210 if (pkglib_path[0] == '\0')
212}
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
char pkglib_path[MAXPGPATH]
Definition: globals.c:82
bool IsPostmasterEnvironment
Definition: globals.c:119
char my_exec_path[MAXPGPATH]
Definition: globals.c:81
BackendType MyBackendType
Definition: miscinit.c:64
static char * argv0
Definition: pg_ctl.c:93
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:956

References argv0, Assert(), B_STANDALONE_BACKEND, BlockSig, elog, FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchWaitSet(), InitializeWaitEventSupport(), 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 681 of file miscinit.c.

682{
684}
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:317

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), and set_config_with_handle().

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 699 of file miscinit.c.

700{
702}
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:319

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

1851{
1852 char *rawstring;
1853 List *elemlist;
1854 ListCell *l;
1855
1856 if (libraries == NULL || libraries[0] == '\0')
1857 return; /* nothing to do */
1858
1859 /* Need a modifiable copy of string */
1860 rawstring = pstrdup(libraries);
1861
1862 /* Parse string into list of filename paths */
1863 if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1864 {
1865 /* syntax error in list */
1866 list_free_deep(elemlist);
1867 pfree(rawstring);
1868 ereport(LOG,
1869 (errcode(ERRCODE_SYNTAX_ERROR),
1870 errmsg("invalid list syntax in parameter \"%s\"",
1871 gucname)));
1872 return;
1873 }
1874
1875 foreach(l, elemlist)
1876 {
1877 /* Note that filename was already canonicalized */
1878 char *filename = (char *) lfirst(l);
1879 char *expanded = NULL;
1880
1881 /* If restricting, insert $libdir/plugins if not mentioned already */
1882 if (restricted && first_dir_separator(filename) == NULL)
1883 {
1884 expanded = psprintf("$libdir/plugins/%s", filename);
1885 filename = expanded;
1886 }
1887 load_file(filename, restricted);
1889 (errmsg_internal("loaded library \"%s\"", filename)));
1890 if (expanded)
1891 pfree(expanded);
1892 }
1893
1894 list_free_deep(elemlist);
1895 pfree(rawstring);
1896}
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:134
#define DEBUG1
Definition: elog.h:30
void list_free_deep(List *list)
Definition: list.c:1560
#define lfirst(lc)
Definition: pg_list.h:172
char * first_dir_separator(const char *filename)
Definition: path.c:110
Definition: pg_list.h:54
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3652

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

1940{
1941#ifdef ENABLE_NLS
1942 if (my_exec_path[0] != '\0')
1943 {
1944 char locale_path[MAXPGPATH];
1945
1946 get_locale_path(my_exec_path, locale_path);
1947 bindtextdomain(domain, locale_path);
1948 pg_bind_textdomain_codeset(domain);
1949 }
1950#endif
1951}
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:965

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

1917{
1919 "session_preload_libraries",
1920 false);
1922 "local_preload_libraries",
1923 true);
1924}
char * session_preload_libraries_string
Definition: miscinit.c:1832
char * local_preload_libraries_string
Definition: miscinit.c:1834
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1850

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

1903{
1906 "shared_preload_libraries",
1907 false);
1910}
bool process_shared_preload_libraries_done
Definition: miscinit.c:1838
char * shared_preload_libraries_string
Definition: miscinit.c:1833
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1837

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

1931{
1936}
bool process_shmem_requests_in_progress
Definition: miscinit.c:1841
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1840

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1697 of file miscinit.c.

1698{
1699 int fd;
1700 int len;
1701 long file_pid;
1702 char buffer[BLCKSZ];
1703
1704 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1705 if (fd < 0)
1706 {
1707 /*
1708 * There are many foreseeable false-positive error conditions. For
1709 * safety, fail only on enumerated clearly-something-is-wrong
1710 * conditions.
1711 */
1712 switch (errno)
1713 {
1714 case ENOENT:
1715 case ENOTDIR:
1716 /* disaster */
1717 ereport(LOG,
1719 errmsg("could not open file \"%s\": %m",
1721 return false;
1722 default:
1723 /* non-fatal, at least for now */
1724 ereport(LOG,
1726 errmsg("could not open file \"%s\": %m; continuing anyway",
1728 return true;
1729 }
1730 }
1731 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ);
1732 len = read(fd, buffer, sizeof(buffer) - 1);
1734 if (len < 0)
1735 {
1736 ereport(LOG,
1738 errmsg("could not read from file \"%s\": %m",
1740 close(fd);
1741 return true; /* treat read failure as nonfatal */
1742 }
1743 buffer[len] = '\0';
1744 close(fd);
1745 file_pid = atol(buffer);
1746 if (file_pid == getpid())
1747 return true; /* all is well */
1748
1749 /* Trouble: someone's overwritten the lock file */
1750 ereport(LOG,
1751 (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1752 DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1753 return false;
1754}

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

1135{
1137
1138 memcpy(&serialized, conninfo, sizeof(serialized));
1139
1140 /* Copy the fields back into place */
1143
1144 if (serialized.authn_id_len >= 0)
1145 {
1146 char *authn_id;
1147
1148 authn_id = conninfo + sizeof(serialized);
1150 authn_id);
1151 }
1152}
UserAuth auth_method
Definition: libpq-be.h:105

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

Referenced by ParallelWorkerMain().

◆ SerializeClientConnectionInfo()

void SerializeClientConnectionInfo ( Size  maxsize,
char *  start_address 
)

Definition at line 1102 of file miscinit.c.

1103{
1104 SerializedClientConnectionInfo serialized = {0};
1105
1106 serialized.authn_id_len = -1;
1108
1110 serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1111
1112 /* Copy serialized representation to buffer */
1113 Assert(maxsize >= sizeof(serialized));
1114 memcpy(start_address, &serialized, sizeof(serialized));
1115
1116 maxsize -= sizeof(serialized);
1117 start_address += sizeof(serialized);
1118
1119 /* Copy authn_id into the space after the struct */
1120 if (serialized.authn_id_len >= 0)
1121 {
1122 Assert(maxsize >= (serialized.authn_id_len + 1));
1123 memcpy(start_address,
1125 /* include the NULL terminator to ease deserialization */
1126 serialized.authn_id_len + 1);
1127 }
1128}

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

Referenced by InitializeParallelDSM().

◆ SetAuthenticatedUserId()

void SetAuthenticatedUserId ( Oid  userid)

Definition at line 603 of file miscinit.c.

604{
605 Assert(OidIsValid(userid));
606
607 /* call only once */
609
610 AuthenticatedUserId = userid;
611
612 /* Also mark our PGPROC entry with the authenticated user id */
613 /* (We assume this is an atomic store so no lock is needed) */
614 MyProc->roleId = userid;
615}
PGPROC * MyProc
Definition: proc.c:66
Oid roleId
Definition: proc.h:209

References Assert(), AuthenticatedUserId, MyProc, OidIsValid, and PGPROC::roleId.

Referenced by InitializeSessionUserId(), and ParallelWorkerMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 1007 of file miscinit.c.

1008{
1009 /*
1010 * Get correct info if it's SET ROLE NONE
1011 *
1012 * If SessionUserId hasn't been set yet, do nothing beyond updating
1013 * SetRoleIsActive --- the eventual SetSessionAuthorization call will
1014 * update the derived state. This is needed since we will get called
1015 * during GUC initialization.
1016 */
1017 if (!OidIsValid(roleid))
1018 {
1019 SetRoleIsActive = false;
1020
1022 return;
1023
1024 roleid = SessionUserId;
1026 }
1027 else
1028 SetRoleIsActive = true;
1029
1031}
static void SetOuterUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:539

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

Referenced by assign_role(), InitializeSessionUserIdStandalone(), and ParallelWorkerMain().

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 334 of file miscinit.c.

335{
336 /* This should happen only once per process */
339}
char * DatabasePath
Definition: globals.c:104

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 440 of file miscinit.c.

441{
442 char *new;
443
444 Assert(dir);
445
446 /* If presented path is relative, convert to absolute */
447 new = make_absolute_path(dir);
448
449 free(DataDir);
450 DataDir = new;
451}
#define free(a)
Definition: header.h:65
char * make_absolute_path(const char *path)
Definition: path.c:807

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

Referenced by SelectConfigFiles().

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 539 of file miscinit.c.

540{
542 Assert(OidIsValid(userid));
543 OuterUserId = userid;
544
545 /* We force the effective user ID to match, too */
546 CurrentUserId = userid;
547
548 /* Also update the is_superuser GUC to match OuterUserId's property */
549 SetConfigOption("is_superuser",
550 is_superuser ? "on" : "off",
552}
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:114
@ PGC_INTERNAL
Definition: guc.h:73

References Assert(), CurrentUserId, is_superuser(), OidIsValid, OuterUserId, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT, SecurityRestrictionContext, and SetConfigOption().

Referenced by SetCurrentRoleId(), and SetSessionAuthorization().

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 971 of file miscinit.c.

972{
974
975 if (!SetRoleIsActive)
977}
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:573

References is_superuser(), SetOuterUserId(), SetRoleIsActive, and SetSessionUserId().

Referenced by assign_session_authorization(), InitializeSessionUserIdStandalone(), and ParallelWorkerMain().

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 719 of file miscinit.c.

720{
721 /* We throw the same error SET ROLE would. */
724 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
725 errmsg("cannot set parameter \"%s\" within security-restricted operation",
726 "role")));
727 CurrentUserId = userid;
728 if (sec_def_context)
730 else
731 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
732}
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:690

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

◆ SetUserIdAndSecContext()

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 242 of file miscinit.c.

243{
245 Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
246
248
249 if (FeBeWaitSet)
251 MyLatch);
252
254}
void SetLatch(Latch *latch)
Definition: latch.c:288
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:166
Latch procLatch
Definition: proc.h:170
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: waiteventset.c:655
#define WL_LATCH_SET
Definition: waiteventset.h:34

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

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

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

950{
951 const char *sysuser = GetSystemUser();
952
953 if (sysuser)
955 else
957}
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
const char * GetSystemUser(void)
Definition: miscinit.c:586

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

1542{
1543 ListCell *l;
1544
1545 foreach(l, lock_files)
1546 {
1547 char *socketLockFile = (char *) lfirst(l);
1548
1549 /* No need to touch the data directory lock file, we trust */
1550 if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1551 continue;
1552
1553 /* we just ignore any error here */
1554 (void) utime(socketLockFile, NULL);
1555 }
1556}

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 1174 of file miscinit.c.

1175{
1176 ListCell *l;
1177
1178 foreach(l, lock_files)
1179 {
1180 char *curfile = (char *) lfirst(l);
1181
1182 unlink(curfile);
1183 /* Should we complain if the unlink fails? */
1184 }
1185 /* Since we're about to exit, no need to reclaim storage */
1186 lock_files = NIL;
1187
1188 /*
1189 * Lock file removal should always be the last externally visible action
1190 * of a postmaster or standalone backend, while we won't come here at all
1191 * when exiting postmaster child processes. Therefore, this is a good
1192 * place to log completion of shutdown. We could alternatively teach
1193 * proc_exit() to do it, but that seems uglier. In a standalone backend,
1194 * use NOTICE elevel to be less chatty.
1195 */
1197 (errmsg("database system is shut down")));
1198}
#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 1769 of file miscinit.c.

1770{
1771 char full_path[MAXPGPATH];
1772 FILE *file;
1773 int ret;
1774 long file_major;
1775 long my_major;
1776 char *endptr;
1777 char file_version_string[64];
1778 const char *my_version_string = PG_VERSION;
1779
1780 my_major = strtol(my_version_string, &endptr, 10);
1781
1782 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1783
1784 file = AllocateFile(full_path, "r");
1785 if (!file)
1786 {
1787 if (errno == ENOENT)
1788 ereport(FATAL,
1789 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1790 errmsg("\"%s\" is not a valid data directory",
1791 path),
1792 errdetail("File \"%s\" is missing.", full_path)));
1793 else
1794 ereport(FATAL,
1796 errmsg("could not open file \"%s\": %m", full_path)));
1797 }
1798
1799 file_version_string[0] = '\0';
1800 ret = fscanf(file, "%63s", file_version_string);
1801 file_major = strtol(file_version_string, &endptr, 10);
1802
1803 if (ret != 1 || endptr == file_version_string)
1804 ereport(FATAL,
1805 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1806 errmsg("\"%s\" is not a valid data directory",
1807 path),
1808 errdetail("File \"%s\" does not contain valid data.",
1809 full_path),
1810 errhint("You might need to initdb.")));
1811
1812 FreeFile(file);
1813
1814 if (my_major != file_major)
1815 ereport(FATAL,
1816 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1817 errmsg("database files are incompatible with server"),
1818 errdetail("The data directory was initialized by PostgreSQL version %s, "
1819 "which is not compatible with this version %s.",
1820 file_version_string, my_version_string)));
1821}
int FreeFile(FILE *file)
Definition: fd.c:2843
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2644

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

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

Definition at line 69 of file miscinit.c.

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

◆ lock_files

List* lock_files = NIL
static

Definition at line 67 of file miscinit.c.

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

◆ Mode

Definition at line 62 of file miscinit.c.

◆ MyBackendType

◆ MyClientConnectionInfo

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 502 of file miscinit.c.

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

◆ process_shared_preload_libraries_done

bool process_shared_preload_libraries_done = false

◆ process_shared_preload_libraries_in_progress

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

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 507 of file miscinit.c.

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

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 512 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1833 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

shmem_request_hook_type shmem_request_hook = NULL

Definition at line 1840 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ SystemUser

const char* SystemUser = NULL
static

Definition at line 504 of file miscinit.c.

Referenced by GetSystemUser(), and InitializeSystemUser().