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

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 1254 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().

1255 {
1256  int fd;
1257  int len;
1258  int lineno;
1259  char *srcptr;
1260  char *destptr;
1261  char srcbuffer[BLCKSZ];
1262  char destbuffer[BLCKSZ];
1263 
1264  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1265  if (fd < 0)
1266  {
1267  ereport(LOG,
1269  errmsg("could not open file \"%s\": %m",
1271  return;
1272  }
1274  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1276  if (len < 0)
1277  {
1278  ereport(LOG,
1280  errmsg("could not read from file \"%s\": %m",
1282  close(fd);
1283  return;
1284  }
1285  srcbuffer[len] = '\0';
1286 
1287  /*
1288  * Advance over lines we are not supposed to rewrite, then copy them to
1289  * destbuffer.
1290  */
1291  srcptr = srcbuffer;
1292  for (lineno = 1; lineno < target_line; lineno++)
1293  {
1294  char *eol = strchr(srcptr, '\n');
1295 
1296  if (eol == NULL)
1297  break; /* not enough lines in file yet */
1298  srcptr = eol + 1;
1299  }
1300  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1301  destptr = destbuffer + (srcptr - srcbuffer);
1302 
1303  /*
1304  * Fill in any missing lines before the target line, in case lines are
1305  * added to the file out of order.
1306  */
1307  for (; lineno < target_line; lineno++)
1308  {
1309  if (destptr < destbuffer + sizeof(destbuffer))
1310  *destptr++ = '\n';
1311  }
1312 
1313  /*
1314  * Write or rewrite the target line.
1315  */
1316  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1317  destptr += strlen(destptr);
1318 
1319  /*
1320  * If there are more lines in the old file, append them to destbuffer.
1321  */
1322  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1323  {
1324  srcptr++;
1325  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1326  srcptr);
1327  }
1328 
1329  /*
1330  * And rewrite the data. Since we write in a single kernel call, this
1331  * update should appear atomic to onlookers.
1332  */
1333  len = strlen(destbuffer);
1334  errno = 0;
1336  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1337  (int) write(fd, destbuffer, len) != len)
1338  {
1340  /* if write didn't set errno, assume problem is no disk space */
1341  if (errno == 0)
1342  errno = ENOSPC;
1343  ereport(LOG,
1345  errmsg("could not write to file \"%s\": %m",
1347  close(fd);
1348  return;
1349  }
1352  if (pg_fsync(fd) != 0)
1353  {
1354  ereport(LOG,
1356  errmsg("could not write to file \"%s\": %m",
1358  }
1360  if (close(fd) != 0)
1361  {
1362  ereport(LOG,
1364  errmsg("could not write to file \"%s\": %m",
1366  }
1367 }
#define write(a, b, c)
Definition: win32.h:14
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#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:1222
int errcode_for_file_access(void)
Definition: elog.c:631
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
#define ereport(elevel, rest)
Definition: elog.h:141
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1318
int errmsg(const char *fmt,...)
Definition: elog.c:822
int pg_fsync(int fd)
Definition: fd.c:330
#define close(a)
Definition: win32.h:12
#define snprintf
Definition: port.h:192
#define read(a, b, c)
Definition: win32.h:13

◆ ChangeToDataDir()

void ChangeToDataDir ( void  )

Definition at line 213 of file miscinit.c.

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

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

214 {
216 
217  if (chdir(DataDir) < 0)
218  ereport(FATAL,
220  errmsg("could not change directory to \"%s\": %m",
221  DataDir)));
222 }
#define AssertState(condition)
Definition: c.h:742
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:631
#define ereport(elevel, rest)
Definition: elog.h:141
int errmsg(const char *fmt,...)
Definition: elog.c:822
char * DataDir
Definition: globals.c:62

◆ checkDataDir()

void checkDataDir ( void  )

Definition at line 99 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().

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

◆ CreateDataDirLockFile()

void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1177 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1178 {
1179  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1180 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:872
char * DataDir
Definition: globals.c:62

◆ CreateLockFile()

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

Definition at line 872 of file miscinit.c.

References 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().

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

References CreateLockFile(), MAXPGPATH, and snprintf.

Referenced by StreamServerPort().

1188 {
1189  char lockfile[MAXPGPATH];
1190 
1191  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1192  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1193 }
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:872
#define MAXPGPATH
#define snprintf
Definition: port.h:192

◆ GetAuthenticatedUserId()

Oid GetAuthenticatedUserId ( void  )

Definition at line 439 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

440 {
442  return AuthenticatedUserId;
443 }
#define AssertState(condition)
Definition: c.h:742
#define OidIsValid(objectId)
Definition: c.h:645
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ GetCurrentRoleId()

Oid GetCurrentRoleId ( void  )

Definition at line 739 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by InitializeParallelDSM(), and show_role().

740 {
741  if (SetRoleIsActive)
742  return OuterUserId;
743  else
744  return InvalidOid;
745 }
static Oid OuterUserId
Definition: miscinit.c:255
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:265

◆ GetOuterUserId()

Oid GetOuterUserId ( void  )

Definition at line 391 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

392 {
394  return OuterUserId;
395 }
#define AssertState(condition)
Definition: c.h:742
static Oid OuterUserId
Definition: miscinit.c:255
#define OidIsValid(objectId)
Definition: c.h:645

◆ GetSessionUserId()

Oid GetSessionUserId ( void  )

Definition at line 414 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().

415 {
417  return SessionUserId;
418 }
#define AssertState(condition)
Definition: c.h:742
static Oid SessionUserId
Definition: miscinit.c:254
#define OidIsValid(objectId)
Definition: c.h:645

◆ GetUserId()

Oid GetUserId ( void  )

Definition at line 380 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(), AlterStatistics(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), 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_explain_guc_options(), 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(), ShowAllGUCConfig(), statext_is_compatible_clause(), superuser(), TerminateOtherDBBackends(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_is_relation_owner(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

381 {
383  return CurrentUserId;
384 }
#define AssertState(condition)
Definition: c.h:742
#define OidIsValid(objectId)
Definition: c.h:645
static Oid CurrentUserId
Definition: miscinit.c:256

◆ GetUserIdAndContext()

void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 534 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

535 {
536  *userid = CurrentUserId;
537  *sec_def_context = InLocalUserIdChange();
538 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:503
static Oid CurrentUserId
Definition: miscinit.c:256

◆ GetUserIdAndSecContext()

void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)

◆ GetUserNameFromId()

char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 795 of file miscinit.c.

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

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

796 {
797  HeapTuple tuple;
798  char *result;
799 
800  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
801  if (!HeapTupleIsValid(tuple))
802  {
803  if (!noerr)
804  ereport(ERROR,
805  (errcode(ERRCODE_UNDEFINED_OBJECT),
806  errmsg("invalid role OID: %u", roleid)));
807  result = NULL;
808  }
809  else
810  {
811  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
812  ReleaseSysCache(tuple);
813  }
814  return result;
815 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
NameData rolname
Definition: pg_authid.h:34
char * pstrdup(const char *in)
Definition: mcxt.c:1186
int errcode(int sqlerrcode)
Definition: elog.c:608
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:141
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1116
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1164
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define NameStr(name)
Definition: c.h:616

◆ has_rolreplication()

bool has_rolreplication ( Oid  roleid)

Definition at line 561 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

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

◆ InitializeSessionUserId()

void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 579 of file miscinit.c.

References AcceptInvalidationMessages(), AssertState, AuthenticatedUserId, AuthenticatedUserIsSuperuser, AUTHNAME, AUTHOID, CountUserBackends(), ereport, errcode(), errmsg(), FATAL, GETSTRUCT, 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().

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

◆ InitializeSessionUserIdStandalone()

void InitializeSessionUserIdStandalone ( void  )

Definition at line 682 of file miscinit.c.

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

Referenced by InitPostgres().

683 {
684  /*
685  * This function should only be called in single-user mode, in autovacuum
686  * workers, and in background workers.
687  */
689 
690  /* call only once */
692 
693  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
695 
696  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
697 }
#define AssertState(condition)
Definition: c.h:742
#define OidIsValid(objectId)
Definition: c.h:645
bool IsBackgroundWorker
Definition: globals.c:111
bool IsUnderPostmaster
Definition: globals.c:109
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:259
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3281
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:422
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ InitPostmasterChild()

void InitPostmasterChild ( void  )

Definition at line 273 of file miscinit.c.

References elog, FATAL, InitializeLatchSupport(), InitLatch(), InitProcessGlobals(), IsUnderPostmaster, LocalLatchData, MyLatch, on_exit_reset(), and PostmasterDeathSignalInit().

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

274 {
275  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
276 
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 
308  /* Request a signal if the postmaster dies, if possible. */
310 }
void InitLatch(Latch *latch)
Definition: latch.c:228
void InitProcessGlobals(void)
Definition: postmaster.c:2597
void on_exit_reset(void)
Definition: ipc.c:409
static Latch LocalLatchData
Definition: miscinit.c:65
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:109
void InitializeLatchSupport(void)
Definition: latch.c:155
#define elog(elevel,...)
Definition: elog.h:228
struct Latch * MyLatch
Definition: globals.c:54
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:370

◆ InitStandaloneProcess()

void InitStandaloneProcess ( const char *  argv0)

Definition at line 318 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), and PostgresMain().

319 {
321 
323 
324  /* Initialize process-local latch support */
328 
329  /* Compute paths, no postmaster to inherit from */
330  if (my_exec_path[0] == '\0')
331  {
332  if (find_my_exec(argv0, my_exec_path) < 0)
333  elog(FATAL, "%s: could not locate my own executable path",
334  argv0);
335  }
336 
337  if (pkglib_path[0] == '\0')
339 }
bool IsPostmasterEnvironment
Definition: globals.c:108
static char * argv0
Definition: pg_ctl.c:97
void InitLatch(Latch *latch)
Definition: latch.c:228
void InitProcessGlobals(void)
Definition: postmaster.c:2597
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:65
#define FATAL
Definition: elog.h:52
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:129
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
void InitializeLatchSupport(void)
Definition: latch.c:155
#define Assert(condition)
Definition: c.h:739
#define elog(elevel,...)
Definition: elog.h:228
struct Latch * MyLatch
Definition: globals.c:54
char pkglib_path[MAXPGPATH]
Definition: globals.c:73

◆ InLocalUserIdChange()

bool InLocalUserIdChange ( void  )

Definition at line 503 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

504 {
506 }
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:299

◆ InNoForceRLSOperation()

bool InNoForceRLSOperation ( void  )

Definition at line 521 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

522 {
524 }
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:301

◆ InSecurityRestrictedOperation()

bool InSecurityRestrictedOperation ( void  )

Definition at line 512 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

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

513 {
515 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:300
static int SecurityRestrictionContext
Definition: miscinit.c:262

◆ load_libraries()

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

Definition at line 1531 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().

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

◆ pg_bindtextdomain()

void pg_bindtextdomain ( const char *  domain)

Definition at line 1607 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1608 {
1609 #ifdef ENABLE_NLS
1610  if (my_exec_path[0] != '\0')
1611  {
1612  char locale_path[MAXPGPATH];
1613 
1614  get_locale_path(my_exec_path, locale_path);
1615  bindtextdomain(domain, locale_path);
1616  pg_bind_textdomain_codeset(domain);
1617  }
1618 #endif
1619 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:72
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 1596 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1597 {
1599  "session_preload_libraries",
1600  false);
1602  "local_preload_libraries",
1603  true);
1604 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1531
char * local_preload_libraries_string
Definition: miscinit.c:1519
char * session_preload_libraries_string
Definition: miscinit.c:1517

◆ process_shared_preload_libraries()

void process_shared_preload_libraries ( void  )

Definition at line 1583 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by BackendRun(), and PostmasterMain().

1584 {
1587  "shared_preload_libraries",
1588  false);
1590 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1522
char * shared_preload_libraries_string
Definition: miscinit.c:1518
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1531

◆ RecheckDataDirLockFile()

bool RecheckDataDirLockFile ( void  )

Definition at line 1382 of file miscinit.c.

References 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().

1383 {
1384  int fd;
1385  int len;
1386  long file_pid;
1387  char buffer[BLCKSZ];
1388 
1389  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1390  if (fd < 0)
1391  {
1392  /*
1393  * There are many foreseeable false-positive error conditions. For
1394  * safety, fail only on enumerated clearly-something-is-wrong
1395  * conditions.
1396  */
1397  switch (errno)
1398  {
1399  case ENOENT:
1400  case ENOTDIR:
1401  /* disaster */
1402  ereport(LOG,
1404  errmsg("could not open file \"%s\": %m",
1406  return false;
1407  default:
1408  /* non-fatal, at least for now */
1409  ereport(LOG,
1411  errmsg("could not open file \"%s\": %m; continuing anyway",
1413  return true;
1414  }
1415  }
1417  len = read(fd, buffer, sizeof(buffer) - 1);
1419  if (len < 0)
1420  {
1421  ereport(LOG,
1423  errmsg("could not read from file \"%s\": %m",
1425  close(fd);
1426  return true; /* treat read failure as nonfatal */
1427  }
1428  buffer[len] = '\0';
1429  close(fd);
1430  file_pid = atol(buffer);
1431  if (file_pid == getpid())
1432  return true; /* all is well */
1433 
1434  /* Trouble: someone's overwritten the lock file */
1435  ereport(LOG,
1436  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1437  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1438  return false;
1439 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:58
#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:1222
int errcode_for_file_access(void)
Definition: elog.c:631
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1342
#define ereport(elevel, rest)
Definition: elog.h:141
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: pgstat.h:1318
int errmsg(const char *fmt,...)
Definition: elog.c:822
#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 760 of file miscinit.c.

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

Referenced by assign_role(), and ParallelWorkerMain().

761 {
762  /*
763  * Get correct info if it's SET ROLE NONE
764  *
765  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
766  * SetSessionUserId call will fix everything. This is needed since we
767  * will get called during GUC initialization.
768  */
769  if (!OidIsValid(roleid))
770  {
772  return;
773 
774  roleid = SessionUserId;
776 
777  SetRoleIsActive = false;
778  }
779  else
780  SetRoleIsActive = true;
781 
782  SetOuterUserId(roleid);
783 
784  SetConfigOption("is_superuser",
785  is_superuser ? "on" : "off",
787 }
static Oid SessionUserId
Definition: miscinit.c:254
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:399
#define OidIsValid(objectId)
Definition: c.h:645
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7550
static bool SetRoleIsActive
Definition: miscinit.c:265
static bool SessionUserIsSuperuser
Definition: miscinit.c:260
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4077

◆ SetDatabasePath()

void SetDatabasePath ( const char *  path)

Definition at line 86 of file miscinit.c.

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

Referenced by InitPostgres().

87 {
88  /* This should happen only once per process */
91 }
MemoryContext TopMemoryContext
Definition: mcxt.c:44
char * DatabasePath
Definition: globals.c:93
#define Assert(condition)
Definition: c.h:739
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1173

◆ SetDataDir()

void SetDataDir ( const char *  dir)

Definition at line 192 of file miscinit.c.

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

Referenced by PostmasterMarkPIDForWorkerNotify(), and SelectConfigFiles().

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

◆ SetOuterUserId()

static void SetOuterUserId ( Oid  userid)
static

Definition at line 399 of file miscinit.c.

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

Referenced by SetCurrentRoleId().

400 {
402  AssertArg(OidIsValid(userid));
403  OuterUserId = userid;
404 
405  /* We force the effective user ID to match, too */
406  CurrentUserId = userid;
407 }
#define AssertState(condition)
Definition: c.h:742
static Oid OuterUserId
Definition: miscinit.c:255
#define OidIsValid(objectId)
Definition: c.h:645
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define AssertArg(condition)
Definition: c.h:741
static Oid CurrentUserId
Definition: miscinit.c:256

◆ SetSessionAuthorization()

void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

Definition at line 714 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().

715 {
716  /* Must have authenticated already, else can't make permission check */
718 
719  if (userid != AuthenticatedUserId &&
721  ereport(ERROR,
722  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
723  errmsg("permission denied to set session authorization")));
724 
726 
727  SetConfigOption("is_superuser",
728  is_superuser ? "on" : "off",
730 }
#define AssertState(condition)
Definition: c.h:742
int errcode(int sqlerrcode)
Definition: elog.c:608
#define OidIsValid(objectId)
Definition: c.h:645
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:7550
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:259
#define ereport(elevel, rest)
Definition: elog.h:141
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4077
int errmsg(const char *fmt,...)
Definition: elog.c:822
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:422
static Oid AuthenticatedUserId
Definition: miscinit.c:253

◆ SetSessionUserId()

static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 422 of file miscinit.c.

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

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

423 {
425  AssertArg(OidIsValid(userid));
426  SessionUserId = userid;
428  SetRoleIsActive = false;
429 
430  /* We force the effective user IDs to match, too */
431  OuterUserId = userid;
432  CurrentUserId = userid;
433 }
#define AssertState(condition)
Definition: c.h:742
static Oid SessionUserId
Definition: miscinit.c:254
static Oid OuterUserId
Definition: miscinit.c:255
#define OidIsValid(objectId)
Definition: c.h:645
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define AssertArg(condition)
Definition: c.h:741
static bool SetRoleIsActive
Definition: miscinit.c:265
static bool SessionUserIsSuperuser
Definition: miscinit.c:260
static Oid CurrentUserId
Definition: miscinit.c:256
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4077

◆ SetUserIdAndContext()

void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 541 of file miscinit.c.

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

542 {
543  /* We throw the same error SET ROLE would. */
545  ereport(ERROR,
546  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
547  errmsg("cannot set parameter \"%s\" within security-restricted operation",
548  "role")));
549  CurrentUserId = userid;
550  if (sec_def_context)
552  else
554 }
int errcode(int sqlerrcode)
Definition: elog.c:608
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:262
#define ereport(elevel, rest)
Definition: elog.h:141
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:299
static Oid CurrentUserId
Definition: miscinit.c:256
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:512
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ SetUserIdAndSecContext()

void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)

◆ SwitchBackToLocalLatch()

void SwitchBackToLocalLatch ( void  )

Definition at line 361 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

362 {
364  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
365 
367 
368  if (FeBeWaitSet)
370 
371  SetLatch(MyLatch);
372 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:766
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:186
void SetLatch(Latch *latch)
Definition: latch.c:436
Latch procLatch
Definition: proc.h:104
static Latch LocalLatchData
Definition: miscinit.c:65
#define Assert(condition)
Definition: c.h:739
struct Latch * MyLatch
Definition: globals.c:54
#define WL_LATCH_SET
Definition: latch.h:124

◆ SwitchToSharedLatch()

void SwitchToSharedLatch ( void  )

Definition at line 342 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

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

◆ TouchSocketLockFiles()

void TouchSocketLockFiles ( void  )

Definition at line 1204 of file miscinit.c.

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

Referenced by ServerLoop().

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

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

Referenced by CreateLockFile().

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

◆ ValidatePgVersion()

void ValidatePgVersion ( const char *  path)

Definition at line 1454 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().

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

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

Referenced by process_session_preload_libraries().

◆ LocalLatchData

Latch LocalLatchData
static

Definition at line 65 of file miscinit.c.

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

◆ lock_files

List* lock_files = NIL
static

Definition at line 63 of file miscinit.c.

◆ Mode

Definition at line 60 of file miscinit.c.

◆ OuterUserId

Oid OuterUserId = InvalidOid
static

Definition at line 255 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 1517 of file miscinit.c.

Referenced by process_session_preload_libraries().

◆ SessionUserId

Oid SessionUserId = InvalidOid
static

Definition at line 254 of file miscinit.c.

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

◆ SessionUserIsSuperuser

bool SessionUserIsSuperuser = false
static

Definition at line 260 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

◆ SetRoleIsActive

bool SetRoleIsActive = false
static

Definition at line 265 of file miscinit.c.

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

◆ shared_preload_libraries_string

char* shared_preload_libraries_string = NULL

Definition at line 1518 of file miscinit.c.

Referenced by process_shared_preload_libraries().