PostgreSQL Source Code  git master
miscinit.c File Reference
#include "postgres.h"
#include <sys/param.h>
#include <signal.h>
#include <time.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "access/htup_details.h"
#include "catalog/pg_authid.h"
#include "common/file_perm.h"
#include "libpq/libpq.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/autovacuum.h"
#include "postmaster/postmaster.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/pg_shmem.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/builtins.h"
#include "utils/guc.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.

Macros

#define DIRECTORY_LOCK_FILE   "postmaster.pid"
 

Functions

void SetDatabasePath (const char *path)
 
void checkDataDir (void)
 
void SetDataDir (const char *dir)
 
void ChangeToDataDir (void)
 
void InitPostmasterChild (void)
 
void InitStandaloneProcess (const char *argv0)
 
void SwitchToSharedLatch (void)
 
void SwitchBackToLocalLatch (void)
 
Oid GetUserId (void)
 
Oid GetOuterUserId (void)
 
static void SetOuterUserId (Oid userid)
 
Oid GetSessionUserId (void)
 
static void SetSessionUserId (Oid userid, bool is_superuser)
 
Oid GetAuthenticatedUserId (void)
 
void GetUserIdAndSecContext (Oid *userid, int *sec_context)
 
void SetUserIdAndSecContext (Oid userid, int sec_context)
 
bool InLocalUserIdChange (void)
 
bool InSecurityRestrictedOperation (void)
 
bool InNoForceRLSOperation (void)
 
void GetUserIdAndContext (Oid *userid, bool *sec_def_context)
 
void SetUserIdAndContext (Oid userid, bool sec_def_context)
 
bool has_rolreplication (Oid roleid)
 
void InitializeSessionUserId (const char *rolename, Oid roleid)
 
void InitializeSessionUserIdStandalone (void)
 
void SetSessionAuthorization (Oid userid, bool is_superuser)
 
Oid GetCurrentRoleId (void)
 
void SetCurrentRoleId (Oid roleid, bool is_superuser)
 
char * GetUserNameFromId (Oid roleid, bool noerr)
 
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 pg_bindtextdomain (const char *domain)
 

Variables

ProcessingMode Mode = InitProcessing
 
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 bool AuthenticatedUserIsSuperuser = false
 
static bool SessionUserIsSuperuser = false
 
static int SecurityRestrictionContext = 0
 
static bool SetRoleIsActive = false
 
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
 

Macro Definition Documentation

◆ DIRECTORY_LOCK_FILE

#define DIRECTORY_LOCK_FILE   "postmaster.pid"

Function Documentation

◆ AddToDataDirLockFile()

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1250 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, snprintf(), WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC, WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE, and write.

Referenced by InternalIpcMemoryCreate(), pmdie(), PostmasterMain(), reaper(), and sigusr1_handler().

1251 {
1252  int fd;
1253  int len;
1254  int lineno;
1255  char *srcptr;
1256  char *destptr;
1257  char srcbuffer[BLCKSZ];
1258  char destbuffer[BLCKSZ];
1259 
1260  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1261  if (fd < 0)
1262  {
1263  ereport(LOG,
1265  errmsg("could not open file \"%s\": %m",
1267  return;
1268  }
1270  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1272  if (len < 0)
1273  {
1274  ereport(LOG,
1276  errmsg("could not read from file \"%s\": %m",
1278  close(fd);
1279  return;
1280  }
1281  srcbuffer[len] = '\0';
1282 
1283  /*
1284  * Advance over lines we are not supposed to rewrite, then copy them to
1285  * destbuffer.
1286  */
1287  srcptr = srcbuffer;
1288  for (lineno = 1; lineno < target_line; lineno++)
1289  {
1290  char *eol = strchr(srcptr, '\n');
1291 
1292  if (eol == NULL)
1293  break; /* not enough lines in file yet */
1294  srcptr = eol + 1;
1295  }
1296  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1297  destptr = destbuffer + (srcptr - srcbuffer);
1298 
1299  /*
1300  * Fill in any missing lines before the target line, in case lines are
1301  * added to the file out of order.
1302  */
1303  for (; lineno < target_line; lineno++)
1304  {
1305  if (destptr < destbuffer + sizeof(destbuffer))
1306  *destptr++ = '\n';
1307  }
1308 
1309  /*
1310  * Write or rewrite the target line.
1311  */
1312  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1313  destptr += strlen(destptr);
1314 
1315  /*
1316  * If there are more lines in the old file, append them to destbuffer.
1317  */
1318  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1319  {
1320  srcptr++;
1321  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1322  srcptr);
1323  }
1324 
1325  /*
1326  * And rewrite the data. Since we write in a single kernel call, this
1327  * update should appear atomic to onlookers.
1328  */
1329  len = strlen(destbuffer);
1330  errno = 0;
1332  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1333  (int) write(fd, destbuffer, len) != len)
1334  {
1336  /* if write didn't set errno, assume problem is no disk space */
1337  if (errno == 0)
1338  errno = ENOSPC;
1339  ereport(LOG,
1341  errmsg("could not write to file \"%s\": %m",
1343  close(fd);
1344  return;
1345  }
1348  if (pg_fsync(fd) != 0)
1349  {
1350  ereport(LOG,
1352  errmsg("could not write to file \"%s\": %m",
1354  }
1356  if (close(fd) != 0)
1357  {
1358  ereport(LOG,
1360  errmsg("could not write to file \"%s\": %m",
1362  }
1363 }
#define write(a, b, c)
Definition: win32.h:14
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1080
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
#define ereport(elevel, rest)
Definition: elog.h:122
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1236
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:341
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 211 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

212 {
214 
215  if (chdir(DataDir) < 0)
216  ereport(FATAL,
218  errmsg("could not change directory to \"%s\": %m",
219  DataDir)));
220 }
#define AssertState(condition)
Definition: c.h:702
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:61

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 97 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), BackendRun(), PostgresMain(), and PostmasterMain().

98 {
99  struct stat stat_buf;
100 
101  Assert(DataDir);
102 
103  if (stat(DataDir, &stat_buf) != 0)
104  {
105  if (errno == ENOENT)
106  ereport(FATAL,
108  errmsg("data directory \"%s\" does not exist",
109  DataDir)));
110  else
111  ereport(FATAL,
113  errmsg("could not read permissions of directory \"%s\": %m",
114  DataDir)));
115  }
116 
117  /* eventual chdir would fail anyway, but let's test ... */
118  if (!S_ISDIR(stat_buf.st_mode))
119  ereport(FATAL,
120  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
121  errmsg("specified data directory \"%s\" is not a directory",
122  DataDir)));
123 
124  /*
125  * Check that the directory belongs to my userid; if not, reject.
126  *
127  * This check is an essential part of the interlock that prevents two
128  * postmasters from starting in the same directory (see CreateLockFile()).
129  * Do not remove or weaken it.
130  *
131  * XXX can we safely enable this check on Windows?
132  */
133 #if !defined(WIN32) && !defined(__CYGWIN__)
134  if (stat_buf.st_uid != geteuid())
135  ereport(FATAL,
136  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
137  errmsg("data directory \"%s\" has wrong ownership",
138  DataDir),
139  errhint("The server must be started by the user that owns the data directory.")));
140 #endif
141 
142  /*
143  * Check if the directory has correct permissions. If not, reject.
144  *
145  * Only two possible modes are allowed, 0700 and 0750. The latter mode
146  * indicates that group read/execute should be allowed on all newly
147  * created files and directories.
148  *
149  * XXX temporarily suppress check when on Windows, because there may not
150  * be proper support for Unix-y file permissions. Need to think of a
151  * reasonable check to apply on Windows.
152  */
153 #if !defined(WIN32) && !defined(__CYGWIN__)
154  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
155  ereport(FATAL,
156  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
157  errmsg("data directory \"%s\" has invalid permissions",
158  DataDir),
159  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
160 #endif
161 
162  /*
163  * Reset creation modes and mask based on the mode of the data directory.
164  *
165  * The mask was set earlier in startup to disallow group permissions on
166  * newly created files and directories. However, if group read/execute
167  * are present on the data directory then modify the create modes and mask
168  * to allow group read/execute on newly created files and directories and
169  * set the data_directory_mode GUC.
170  *
171  * Suppress when on Windows, because there may not be proper support for
172  * Unix-y file permissions.
173  */
174 #if !defined(WIN32) && !defined(__CYGWIN__)
176 
177  umask(pg_mode_mask);
179 #endif
180 
181  /* Check for PG_VERSION */
183 }
int errhint(const char *fmt,...)
Definition: elog.c:987
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1450
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
struct stat stat_buf
Definition: pg_standby.c:103
#define FATAL
Definition: elog.h:52
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define stat(a, b)
Definition: win32_port.h:266
int pg_dir_create_mode
Definition: file_perm.c:18
#define Assert(condition)
Definition: c.h:699
#define S_ISDIR(m)
Definition: win32_port.h:307
int errmsg(const char *fmt,...)
Definition: elog.c:797
int data_directory_mode
Definition: globals.c:67
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
char * DataDir
Definition: globals.c:61
int pg_mode_mask
Definition: file_perm.c:25

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1173 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

Referenced by AuxiliaryProcessMain(), PostgresMain(), and PostmasterMain().

1174 {
1175  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1176 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:864
char * DataDir
Definition: globals.c:61

◆ CreateLockFile()

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

Definition at line 864 of file miscinit.c.

References buffer, close, DataDir, elog, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), kill, lcons(), LOCK_FILE_LINE_SHMEM_KEY, MAXPGPATH, MyStartTime, NIL, on_proc_exit(), pg_file_create_mode, pg_fsync(), PGSharedMemoryIsInUse(), pgstat_report_wait_end(), pgstat_report_wait_start(), PostPortNumber, pstrdup(), read, snprintf(), strlcat(), UnlinkLockFiles(), WAIT_EVENT_LOCK_FILE_CREATE_READ, WAIT_EVENT_LOCK_FILE_CREATE_SYNC, WAIT_EVENT_LOCK_FILE_CREATE_WRITE, and write.

Referenced by CreateDataDirLockFile(), and CreateSocketLockFile().

867 {
868  int fd;
869  char buffer[MAXPGPATH * 2 + 256];
870  int ntries;
871  int len;
872  int encoded_pid;
873  pid_t other_pid;
874  pid_t my_pid,
875  my_p_pid,
876  my_gp_pid;
877  const char *envvar;
878 
879  /*
880  * If the PID in the lockfile is our own PID or our parent's or
881  * grandparent's PID, then the file must be stale (probably left over from
882  * a previous system boot cycle). We need to check this because of the
883  * likelihood that a reboot will assign exactly the same PID as we had in
884  * the previous reboot, or one that's only one or two counts larger and
885  * hence the lockfile's PID now refers to an ancestor shell process. We
886  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
887  * via the environment variable PG_GRANDPARENT_PID; this is so that
888  * launching the postmaster via pg_ctl can be just as reliable as
889  * launching it directly. There is no provision for detecting
890  * further-removed ancestor processes, but if the init script is written
891  * carefully then all but the immediate parent shell will be root-owned
892  * processes and so the kill test will fail with EPERM. Note that we
893  * cannot get a false negative this way, because an existing postmaster
894  * would surely never launch a competing postmaster or pg_ctl process
895  * directly.
896  */
897  my_pid = getpid();
898 
899 #ifndef WIN32
900  my_p_pid = getppid();
901 #else
902 
903  /*
904  * Windows hasn't got getppid(), but doesn't need it since it's not using
905  * real kill() either...
906  */
907  my_p_pid = 0;
908 #endif
909 
910  envvar = getenv("PG_GRANDPARENT_PID");
911  if (envvar)
912  my_gp_pid = atoi(envvar);
913  else
914  my_gp_pid = 0;
915 
916  /*
917  * We need a loop here because of race conditions. But don't loop forever
918  * (for example, a non-writable $PGDATA directory might cause a failure
919  * that won't go away). 100 tries seems like plenty.
920  */
921  for (ntries = 0;; ntries++)
922  {
923  /*
924  * Try to create the lock file --- O_EXCL makes this atomic.
925  *
926  * Think not to make the file protection weaker than 0600/0640. See
927  * comments below.
928  */
929  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
930  if (fd >= 0)
931  break; /* Success; exit the retry loop */
932 
933  /*
934  * Couldn't create the pid file. Probably it already exists.
935  */
936  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
937  ereport(FATAL,
939  errmsg("could not create lock file \"%s\": %m",
940  filename)));
941 
942  /*
943  * Read the file to get the old owner's PID. Note race condition
944  * here: file might have been deleted since we tried to create it.
945  */
946  fd = open(filename, O_RDONLY, pg_file_create_mode);
947  if (fd < 0)
948  {
949  if (errno == ENOENT)
950  continue; /* race condition; try again */
951  ereport(FATAL,
953  errmsg("could not open lock file \"%s\": %m",
954  filename)));
955  }
957  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
958  ereport(FATAL,
960  errmsg("could not read lock file \"%s\": %m",
961  filename)));
963  close(fd);
964 
965  if (len == 0)
966  {
967  ereport(FATAL,
968  (errcode(ERRCODE_LOCK_FILE_EXISTS),
969  errmsg("lock file \"%s\" is empty", filename),
970  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
971  }
972 
973  buffer[len] = '\0';
974  encoded_pid = atoi(buffer);
975 
976  /* if pid < 0, the pid is for postgres, not postmaster */
977  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
978 
979  if (other_pid <= 0)
980  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
981  filename, buffer);
982 
983  /*
984  * Check to see if the other process still exists
985  *
986  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
987  * ignored as false matches.
988  *
989  * Normally kill() will fail with ESRCH if the given PID doesn't
990  * exist.
991  *
992  * We can treat the EPERM-error case as okay because that error
993  * implies that the existing process has a different userid than we
994  * do, which means it cannot be a competing postmaster. A postmaster
995  * cannot successfully attach to a data directory owned by a userid
996  * other than its own, as enforced in checkDataDir(). Also, since we
997  * create the lockfiles mode 0600/0640, we'd have failed above if the
998  * lockfile belonged to another userid --- which means that whatever
999  * process kill() is reporting about isn't the one that made the
1000  * lockfile. (NOTE: this last consideration is the only one that
1001  * keeps us from blowing away a Unix socket file belonging to an
1002  * instance of Postgres being run by someone else, at least on
1003  * machines where /tmp hasn't got a stickybit.)
1004  */
1005  if (other_pid != my_pid && other_pid != my_p_pid &&
1006  other_pid != my_gp_pid)
1007  {
1008  if (kill(other_pid, 0) == 0 ||
1009  (errno != ESRCH && errno != EPERM))
1010  {
1011  /* lockfile belongs to a live process */
1012  ereport(FATAL,
1013  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1014  errmsg("lock file \"%s\" already exists",
1015  filename),
1016  isDDLock ?
1017  (encoded_pid < 0 ?
1018  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
1019  (int) other_pid, refName) :
1020  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
1021  (int) other_pid, refName)) :
1022  (encoded_pid < 0 ?
1023  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
1024  (int) other_pid, refName) :
1025  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
1026  (int) other_pid, refName))));
1027  }
1028  }
1029 
1030  /*
1031  * No, the creating process did not exist. However, it could be that
1032  * the postmaster crashed (or more likely was kill -9'd by a clueless
1033  * admin) but has left orphan backends behind. Check for this by
1034  * looking to see if there is an associated shmem segment that is
1035  * still in use.
1036  *
1037  * Note: because postmaster.pid is written in multiple steps, we might
1038  * not find the shmem ID values in it; we can't treat that as an
1039  * error.
1040  */
1041  if (isDDLock)
1042  {
1043  char *ptr = buffer;
1044  unsigned long id1,
1045  id2;
1046  int lineno;
1047 
1048  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
1049  {
1050  if ((ptr = strchr(ptr, '\n')) == NULL)
1051  break;
1052  ptr++;
1053  }
1054 
1055  if (ptr != NULL &&
1056  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
1057  {
1058  if (PGSharedMemoryIsInUse(id1, id2))
1059  ereport(FATAL,
1060  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1061  errmsg("pre-existing shared memory block "
1062  "(key %lu, ID %lu) is still in use",
1063  id1, id2),
1064  errhint("If you're sure there are no old "
1065  "server processes still running, remove "
1066  "the shared memory block "
1067  "or just delete the file \"%s\".",
1068  filename)));
1069  }
1070  }
1071 
1072  /*
1073  * Looks like nobody's home. Unlink the file and try again to create
1074  * it. Need a loop because of possible race condition against other
1075  * would-be creators.
1076  */
1077  if (unlink(filename) < 0)
1078  ereport(FATAL,
1080  errmsg("could not remove old lock file \"%s\": %m",
1081  filename),
1082  errhint("The file seems accidentally left over, but "
1083  "it could not be removed. Please remove the file "
1084  "by hand and try again.")));
1085  }
1086 
1087  /*
1088  * Successfully created the file, now fill it. See comment in miscadmin.h
1089  * about the contents. Note that we write the same first five lines into
1090  * both datadir and socket lockfiles; although more stuff may get added to
1091  * the datadir lockfile later.
1092  */
1093  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
1094  amPostmaster ? (int) my_pid : -((int) my_pid),
1095  DataDir,
1096  (long) MyStartTime,
1098  socketDir);
1099 
1100  /*
1101  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1102  * will never receive data, so fill it in as empty now.
1103  */
1104  if (isDDLock && !amPostmaster)
1105  strlcat(buffer, "\n", sizeof(buffer));
1106 
1107  errno = 0;
1109  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1110  {
1111  int save_errno = errno;
1112 
1113  close(fd);
1114  unlink(filename);
1115  /* if write didn't set errno, assume problem is no disk space */
1116  errno = save_errno ? save_errno : ENOSPC;
1117  ereport(FATAL,
1119  errmsg("could not write lock file \"%s\": %m", filename)));
1120  }
1122 
1124  if (pg_fsync(fd) != 0)
1125  {
1126  int save_errno = errno;
1127 
1128  close(fd);
1129  unlink(filename);
1130  errno = save_errno;
1131  ereport(FATAL,
1133  errmsg("could not write lock file \"%s\": %m", filename)));
1134  }
1136  if (close(fd) != 0)
1137  {
1138  int save_errno = errno;
1139 
1140  unlink(filename);
1141  errno = save_errno;
1142  ereport(FATAL,
1144  errmsg("could not write lock file \"%s\": %m", filename)));
1145  }
1146 
1147  /*
1148  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1149  * one, set up the on_proc_exit function to do it; then add this lock file
1150  * to the list of files to unlink.
1151  */
1152  if (lock_files == NIL)
1154 
1155  /*
1156  * Use lcons so that the lock files are unlinked in reverse order of
1157  * creation; this is critical!
1158  */
1160 }
#define NIL
Definition: pg_list.h:69
int pg_file_create_mode
Definition: file_perm.c:19
int errhint(const char *fmt,...)
Definition: elog.c:987
#define write(a, b, c)
Definition: win32.h:14
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:303
static List * lock_files
Definition: miscinit.c:61
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: pidfile.h:42
char * pstrdup(const char *in)
Definition: mcxt.c:1161
pg_time_t MyStartTime
Definition: globals.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
#define kill(pid, sig)
Definition: win32_port.h:437
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int PostPortNumber
Definition: postmaster.c:196
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
#define ereport(elevel, rest)
Definition: elog.h:122
List * lcons(void *datum, List *list)
Definition: list.c:259
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1236
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:289
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:829
static char * filename
Definition: pg_dumpall.c:87
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:61
int pg_fsync(int fd)
Definition: fd.c:341
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33

◆ CreateSocketLockFile()

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

Definition at line 1182 of file miscinit.c.

References CreateLockFile(), MAXPGPATH, and snprintf().

Referenced by StreamServerPort().

1184 {
1185  char lockfile[MAXPGPATH];
1186 
1187  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1188  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1189 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:864
#define MAXPGPATH

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 438 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

439 {
441  return AuthenticatedUserId;
442 }
#define AssertState(condition)
Definition: c.h:702
#define OidIsValid(objectId)
Definition: c.h:605
static Oid AuthenticatedUserId
Definition: miscinit.c:251

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 731 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

732 {
733  if (SetRoleIsActive)
734  return OuterUserId;
735  else
736  return InvalidOid;
737 }
static Oid OuterUserId
Definition: miscinit.c:253
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:263

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 390 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

391 {
393  return OuterUserId;
394 }
#define AssertState(condition)
Definition: c.h:702
static Oid OuterUserId
Definition: miscinit.c:253
#define OidIsValid(objectId)
Definition: c.h:605

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 413 of file miscinit.c.

References AssertState, OidIsValid, and SessionUserId.

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

414 {
416  return SessionUserId;
417 }
#define AssertState(condition)
Definition: c.h:702
static Oid SessionUserId
Definition: miscinit.c:252
#define OidIsValid(objectId)
Definition: c.h:605

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 379 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), AlterCollation(), AlterDatabase(), AlterDatabaseOwner(), AlterDatabaseSet(), AlterEventTrigger(), AlterEventTriggerOwner_internal(), AlterExtensionNamespace(), AlterForeignServer(), AlterForeignServerOwner_internal(), AlterFunction(), AlterObjectNamespace_internal(), AlterObjectOwner_internal(), AlterObjectRename_internal(), AlterOperator(), AlterOpFamilyAdd(), AlterPublication(), AlterPublicationOwner_internal(), AlterRole(), AlterRoleSet(), AlterSchemaOwner_internal(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), analyze_rel(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetStatistics(), ATPrepSetTableSpace(), ATSimplePermissions(), be_lo_put(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_desummarize_range(), brin_summarize_range(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), call_pltcl_start_proc(), check_enable_rls(), check_permissions(), check_temp_tablespaces(), CheckCachedPlan(), checkDomainOwner(), checkEnumOwner(), checkFkeyPermissions(), CheckFunctionValidatorAccess(), CheckMyDatabase(), cluster_rel(), CommentObject(), compile_plperl_function(), compile_pltcl_function(), CompleteCachedPlan(), compute_return_type(), convert_and_check_filename(), create_foreign_modify(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTrigger(), current_user(), currtid_byrelname(), currtid_byreloid(), currval_oid(), DefineAggregate(), DefineCollation(), DefineDomain(), DefineEnum(), DefineIndex(), DefineOpClass(), DefineOperator(), DefineOpFamily(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineTSConfiguration(), DefineTSDictionary(), DefineType(), DelRoleMems(), do_setval(), DoCopy(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), EnableDisableRule(), examine_simple_variable(), examine_variable(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecBuildGroupingEqual(), ExecBuildSlotPartitionKeyDescription(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitExprRec(), ExecInitFunc(), ExecInitWindowAgg(), ExecSecLabelStmt(), ExecuteCallStmt(), ExecuteDoStmt(), ExecuteTruncateGuts(), file_fdw_validator(), findRangeCanonicalFunction(), findRangeSubtypeDiffFunction(), FinishPreparedTransaction(), get_connect_string(), get_other_operator(), get_rel_from_relname(), get_rolespec_oid(), get_rolespec_tuple(), get_row_security_policies(), get_tables_to_cluster(), GetConfigOption(), GetConfigOptionByName(), GetConfigOptionByNum(), GetConfigOptionResetString(), 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_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(), ImportForeignSchema(), init_sexpr(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), inv_open(), LargeObjectCreate(), lastval(), LockTableCommand(), lookup_agg_function(), LookupCreationNamespace(), LookupExplicitNamespace(), MergeAttributes(), movedb(), nextval_internal(), OperatorCreate(), OperatorShellMake(), pg_has_role_id(), pg_has_role_name(), pg_import_system_collations(), pg_prewarm(), pg_sequence_last_value(), pg_sequence_parameters(), pg_signal_backend(), pg_stat_get_activity(), pg_stat_get_backend_activity(), pg_stat_get_backend_activity_start(), pg_stat_get_backend_client_addr(), pg_stat_get_backend_client_port(), pg_stat_get_backend_start(), pg_stat_get_backend_wait_event(), pg_stat_get_backend_wait_event_type(), pg_stat_get_backend_xact_start(), pg_stat_get_progress_info(), 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(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), RangeVarCallbackForLockTable(), RangeVarCallbackForPolicy(), RangeVarCallbackForReindexIndex(), RangeVarCallbackForRenameRule(), RangeVarCallbackForRenameTrigger(), RangeVarCallbackOwnsRelation(), RangeVarCallbackOwnsTable(), RangeVarGetAndCheckCreationNamespace(), ReassignOwnedObjects(), recomputeNamespacePath(), ReindexMultipleTables(), RemoveObjects(), RemoveRoleFromObjectPolicy(), renameatt_check(), RenameDatabase(), RenameSchema(), RenameTableSpace(), RenameType(), RevalidateCachedQuery(), RI_Initial_Check(), ri_ReportViolation(), select_perl_context(), set_foreign_rel_properties(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_rel(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

380 {
382  return CurrentUserId;
383 }
#define AssertState(condition)
Definition: c.h:702
#define OidIsValid(objectId)
Definition: c.h:605
static Oid CurrentUserId
Definition: miscinit.c:254

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 533 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

534 {
535  *userid = CurrentUserId;
536  *sec_def_context = InLocalUserIdChange();
537 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:502
static Oid CurrentUserId
Definition: miscinit.c:254

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 787 of file miscinit.c.

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

Referenced by check_is_member_of_role(), current_user(), getObjectDescription(), getObjectIdentityParts(), insert_username(), regroleout(), RemoveRoleFromObjectPolicy(), session_user(), and timetravel().

788 {
789  HeapTuple tuple;
790  char *result;
791 
792  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
793  if (!HeapTupleIsValid(tuple))
794  {
795  if (!noerr)
796  ereport(ERROR,
797  (errcode(ERRCODE_UNDEFINED_OBJECT),
798  errmsg("invalid role OID: %u", roleid)));
799  result = NULL;
800  }
801  else
802  {
803  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
804  ReleaseSysCache(tuple);
805  }
806  return result;
807 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
char * pstrdup(const char *in)
Definition: mcxt.c:1161
int errcode(int sqlerrcode)
Definition: elog.c:575
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:576

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 560 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

561 {
562  bool result = false;
563  HeapTuple utup;
564 
565  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
566  if (HeapTupleIsValid(utup))
567  {
568  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
569  ReleaseSysCache(utup);
570  }
571  return result;
572 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
bool rolreplication
Definition: pg_authid.h:39
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 578 of file miscinit.c.

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

Referenced by InitPostgres().

579 {
580  HeapTuple roleTup;
581  Form_pg_authid rform;
582  char *rname;
583 
584  /*
585  * Don't do scans if we're bootstrapping, none of the system catalogs
586  * exist yet, and they should be owned by postgres anyway.
587  */
589 
590  /* call only once */
592 
593  if (rolename != NULL)
594  {
595  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
596  if (!HeapTupleIsValid(roleTup))
597  ereport(FATAL,
598  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
599  errmsg("role \"%s\" does not exist", rolename)));
600  }
601  else
602  {
603  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
604  if (!HeapTupleIsValid(roleTup))
605  ereport(FATAL,
606  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
607  errmsg("role with OID %u does not exist", roleid)));
608  }
609 
610  rform = (Form_pg_authid) GETSTRUCT(roleTup);
611  roleid = HeapTupleGetOid(roleTup);
612  rname = NameStr(rform->rolname);
613 
614  AuthenticatedUserId = roleid;
615  AuthenticatedUserIsSuperuser = rform->rolsuper;
616 
617  /* This sets OuterUserId/CurrentUserId too */
619 
620  /* Also mark our PGPROC entry with the authenticated user id */
621  /* (We assume this is an atomic store so no lock is needed) */
622  MyProc->roleId = roleid;
623 
624  /*
625  * These next checks are not enforced when in standalone mode, so that
626  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
627  * rolcanlogin = false;".
628  */
629  if (IsUnderPostmaster)
630  {
631  /*
632  * Is role allowed to login at all?
633  */
634  if (!rform->rolcanlogin)
635  ereport(FATAL,
636  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
637  errmsg("role \"%s\" is not permitted to log in",
638  rname)));
639 
640  /*
641  * Check connection limit for this role.
642  *
643  * There is a race condition here --- we create our PGPROC before
644  * checking for other PGPROCs. If two backends did this at about the
645  * same time, they might both think they were over the limit, while
646  * ideally one should succeed and one fail. Getting that to work
647  * exactly seems more trouble than it is worth, however; instead we
648  * just document that the connection limit is approximate.
649  */
650  if (rform->rolconnlimit >= 0 &&
652  CountUserBackends(roleid) > rform->rolconnlimit)
653  ereport(FATAL,
654  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
655  errmsg("too many connections for role \"%s\"",
656  rname)));
657  }
658 
659  /* Record username and superuser status as GUC settings too */
660  SetConfigOption("session_authorization", rname,
662  SetConfigOption("is_superuser",
663  AuthenticatedUserIsSuperuser ? "on" : "off",
665 
666  ReleaseSysCache(roleTup);
667 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
#define AssertState(condition)
Definition: c.h:702
PGPROC * MyProc
Definition: proc.c:67
#define PointerGetDatum(X)
Definition: postgres.h:541
Oid roleId
Definition: proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:605
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:55
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define FATAL
Definition: elog.h:52
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6917
bool IsUnderPostmaster
Definition: globals.c:108
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:257
#define ereport(elevel, rest)
Definition: elog.h:122
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1112
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1160
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int CountUserBackends(Oid roleid)
Definition: procarray.c:2840
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:372
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:576
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:707
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:421
static Oid AuthenticatedUserId
Definition: miscinit.c:251

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 674 of file miscinit.c.

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

Referenced by InitPostgres().

675 {
676  /*
677  * This function should only be called in single-user mode, in autovacuum
678  * workers, and in background workers.
679  */
681 
682  /* call only once */
684 
685  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
687 
688  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
689 }
#define AssertState(condition)
Definition: c.h:702
#define OidIsValid(objectId)
Definition: c.h:605
bool IsBackgroundWorker
Definition: globals.c:110
bool IsUnderPostmaster
Definition: globals.c:108
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:257
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3295
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:421
static Oid AuthenticatedUserId
Definition: miscinit.c:251

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 271 of file miscinit.c.

References elog, FATAL, InitializeLatchSupport(), InitLatch(), IsUnderPostmaster, LocalLatchData, MyLatch, MyProcPid, MyStartTime, and on_exit_reset().

Referenced by BackendRun(), BackendStartup(), do_start_bgworker(), pgarch_start(), pgstat_start(), StartAutoVacLauncher(), StartAutoVacWorker(), StartChildProcess(), and SysLogger_Start().

272 {
273  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
274 
275  MyProcPid = getpid(); /* reset MyProcPid */
276 
277  MyStartTime = time(NULL); /* set our start time in case we call elog */
278 
279  /*
280  * make sure stderr is in binary mode before anything can possibly be
281  * written to it, in case it's actually the syslogger pipe, so the pipe
282  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
283  * redirection (e.g. via pg_ctl -l) anyway.
284  */
285 #ifdef WIN32
286  _setmode(fileno(stderr), _O_BINARY);
287 #endif
288 
289  /* We don't want the postmaster's proc_exit() handlers */
290  on_exit_reset();
291 
292  /* Initialize process-local latch support */
296 
297  /*
298  * If possible, make this process a group leader, so that the postmaster
299  * can signal any child processes too. Not all processes will have
300  * children, but for consistency we make all postmaster child processes do
301  * this.
302  */
303 #ifdef HAVE_SETSID
304  if (setsid() < 0)
305  elog(FATAL, "setsid() failed: %m");
306 #endif
307 }
int MyProcPid
Definition: globals.c:40
pg_time_t MyStartTime
Definition: globals.c:41
void on_exit_reset(void)
Definition: ipc.c:407
static Latch LocalLatchData
Definition: miscinit.c:63
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:108
void InitializeLatchSupport(void)
Definition: latch.c:147
void InitLatch(volatile Latch *latch)
Definition: latch.c:220
struct Latch * MyLatch
Definition: globals.c:53
#define elog
Definition: elog.h:219

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 315 of file miscinit.c.

References Assert, elog, FATAL, find_my_exec(), get_pkglib_path(), InitializeLatchSupport(), InitLatch(), IsPostmasterEnvironment, LocalLatchData, my_exec_path, MyLatch, MyProcPid, MyStartTime, and pkglib_path.

Referenced by AuxiliaryProcessMain(), and PostgresMain().

316 {
318 
319  MyProcPid = getpid(); /* reset MyProcPid */
320 
321  MyStartTime = time(NULL); /* set our start time in case we call elog */
322 
323  /* Initialize process-local latch support */
327 
328  /* Compute paths, no postmaster to inherit from */
329  if (my_exec_path[0] == '\0')
330  {
331  if (find_my_exec(argv0, my_exec_path) < 0)
332  elog(FATAL, "%s: could not locate my own executable path",
333  argv0);
334  }
335 
336  if (pkglib_path[0] == '\0')
338 }
bool IsPostmasterEnvironment
Definition: globals.c:107
static char * argv0
Definition: pg_ctl.c:94
int MyProcPid
Definition: globals.c:40
pg_time_t MyStartTime
Definition: globals.c:41
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:63
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:119
char my_exec_path[MAXPGPATH]
Definition: globals.c:71
void InitializeLatchSupport(void)
Definition: latch.c:147
#define Assert(condition)
Definition: c.h:699
void InitLatch(volatile Latch *latch)
Definition: latch.c:220
struct Latch * MyLatch
Definition: globals.c:53
#define elog
Definition: elog.h:219
char pkglib_path[MAXPGPATH]
Definition: globals.c:72

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 502 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

Referenced by GetUserIdAndContext(), is_admin_of_role(), and set_config_option().

503 {
505 }
static int SecurityRestrictionContext
Definition: miscinit.c:260
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 520 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

521 {
523 }
static int SecurityRestrictionContext
Definition: miscinit.c:260
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:299

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

Definition at line 511 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

Referenced by CheckRestrictedOperation(), DefineRelation(), is_admin_of_role(), set_config_option(), and SetUserIdAndContext().

512 {
514 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:298
static int SecurityRestrictionContext
Definition: miscinit.c:260

◆ load_libraries()

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

Definition at line 1527 of file miscinit.c.

References DEBUG1, ereport, errcode(), errmsg(), 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().

1528 {
1529  char *rawstring;
1530  List *elemlist;
1531  ListCell *l;
1532 
1533  if (libraries == NULL || libraries[0] == '\0')
1534  return; /* nothing to do */
1535 
1536  /* Need a modifiable copy of string */
1537  rawstring = pstrdup(libraries);
1538 
1539  /* Parse string into list of filename paths */
1540  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1541  {
1542  /* syntax error in list */
1543  list_free_deep(elemlist);
1544  pfree(rawstring);
1545  ereport(LOG,
1546  (errcode(ERRCODE_SYNTAX_ERROR),
1547  errmsg("invalid list syntax in parameter \"%s\"",
1548  gucname)));
1549  return;
1550  }
1551 
1552  foreach(l, elemlist)
1553  {
1554  /* Note that filename was already canonicalized */
1555  char *filename = (char *) lfirst(l);
1556  char *expanded = NULL;
1557 
1558  /* If restricting, insert $libdir/plugins if not mentioned already */
1559  if (restricted && first_dir_separator(filename) == NULL)
1560  {
1561  expanded = psprintf("$libdir/plugins/%s", filename);
1562  filename = expanded;
1563  }
1564  load_file(filename, restricted);
1565  ereport(DEBUG1,
1566  (errmsg("loaded library \"%s\"", filename)));
1567  if (expanded)
1568  pfree(expanded);
1569  }
1570 
1571  list_free_deep(elemlist);
1572  pfree(rawstring);
1573 }
#define DEBUG1
Definition: elog.h:25
char * pstrdup(const char *in)
Definition: mcxt.c:1161
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
void list_free_deep(List *list)
Definition: list.c:1147
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3417
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ereport(elevel, rest)
Definition: elog.h:122
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define lfirst(lc)
Definition: pg_list.h:106
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:137
static char * filename
Definition: pg_dumpall.c:87
int errmsg(const char *fmt,...)
Definition: elog.c:797
Definition: pg_list.h:45

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1603 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1604 {
1605 #ifdef ENABLE_NLS
1606  if (my_exec_path[0] != '\0')
1607  {
1608  char locale_path[MAXPGPATH];
1609 
1610  get_locale_path(my_exec_path, locale_path);
1611  bindtextdomain(domain, locale_path);
1612  pg_bind_textdomain_codeset(domain);
1613  }
1614 #endif
1615 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:71
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767

◆ process_session_preload_libraries()

void process_session_preload_libraries ( void  )

Definition at line 1592 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1593 {
1595  "session_preload_libraries",
1596  false);
1598  "local_preload_libraries",
1599  true);
1600 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1527
char * local_preload_libraries_string
Definition: miscinit.c:1515
char * session_preload_libraries_string
Definition: miscinit.c:1513

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1579 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1580 {
1583  "shared_preload_libraries",
1584  false);
1586 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1518
char * shared_preload_libraries_string
Definition: miscinit.c:1514
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1527

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1378 of file miscinit.c.

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

Referenced by ServerLoop().

1379 {
1380  int fd;
1381  int len;
1382  long file_pid;
1383  char buffer[BLCKSZ];
1384 
1385  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1386  if (fd < 0)
1387  {
1388  /*
1389  * There are many foreseeable false-positive error conditions. For
1390  * safety, fail only on enumerated clearly-something-is-wrong
1391  * conditions.
1392  */
1393  switch (errno)
1394  {
1395  case ENOENT:
1396  case ENOTDIR:
1397  /* disaster */
1398  ereport(LOG,
1400  errmsg("could not open file \"%s\": %m",
1402  return false;
1403  default:
1404  /* non-fatal, at least for now */
1405  ereport(LOG,
1407  errmsg("could not open file \"%s\": %m; continuing anyway",
1409  return true;
1410  }
1411  }
1413  len = read(fd, buffer, sizeof(buffer) - 1);
1415  if (len < 0)
1416  {
1417  ereport(LOG,
1419  errmsg("could not read from file \"%s\": %m",
1421  close(fd);
1422  return true; /* treat read failure as nonfatal */
1423  }
1424  buffer[len] = '\0';
1425  close(fd);
1426  file_pid = atol(buffer);
1427  if (file_pid == getpid())
1428  return true; /* all is well */
1429 
1430  /* Trouble: someone's overwritten the lock file */
1431  ereport(LOG,
1432  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1433  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1434  return false;
1435 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
#define LOG
Definition: elog.h:26
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1080
int errcode_for_file_access(void)
Definition: elog.c:598
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
#define ereport(elevel, rest)
Definition: elog.h:122
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1236
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ SetCurrentRoleId()

void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 752 of file miscinit.c.

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

Referenced by assign_role(), and ParallelWorkerMain().

753 {
754  /*
755  * Get correct info if it's SET ROLE NONE
756  *
757  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
758  * SetSessionUserId call will fix everything. This is needed since we
759  * will get called during GUC initialization.
760  */
761  if (!OidIsValid(roleid))
762  {
764  return;
765 
766  roleid = SessionUserId;
768 
769  SetRoleIsActive = false;
770  }
771  else
772  SetRoleIsActive = true;
773 
774  SetOuterUserId(roleid);
775 
776  SetConfigOption("is_superuser",
777  is_superuser ? "on" : "off",
779 }
static Oid SessionUserId
Definition: miscinit.c:252
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:398
#define OidIsValid(objectId)
Definition: c.h:605
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6917
static bool SetRoleIsActive
Definition: miscinit.c:263
static bool SessionUserIsSuperuser
Definition: miscinit.c:258
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4011

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 84 of file miscinit.c.

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

Referenced by InitPostgres().

85 {
86  /* This should happen only once per process */
89 }
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * DatabasePath
Definition: globals.c:92
#define Assert(condition)
Definition: c.h:699
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 190 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

191 {
192  char *new;
193 
194  AssertArg(dir);
195 
196  /* If presented path is relative, convert to absolute */
197  new = make_absolute_path(dir);
198 
199  if (DataDir)
200  free(DataDir);
201  DataDir = new;
202 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:701
#define free(a)
Definition: header.h:65
char * DataDir
Definition: globals.c:61

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 398 of file miscinit.c.

References AssertArg, AssertState, CurrentUserId, OidIsValid, OuterUserId, and SecurityRestrictionContext.

Referenced by SetCurrentRoleId().

399 {
401  AssertArg(OidIsValid(userid));
402  OuterUserId = userid;
403 
404  /* We force the effective user ID to match, too */
405  CurrentUserId = userid;
406 }
#define AssertState(condition)
Definition: c.h:702
static Oid OuterUserId
Definition: miscinit.c:253
#define OidIsValid(objectId)
Definition: c.h:605
static int SecurityRestrictionContext
Definition: miscinit.c:260
#define AssertArg(condition)
Definition: c.h:701
static Oid CurrentUserId
Definition: miscinit.c:254

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 706 of file miscinit.c.

References AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, ereport, errcode(), errmsg(), ERROR, OidIsValid, PGC_INTERNAL, PGC_S_OVERRIDE, SetConfigOption(), and SetSessionUserId().

Referenced by assign_session_authorization().

707 {
708  /* Must have authenticated already, else can't make permission check */
710 
711  if (userid != AuthenticatedUserId &&
713  ereport(ERROR,
714  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
715  errmsg("permission denied to set session authorization")));
716 
718 
719  SetConfigOption("is_superuser",
720  is_superuser ? "on" : "off",
722 }
#define AssertState(condition)
Definition: c.h:702
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:605
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6917
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:257
#define ereport(elevel, rest)
Definition: elog.h:122
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4011
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:421
static Oid AuthenticatedUserId
Definition: miscinit.c:251

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 421 of file miscinit.c.

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

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

422 {
424  AssertArg(OidIsValid(userid));
425  SessionUserId = userid;
427  SetRoleIsActive = false;
428 
429  /* We force the effective user IDs to match, too */
430  OuterUserId = userid;
431  CurrentUserId = userid;
432 }
#define AssertState(condition)
Definition: c.h:702
static Oid SessionUserId
Definition: miscinit.c:252
static Oid OuterUserId
Definition: miscinit.c:253
#define OidIsValid(objectId)
Definition: c.h:605
static int SecurityRestrictionContext
Definition: miscinit.c:260
#define AssertArg(condition)
Definition: c.h:701
static bool SetRoleIsActive
Definition: miscinit.c:263
static bool SessionUserIsSuperuser
Definition: miscinit.c:258
static Oid CurrentUserId
Definition: miscinit.c:254
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4011

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 540 of file miscinit.c.

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

541 {
542  /* We throw the same error SET ROLE would. */
544  ereport(ERROR,
545  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
546  errmsg("cannot set parameter \"%s\" within security-restricted operation",
547  "role")));
548  CurrentUserId = userid;
549  if (sec_def_context)
551  else
553 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:260
#define ereport(elevel, rest)
Definition: elog.h:122
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:297
static Oid CurrentUserId
Definition: miscinit.c:254
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:511
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 360 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

361 {
363  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
364 
366 
367  if (FeBeWaitSet)
369 
370  SetLatch(MyLatch);
371 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:736
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:63
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:699
struct Latch * MyLatch
Definition: globals.c:53
#define WL_LATCH_SET
Definition: latch.h:124

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 341 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

342 {
344  Assert(MyProc != NULL);
345 
347 
348  if (FeBeWaitSet)
350 
351  /*
352  * Set the shared latch as the local one might have been set. This
353  * shouldn't normally be necessary as code is supposed to check the
354  * condition before waiting for the latch, but a bit care can't hurt.
355  */
356  SetLatch(MyLatch);
357 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:736
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:63
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:699
struct Latch * MyLatch
Definition: globals.c:53
#define WL_LATCH_SET
Definition: latch.h:124

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1200 of file miscinit.c.

References buffer, close, DIRECTORY_LOCK_FILE, fd(), lfirst, PG_BINARY, and read.

Referenced by ServerLoop().

1201 {
1202  ListCell *l;
1203 
1204  foreach(l, lock_files)
1205  {
1206  char *socketLockFile = (char *) lfirst(l);
1207 
1208  /* No need to touch the data directory lock file, we trust */
1209  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1210  continue;
1211 
1212  /*
1213  * utime() is POSIX standard, utimes() is a common alternative; if we
1214  * have neither, fall back to actually reading the file (which only
1215  * sets the access time not mod time, but that should be enough in
1216  * most cases). In all paths, we ignore errors.
1217  */
1218 #ifdef HAVE_UTIME
1219  utime(socketLockFile, NULL);
1220 #else /* !HAVE_UTIME */
1221 #ifdef HAVE_UTIMES
1222  utimes(socketLockFile, NULL);
1223 #else /* !HAVE_UTIMES */
1224  int fd;
1225  char buffer[1];
1226 
1227  fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1228  if (fd >= 0)
1229  {
1230  read(fd, buffer, sizeof(buffer));
1231  close(fd);
1232  }
1233 #endif /* HAVE_UTIMES */
1234 #endif /* HAVE_UTIME */
1235  }
1236 }
static List * lock_files
Definition: miscinit.c:61
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:56
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1080
#define lfirst(lc)
Definition: pg_list.h:106
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:215
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13

◆ UnlinkLockFiles()

static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 829 of file miscinit.c.

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

Referenced by CreateLockFile().

830 {
831  ListCell *l;
832 
833  foreach(l, lock_files)
834  {
835  char *curfile = (char *) lfirst(l);
836 
837  unlink(curfile);
838  /* Should we complain if the unlink fails? */
839  }
840  /* Since we're about to exit, no need to reclaim storage */
841  lock_files = NIL;
842 
843  /*
844  * Lock file removal should always be the last externally visible action
845  * of a postmaster or standalone backend, while we won't come here at all
846  * when exiting postmaster child processes. Therefore, this is a good
847  * place to log completion of shutdown. We could alternatively teach
848  * proc_exit() to do it, but that seems uglier. In a standalone backend,
849  * use NOTICE elevel to be less chatty.
850  */
852  (errmsg("database system is shut down")));
853 }
#define NIL
Definition: pg_list.h:69
bool IsPostmasterEnvironment
Definition: globals.c:107
static List * lock_files
Definition: miscinit.c:61
#define LOG
Definition: elog.h:26
#define ereport(elevel, rest)
Definition: elog.h:122
#define NOTICE
Definition: elog.h:37
#define lfirst(lc)
Definition: pg_list.h:106
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1450 of file miscinit.c.

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

Referenced by checkDataDir(), and InitPostgres().

1451 {
1452  char full_path[MAXPGPATH];
1453  FILE *file;
1454  int ret;
1455  long file_major;
1456  long my_major;
1457  char *endptr;
1458  char file_version_string[64];
1459  const char *my_version_string = PG_VERSION;
1460 
1461  my_major = strtol(my_version_string, &endptr, 10);
1462 
1463  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1464 
1465  file = AllocateFile(full_path, "r");
1466  if (!file)
1467  {
1468  if (errno == ENOENT)
1469  ereport(FATAL,
1470  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1471  errmsg("\"%s\" is not a valid data directory",
1472  path),
1473  errdetail("File \"%s\" is missing.", full_path)));
1474  else
1475  ereport(FATAL,
1477  errmsg("could not open file \"%s\": %m", full_path)));
1478  }
1479 
1480  file_version_string[0] = '\0';
1481  ret = fscanf(file, "%63s", file_version_string);
1482  file_major = strtol(file_version_string, &endptr, 10);
1483 
1484  if (ret != 1 || endptr == file_version_string)
1485  ereport(FATAL,
1486  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1487  errmsg("\"%s\" is not a valid data directory",
1488  path),
1489  errdetail("File \"%s\" does not contain valid data.",
1490  full_path),
1491  errhint("You might need to initdb.")));
1492 
1493  FreeFile(file);
1494 
1495  if (my_major != file_major)
1496  ereport(FATAL,
1497  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1498  errmsg("database files are incompatible with server"),
1499  errdetail("The data directory was initialized by PostgreSQL version %s, "
1500  "which is not compatible with this version %s.",
1501  file_version_string, my_version_string)));
1502 }
int errhint(const char *fmt,...)
Definition: elog.c:987
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2336
#define ereport(elevel, rest)
Definition: elog.h:122
int FreeFile(FILE *file)
Definition: fd.c:2528
int errmsg(const char *fmt,...)
Definition: elog.c:797

Variable Documentation

◆ AuthenticatedUserId

◆ AuthenticatedUserIsSuperuser

bool AuthenticatedUserIsSuperuser = false
static

◆ CurrentUserId

◆ IgnoreSystemIndexes

bool IgnoreSystemIndexes = false

◆ local_preload_libraries_string

char* local_preload_libraries_string = NULL

Definition at line 1515 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

Definition at line 63 of file miscinit.c.

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

◆ lock_files

List* lock_files = NIL
static

Definition at line 61 of file miscinit.c.

◆ Mode

Definition at line 58 of file miscinit.c.

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 253 of file miscinit.c.

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

◆ process_shared_preload_libraries_in_progress

bool process_shared_preload_libraries_in_progress = false

◆ SecurityRestrictionContext

◆ session_preload_libraries_string

char* session_preload_libraries_string = NULL

Definition at line 1513 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 252 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 258 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 263 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1514 of file miscinit.c.

Referenced by process_shared_preload_libraries().