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

1568{
1569 int fd;
1570 int len;
1571 int lineno;
1572 char *srcptr;
1573 char *destptr;
1574 char srcbuffer[BLCKSZ];
1575 char destbuffer[BLCKSZ];
1576
1577 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1578 if (fd < 0)
1579 {
1580 ereport(LOG,
1582 errmsg("could not open file \"%s\": %m",
1584 return;
1585 }
1586 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
1587 len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1589 if (len < 0)
1590 {
1591 ereport(LOG,
1593 errmsg("could not read from file \"%s\": %m",
1595 close(fd);
1596 return;
1597 }
1598 srcbuffer[len] = '\0';
1599
1600 /*
1601 * Advance over lines we are not supposed to rewrite, then copy them to
1602 * destbuffer.
1603 */
1604 srcptr = srcbuffer;
1605 for (lineno = 1; lineno < target_line; lineno++)
1606 {
1607 char *eol = strchr(srcptr, '\n');
1608
1609 if (eol == NULL)
1610 break; /* not enough lines in file yet */
1611 srcptr = eol + 1;
1612 }
1613 memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1614 destptr = destbuffer + (srcptr - srcbuffer);
1615
1616 /*
1617 * Fill in any missing lines before the target line, in case lines are
1618 * added to the file out of order.
1619 */
1620 for (; lineno < target_line; lineno++)
1621 {
1622 if (destptr < destbuffer + sizeof(destbuffer))
1623 *destptr++ = '\n';
1624 }
1625
1626 /*
1627 * Write or rewrite the target line.
1628 */
1629 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1630 destptr += strlen(destptr);
1631
1632 /*
1633 * If there are more lines in the old file, append them to destbuffer.
1634 */
1635 if ((srcptr = strchr(srcptr, '\n')) != NULL)
1636 {
1637 srcptr++;
1638 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1639 srcptr);
1640 }
1641
1642 /*
1643 * And rewrite the data. Since we write in a single kernel call, this
1644 * update should appear atomic to onlookers.
1645 */
1646 len = strlen(destbuffer);
1647 errno = 0;
1648 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
1649 if (pg_pwrite(fd, destbuffer, len, 0) != len)
1650 {
1652 /* if write didn't set errno, assume problem is no disk space */
1653 if (errno == 0)
1654 errno = ENOSPC;
1655 ereport(LOG,
1657 errmsg("could not write to file \"%s\": %m",
1659 close(fd);
1660 return;
1661 }
1663 pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
1664 if (pg_fsync(fd) != 0)
1665 {
1666 ereport(LOG,
1668 errmsg("could not write to file \"%s\": %m",
1670 }
1672 if (close(fd) != 0)
1673 {
1674 ereport(LOG,
1676 errmsg("could not write to file \"%s\": %m",
1678 }
1679}
#define PG_BINARY
Definition: c.h:1227
int errcode_for_file_access(void)
Definition: elog.c:876
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define ereport(elevel,...)
Definition: elog.h:149
int pg_fsync(int fd)
Definition: fd.c:385
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:226
#define snprintf
Definition: port.h:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h: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 457 of file miscinit.c.

458{
460
461 if (chdir(DataDir) < 0)
464 errmsg("could not change directory to \"%s\": %m",
465 DataDir)));
466}
#define Assert(condition)
Definition: c.h:812
#define FATAL
Definition: elog.h:41
char * DataDir
Definition: globals.c:70

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

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

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 344 of file miscinit.c.

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

References Assert, data_directory_mode, DataDir, ereport, errcode(), errcode_for_file_access(), errdetail(), errhint(), errmsg(), FATAL, pg_dir_create_mode, pg_mode_mask, PG_MODE_MASK_GROUP, S_ISDIR, SetDataDirectoryCreatePerm(), stat::st_mode, stat::st_uid, stat, and ValidatePgVersion().

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

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1511 of file miscinit.c.

1512{
1513 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1514}
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1206

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

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

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

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

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by Lock_AF_UNIX().

◆ EstimateClientConnectionInfoSpace()

Size EstimateClientConnectionInfoSpace ( void  )

Definition at line 1083 of file miscinit.c.

1084{
1085 Size size = 0;
1086
1088
1091
1092 return size;
1093}
size_t Size
Definition: c.h:559
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1066
Size add_size(Size s1, Size s2)
Definition: shmem.c:488
static pg_noinline void Size size
Definition: slab.c:607
const char * authn_id
Definition: libpq-be.h:103

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

Referenced by InitializeParallelDSM().

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 593 of file miscinit.c.

594{
596 return AuthenticatedUserId;
597}
#define OidIsValid(objectId)
Definition: c.h:729
static Oid AuthenticatedUserId
Definition: miscinit.c:497

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_LOGGER:
297 backendDesc = gettext_noop("logger");
298 break;
300 backendDesc = gettext_noop("slotsync worker");
301 break;
303 backendDesc = gettext_noop("standalone backend");
304 break;
305 case B_STARTUP:
306 backendDesc = gettext_noop("startup");
307 break;
308 case B_WAL_RECEIVER:
309 backendDesc = gettext_noop("walreceiver");
310 break;
311 case B_WAL_SENDER:
312 backendDesc = gettext_noop("walsender");
313 break;
314 case B_WAL_SUMMARIZER:
315 backendDesc = gettext_noop("walsummarizer");
316 break;
317 case B_WAL_WRITER:
318 backendDesc = gettext_noop("walwriter");
319 break;
320 }
321
322 return backendDesc;
323}
#define gettext_noop(x)
Definition: c.h:1150
@ B_WAL_SUMMARIZER
Definition: miscadmin.h:365
@ B_WAL_WRITER
Definition: miscadmin.h:366
@ B_WAL_RECEIVER
Definition: miscadmin.h:364
@ B_CHECKPOINTER
Definition: miscadmin.h:362
@ B_WAL_SENDER
Definition: miscadmin.h:346
@ B_LOGGER
Definition: miscadmin.h:372
@ B_STARTUP
Definition: miscadmin.h:363
@ 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_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 SignalChildren().

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 983 of file miscinit.c.

984{
985 if (SetRoleIsActive)
986 return OuterUserId;
987 else
988 return InvalidOid;
989}
static Oid OuterUserId
Definition: miscinit.c:499
static bool SetRoleIsActive
Definition: miscinit.c:509
#define InvalidOid
Definition: postgres_ext.h:36

References InvalidOid, OuterUserId, and SetRoleIsActive.

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

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 528 of file miscinit.c.

529{
531 return OuterUserId;
532}

References Assert, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

◆ GetSessionUserIsSuperuser()

bool GetSessionUserIsSuperuser ( void  )

Definition at line 563 of file miscinit.c.

564{
567}
static bool SessionUserIsSuperuser
Definition: miscinit.c:504

References Assert, OidIsValid, SessionUserId, and SessionUserIsSuperuser.

Referenced by check_session_authorization(), and InitializeParallelDSM().

◆ GetSystemUser()

const char * GetSystemUser ( void  )

Definition at line 583 of file miscinit.c.

584{
585 return SystemUser;
586}
static const char * SystemUser
Definition: miscinit.c:501

References SystemUser.

Referenced by system_user().

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 517 of file miscinit.c.

518{
520 return CurrentUserId;
521}
static Oid CurrentUserId
Definition: miscinit.c:500

References Assert, CurrentUserId, and OidIsValid.

Referenced by AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseRefreshColl(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterSystemSetConfigFile(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterType(), AlterTypeNamespace_oid(), AlterTypeOwner(), 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 709 of file miscinit.c.

710{
711 *userid = CurrentUserId;
712 *sec_def_context = InLocalUserIdChange();
713}
bool InLocalUserIdChange(void)
Definition: miscinit.c:678

References CurrentUserId, and InLocalUserIdChange().

◆ GetUserIdAndSecContext()

◆ GetUserNameFromId()

char * GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 1036 of file miscinit.c.

1037{
1038 HeapTuple tuple;
1039 char *result;
1040
1041 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
1042 if (!HeapTupleIsValid(tuple))
1043 {
1044 if (!noerr)
1045 ereport(ERROR,
1046 (errcode(ERRCODE_UNDEFINED_OBJECT),
1047 errmsg("invalid role OID: %u", roleid)));
1048 result = NULL;
1049 }
1050 else
1051 {
1052 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
1053 ReleaseSysCache(tuple);
1054 }
1055 return result;
1056}
#define NameStr(name)
Definition: c.h:700
#define ERROR
Definition: elog.h:39
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
NameData rolname
Definition: pg_authid.h:34
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c: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 736 of file miscinit.c.

737{
738 bool result = false;
739 HeapTuple utup;
740
741 /* Superusers bypass all permission checking. */
742 if (superuser_arg(roleid))
743 return true;
744
745 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
746 if (HeapTupleIsValid(utup))
747 {
748 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
749 ReleaseSysCache(utup);
750 }
751 return result;
752}
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 758 of file miscinit.c.

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

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

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

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

References Assert, 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:953
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:73
void on_exit_reset(void)
Definition: ipc.c:416
void InitializeLatchWaitSet(void)
Definition: latch.c:346
void InitializeLatchSupport(void)
Definition: latch.c:232
void InitProcessLocalLatch(void)
Definition: miscinit.c:235
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:407
pqsigfunc pqsignal(int signo, pqsigfunc func)
void InitProcessGlobals(void)
Definition: postmaster.c:1904
int postmaster_alive_fds[2]
Definition: postmaster.c:460
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:84
void pgwin32_signal_initialize(void)
Definition: signal.c:79
#define SIGQUIT
Definition: win32_port.h:169

References BlockSig, elog, ereport, errcode_for_socket_access(), errmsg_internal(), FATAL, InitializeLatchSupport(), InitializeLatchWaitSet(), InitProcessGlobals(), InitProcessLocalLatch(), IsUnderPostmaster, on_exit_reset(), pgwin32_signal_initialize(), postmaster_alive_fds, POSTMASTER_FD_WATCH, PostmasterDeathSignalInit(), pqinitmask(), pqsignal(), 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:62
void InitLatch(Latch *latch)
Definition: latch.c:394
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:81
bool IsPostmasterEnvironment
Definition: globals.c:118
char my_exec_path[MAXPGPATH]
Definition: globals.c:80
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:879

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

Referenced by BootstrapModeMain(), and PostgresSingleUserMain().

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 678 of file miscinit.c.

679{
681}
#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 696 of file miscinit.c.

697{
699}
#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 1847 of file miscinit.c.

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

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

1937{
1938#ifdef ENABLE_NLS
1939 if (my_exec_path[0] != '\0')
1940 {
1941 char locale_path[MAXPGPATH];
1942
1943 get_locale_path(my_exec_path, locale_path);
1944 bindtextdomain(domain, locale_path);
1945 pg_bind_textdomain_codeset(domain);
1946 }
1947#endif
1948}
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 1913 of file miscinit.c.

1914{
1916 "session_preload_libraries",
1917 false);
1919 "local_preload_libraries",
1920 true);
1921}
char * session_preload_libraries_string
Definition: miscinit.c:1829
char * local_preload_libraries_string
Definition: miscinit.c:1831
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1847

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

1900{
1903 "shared_preload_libraries",
1904 false);
1907}
bool process_shared_preload_libraries_done
Definition: miscinit.c:1835
char * shared_preload_libraries_string
Definition: miscinit.c:1830
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1834

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

1928{
1933}
bool process_shmem_requests_in_progress
Definition: miscinit.c:1838
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1837

References process_shmem_requests_in_progress, and shmem_request_hook.

Referenced by PostgresSingleUserMain(), and PostmasterMain().

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1694 of file miscinit.c.

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

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

1132{
1134
1135 memcpy(&serialized, conninfo, sizeof(serialized));
1136
1137 /* Copy the fields back into place */
1140
1141 if (serialized.authn_id_len >= 0)
1142 {
1143 char *authn_id;
1144
1145 authn_id = conninfo + sizeof(serialized);
1147 authn_id);
1148 }
1149}
UserAuth auth_method
Definition: libpq-be.h:109

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

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

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

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

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

Referenced by InitializeSessionUserId(), and ParallelWorkerMain().

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 1004 of file miscinit.c.

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

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

332{
333 /* This should happen only once per process */
336}
char * DatabasePath
Definition: globals.c:103

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

Referenced by InitPostgres().

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 437 of file miscinit.c.

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

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

Referenced by SelectConfigFiles().

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 536 of file miscinit.c.

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

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

969{
971
972 if (!SetRoleIsActive)
974}
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:570

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

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

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 ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1043
void SetLatch(Latch *latch)
Definition: latch.c:632
#define WL_LATCH_SET
Definition: latch.h:127
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:166
Latch procLatch
Definition: proc.h:169

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

947{
948 const char *sysuser = GetSystemUser();
949
950 if (sysuser)
952 else
954}
#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:583

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

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

References DIRECTORY_LOCK_FILE, lfirst, and lock_files.

Referenced by ServerLoop().

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 1171 of file miscinit.c.

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

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

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 1831 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 499 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 1829 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 504 of file miscinit.c.

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

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 509 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1830 of file miscinit.c.

Referenced by process_shared_preload_libraries().

◆ shmem_request_hook

shmem_request_hook_type shmem_request_hook = NULL

Definition at line 1837 of file miscinit.c.

Referenced by _PG_init(), and process_shmem_requests().

◆ SystemUser

const char* SystemUser = NULL
static

Definition at line 501 of file miscinit.c.

Referenced by GetSystemUser(), and InitializeSystemUser().