PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 "libpq/libpq.h"
#include "mb/pg_wchar.h"
#include "miscadmin.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/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 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

#define DIRECTORY_LOCK_FILE   "postmaster.pid"

Function Documentation

void AddToDataDirLockFile ( int  target_line,
const char *  str 
)

Definition at line 1148 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, elog, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, NULL, PG_BINARY, pg_fsync(), read, snprintf(), and write.

Referenced by InternalIpcMemoryCreate(), and PostmasterMain().

1149 {
1150  int fd;
1151  int len;
1152  int lineno;
1153  char *srcptr;
1154  char *destptr;
1155  char srcbuffer[BLCKSZ];
1156  char destbuffer[BLCKSZ];
1157 
1158  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1159  if (fd < 0)
1160  {
1161  ereport(LOG,
1163  errmsg("could not open file \"%s\": %m",
1165  return;
1166  }
1167  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1168  if (len < 0)
1169  {
1170  ereport(LOG,
1172  errmsg("could not read from file \"%s\": %m",
1174  close(fd);
1175  return;
1176  }
1177  srcbuffer[len] = '\0';
1178 
1179  /*
1180  * Advance over lines we are not supposed to rewrite, then copy them to
1181  * destbuffer.
1182  */
1183  srcptr = srcbuffer;
1184  for (lineno = 1; lineno < target_line; lineno++)
1185  {
1186  if ((srcptr = strchr(srcptr, '\n')) == NULL)
1187  {
1188  elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
1189  DIRECTORY_LOCK_FILE, lineno - 1, target_line);
1190  close(fd);
1191  return;
1192  }
1193  srcptr++;
1194  }
1195  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1196  destptr = destbuffer + (srcptr - srcbuffer);
1197 
1198  /*
1199  * Write or rewrite the target line.
1200  */
1201  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1202  destptr += strlen(destptr);
1203 
1204  /*
1205  * If there are more lines in the old file, append them to destbuffer.
1206  */
1207  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1208  {
1209  srcptr++;
1210  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1211  srcptr);
1212  }
1213 
1214  /*
1215  * And rewrite the data. Since we write in a single kernel call, this
1216  * update should appear atomic to onlookers.
1217  */
1218  len = strlen(destbuffer);
1219  errno = 0;
1220  if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1221  (int) write(fd, destbuffer, len) != len)
1222  {
1223  /* if write didn't set errno, assume problem is no disk space */
1224  if (errno == 0)
1225  errno = ENOSPC;
1226  ereport(LOG,
1228  errmsg("could not write to file \"%s\": %m",
1230  close(fd);
1231  return;
1232  }
1233  if (pg_fsync(fd) != 0)
1234  {
1235  ereport(LOG,
1237  errmsg("could not write to file \"%s\": %m",
1239  }
1240  if (close(fd) != 0)
1241  {
1242  ereport(LOG,
1244  errmsg("could not write to file \"%s\": %m",
1246  }
1247 }
#define write(a, b, c)
Definition: win32.h:19
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
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:1038
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
int pg_fsync(int fd)
Definition: fd.c:333
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
void ChangeToDataDir ( void  )

Definition at line 114 of file miscinit.c.

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

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

115 {
117 
118  if (chdir(DataDir) < 0)
119  ereport(FATAL,
121  errmsg("could not change directory to \"%s\": %m",
122  DataDir)));
123 }
#define AssertState(condition)
Definition: c.h:674
#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:59
void CreateDataDirLockFile ( bool  amPostmaster)

Definition at line 1072 of file miscinit.c.

References CreateLockFile(), DataDir, and DIRECTORY_LOCK_FILE.

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

1073 {
1074  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1075 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:767
char * DataDir
Definition: globals.c:59
static void CreateLockFile ( const char *  filename,
bool  amPostmaster,
const char *  socketDir,
bool  isDDLock,
const char *  refName 
)
static

Definition at line 767 of file miscinit.c.

References close, DataDir, elog, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), lcons(), LOCK_FILE_LINE_SHMEM_KEY, MAXPGPATH, MyStartTime, NIL, NULL, on_proc_exit(), pg_fsync(), PGSharedMemoryIsInUse(), PostPortNumber, pstrdup(), read, snprintf(), strlcat(), unlink(), UnlinkLockFiles(), and write.

Referenced by CreateDataDirLockFile(), and CreateSocketLockFile().

770 {
771  int fd;
772  char buffer[MAXPGPATH * 2 + 256];
773  int ntries;
774  int len;
775  int encoded_pid;
776  pid_t other_pid;
777  pid_t my_pid,
778  my_p_pid,
779  my_gp_pid;
780  const char *envvar;
781 
782  /*
783  * If the PID in the lockfile is our own PID or our parent's or
784  * grandparent's PID, then the file must be stale (probably left over from
785  * a previous system boot cycle). We need to check this because of the
786  * likelihood that a reboot will assign exactly the same PID as we had in
787  * the previous reboot, or one that's only one or two counts larger and
788  * hence the lockfile's PID now refers to an ancestor shell process. We
789  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
790  * via the environment variable PG_GRANDPARENT_PID; this is so that
791  * launching the postmaster via pg_ctl can be just as reliable as
792  * launching it directly. There is no provision for detecting
793  * further-removed ancestor processes, but if the init script is written
794  * carefully then all but the immediate parent shell will be root-owned
795  * processes and so the kill test will fail with EPERM. Note that we
796  * cannot get a false negative this way, because an existing postmaster
797  * would surely never launch a competing postmaster or pg_ctl process
798  * directly.
799  */
800  my_pid = getpid();
801 
802 #ifndef WIN32
803  my_p_pid = getppid();
804 #else
805 
806  /*
807  * Windows hasn't got getppid(), but doesn't need it since it's not using
808  * real kill() either...
809  */
810  my_p_pid = 0;
811 #endif
812 
813  envvar = getenv("PG_GRANDPARENT_PID");
814  if (envvar)
815  my_gp_pid = atoi(envvar);
816  else
817  my_gp_pid = 0;
818 
819  /*
820  * We need a loop here because of race conditions. But don't loop forever
821  * (for example, a non-writable $PGDATA directory might cause a failure
822  * that won't go away). 100 tries seems like plenty.
823  */
824  for (ntries = 0;; ntries++)
825  {
826  /*
827  * Try to create the lock file --- O_EXCL makes this atomic.
828  *
829  * Think not to make the file protection weaker than 0600. See
830  * comments below.
831  */
832  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
833  if (fd >= 0)
834  break; /* Success; exit the retry loop */
835 
836  /*
837  * Couldn't create the pid file. Probably it already exists.
838  */
839  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
840  ereport(FATAL,
842  errmsg("could not create lock file \"%s\": %m",
843  filename)));
844 
845  /*
846  * Read the file to get the old owner's PID. Note race condition
847  * here: file might have been deleted since we tried to create it.
848  */
849  fd = open(filename, O_RDONLY, 0600);
850  if (fd < 0)
851  {
852  if (errno == ENOENT)
853  continue; /* race condition; try again */
854  ereport(FATAL,
856  errmsg("could not open lock file \"%s\": %m",
857  filename)));
858  }
859  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
860  ereport(FATAL,
862  errmsg("could not read lock file \"%s\": %m",
863  filename)));
864  close(fd);
865 
866  if (len == 0)
867  {
868  ereport(FATAL,
869  (errcode(ERRCODE_LOCK_FILE_EXISTS),
870  errmsg("lock file \"%s\" is empty", filename),
871  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
872  }
873 
874  buffer[len] = '\0';
875  encoded_pid = atoi(buffer);
876 
877  /* if pid < 0, the pid is for postgres, not postmaster */
878  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
879 
880  if (other_pid <= 0)
881  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
882  filename, buffer);
883 
884  /*
885  * Check to see if the other process still exists
886  *
887  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
888  * ignored as false matches.
889  *
890  * Normally kill() will fail with ESRCH if the given PID doesn't
891  * exist.
892  *
893  * We can treat the EPERM-error case as okay because that error
894  * implies that the existing process has a different userid than we
895  * do, which means it cannot be a competing postmaster. A postmaster
896  * cannot successfully attach to a data directory owned by a userid
897  * other than its own. (This is now checked directly in
898  * checkDataDir(), but has been true for a long time because of the
899  * restriction that the data directory isn't group- or
900  * world-accessible.) Also, since we create the lockfiles mode 600,
901  * we'd have failed above if the lockfile belonged to another userid
902  * --- which means that whatever process kill() is reporting about
903  * isn't the one that made the lockfile. (NOTE: this last
904  * consideration is the only one that keeps us from blowing away a
905  * Unix socket file belonging to an instance of Postgres being run by
906  * someone else, at least on machines where /tmp hasn't got a
907  * stickybit.)
908  */
909  if (other_pid != my_pid && other_pid != my_p_pid &&
910  other_pid != my_gp_pid)
911  {
912  if (kill(other_pid, 0) == 0 ||
913  (errno != ESRCH && errno != EPERM))
914  {
915  /* lockfile belongs to a live process */
916  ereport(FATAL,
917  (errcode(ERRCODE_LOCK_FILE_EXISTS),
918  errmsg("lock file \"%s\" already exists",
919  filename),
920  isDDLock ?
921  (encoded_pid < 0 ?
922  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
923  (int) other_pid, refName) :
924  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
925  (int) other_pid, refName)) :
926  (encoded_pid < 0 ?
927  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
928  (int) other_pid, refName) :
929  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
930  (int) other_pid, refName))));
931  }
932  }
933 
934  /*
935  * No, the creating process did not exist. However, it could be that
936  * the postmaster crashed (or more likely was kill -9'd by a clueless
937  * admin) but has left orphan backends behind. Check for this by
938  * looking to see if there is an associated shmem segment that is
939  * still in use.
940  *
941  * Note: because postmaster.pid is written in multiple steps, we might
942  * not find the shmem ID values in it; we can't treat that as an
943  * error.
944  */
945  if (isDDLock)
946  {
947  char *ptr = buffer;
948  unsigned long id1,
949  id2;
950  int lineno;
951 
952  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
953  {
954  if ((ptr = strchr(ptr, '\n')) == NULL)
955  break;
956  ptr++;
957  }
958 
959  if (ptr != NULL &&
960  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
961  {
962  if (PGSharedMemoryIsInUse(id1, id2))
963  ereport(FATAL,
964  (errcode(ERRCODE_LOCK_FILE_EXISTS),
965  errmsg("pre-existing shared memory block "
966  "(key %lu, ID %lu) is still in use",
967  id1, id2),
968  errhint("If you're sure there are no old "
969  "server processes still running, remove "
970  "the shared memory block "
971  "or just delete the file \"%s\".",
972  filename)));
973  }
974  }
975 
976  /*
977  * Looks like nobody's home. Unlink the file and try again to create
978  * it. Need a loop because of possible race condition against other
979  * would-be creators.
980  */
981  if (unlink(filename) < 0)
982  ereport(FATAL,
984  errmsg("could not remove old lock file \"%s\": %m",
985  filename),
986  errhint("The file seems accidentally left over, but "
987  "it could not be removed. Please remove the file "
988  "by hand and try again.")));
989  }
990 
991  /*
992  * Successfully created the file, now fill it. See comment in miscadmin.h
993  * about the contents. Note that we write the same first five lines into
994  * both datadir and socket lockfiles; although more stuff may get added to
995  * the datadir lockfile later.
996  */
997  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
998  amPostmaster ? (int) my_pid : -((int) my_pid),
999  DataDir,
1000  (long) MyStartTime,
1002  socketDir);
1003 
1004  /*
1005  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1006  * will never receive data, so fill it in as empty now.
1007  */
1008  if (isDDLock && !amPostmaster)
1009  strlcat(buffer, "\n", sizeof(buffer));
1010 
1011  errno = 0;
1012  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1013  {
1014  int save_errno = errno;
1015 
1016  close(fd);
1017  unlink(filename);
1018  /* if write didn't set errno, assume problem is no disk space */
1019  errno = save_errno ? save_errno : ENOSPC;
1020  ereport(FATAL,
1022  errmsg("could not write lock file \"%s\": %m", filename)));
1023  }
1024  if (pg_fsync(fd) != 0)
1025  {
1026  int save_errno = errno;
1027 
1028  close(fd);
1029  unlink(filename);
1030  errno = save_errno;
1031  ereport(FATAL,
1033  errmsg("could not write lock file \"%s\": %m", filename)));
1034  }
1035  if (close(fd) != 0)
1036  {
1037  int save_errno = errno;
1038 
1039  unlink(filename);
1040  errno = save_errno;
1041  ereport(FATAL,
1043  errmsg("could not write lock file \"%s\": %m", filename)));
1044  }
1045 
1046  /*
1047  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1048  * one, set up the on_proc_exit function to do it; then add this lock file
1049  * to the list of files to unlink.
1050  */
1051  if (lock_files == NIL)
1053 
1054  /*
1055  * Use lcons so that the lock files are unlinked in reverse order of
1056  * creation; this is critical!
1057  */
1059 }
#define NIL
Definition: pg_list.h:69
int errhint(const char *fmt,...)
Definition: elog.c:987
#define write(a, b, c)
Definition: win32.h:19
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:292
static List * lock_files
Definition: miscinit.c:58
char * pstrdup(const char *in)
Definition: mcxt.c:1165
pg_time_t MyStartTime
Definition: globals.c:39
int errcode(int sqlerrcode)
Definition: elog.c:575
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:194
#define FATAL
Definition: elog.h:52
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:598
int unlink(const char *filename)
#define ereport(elevel, rest)
Definition: elog.h:122
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: miscadmin.h:452
List * lcons(void *datum, List *list)
Definition: list.c:259
#define NULL
Definition: c.h:226
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:267
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:732
static char * filename
Definition: pg_dumpall.c:80
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * DataDir
Definition: globals.c:59
int pg_fsync(int fd)
Definition: fd.c:333
#define elog
Definition: elog.h:219
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
void CreateSocketLockFile ( const char *  socketfile,
bool  amPostmaster,
const char *  socketDir 
)

Definition at line 1081 of file miscinit.c.

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

1083 {
1084  char lockfile[MAXPGPATH];
1085 
1086  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1087  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1088 }
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:767
#define MAXPGPATH
Oid GetAuthenticatedUserId ( void  )

Definition at line 341 of file miscinit.c.

References AssertState, AuthenticatedUserId, and OidIsValid.

Referenced by InitializeParallelDSM().

342 {
344  return AuthenticatedUserId;
345 }
#define AssertState(condition)
Definition: c.h:674
#define OidIsValid(objectId)
Definition: c.h:534
static Oid AuthenticatedUserId
Definition: miscinit.c:154
Oid GetCurrentRoleId ( void  )

Definition at line 634 of file miscinit.c.

References InvalidOid, OuterUserId, and SetRoleIsActive.

Referenced by show_role().

635 {
636  if (SetRoleIsActive)
637  return OuterUserId;
638  else
639  return InvalidOid;
640 }
static Oid OuterUserId
Definition: miscinit.c:156
#define InvalidOid
Definition: postgres_ext.h:36
static bool SetRoleIsActive
Definition: miscinit.c:166
Oid GetOuterUserId ( void  )

Definition at line 293 of file miscinit.c.

References AssertState, OidIsValid, and OuterUserId.

Referenced by DropRole(), and RenameRole().

294 {
296  return OuterUserId;
297 }
#define AssertState(condition)
Definition: c.h:674
static Oid OuterUserId
Definition: miscinit.c:156
#define OidIsValid(objectId)
Definition: c.h:534
Oid GetSessionUserId ( void  )

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

317 {
319  return SessionUserId;
320 }
#define AssertState(condition)
Definition: c.h:674
static Oid SessionUserId
Definition: miscinit.c:155
#define OidIsValid(objectId)
Definition: c.h:534
Oid GetUserId ( void  )

Definition at line 282 of file miscinit.c.

References AssertState, CurrentUserId, and OidIsValid.

Referenced by AddRoleMems(), AggregateCreate(), 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(), AlterSequence(), AlterSubscription(), AlterSubscriptionOwner_internal(), AlterTableMoveAll(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespace_oid(), AlterTypeOwner(), analyze_rel(), ATExecAddColumn(), ATExecChangeOwner(), ATPrepAlterColumnType(), ATPrepSetStatistics(), ATPrepSetTableSpace(), ATSimplePermissions(), be_lo_unlink(), binary_upgrade_create_empty_extension(), brin_summarize_new_values(), build_join_rel(), BuildCachedPlan(), BuildDescForRelation(), BuildIndexValueDescription(), calculate_database_size(), calculate_tablespace_size(), 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(), CreateCast(), CreateConversionCommand(), createdb(), CreateEventTrigger(), CreateExtensionInternal(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateFunction(), CreateOpFamily(), CreateProceduralLanguage(), CreatePublication(), CreateRole(), 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(), dropdb(), DropOwnedObjects(), DropRole(), DropSubscription(), DropTableSpace(), EnableDisableRule(), ExecAlterDefaultPrivilegesStmt(), ExecAlterExtensionContentsStmt(), ExecAlterExtensionStmt(), ExecBuildSlotValueDescription(), ExecCheckRTEPerms(), ExecEvalArrayCoerceExpr(), ExecGrant_Attribute(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitAgg(), ExecInitWindowAgg(), ExecSecLabelStmt(), ExecuteDoStmt(), ExecuteTruncate(), 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(), 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_fcache(), InitializeSearchPath(), InitPostgres(), InitTempTableNamespace(), inline_function(), inline_set_returning_function(), insert_username(), interpret_function_parameter_list(), inv_create(), LargeObjectCreate(), lastval(), lo_get_fragment_internal(), lo_read(), lo_truncate_internal(), lo_write(), LockTableAclCheck(), 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_statements_internal(), pgrowlocks(), pgss_store(), pgstat_get_backend_current_activity(), pltcl_fetch_interp(), postgresBeginDirectModify(), postgresBeginForeignModify(), postgresBeginForeignScan(), postgresGetForeignRelSize(), postgresImportForeignSchema(), PrepareTempTablespaces(), PrepareTransaction(), PublicationAddTables(), RangeVarCallbackForAlterRelation(), RangeVarCallbackForDropRelation(), 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(), superuser(), timetravel(), transformTableLikeClause(), truncate_check_rel(), user_mapping_ddl_aclcheck(), vacuum_rel(), ValidateJoinEstimator(), and ValidateRestrictionEstimator().

283 {
285  return CurrentUserId;
286 }
#define AssertState(condition)
Definition: c.h:674
#define OidIsValid(objectId)
Definition: c.h:534
static Oid CurrentUserId
Definition: miscinit.c:157
void GetUserIdAndContext ( Oid userid,
bool sec_def_context 
)

Definition at line 436 of file miscinit.c.

References CurrentUserId, and InLocalUserIdChange().

437 {
438  *userid = CurrentUserId;
439  *sec_def_context = InLocalUserIdChange();
440 }
bool InLocalUserIdChange(void)
Definition: miscinit.c:405
static Oid CurrentUserId
Definition: miscinit.c:157
void GetUserIdAndSecContext ( Oid userid,
int *  sec_context 
)
char* GetUserNameFromId ( Oid  roleid,
bool  noerr 
)

Definition at line 690 of file miscinit.c.

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

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

691 {
692  HeapTuple tuple;
693  char *result;
694 
695  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
696  if (!HeapTupleIsValid(tuple))
697  {
698  if (!noerr)
699  ereport(ERROR,
700  (errcode(ERRCODE_UNDEFINED_OBJECT),
701  errmsg("invalid role OID: %u", roleid)));
702  result = NULL;
703  }
704  else
705  {
706  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
707  ReleaseSysCache(tuple);
708  }
709  return result;
710 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
char * pstrdup(const char *in)
Definition: mcxt.c:1165
int errcode(int sqlerrcode)
Definition: elog.c:575
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:495
bool has_rolreplication ( Oid  roleid)

Definition at line 463 of file miscinit.c.

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

Referenced by check_permissions(), and InitPostgres().

464 {
465  bool result = false;
466  HeapTuple utup;
467 
468  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
469  if (HeapTupleIsValid(utup))
470  {
471  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
472  ReleaseSysCache(utup);
473  }
474  return result;
475 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void InitializeSessionUserId ( const char *  rolename,
Oid  roleid 
)

Definition at line 481 of file miscinit.c.

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

Referenced by InitPostgres().

482 {
483  HeapTuple roleTup;
484  Form_pg_authid rform;
485  char *rname;
486 
487  /*
488  * Don't do scans if we're bootstrapping, none of the system catalogs
489  * exist yet, and they should be owned by postgres anyway.
490  */
492 
493  /* call only once */
495 
496  if (rolename != NULL)
497  {
498  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
499  if (!HeapTupleIsValid(roleTup))
500  ereport(FATAL,
501  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
502  errmsg("role \"%s\" does not exist", rolename)));
503  }
504  else
505  {
506  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
507  if (!HeapTupleIsValid(roleTup))
508  ereport(FATAL,
509  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
510  errmsg("role with OID %u does not exist", roleid)));
511  }
512 
513  rform = (Form_pg_authid) GETSTRUCT(roleTup);
514  roleid = HeapTupleGetOid(roleTup);
515  rname = NameStr(rform->rolname);
516 
517  AuthenticatedUserId = roleid;
518  AuthenticatedUserIsSuperuser = rform->rolsuper;
519 
520  /* This sets OuterUserId/CurrentUserId too */
522 
523  /* Also mark our PGPROC entry with the authenticated user id */
524  /* (We assume this is an atomic store so no lock is needed) */
525  MyProc->roleId = roleid;
526 
527  /*
528  * These next checks are not enforced when in standalone mode, so that
529  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
530  * rolcanlogin = false;".
531  */
532  if (IsUnderPostmaster)
533  {
534  /*
535  * Is role allowed to login at all?
536  */
537  if (!rform->rolcanlogin)
538  ereport(FATAL,
539  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
540  errmsg("role \"%s\" is not permitted to log in",
541  rname)));
542 
543  /*
544  * Check connection limit for this role.
545  *
546  * There is a race condition here --- we create our PGPROC before
547  * checking for other PGPROCs. If two backends did this at about the
548  * same time, they might both think they were over the limit, while
549  * ideally one should succeed and one fail. Getting that to work
550  * exactly seems more trouble than it is worth, however; instead we
551  * just document that the connection limit is approximate.
552  */
553  if (rform->rolconnlimit >= 0 &&
555  CountUserBackends(roleid) > rform->rolconnlimit)
556  ereport(FATAL,
557  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
558  errmsg("too many connections for role \"%s\"",
559  rname)));
560  }
561 
562  /* Record username and superuser status as GUC settings too */
563  SetConfigOption("session_authorization", rname,
565  SetConfigOption("is_superuser",
566  AuthenticatedUserIsSuperuser ? "on" : "off",
568 
569  ReleaseSysCache(roleTup);
570 }
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
#define AssertState(condition)
Definition: c.h:674
PGPROC * MyProc
Definition: proc.c:67
#define PointerGetDatum(X)
Definition: postgres.h:564
Oid roleId
Definition: proc.h:104
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:534
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:149
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:72
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define FATAL
Definition: elog.h:52
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6629
bool IsUnderPostmaster
Definition: globals.c:100
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:160
#define ereport(elevel, rest)
Definition: elog.h:122
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1083
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:226
int CountUserBackends(Oid roleid)
Definition: procarray.c:2823
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NameStr(name)
Definition: c.h:495
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:324
static Oid AuthenticatedUserId
Definition: miscinit.c:154
void InitializeSessionUserIdStandalone ( void  )

Definition at line 577 of file miscinit.c.

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

Referenced by InitPostgres().

578 {
579  /*
580  * This function should only be called in single-user mode, in autovacuum
581  * workers, and in background workers.
582  */
584 
585  /* call only once */
587 
590 
592 }
#define AssertState(condition)
Definition: c.h:674
#define OidIsValid(objectId)
Definition: c.h:534
bool IsBackgroundWorker
Definition: globals.c:102
bool IsUnderPostmaster
Definition: globals.c:100
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:160
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:2988
#define BOOTSTRAP_SUPERUSERID
Definition: pg_authid.h:104
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:324
static Oid AuthenticatedUserId
Definition: miscinit.c:154
void InitPostmasterChild ( void  )

Definition at line 174 of file miscinit.c.

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

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

175 {
176  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
177 
178  MyProcPid = getpid(); /* reset MyProcPid */
179 
180  MyStartTime = time(NULL); /* set our start time in case we call elog */
181 
182  /*
183  * make sure stderr is in binary mode before anything can possibly be
184  * written to it, in case it's actually the syslogger pipe, so the pipe
185  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
186  * redirection (e.g. via pg_ctl -l) anyway.
187  */
188 #ifdef WIN32
189  _setmode(fileno(stderr), _O_BINARY);
190 #endif
191 
192  /* We don't want the postmaster's proc_exit() handlers */
193  on_exit_reset();
194 
195  /* Initialize process-local latch support */
199 
200  /*
201  * If possible, make this process a group leader, so that the postmaster
202  * can signal any child processes too. Not all processes will have
203  * children, but for consistency we make all postmaster child processes do
204  * this.
205  */
206 #ifdef HAVE_SETSID
207  if (setsid() < 0)
208  elog(FATAL, "setsid() failed: %m");
209 #endif
210 }
int MyProcPid
Definition: globals.c:38
pg_time_t MyStartTime
Definition: globals.c:39
void on_exit_reset(void)
Definition: ipc.c:396
static Latch LocalLatchData
Definition: miscinit.c:60
#define FATAL
Definition: elog.h:52
bool IsUnderPostmaster
Definition: globals.c:100
void InitializeLatchSupport(void)
Definition: latch.c:156
#define NULL
Definition: c.h:226
void InitLatch(volatile Latch *latch)
Definition: latch.c:188
struct Latch * MyLatch
Definition: globals.c:51
#define elog
Definition: elog.h:219
void InitStandaloneProcess ( const char *  argv0)

Definition at line 218 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), and PostgresMain().

219 {
221 
222  MyProcPid = getpid(); /* reset MyProcPid */
223 
224  MyStartTime = time(NULL); /* set our start time in case we call elog */
225 
226  /* Initialize process-local latch support */
230 
231  /* Compute paths, no postmaster to inherit from */
232  if (my_exec_path[0] == '\0')
233  {
234  if (find_my_exec(argv0, my_exec_path) < 0)
235  elog(FATAL, "%s: could not locate my own executable path",
236  argv0);
237  }
238 
239  if (pkglib_path[0] == '\0')
241 }
bool IsPostmasterEnvironment
Definition: globals.c:99
static char * argv0
Definition: pg_ctl.c:89
int MyProcPid
Definition: globals.c:38
pg_time_t MyStartTime
Definition: globals.c:39
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:758
static Latch LocalLatchData
Definition: miscinit.c:60
#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:63
void InitializeLatchSupport(void)
Definition: latch.c:156
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
void InitLatch(volatile Latch *latch)
Definition: latch.c:188
struct Latch * MyLatch
Definition: globals.c:51
#define elog
Definition: elog.h:219
char pkglib_path[MAXPGPATH]
Definition: globals.c:64
bool InLocalUserIdChange ( void  )

Definition at line 405 of file miscinit.c.

References SECURITY_LOCAL_USERID_CHANGE, and SecurityRestrictionContext.

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

406 {
408 }
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:291
bool InNoForceRLSOperation ( void  )

Definition at line 423 of file miscinit.c.

References SECURITY_NOFORCE_RLS, and SecurityRestrictionContext.

Referenced by check_enable_rls().

424 {
426 }
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:293
bool InSecurityRestrictedOperation ( void  )

Definition at line 414 of file miscinit.c.

References SECURITY_RESTRICTED_OPERATION, and SecurityRestrictionContext.

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

415 {
417 }
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:292
static int SecurityRestrictionContext
Definition: miscinit.c:163
static void load_libraries ( const char *  libraries,
const char *  gucname,
bool  restricted 
)
static

Definition at line 1409 of file miscinit.c.

References canonicalize_path(), DEBUG1, ereport, errcode(), errmsg(), filename, first_dir_separator(), lfirst, list_free(), load_file(), LOG, NULL, pfree(), psprintf(), pstrdup(), and SplitIdentifierString().

Referenced by process_session_preload_libraries(), and process_shared_preload_libraries().

1410 {
1411  char *rawstring;
1412  List *elemlist;
1413  ListCell *l;
1414 
1415  if (libraries == NULL || libraries[0] == '\0')
1416  return; /* nothing to do */
1417 
1418  /* Need a modifiable copy of string */
1419  rawstring = pstrdup(libraries);
1420 
1421  /* Parse string into list of identifiers */
1422  if (!SplitIdentifierString(rawstring, ',', &elemlist))
1423  {
1424  /* syntax error in list */
1425  pfree(rawstring);
1426  list_free(elemlist);
1427  ereport(LOG,
1428  (errcode(ERRCODE_SYNTAX_ERROR),
1429  errmsg("invalid list syntax in parameter \"%s\"",
1430  gucname)));
1431  return;
1432  }
1433 
1434  foreach(l, elemlist)
1435  {
1436  char *tok = (char *) lfirst(l);
1437  char *filename;
1438 
1439  filename = pstrdup(tok);
1440  canonicalize_path(filename);
1441  /* If restricting, insert $libdir/plugins if not mentioned already */
1442  if (restricted && first_dir_separator(filename) == NULL)
1443  {
1444  char *expanded;
1445 
1446  expanded = psprintf("$libdir/plugins/%s", filename);
1447  pfree(filename);
1448  filename = expanded;
1449  }
1450  load_file(filename, restricted);
1451  ereport(DEBUG1,
1452  (errmsg("loaded library \"%s\"", filename)));
1453  pfree(filename);
1454  }
1455 
1456  pfree(rawstring);
1457  list_free(elemlist);
1458 }
#define DEBUG1
Definition: elog.h:25
char * pstrdup(const char *in)
Definition: mcxt.c:1165
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void canonicalize_path(char *path)
Definition: path.c:254
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LOG
Definition: elog.h:26
void pfree(void *pointer)
Definition: mcxt.c:992
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3129
#define ereport(elevel, rest)
Definition: elog.h:122
char * first_dir_separator(const char *filename)
Definition: path.c:103
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:133
static char * filename
Definition: pg_dumpall.c:80
int errmsg(const char *fmt,...)
Definition: elog.c:797
void list_free(List *list)
Definition: list.c:1133
Definition: pg_list.h:45
void pg_bindtextdomain ( const char *  domain)

Definition at line 1488 of file miscinit.c.

References get_locale_path(), MAXPGPATH, and my_exec_path.

Referenced by _PG_init().

1489 {
1490 #ifdef ENABLE_NLS
1491  if (my_exec_path[0] != '\0')
1492  {
1493  char locale_path[MAXPGPATH];
1494 
1495  get_locale_path(my_exec_path, locale_path);
1496  bindtextdomain(domain, locale_path);
1497  pg_bind_textdomain_codeset(domain);
1498  }
1499 #endif
1500 }
#define MAXPGPATH
char my_exec_path[MAXPGPATH]
Definition: globals.c:63
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:767
void process_session_preload_libraries ( void  )

Definition at line 1477 of file miscinit.c.

References load_libraries(), local_preload_libraries_string, and session_preload_libraries_string.

Referenced by PostgresMain().

1478 {
1480  "session_preload_libraries",
1481  false);
1483  "local_preload_libraries",
1484  true);
1485 }
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1409
char * local_preload_libraries_string
Definition: miscinit.c:1397
char * session_preload_libraries_string
Definition: miscinit.c:1395
void process_shared_preload_libraries ( void  )

Definition at line 1464 of file miscinit.c.

References load_libraries(), process_shared_preload_libraries_in_progress, and shared_preload_libraries_string.

Referenced by PostmasterMain().

1465 {
1468  "shared_preload_libraries",
1469  false);
1471 }
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1400
char * shared_preload_libraries_string
Definition: miscinit.c:1396
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1409
bool RecheckDataDirLockFile ( void  )

Definition at line 1262 of file miscinit.c.

References close, DIRECTORY_LOCK_FILE, ereport, errcode_for_file_access(), errmsg(), fd(), LOG, PG_BINARY, and read.

Referenced by ServerLoop().

1263 {
1264  int fd;
1265  int len;
1266  long file_pid;
1267  char buffer[BLCKSZ];
1268 
1269  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1270  if (fd < 0)
1271  {
1272  /*
1273  * There are many foreseeable false-positive error conditions. For
1274  * safety, fail only on enumerated clearly-something-is-wrong
1275  * conditions.
1276  */
1277  switch (errno)
1278  {
1279  case ENOENT:
1280  case ENOTDIR:
1281  /* disaster */
1282  ereport(LOG,
1284  errmsg("could not open file \"%s\": %m",
1286  return false;
1287  default:
1288  /* non-fatal, at least for now */
1289  ereport(LOG,
1291  errmsg("could not open file \"%s\": %m; continuing anyway",
1293  return true;
1294  }
1295  }
1296  len = read(fd, buffer, sizeof(buffer) - 1);
1297  if (len < 0)
1298  {
1299  ereport(LOG,
1301  errmsg("could not read from file \"%s\": %m",
1303  close(fd);
1304  return true; /* treat read failure as nonfatal */
1305  }
1306  buffer[len] = '\0';
1307  close(fd);
1308  file_pid = atol(buffer);
1309  if (file_pid == getpid())
1310  return true; /* all is well */
1311 
1312  /* Trouble: someone's overwritten the lock file */
1313  ereport(LOG,
1314  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1315  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1316  return false;
1317 }
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
#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:1038
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
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
void SetCurrentRoleId ( Oid  roleid,
bool  is_superuser 
)

Definition at line 655 of file miscinit.c.

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

Referenced by assign_role().

656 {
657  /*
658  * Get correct info if it's SET ROLE NONE
659  *
660  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
661  * SetSessionUserId call will fix everything. This is needed since we
662  * will get called during GUC initialization.
663  */
664  if (!OidIsValid(roleid))
665  {
667  return;
668 
669  roleid = SessionUserId;
671 
672  SetRoleIsActive = false;
673  }
674  else
675  SetRoleIsActive = true;
676 
677  SetOuterUserId(roleid);
678 
679  SetConfigOption("is_superuser",
680  is_superuser ? "on" : "off",
682 }
static Oid SessionUserId
Definition: miscinit.c:155
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:301
#define OidIsValid(objectId)
Definition: c.h:534
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6629
static bool SetRoleIsActive
Definition: miscinit.c:166
static bool SessionUserIsSuperuser
Definition: miscinit.c:161
bool is_superuser(void)
Definition: common.c:1985
void SetDatabasePath ( const char *  path)

Definition at line 81 of file miscinit.c.

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

Referenced by InitPostgres().

82 {
83  /* This should happen only once per process */
86 }
MemoryContext TopMemoryContext
Definition: mcxt.c:43
char * DatabasePath
Definition: globals.c:84
#define Assert(condition)
Definition: c.h:671
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1152
void SetDataDir ( const char *  dir)

Definition at line 93 of file miscinit.c.

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

Referenced by SelectConfigFiles().

94 {
95  char *new;
96 
97  AssertArg(dir);
98 
99  /* If presented path is relative, convert to absolute */
100  new = make_absolute_path(dir);
101 
102  if (DataDir)
103  free(DataDir);
104  DataDir = new;
105 }
char * make_absolute_path(const char *path)
Definition: path.c:608
#define AssertArg(condition)
Definition: c.h:673
#define free(a)
Definition: header.h:60
char * DataDir
Definition: globals.c:59
static void SetOuterUserId ( Oid  userid)
static

Definition at line 301 of file miscinit.c.

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

Referenced by SetCurrentRoleId().

302 {
304  AssertArg(OidIsValid(userid));
305  OuterUserId = userid;
306 
307  /* We force the effective user ID to match, too */
308  CurrentUserId = userid;
309 }
#define AssertState(condition)
Definition: c.h:674
static Oid OuterUserId
Definition: miscinit.c:156
#define OidIsValid(objectId)
Definition: c.h:534
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define AssertArg(condition)
Definition: c.h:673
static Oid CurrentUserId
Definition: miscinit.c:157
void SetSessionAuthorization ( Oid  userid,
bool  is_superuser 
)

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

610 {
611  /* Must have authenticated already, else can't make permission check */
613 
614  if (userid != AuthenticatedUserId &&
616  ereport(ERROR,
617  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
618  errmsg("permission denied to set session authorization")));
619 
621 
622  SetConfigOption("is_superuser",
623  is_superuser ? "on" : "off",
625 }
#define AssertState(condition)
Definition: c.h:674
int errcode(int sqlerrcode)
Definition: elog.c:575
#define OidIsValid(objectId)
Definition: c.h:534
#define ERROR
Definition: elog.h:43
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6629
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:160
#define ereport(elevel, rest)
Definition: elog.h:122
bool is_superuser(void)
Definition: common.c:1985
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:324
static Oid AuthenticatedUserId
Definition: miscinit.c:154
static void SetSessionUserId ( Oid  userid,
bool  is_superuser 
)
static

Definition at line 324 of file miscinit.c.

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

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

325 {
327  AssertArg(OidIsValid(userid));
328  SessionUserId = userid;
330  SetRoleIsActive = false;
331 
332  /* We force the effective user IDs to match, too */
333  OuterUserId = userid;
334  CurrentUserId = userid;
335 }
#define AssertState(condition)
Definition: c.h:674
static Oid SessionUserId
Definition: miscinit.c:155
static Oid OuterUserId
Definition: miscinit.c:156
#define OidIsValid(objectId)
Definition: c.h:534
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define AssertArg(condition)
Definition: c.h:673
static bool SetRoleIsActive
Definition: miscinit.c:166
static bool SessionUserIsSuperuser
Definition: miscinit.c:161
bool is_superuser(void)
Definition: common.c:1985
static Oid CurrentUserId
Definition: miscinit.c:157
void SetUserIdAndContext ( Oid  userid,
bool  sec_def_context 
)

Definition at line 443 of file miscinit.c.

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

444 {
445  /* We throw the same error SET ROLE would. */
447  ereport(ERROR,
448  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
449  errmsg("cannot set parameter \"%s\" within security-restricted operation",
450  "role")));
451  CurrentUserId = userid;
452  if (sec_def_context)
454  else
456 }
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
static int SecurityRestrictionContext
Definition: miscinit.c:163
#define ereport(elevel, rest)
Definition: elog.h:122
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:291
static Oid CurrentUserId
Definition: miscinit.c:157
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:414
int errmsg(const char *fmt,...)
Definition: elog.c:797
void SetUserIdAndSecContext ( Oid  userid,
int  sec_context 
)
void SwitchBackToLocalLatch ( void  )

Definition at line 263 of file miscinit.c.

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

Referenced by AuxiliaryProcKill(), and ProcKill().

264 {
267 
269 
270  if (FeBeWaitSet)
272 
273  SetLatch(MyLatch);
274 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:685
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:167
Latch procLatch
Definition: proc.h:93
static Latch LocalLatchData
Definition: miscinit.c:60
void SetLatch(volatile Latch *latch)
Definition: latch.c:379
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
struct Latch * MyLatch
Definition: globals.c:51
#define WL_LATCH_SET
Definition: latch.h:124
void SwitchToSharedLatch ( void  )

Definition at line 244 of file miscinit.c.

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

Referenced by InitAuxiliaryProcess(), and InitProcess().

245 {
247  Assert(MyProc != NULL);
248 
250 
251  if (FeBeWaitSet)
253 
254  /*
255  * Set the shared latch as the local one might have been set. This
256  * shouldn't normally be necessary as code is supposed to check the
257  * condition before waiting for the latch, but a bit care can't hurt.
258  */
259  SetLatch(MyLatch);
260 }
PGPROC * MyProc
Definition: proc.c:67
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:685
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:167
Latch procLatch
Definition: proc.h:93
static Latch LocalLatchData
Definition: miscinit.c:60
void SetLatch(volatile Latch *latch)
Definition: latch.c:379
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
struct Latch * MyLatch
Definition: globals.c:51
#define WL_LATCH_SET
Definition: latch.h:124
void TouchSocketLockFiles ( void  )

Definition at line 1099 of file miscinit.c.

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

Referenced by ServerLoop().

1100 {
1101  ListCell *l;
1102 
1103  foreach(l, lock_files)
1104  {
1105  char *socketLockFile = (char *) lfirst(l);
1106 
1107  /* No need to touch the data directory lock file, we trust */
1108  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1109  continue;
1110 
1111  /*
1112  * utime() is POSIX standard, utimes() is a common alternative; if we
1113  * have neither, fall back to actually reading the file (which only
1114  * sets the access time not mod time, but that should be enough in
1115  * most cases). In all paths, we ignore errors.
1116  */
1117 #ifdef HAVE_UTIME
1118  utime(socketLockFile, NULL);
1119 #else /* !HAVE_UTIME */
1120 #ifdef HAVE_UTIMES
1121  utimes(socketLockFile, NULL);
1122 #else /* !HAVE_UTIMES */
1123  int fd;
1124  char buffer[1];
1125 
1126  fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1127  if (fd >= 0)
1128  {
1129  read(fd, buffer, sizeof(buffer));
1130  close(fd);
1131  }
1132 #endif /* HAVE_UTIMES */
1133 #endif /* HAVE_UTIME */
1134  }
1135 }
static List * lock_files
Definition: miscinit.c:58
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:53
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1038
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
#define close(a)
Definition: win32.h:17
#define read(a, b, c)
Definition: win32.h:18
static void UnlinkLockFiles ( int  status,
Datum  arg 
)
static

Definition at line 732 of file miscinit.c.

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

Referenced by CreateLockFile().

733 {
734  ListCell *l;
735 
736  foreach(l, lock_files)
737  {
738  char *curfile = (char *) lfirst(l);
739 
740  unlink(curfile);
741  /* Should we complain if the unlink fails? */
742  }
743  /* Since we're about to exit, no need to reclaim storage */
744  lock_files = NIL;
745 
746  /*
747  * Lock file removal should always be the last externally visible action
748  * of a postmaster or standalone backend, while we won't come here at all
749  * when exiting postmaster child processes. Therefore, this is a good
750  * place to log completion of shutdown. We could alternatively teach
751  * proc_exit() to do it, but that seems uglier. In a standalone backend,
752  * use NOTICE elevel to be less chatty.
753  */
755  (errmsg("database system is shut down")));
756 }
#define NIL
Definition: pg_list.h:69
bool IsPostmasterEnvironment
Definition: globals.c:99
static List * lock_files
Definition: miscinit.c:58
#define LOG
Definition: elog.h:26
int unlink(const char *filename)
#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
void ValidatePgVersion ( const char *  path)

Definition at line 1332 of file miscinit.c.

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

Referenced by AuxiliaryProcessMain(), checkDataDir(), InitPostgres(), and PostgresMain().

1333 {
1334  char full_path[MAXPGPATH];
1335  FILE *file;
1336  int ret;
1337  long file_major;
1338  long my_major;
1339  char *endptr;
1340  char file_version_string[64];
1341  const char *my_version_string = PG_VERSION;
1342 
1343  my_major = strtol(my_version_string, &endptr, 10);
1344 
1345  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1346 
1347  file = AllocateFile(full_path, "r");
1348  if (!file)
1349  {
1350  if (errno == ENOENT)
1351  ereport(FATAL,
1352  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1353  errmsg("\"%s\" is not a valid data directory",
1354  path),
1355  errdetail("File \"%s\" is missing.", full_path)));
1356  else
1357  ereport(FATAL,
1359  errmsg("could not open file \"%s\": %m", full_path)));
1360  }
1361 
1362  file_version_string[0] = '\0';
1363  ret = fscanf(file, "%63s", file_version_string);
1364  file_major = strtol(file_version_string, &endptr, 10);
1365 
1366  if (ret != 1 || endptr == file_version_string)
1367  ereport(FATAL,
1368  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1369  errmsg("\"%s\" is not a valid data directory",
1370  path),
1371  errdetail("File \"%s\" does not contain valid data.",
1372  full_path),
1373  errhint("You might need to initdb.")));
1374 
1375  FreeFile(file);
1376 
1377  if (my_major != file_major)
1378  ereport(FATAL,
1379  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1380  errmsg("database files are incompatible with server"),
1381  errdetail("The data directory was initialized by PostgreSQL version %s, "
1382  "which is not compatible with this version %s.",
1383  file_version_string, my_version_string)));
1384 }
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:2043
#define ereport(elevel, rest)
Definition: elog.h:122
int FreeFile(FILE *file)
Definition: fd.c:2226
int errmsg(const char *fmt,...)
Definition: elog.c:797

Variable Documentation

bool AuthenticatedUserIsSuperuser = false
static
bool IgnoreSystemIndexes = false
char* local_preload_libraries_string = NULL

Definition at line 1397 of file miscinit.c.

Referenced by process_session_preload_libraries().

Latch LocalLatchData
static

Definition at line 60 of file miscinit.c.

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

List* lock_files = NIL
static

Definition at line 58 of file miscinit.c.

Definition at line 55 of file miscinit.c.

Oid OuterUserId = InvalidOid
static

Definition at line 156 of file miscinit.c.

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

bool process_shared_preload_libraries_in_progress = false
char* session_preload_libraries_string = NULL

Definition at line 1395 of file miscinit.c.

Referenced by process_session_preload_libraries().

Oid SessionUserId = InvalidOid
static

Definition at line 155 of file miscinit.c.

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

bool SessionUserIsSuperuser = false
static

Definition at line 161 of file miscinit.c.

Referenced by SetCurrentRoleId(), and SetSessionUserId().

bool SetRoleIsActive = false
static

Definition at line 166 of file miscinit.c.

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

char* shared_preload_libraries_string = NULL

Definition at line 1396 of file miscinit.c.

Referenced by process_shared_preload_libraries().