PostgreSQL Source Code  git master
miscinit.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * miscinit.c
4  * miscellaneous initialization support stuff
5  *
6  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/utils/init/miscinit.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <sys/param.h>
18 #include <signal.h>
19 #include <time.h>
20 #include <sys/file.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <grp.h>
26 #include <pwd.h>
27 #include <netinet/in.h>
28 #include <arpa/inet.h>
29 #include <utime.h>
30 
31 #include "access/htup_details.h"
32 #include "catalog/pg_authid.h"
33 #include "common/file_perm.h"
34 #include "libpq/libpq.h"
35 #include "libpq/pqsignal.h"
36 #include "mb/pg_wchar.h"
37 #include "miscadmin.h"
38 #include "pgstat.h"
39 #include "postmaster/autovacuum.h"
40 #include "postmaster/interrupt.h"
41 #include "postmaster/pgarch.h"
42 #include "postmaster/postmaster.h"
43 #include "storage/fd.h"
44 #include "storage/ipc.h"
45 #include "storage/latch.h"
46 #include "storage/pg_shmem.h"
47 #include "storage/pmsignal.h"
48 #include "storage/proc.h"
49 #include "storage/procarray.h"
50 #include "utils/builtins.h"
51 #include "utils/guc.h"
52 #include "utils/inval.h"
53 #include "utils/memutils.h"
54 #include "utils/pidfile.h"
55 #include "utils/syscache.h"
56 #include "utils/varlena.h"
57 
58 
59 #define DIRECTORY_LOCK_FILE "postmaster.pid"
60 
62 
64 
65 /* List of lock files to be removed at proc exit */
66 static List *lock_files = NIL;
67 
69 
70 /* ----------------------------------------------------------------
71  * ignoring system indexes support stuff
72  *
73  * NOTE: "ignoring system indexes" means we do not use the system indexes
74  * for lookups (either in hardwired catalog accesses or in planner-generated
75  * plans). We do, however, still update the indexes when a catalog
76  * modification is made.
77  * ----------------------------------------------------------------
78  */
79 
80 bool IgnoreSystemIndexes = false;
81 
82 
83 /* ----------------------------------------------------------------
84  * common process startup code
85  * ----------------------------------------------------------------
86  */
87 
88 /*
89  * Initialize the basic environment for a postmaster child
90  *
91  * Should be called as early as possible after the child's startup. However,
92  * on EXEC_BACKEND builds it does need to be after read_backend_variables().
93  */
94 void
96 {
97  IsUnderPostmaster = true; /* we are a postmaster subprocess now */
98 
99  /*
100  * Start our win32 signal implementation. This has to be done after we
101  * read the backend variables, because we need to pick up the signal pipe
102  * from the parent process.
103  */
104 #ifdef WIN32
106 #endif
107 
108  /*
109  * Set reference point for stack-depth checking. This might seem
110  * redundant in !EXEC_BACKEND builds; but it's not because the postmaster
111  * launches its children from signal handlers, so we might be running on
112  * an alternative stack.
113  */
114  (void) set_stack_base();
115 
117 
118  /*
119  * make sure stderr is in binary mode before anything can possibly be
120  * written to it, in case it's actually the syslogger pipe, so the pipe
121  * chunking protocol isn't disturbed. Non-logpipe data gets translated on
122  * redirection (e.g. via pg_ctl -l) anyway.
123  */
124 #ifdef WIN32
125  _setmode(fileno(stderr), _O_BINARY);
126 #endif
127 
128  /* We don't want the postmaster's proc_exit() handlers */
129  on_exit_reset();
130 
131  /* In EXEC_BACKEND case we will not have inherited BlockSig etc values */
132 #ifdef EXEC_BACKEND
133  pqinitmask();
134 #endif
135 
136  /* Initialize process-local latch support */
140 
141  /*
142  * If possible, make this process a group leader, so that the postmaster
143  * can signal any child processes too. Not all processes will have
144  * children, but for consistency we make all postmaster child processes do
145  * this.
146  */
147 #ifdef HAVE_SETSID
148  if (setsid() < 0)
149  elog(FATAL, "setsid() failed: %m");
150 #endif
151 
152  /*
153  * Every postmaster child process is expected to respond promptly to
154  * SIGQUIT at all times. Therefore we centrally remove SIGQUIT from
155  * BlockSig and install a suitable signal handler. (Client-facing
156  * processes may choose to replace this default choice of handler with
157  * quickdie().) All other blockable signals remain blocked for now.
158  */
160 
161  sigdelset(&BlockSig, SIGQUIT);
162  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
163 
164  /* Request a signal if the postmaster dies, if possible. */
166 
167  /* Don't give the pipe to subprograms that we execute. */
168 #ifndef WIN32
169  if (fcntl(postmaster_alive_fds[POSTMASTER_FD_WATCH], F_SETFD, FD_CLOEXEC) < 0)
170  ereport(FATAL,
172  errmsg_internal("could not set postmaster death monitoring pipe to FD_CLOEXEC mode: %m")));
173 #endif
174 }
175 
176 /*
177  * Initialize the basic environment for a standalone process.
178  *
179  * argv0 has to be suitable to find the program's executable.
180  */
181 void
183 {
185 
187 
188  /*
189  * Start our win32 signal implementation
190  */
191 #ifdef WIN32
193 #endif
194 
196 
197  /* Initialize process-local latch support */
201 
202  /*
203  * For consistency with InitPostmasterChild, initialize signal mask here.
204  * But we don't unblock SIGQUIT or provide a default handler for it.
205  */
206  pqinitmask();
207  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
208 
209  /* Compute paths, no postmaster to inherit from */
210  if (my_exec_path[0] == '\0')
211  {
212  if (find_my_exec(argv0, my_exec_path) < 0)
213  elog(FATAL, "%s: could not locate my own executable path",
214  argv0);
215  }
216 
217  if (pkglib_path[0] == '\0')
219 }
220 
221 void
223 {
225  Assert(MyProc != NULL);
226 
228 
229  if (FeBeWaitSet)
231  MyLatch);
232 
233  /*
234  * Set the shared latch as the local one might have been set. This
235  * shouldn't normally be necessary as code is supposed to check the
236  * condition before waiting for the latch, but a bit care can't hurt.
237  */
238  SetLatch(MyLatch);
239 }
240 
241 void
243 {
246 }
247 
248 void
250 {
252  Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
253 
255 
256  if (FeBeWaitSet)
258  MyLatch);
259 
260  SetLatch(MyLatch);
261 }
262 
263 const char *
265 {
266  const char *backendDesc = "unknown process type";
267 
268  switch (backendType)
269  {
270  case B_INVALID:
271  backendDesc = "not initialized";
272  break;
273  case B_ARCHIVER:
274  backendDesc = "archiver";
275  break;
276  case B_AUTOVAC_LAUNCHER:
277  backendDesc = "autovacuum launcher";
278  break;
279  case B_AUTOVAC_WORKER:
280  backendDesc = "autovacuum worker";
281  break;
282  case B_BACKEND:
283  backendDesc = "client backend";
284  break;
285  case B_BG_WORKER:
286  backendDesc = "background worker";
287  break;
288  case B_BG_WRITER:
289  backendDesc = "background writer";
290  break;
291  case B_CHECKPOINTER:
292  backendDesc = "checkpointer";
293  break;
294  case B_LOGGER:
295  backendDesc = "logger";
296  break;
298  backendDesc = "standalone backend";
299  break;
300  case B_STARTUP:
301  backendDesc = "startup";
302  break;
303  case B_WAL_RECEIVER:
304  backendDesc = "walreceiver";
305  break;
306  case B_WAL_SENDER:
307  backendDesc = "walsender";
308  break;
309  case B_WAL_WRITER:
310  backendDesc = "walwriter";
311  break;
312  }
313 
314  return backendDesc;
315 }
316 
317 /* ----------------------------------------------------------------
318  * database path / name support stuff
319  * ----------------------------------------------------------------
320  */
321 
322 void
323 SetDatabasePath(const char *path)
324 {
325  /* This should happen only once per process */
328 }
329 
330 /*
331  * Validate the proposed data directory.
332  *
333  * Also initialize file and directory create modes and mode mask.
334  */
335 void
337 {
338  struct stat stat_buf;
339 
340  Assert(DataDir);
341 
342  if (stat(DataDir, &stat_buf) != 0)
343  {
344  if (errno == ENOENT)
345  ereport(FATAL,
347  errmsg("data directory \"%s\" does not exist",
348  DataDir)));
349  else
350  ereport(FATAL,
352  errmsg("could not read permissions of directory \"%s\": %m",
353  DataDir)));
354  }
355 
356  /* eventual chdir would fail anyway, but let's test ... */
357  if (!S_ISDIR(stat_buf.st_mode))
358  ereport(FATAL,
359  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
360  errmsg("specified data directory \"%s\" is not a directory",
361  DataDir)));
362 
363  /*
364  * Check that the directory belongs to my userid; if not, reject.
365  *
366  * This check is an essential part of the interlock that prevents two
367  * postmasters from starting in the same directory (see CreateLockFile()).
368  * Do not remove or weaken it.
369  *
370  * XXX can we safely enable this check on Windows?
371  */
372 #if !defined(WIN32) && !defined(__CYGWIN__)
373  if (stat_buf.st_uid != geteuid())
374  ereport(FATAL,
375  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
376  errmsg("data directory \"%s\" has wrong ownership",
377  DataDir),
378  errhint("The server must be started by the user that owns the data directory.")));
379 #endif
380 
381  /*
382  * Check if the directory has correct permissions. If not, reject.
383  *
384  * Only two possible modes are allowed, 0700 and 0750. The latter mode
385  * indicates that group read/execute should be allowed on all newly
386  * created files and directories.
387  *
388  * XXX temporarily suppress check when on Windows, because there may not
389  * be proper support for Unix-y file permissions. Need to think of a
390  * reasonable check to apply on Windows.
391  */
392 #if !defined(WIN32) && !defined(__CYGWIN__)
393  if (stat_buf.st_mode & PG_MODE_MASK_GROUP)
394  ereport(FATAL,
395  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
396  errmsg("data directory \"%s\" has invalid permissions",
397  DataDir),
398  errdetail("Permissions should be u=rwx (0700) or u=rwx,g=rx (0750).")));
399 #endif
400 
401  /*
402  * Reset creation modes and mask based on the mode of the data directory.
403  *
404  * The mask was set earlier in startup to disallow group permissions on
405  * newly created files and directories. However, if group read/execute
406  * are present on the data directory then modify the create modes and mask
407  * to allow group read/execute on newly created files and directories and
408  * set the data_directory_mode GUC.
409  *
410  * Suppress when on Windows, because there may not be proper support for
411  * Unix-y file permissions.
412  */
413 #if !defined(WIN32) && !defined(__CYGWIN__)
415 
416  umask(pg_mode_mask);
418 #endif
419 
420  /* Check for PG_VERSION */
422 }
423 
424 /*
425  * Set data directory, but make sure it's an absolute path. Use this,
426  * never set DataDir directly.
427  */
428 void
429 SetDataDir(const char *dir)
430 {
431  char *new;
432 
433  Assert(dir);
434 
435  /* If presented path is relative, convert to absolute */
436  new = make_absolute_path(dir);
437 
438  free(DataDir);
439  DataDir = new;
440 }
441 
442 /*
443  * Change working directory to DataDir. Most of the postmaster and backend
444  * code assumes that we are in DataDir so it can use relative paths to access
445  * stuff in and under the data directory. For convenience during path
446  * setup, however, we don't force the chdir to occur during SetDataDir.
447  */
448 void
450 {
451  Assert(DataDir);
452 
453  if (chdir(DataDir) < 0)
454  ereport(FATAL,
456  errmsg("could not change directory to \"%s\": %m",
457  DataDir)));
458 }
459 
460 
461 /* ----------------------------------------------------------------
462  * User ID state
463  *
464  * We have to track several different values associated with the concept
465  * of "user ID".
466  *
467  * AuthenticatedUserId is determined at connection start and never changes.
468  *
469  * SessionUserId is initially the same as AuthenticatedUserId, but can be
470  * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
471  * This is the ID reported by the SESSION_USER SQL function.
472  *
473  * OuterUserId is the current user ID in effect at the "outer level" (outside
474  * any transaction or function). This is initially the same as SessionUserId,
475  * but can be changed by SET ROLE to any role that SessionUserId is a
476  * member of. (XXX rename to something like CurrentRoleId?)
477  *
478  * CurrentUserId is the current effective user ID; this is the one to use
479  * for all normal permissions-checking purposes. At outer level this will
480  * be the same as OuterUserId, but it changes during calls to SECURITY
481  * DEFINER functions, as well as locally in some specialized commands.
482  *
483  * SecurityRestrictionContext holds flags indicating reason(s) for changing
484  * CurrentUserId. In some cases we need to lock down operations that are
485  * not directly controlled by privilege settings, and this provides a
486  * convenient way to do it.
487  * ----------------------------------------------------------------
488  */
493 static const char *SystemUser = NULL;
494 
495 /* We also have to remember the superuser state of some of these levels */
496 static bool AuthenticatedUserIsSuperuser = false;
497 static bool SessionUserIsSuperuser = false;
498 
500 
501 /* We also remember if a SET ROLE is currently active */
502 static bool SetRoleIsActive = false;
503 
504 /*
505  * GetUserId - get the current effective user ID.
506  *
507  * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
508  */
509 Oid
511 {
513  return CurrentUserId;
514 }
515 
516 
517 /*
518  * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
519  */
520 Oid
522 {
524  return OuterUserId;
525 }
526 
527 
528 static void
530 {
532  Assert(OidIsValid(userid));
533  OuterUserId = userid;
534 
535  /* We force the effective user ID to match, too */
536  CurrentUserId = userid;
537 }
538 
539 
540 /*
541  * GetSessionUserId/SetSessionUserId - get/set the session user ID.
542  */
543 Oid
545 {
547  return SessionUserId;
548 }
549 
550 
551 static void
553 {
555  Assert(OidIsValid(userid));
556  SessionUserId = userid;
558  SetRoleIsActive = false;
559 
560  /* We force the effective user IDs to match, too */
561  OuterUserId = userid;
562  CurrentUserId = userid;
563 }
564 
565 /*
566  * Return the system user representing the authenticated identity.
567  * It is defined in InitializeSystemUser() as auth_method:authn_id.
568  */
569 const char *
571 {
572  return SystemUser;
573 }
574 
575 /*
576  * GetAuthenticatedUserId - get the authenticated user ID
577  */
578 Oid
580 {
582  return AuthenticatedUserId;
583 }
584 
585 
586 /*
587  * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
588  * and the SecurityRestrictionContext flags.
589  *
590  * Currently there are three valid bits in SecurityRestrictionContext:
591  *
592  * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
593  * that is temporarily changing CurrentUserId via these functions. This is
594  * needed to indicate that the actual value of CurrentUserId is not in sync
595  * with guc.c's internal state, so SET ROLE has to be disallowed.
596  *
597  * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
598  * that does not wish to trust called user-defined functions at all. The
599  * policy is to use this before operations, e.g. autovacuum and REINDEX, that
600  * enumerate relations of a database or schema and run functions associated
601  * with each found relation. The relation owner is the new user ID. Set this
602  * as soon as possible after locking the relation. Restore the old user ID as
603  * late as possible before closing the relation; restoring it shortly after
604  * close is also tolerable. If a command has both relation-enumerating and
605  * non-enumerating modes, e.g. ANALYZE, both modes set this bit. This bit
606  * prevents not only SET ROLE, but various other changes of session state that
607  * normally is unprotected but might possibly be used to subvert the calling
608  * session later. An example is replacing an existing prepared statement with
609  * new code, which will then be executed with the outer session's permissions
610  * when the prepared statement is next used. These restrictions are fairly
611  * draconian, but the functions called in relation-enumerating operations are
612  * really supposed to be side-effect-free anyway.
613  *
614  * SECURITY_NOFORCE_RLS indicates that we are inside an operation which should
615  * ignore the FORCE ROW LEVEL SECURITY per-table indication. This is used to
616  * ensure that FORCE RLS does not mistakenly break referential integrity
617  * checks. Note that this is intentionally only checked when running as the
618  * owner of the table (which should always be the case for referential
619  * integrity checks).
620  *
621  * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
622  * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
623  * the new value to be valid. In fact, these routines had better not
624  * ever throw any kind of error. This is because they are used by
625  * StartTransaction and AbortTransaction to save/restore the settings,
626  * and during the first transaction within a backend, the value to be saved
627  * and perhaps restored is indeed invalid. We have to be able to get
628  * through AbortTransaction without asserting in case InitPostgres fails.
629  */
630 void
631 GetUserIdAndSecContext(Oid *userid, int *sec_context)
632 {
633  *userid = CurrentUserId;
634  *sec_context = SecurityRestrictionContext;
635 }
636 
637 void
638 SetUserIdAndSecContext(Oid userid, int sec_context)
639 {
640  CurrentUserId = userid;
641  SecurityRestrictionContext = sec_context;
642 }
643 
644 
645 /*
646  * InLocalUserIdChange - are we inside a local change of CurrentUserId?
647  */
648 bool
650 {
652 }
653 
654 /*
655  * InSecurityRestrictedOperation - are we inside a security-restricted command?
656  */
657 bool
659 {
661 }
662 
663 /*
664  * InNoForceRLSOperation - are we ignoring FORCE ROW LEVEL SECURITY ?
665  */
666 bool
668 {
670 }
671 
672 
673 /*
674  * These are obsolete versions of Get/SetUserIdAndSecContext that are
675  * only provided for bug-compatibility with some rather dubious code in
676  * pljava. We allow the userid to be set, but only when not inside a
677  * security restriction context.
678  */
679 void
680 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
681 {
682  *userid = CurrentUserId;
683  *sec_def_context = InLocalUserIdChange();
684 }
685 
686 void
687 SetUserIdAndContext(Oid userid, bool sec_def_context)
688 {
689  /* We throw the same error SET ROLE would. */
691  ereport(ERROR,
692  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
693  errmsg("cannot set parameter \"%s\" within security-restricted operation",
694  "role")));
695  CurrentUserId = userid;
696  if (sec_def_context)
698  else
700 }
701 
702 
703 /*
704  * Check whether specified role has explicit REPLICATION privilege
705  */
706 bool
708 {
709  bool result = false;
710  HeapTuple utup;
711 
712  /* Superusers bypass all permission checking. */
713  if (superuser_arg(roleid))
714  return true;
715 
716  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
717  if (HeapTupleIsValid(utup))
718  {
719  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
720  ReleaseSysCache(utup);
721  }
722  return result;
723 }
724 
725 /*
726  * Initialize user identity during normal backend startup
727  */
728 void
729 InitializeSessionUserId(const char *rolename, Oid roleid)
730 {
731  HeapTuple roleTup;
732  Form_pg_authid rform;
733  char *rname;
734 
735  /*
736  * Don't do scans if we're bootstrapping, none of the system catalogs
737  * exist yet, and they should be owned by postgres anyway.
738  */
740 
741  /* call only once */
743 
744  /*
745  * Make sure syscache entries are flushed for recent catalog changes. This
746  * allows us to find roles that were created on-the-fly during
747  * authentication.
748  */
750 
751  if (rolename != NULL)
752  {
753  roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
754  if (!HeapTupleIsValid(roleTup))
755  ereport(FATAL,
756  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
757  errmsg("role \"%s\" does not exist", rolename)));
758  }
759  else
760  {
761  roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
762  if (!HeapTupleIsValid(roleTup))
763  ereport(FATAL,
764  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
765  errmsg("role with OID %u does not exist", roleid)));
766  }
767 
768  rform = (Form_pg_authid) GETSTRUCT(roleTup);
769  roleid = rform->oid;
770  rname = NameStr(rform->rolname);
771 
772  AuthenticatedUserId = roleid;
773  AuthenticatedUserIsSuperuser = rform->rolsuper;
774 
775  /* This sets OuterUserId/CurrentUserId too */
777 
778  /* Also mark our PGPROC entry with the authenticated user id */
779  /* (We assume this is an atomic store so no lock is needed) */
780  MyProc->roleId = roleid;
781 
782  /*
783  * These next checks are not enforced when in standalone mode, so that
784  * there is a way to recover from sillinesses like "UPDATE pg_authid SET
785  * rolcanlogin = false;".
786  */
787  if (IsUnderPostmaster)
788  {
789  /*
790  * Is role allowed to login at all?
791  */
792  if (!rform->rolcanlogin)
793  ereport(FATAL,
794  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
795  errmsg("role \"%s\" is not permitted to log in",
796  rname)));
797 
798  /*
799  * Check connection limit for this role.
800  *
801  * There is a race condition here --- we create our PGPROC before
802  * checking for other PGPROCs. If two backends did this at about the
803  * same time, they might both think they were over the limit, while
804  * ideally one should succeed and one fail. Getting that to work
805  * exactly seems more trouble than it is worth, however; instead we
806  * just document that the connection limit is approximate.
807  */
808  if (rform->rolconnlimit >= 0 &&
810  CountUserBackends(roleid) > rform->rolconnlimit)
811  ereport(FATAL,
812  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
813  errmsg("too many connections for role \"%s\"",
814  rname)));
815  }
816 
817  /* Record username and superuser status as GUC settings too */
818  SetConfigOption("session_authorization", rname,
820  SetConfigOption("is_superuser",
821  AuthenticatedUserIsSuperuser ? "on" : "off",
823 
824  ReleaseSysCache(roleTup);
825 }
826 
827 
828 /*
829  * Initialize user identity during special backend startup
830  */
831 void
833 {
834  /*
835  * This function should only be called in single-user mode, in autovacuum
836  * workers, and in background workers.
837  */
839 
840  /* call only once */
842 
843  AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
845 
846  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
847 }
848 
849 /*
850  * Initialize the system user.
851  *
852  * This is built as auth_method:authn_id.
853  */
854 void
855 InitializeSystemUser(const char *authn_id, const char *auth_method)
856 {
857  char *system_user;
858 
859  /* call only once */
860  Assert(SystemUser == NULL);
861 
862  /*
863  * InitializeSystemUser should be called only when authn_id is not NULL,
864  * meaning that auth_method is valid.
865  */
866  Assert(authn_id != NULL);
867 
868  system_user = psprintf("%s:%s", auth_method, authn_id);
869 
870  /* Store SystemUser in long-lived storage */
873 }
874 
875 /*
876  * SQL-function SYSTEM_USER
877  */
878 Datum
880 {
881  const char *sysuser = GetSystemUser();
882 
883  if (sysuser)
885  else
886  PG_RETURN_NULL();
887 }
888 
889 /*
890  * Change session auth ID while running
891  *
892  * Only a superuser may set auth ID to something other than himself. Note
893  * that in case of multiple SETs in a single session, the original userid's
894  * superuserness is what matters. But we set the GUC variable is_superuser
895  * to indicate whether the *current* session userid is a superuser.
896  *
897  * Note: this is not an especially clean place to do the permission check.
898  * It's OK because the check does not require catalog access and can't
899  * fail during an end-of-transaction GUC reversion, but we may someday
900  * have to push it up into assign_session_authorization.
901  */
902 void
904 {
905  /* Must have authenticated already, else can't make permission check */
907 
908  if (userid != AuthenticatedUserId &&
910  ereport(ERROR,
911  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
912  errmsg("permission denied to set session authorization")));
913 
915 
916  SetConfigOption("is_superuser",
917  is_superuser ? "on" : "off",
919 }
920 
921 /*
922  * Report current role id
923  * This follows the semantics of SET ROLE, ie return the outer-level ID
924  * not the current effective ID, and return InvalidOid when the setting
925  * is logically SET ROLE NONE.
926  */
927 Oid
929 {
930  if (SetRoleIsActive)
931  return OuterUserId;
932  else
933  return InvalidOid;
934 }
935 
936 /*
937  * Change Role ID while running (SET ROLE)
938  *
939  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
940  * session user authorization. In this case the is_superuser argument
941  * is ignored.
942  *
943  * When roleid is not InvalidOid, the caller must have checked whether
944  * the session user has permission to become that role. (We cannot check
945  * here because this routine must be able to execute in a failed transaction
946  * to restore a prior value of the ROLE GUC variable.)
947  */
948 void
950 {
951  /*
952  * Get correct info if it's SET ROLE NONE
953  *
954  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
955  * SetSessionUserId call will fix everything. This is needed since we
956  * will get called during GUC initialization.
957  */
958  if (!OidIsValid(roleid))
959  {
961  return;
962 
963  roleid = SessionUserId;
965 
966  SetRoleIsActive = false;
967  }
968  else
969  SetRoleIsActive = true;
970 
971  SetOuterUserId(roleid);
972 
973  SetConfigOption("is_superuser",
974  is_superuser ? "on" : "off",
976 }
977 
978 
979 /*
980  * Get user name from user oid, returns NULL for nonexistent roleid if noerr
981  * is true.
982  */
983 char *
984 GetUserNameFromId(Oid roleid, bool noerr)
985 {
986  HeapTuple tuple;
987  char *result;
988 
989  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
990  if (!HeapTupleIsValid(tuple))
991  {
992  if (!noerr)
993  ereport(ERROR,
994  (errcode(ERRCODE_UNDEFINED_OBJECT),
995  errmsg("invalid role OID: %u", roleid)));
996  result = NULL;
997  }
998  else
999  {
1000  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
1001  ReleaseSysCache(tuple);
1002  }
1003  return result;
1004 }
1005 
1006 /* ------------------------------------------------------------------------
1007  * Client connection state shared with parallel workers
1008  *
1009  * ClientConnectionInfo contains pieces of information about the client that
1010  * need to be synced to parallel workers when they initialize.
1011  *-------------------------------------------------------------------------
1012  */
1013 
1015 
1016 /*
1017  * Intermediate representation of ClientConnectionInfo for easier
1018  * serialization. Variable-length fields are allocated right after this
1019  * header.
1020  */
1022 {
1023  int32 authn_id_len; /* strlen(authn_id), or -1 if NULL */
1026 
1027 /*
1028  * Calculate the space needed to serialize MyClientConnectionInfo.
1029  */
1030 Size
1032 {
1033  Size size = 0;
1034 
1035  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1036 
1038  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1039 
1040  return size;
1041 }
1042 
1043 /*
1044  * Serialize MyClientConnectionInfo for use by parallel workers.
1045  */
1046 void
1047 SerializeClientConnectionInfo(Size maxsize, char *start_address)
1048 {
1049  SerializedClientConnectionInfo serialized = {0};
1050 
1051  serialized.authn_id_len = -1;
1053 
1055  serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1056 
1057  /* Copy serialized representation to buffer */
1058  Assert(maxsize >= sizeof(serialized));
1059  memcpy(start_address, &serialized, sizeof(serialized));
1060 
1061  maxsize -= sizeof(serialized);
1062  start_address += sizeof(serialized);
1063 
1064  /* Copy authn_id into the space after the struct */
1065  if (serialized.authn_id_len >= 0)
1066  {
1067  Assert(maxsize >= (serialized.authn_id_len + 1));
1068  memcpy(start_address,
1070  /* include the NULL terminator to ease deserialization */
1071  serialized.authn_id_len + 1);
1072  }
1073 }
1074 
1075 /*
1076  * Restore MyClientConnectionInfo from its serialized representation.
1077  */
1078 void
1080 {
1081  SerializedClientConnectionInfo serialized;
1082 
1083  memcpy(&serialized, conninfo, sizeof(serialized));
1084 
1085  /* Copy the fields back into place */
1088 
1089  if (serialized.authn_id_len >= 0)
1090  {
1091  char *authn_id;
1092 
1093  authn_id = conninfo + sizeof(serialized);
1095  authn_id);
1096  }
1097 }
1098 
1099 
1100 /*-------------------------------------------------------------------------
1101  * Interlock-file support
1102  *
1103  * These routines are used to create both a data-directory lockfile
1104  * ($DATADIR/postmaster.pid) and Unix-socket-file lockfiles ($SOCKFILE.lock).
1105  * Both kinds of files contain the same info initially, although we can add
1106  * more information to a data-directory lockfile after it's created, using
1107  * AddToDataDirLockFile(). See pidfile.h for documentation of the contents
1108  * of these lockfiles.
1109  *
1110  * On successful lockfile creation, a proc_exit callback to remove the
1111  * lockfile is automatically created.
1112  *-------------------------------------------------------------------------
1113  */
1114 
1115 /*
1116  * proc_exit callback to remove lockfiles.
1117  */
1118 static void
1120 {
1121  ListCell *l;
1122 
1123  foreach(l, lock_files)
1124  {
1125  char *curfile = (char *) lfirst(l);
1126 
1127  unlink(curfile);
1128  /* Should we complain if the unlink fails? */
1129  }
1130  /* Since we're about to exit, no need to reclaim storage */
1131  lock_files = NIL;
1132 
1133  /*
1134  * Lock file removal should always be the last externally visible action
1135  * of a postmaster or standalone backend, while we won't come here at all
1136  * when exiting postmaster child processes. Therefore, this is a good
1137  * place to log completion of shutdown. We could alternatively teach
1138  * proc_exit() to do it, but that seems uglier. In a standalone backend,
1139  * use NOTICE elevel to be less chatty.
1140  */
1142  (errmsg("database system is shut down")));
1143 }
1144 
1145 /*
1146  * Create a lockfile.
1147  *
1148  * filename is the path name of the lockfile to create.
1149  * amPostmaster is used to determine how to encode the output PID.
1150  * socketDir is the Unix socket directory path to include (possibly empty).
1151  * isDDLock and refName are used to determine what error message to produce.
1152  */
1153 static void
1154 CreateLockFile(const char *filename, bool amPostmaster,
1155  const char *socketDir,
1156  bool isDDLock, const char *refName)
1157 {
1158  int fd;
1159  char buffer[MAXPGPATH * 2 + 256];
1160  int ntries;
1161  int len;
1162  int encoded_pid;
1163  pid_t other_pid;
1164  pid_t my_pid,
1165  my_p_pid,
1166  my_gp_pid;
1167  const char *envvar;
1168 
1169  /*
1170  * If the PID in the lockfile is our own PID or our parent's or
1171  * grandparent's PID, then the file must be stale (probably left over from
1172  * a previous system boot cycle). We need to check this because of the
1173  * likelihood that a reboot will assign exactly the same PID as we had in
1174  * the previous reboot, or one that's only one or two counts larger and
1175  * hence the lockfile's PID now refers to an ancestor shell process. We
1176  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
1177  * via the environment variable PG_GRANDPARENT_PID; this is so that
1178  * launching the postmaster via pg_ctl can be just as reliable as
1179  * launching it directly. There is no provision for detecting
1180  * further-removed ancestor processes, but if the init script is written
1181  * carefully then all but the immediate parent shell will be root-owned
1182  * processes and so the kill test will fail with EPERM. Note that we
1183  * cannot get a false negative this way, because an existing postmaster
1184  * would surely never launch a competing postmaster or pg_ctl process
1185  * directly.
1186  */
1187  my_pid = getpid();
1188 
1189 #ifndef WIN32
1190  my_p_pid = getppid();
1191 #else
1192 
1193  /*
1194  * Windows hasn't got getppid(), but doesn't need it since it's not using
1195  * real kill() either...
1196  */
1197  my_p_pid = 0;
1198 #endif
1199 
1200  envvar = getenv("PG_GRANDPARENT_PID");
1201  if (envvar)
1202  my_gp_pid = atoi(envvar);
1203  else
1204  my_gp_pid = 0;
1205 
1206  /*
1207  * We need a loop here because of race conditions. But don't loop forever
1208  * (for example, a non-writable $PGDATA directory might cause a failure
1209  * that won't go away). 100 tries seems like plenty.
1210  */
1211  for (ntries = 0;; ntries++)
1212  {
1213  /*
1214  * Try to create the lock file --- O_EXCL makes this atomic.
1215  *
1216  * Think not to make the file protection weaker than 0600/0640. See
1217  * comments below.
1218  */
1219  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
1220  if (fd >= 0)
1221  break; /* Success; exit the retry loop */
1222 
1223  /*
1224  * Couldn't create the pid file. Probably it already exists.
1225  */
1226  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
1227  ereport(FATAL,
1229  errmsg("could not create lock file \"%s\": %m",
1230  filename)));
1231 
1232  /*
1233  * Read the file to get the old owner's PID. Note race condition
1234  * here: file might have been deleted since we tried to create it.
1235  */
1236  fd = open(filename, O_RDONLY, pg_file_create_mode);
1237  if (fd < 0)
1238  {
1239  if (errno == ENOENT)
1240  continue; /* race condition; try again */
1241  ereport(FATAL,
1243  errmsg("could not open lock file \"%s\": %m",
1244  filename)));
1245  }
1247  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
1248  ereport(FATAL,
1250  errmsg("could not read lock file \"%s\": %m",
1251  filename)));
1253  close(fd);
1254 
1255  if (len == 0)
1256  {
1257  ereport(FATAL,
1258  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1259  errmsg("lock file \"%s\" is empty", filename),
1260  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
1261  }
1262 
1263  buffer[len] = '\0';
1264  encoded_pid = atoi(buffer);
1265 
1266  /* if pid < 0, the pid is for postgres, not postmaster */
1267  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
1268 
1269  if (other_pid <= 0)
1270  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
1271  filename, buffer);
1272 
1273  /*
1274  * Check to see if the other process still exists
1275  *
1276  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
1277  * ignored as false matches.
1278  *
1279  * Normally kill() will fail with ESRCH if the given PID doesn't
1280  * exist.
1281  *
1282  * We can treat the EPERM-error case as okay because that error
1283  * implies that the existing process has a different userid than we
1284  * do, which means it cannot be a competing postmaster. A postmaster
1285  * cannot successfully attach to a data directory owned by a userid
1286  * other than its own, as enforced in checkDataDir(). Also, since we
1287  * create the lockfiles mode 0600/0640, we'd have failed above if the
1288  * lockfile belonged to another userid --- which means that whatever
1289  * process kill() is reporting about isn't the one that made the
1290  * lockfile. (NOTE: this last consideration is the only one that
1291  * keeps us from blowing away a Unix socket file belonging to an
1292  * instance of Postgres being run by someone else, at least on
1293  * machines where /tmp hasn't got a stickybit.)
1294  */
1295  if (other_pid != my_pid && other_pid != my_p_pid &&
1296  other_pid != my_gp_pid)
1297  {
1298  if (kill(other_pid, 0) == 0 ||
1299  (errno != ESRCH && errno != EPERM))
1300  {
1301  /* lockfile belongs to a live process */
1302  ereport(FATAL,
1303  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1304  errmsg("lock file \"%s\" already exists",
1305  filename),
1306  isDDLock ?
1307  (encoded_pid < 0 ?
1308  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
1309  (int) other_pid, refName) :
1310  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
1311  (int) other_pid, refName)) :
1312  (encoded_pid < 0 ?
1313  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
1314  (int) other_pid, refName) :
1315  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
1316  (int) other_pid, refName))));
1317  }
1318  }
1319 
1320  /*
1321  * No, the creating process did not exist. However, it could be that
1322  * the postmaster crashed (or more likely was kill -9'd by a clueless
1323  * admin) but has left orphan backends behind. Check for this by
1324  * looking to see if there is an associated shmem segment that is
1325  * still in use.
1326  *
1327  * Note: because postmaster.pid is written in multiple steps, we might
1328  * not find the shmem ID values in it; we can't treat that as an
1329  * error.
1330  */
1331  if (isDDLock)
1332  {
1333  char *ptr = buffer;
1334  unsigned long id1,
1335  id2;
1336  int lineno;
1337 
1338  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
1339  {
1340  if ((ptr = strchr(ptr, '\n')) == NULL)
1341  break;
1342  ptr++;
1343  }
1344 
1345  if (ptr != NULL &&
1346  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
1347  {
1348  if (PGSharedMemoryIsInUse(id1, id2))
1349  ereport(FATAL,
1350  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1351  errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
1352  id1, id2),
1353  errhint("Terminate any old server processes associated with data directory \"%s\".",
1354  refName)));
1355  }
1356  }
1357 
1358  /*
1359  * Looks like nobody's home. Unlink the file and try again to create
1360  * it. Need a loop because of possible race condition against other
1361  * would-be creators.
1362  */
1363  if (unlink(filename) < 0)
1364  ereport(FATAL,
1366  errmsg("could not remove old lock file \"%s\": %m",
1367  filename),
1368  errhint("The file seems accidentally left over, but "
1369  "it could not be removed. Please remove the file "
1370  "by hand and try again.")));
1371  }
1372 
1373  /*
1374  * Successfully created the file, now fill it. See comment in pidfile.h
1375  * about the contents. Note that we write the same first five lines into
1376  * both datadir and socket lockfiles; although more stuff may get added to
1377  * the datadir lockfile later.
1378  */
1379  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
1380  amPostmaster ? (int) my_pid : -((int) my_pid),
1381  DataDir,
1382  (long) MyStartTime,
1384  socketDir);
1385 
1386  /*
1387  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1388  * will never receive data, so fill it in as empty now.
1389  */
1390  if (isDDLock && !amPostmaster)
1391  strlcat(buffer, "\n", sizeof(buffer));
1392 
1393  errno = 0;
1395  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1396  {
1397  int save_errno = errno;
1398 
1399  close(fd);
1400  unlink(filename);
1401  /* if write didn't set errno, assume problem is no disk space */
1402  errno = save_errno ? save_errno : ENOSPC;
1403  ereport(FATAL,
1405  errmsg("could not write lock file \"%s\": %m", filename)));
1406  }
1408 
1410  if (pg_fsync(fd) != 0)
1411  {
1412  int save_errno = errno;
1413 
1414  close(fd);
1415  unlink(filename);
1416  errno = save_errno;
1417  ereport(FATAL,
1419  errmsg("could not write lock file \"%s\": %m", filename)));
1420  }
1422  if (close(fd) != 0)
1423  {
1424  int save_errno = errno;
1425 
1426  unlink(filename);
1427  errno = save_errno;
1428  ereport(FATAL,
1430  errmsg("could not write lock file \"%s\": %m", filename)));
1431  }
1432 
1433  /*
1434  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1435  * one, set up the on_proc_exit function to do it; then add this lock file
1436  * to the list of files to unlink.
1437  */
1438  if (lock_files == NIL)
1440 
1441  /*
1442  * Use lcons so that the lock files are unlinked in reverse order of
1443  * creation; this is critical!
1444  */
1446 }
1447 
1448 /*
1449  * Create the data directory lockfile.
1450  *
1451  * When this is called, we must have already switched the working
1452  * directory to DataDir, so we can just use a relative path. This
1453  * helps ensure that we are locking the directory we should be.
1454  *
1455  * Note that the socket directory path line is initially written as empty.
1456  * postmaster.c will rewrite it upon creating the first Unix socket.
1457  */
1458 void
1459 CreateDataDirLockFile(bool amPostmaster)
1460 {
1461  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1462 }
1463 
1464 /*
1465  * Create a lockfile for the specified Unix socket file.
1466  */
1467 void
1468 CreateSocketLockFile(const char *socketfile, bool amPostmaster,
1469  const char *socketDir)
1470 {
1471  char lockfile[MAXPGPATH];
1472 
1473  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1474  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1475 }
1476 
1477 /*
1478  * TouchSocketLockFiles -- mark socket lock files as recently accessed
1479  *
1480  * This routine should be called every so often to ensure that the socket
1481  * lock files have a recent mod or access date. That saves them
1482  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
1483  * (Another reason we should never have put the socket file in /tmp...)
1484  */
1485 void
1487 {
1488  ListCell *l;
1489 
1490  foreach(l, lock_files)
1491  {
1492  char *socketLockFile = (char *) lfirst(l);
1493 
1494  /* No need to touch the data directory lock file, we trust */
1495  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1496  continue;
1497 
1498  /* we just ignore any error here */
1499  (void) utime(socketLockFile, NULL);
1500  }
1501 }
1502 
1503 
1504 /*
1505  * Add (or replace) a line in the data directory lock file.
1506  * The given string should not include a trailing newline.
1507  *
1508  * Note: because we don't truncate the file, if we were to rewrite a line
1509  * with less data than it had before, there would be garbage after the last
1510  * line. While we could fix that by adding a truncate call, that would make
1511  * the file update non-atomic, which we'd rather avoid. Therefore, callers
1512  * should endeavor never to shorten a line once it's been written.
1513  */
1514 void
1515 AddToDataDirLockFile(int target_line, const char *str)
1516 {
1517  int fd;
1518  int len;
1519  int lineno;
1520  char *srcptr;
1521  char *destptr;
1522  char srcbuffer[BLCKSZ];
1523  char destbuffer[BLCKSZ];
1524 
1525  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1526  if (fd < 0)
1527  {
1528  ereport(LOG,
1530  errmsg("could not open file \"%s\": %m",
1532  return;
1533  }
1535  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1537  if (len < 0)
1538  {
1539  ereport(LOG,
1541  errmsg("could not read from file \"%s\": %m",
1543  close(fd);
1544  return;
1545  }
1546  srcbuffer[len] = '\0';
1547 
1548  /*
1549  * Advance over lines we are not supposed to rewrite, then copy them to
1550  * destbuffer.
1551  */
1552  srcptr = srcbuffer;
1553  for (lineno = 1; lineno < target_line; lineno++)
1554  {
1555  char *eol = strchr(srcptr, '\n');
1556 
1557  if (eol == NULL)
1558  break; /* not enough lines in file yet */
1559  srcptr = eol + 1;
1560  }
1561  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1562  destptr = destbuffer + (srcptr - srcbuffer);
1563 
1564  /*
1565  * Fill in any missing lines before the target line, in case lines are
1566  * added to the file out of order.
1567  */
1568  for (; lineno < target_line; lineno++)
1569  {
1570  if (destptr < destbuffer + sizeof(destbuffer))
1571  *destptr++ = '\n';
1572  }
1573 
1574  /*
1575  * Write or rewrite the target line.
1576  */
1577  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1578  destptr += strlen(destptr);
1579 
1580  /*
1581  * If there are more lines in the old file, append them to destbuffer.
1582  */
1583  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1584  {
1585  srcptr++;
1586  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1587  srcptr);
1588  }
1589 
1590  /*
1591  * And rewrite the data. Since we write in a single kernel call, this
1592  * update should appear atomic to onlookers.
1593  */
1594  len = strlen(destbuffer);
1595  errno = 0;
1597  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1598  {
1600  /* if write didn't set errno, assume problem is no disk space */
1601  if (errno == 0)
1602  errno = ENOSPC;
1603  ereport(LOG,
1605  errmsg("could not write to file \"%s\": %m",
1607  close(fd);
1608  return;
1609  }
1612  if (pg_fsync(fd) != 0)
1613  {
1614  ereport(LOG,
1616  errmsg("could not write to file \"%s\": %m",
1618  }
1620  if (close(fd) != 0)
1621  {
1622  ereport(LOG,
1624  errmsg("could not write to file \"%s\": %m",
1626  }
1627 }
1628 
1629 
1630 /*
1631  * Recheck that the data directory lock file still exists with expected
1632  * content. Return true if the lock file appears OK, false if it isn't.
1633  *
1634  * We call this periodically in the postmaster. The idea is that if the
1635  * lock file has been removed or replaced by another postmaster, we should
1636  * do a panic database shutdown. Therefore, we should return true if there
1637  * is any doubt: we do not want to cause a panic shutdown unnecessarily.
1638  * Transient failures like EINTR or ENFILE should not cause us to fail.
1639  * (If there really is something wrong, we'll detect it on a future recheck.)
1640  */
1641 bool
1643 {
1644  int fd;
1645  int len;
1646  long file_pid;
1647  char buffer[BLCKSZ];
1648 
1649  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1650  if (fd < 0)
1651  {
1652  /*
1653  * There are many foreseeable false-positive error conditions. For
1654  * safety, fail only on enumerated clearly-something-is-wrong
1655  * conditions.
1656  */
1657  switch (errno)
1658  {
1659  case ENOENT:
1660  case ENOTDIR:
1661  /* disaster */
1662  ereport(LOG,
1664  errmsg("could not open file \"%s\": %m",
1666  return false;
1667  default:
1668  /* non-fatal, at least for now */
1669  ereport(LOG,
1671  errmsg("could not open file \"%s\": %m; continuing anyway",
1673  return true;
1674  }
1675  }
1677  len = read(fd, buffer, sizeof(buffer) - 1);
1679  if (len < 0)
1680  {
1681  ereport(LOG,
1683  errmsg("could not read from file \"%s\": %m",
1685  close(fd);
1686  return true; /* treat read failure as nonfatal */
1687  }
1688  buffer[len] = '\0';
1689  close(fd);
1690  file_pid = atol(buffer);
1691  if (file_pid == getpid())
1692  return true; /* all is well */
1693 
1694  /* Trouble: someone's overwritten the lock file */
1695  ereport(LOG,
1696  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1697  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1698  return false;
1699 }
1700 
1701 
1702 /*-------------------------------------------------------------------------
1703  * Version checking support
1704  *-------------------------------------------------------------------------
1705  */
1706 
1707 /*
1708  * Determine whether the PG_VERSION file in directory `path' indicates
1709  * a data version compatible with the version of this program.
1710  *
1711  * If compatible, return. Otherwise, ereport(FATAL).
1712  */
1713 void
1714 ValidatePgVersion(const char *path)
1715 {
1716  char full_path[MAXPGPATH];
1717  FILE *file;
1718  int ret;
1719  long file_major;
1720  long my_major;
1721  char *endptr;
1722  char file_version_string[64];
1723  const char *my_version_string = PG_VERSION;
1724 
1725  my_major = strtol(my_version_string, &endptr, 10);
1726 
1727  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1728 
1729  file = AllocateFile(full_path, "r");
1730  if (!file)
1731  {
1732  if (errno == ENOENT)
1733  ereport(FATAL,
1734  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1735  errmsg("\"%s\" is not a valid data directory",
1736  path),
1737  errdetail("File \"%s\" is missing.", full_path)));
1738  else
1739  ereport(FATAL,
1741  errmsg("could not open file \"%s\": %m", full_path)));
1742  }
1743 
1744  file_version_string[0] = '\0';
1745  ret = fscanf(file, "%63s", file_version_string);
1746  file_major = strtol(file_version_string, &endptr, 10);
1747 
1748  if (ret != 1 || endptr == file_version_string)
1749  ereport(FATAL,
1750  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1751  errmsg("\"%s\" is not a valid data directory",
1752  path),
1753  errdetail("File \"%s\" does not contain valid data.",
1754  full_path),
1755  errhint("You might need to initdb.")));
1756 
1757  FreeFile(file);
1758 
1759  if (my_major != file_major)
1760  ereport(FATAL,
1761  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1762  errmsg("database files are incompatible with server"),
1763  errdetail("The data directory was initialized by PostgreSQL version %s, "
1764  "which is not compatible with this version %s.",
1765  file_version_string, my_version_string)));
1766 }
1767 
1768 /*-------------------------------------------------------------------------
1769  * Library preload support
1770  *-------------------------------------------------------------------------
1771  */
1772 
1773 /*
1774  * GUC variables: lists of library names to be preloaded at postmaster
1775  * start and at backend start
1776  */
1780 
1781 /* Flag telling that we are loading shared_preload_libraries */
1784 
1787 
1788 /*
1789  * load the shared libraries listed in 'libraries'
1790  *
1791  * 'gucname': name of GUC variable, for error reports
1792  * 'restricted': if true, force libraries to be in $libdir/plugins/
1793  */
1794 static void
1795 load_libraries(const char *libraries, const char *gucname, bool restricted)
1796 {
1797  char *rawstring;
1798  List *elemlist;
1799  ListCell *l;
1800 
1801  if (libraries == NULL || libraries[0] == '\0')
1802  return; /* nothing to do */
1803 
1804  /* Need a modifiable copy of string */
1805  rawstring = pstrdup(libraries);
1806 
1807  /* Parse string into list of filename paths */
1808  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1809  {
1810  /* syntax error in list */
1811  list_free_deep(elemlist);
1812  pfree(rawstring);
1813  ereport(LOG,
1814  (errcode(ERRCODE_SYNTAX_ERROR),
1815  errmsg("invalid list syntax in parameter \"%s\"",
1816  gucname)));
1817  return;
1818  }
1819 
1820  foreach(l, elemlist)
1821  {
1822  /* Note that filename was already canonicalized */
1823  char *filename = (char *) lfirst(l);
1824  char *expanded = NULL;
1825 
1826  /* If restricting, insert $libdir/plugins if not mentioned already */
1827  if (restricted && first_dir_separator(filename) == NULL)
1828  {
1829  expanded = psprintf("$libdir/plugins/%s", filename);
1830  filename = expanded;
1831  }
1832  load_file(filename, restricted);
1833  ereport(DEBUG1,
1834  (errmsg_internal("loaded library \"%s\"", filename)));
1835  if (expanded)
1836  pfree(expanded);
1837  }
1838 
1839  list_free_deep(elemlist);
1840  pfree(rawstring);
1841 }
1842 
1843 /*
1844  * process any libraries that should be preloaded at postmaster start
1845  */
1846 void
1848 {
1851  "shared_preload_libraries",
1852  false);
1855 }
1856 
1857 /*
1858  * process any libraries that should be preloaded at backend start
1859  */
1860 void
1862 {
1864  "session_preload_libraries",
1865  false);
1867  "local_preload_libraries",
1868  true);
1869 }
1870 
1871 /*
1872  * process any shared memory requests from preloaded libraries
1873  */
1874 void
1876 {
1878  if (shmem_request_hook)
1881 }
1882 
1883 void
1884 pg_bindtextdomain(const char *domain)
1885 {
1886 #ifdef ENABLE_NLS
1887  if (my_exec_path[0] != '\0')
1888  {
1889  char locale_path[MAXPGPATH];
1890 
1891  get_locale_path(my_exec_path, locale_path);
1892  bindtextdomain(domain, locale_path);
1893  pg_bind_textdomain_codeset(domain);
1894  }
1895 #endif
1896 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3324
void pqinitmask(void)
Definition: pqsignal.c:41
sigset_t BlockSig
Definition: pqsignal.c:23
#define CStringGetTextDatum(s)
Definition: builtins.h:94
#define NameStr(name)
Definition: c.h:730
signed int int32
Definition: c.h:478
#define PG_BINARY
Definition: c.h:1260
#define OidIsValid(objectId)
Definition: c.h:759
size_t Size
Definition: c.h:589
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:158
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errcode_for_socket_access(void)
Definition: elog.c:952
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errcode_for_file_access(void)
Definition: elog.c:881
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define NOTICE
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:149
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2384
int FreeFile(FILE *file)
Definition: fd.c:2582
int pg_fsync(int fd)
Definition: fd.c:356
int pg_file_create_mode
Definition: file_perm.c:19
void SetDataDirectoryCreatePerm(int dataDirMode)
Definition: file_perm.c:34
int pg_mode_mask
Definition: file_perm.c:25
int pg_dir_create_mode
Definition: file_perm.c:18
#define PG_MODE_MASK_GROUP
Definition: file_perm.h:29
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
char pkglib_path[MAXPGPATH]
Definition: globals.c:77
bool IsUnderPostmaster
Definition: globals.c:113
int data_directory_mode
Definition: globals.c:72
bool IsBackgroundWorker
Definition: globals.c:115
char * DataDir
Definition: globals.c:66
bool IsPostmasterEnvironment
Definition: globals.c:112
pg_time_t MyStartTime
Definition: globals.c:45
struct Latch * MyLatch
Definition: globals.c:58
char * DatabasePath
Definition: globals.c:97
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4176
@ PGC_S_DYNAMIC_DEFAULT
Definition: guc.h:110
@ PGC_S_OVERRIDE
Definition: guc.h:119
@ PGC_INTERNAL
Definition: guc.h:69
@ PGC_BACKEND
Definition: guc.h:73
UserAuth
Definition: hba.h:26
#define free(a)
Definition: header.h:65
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
#define close(a)
Definition: win32.h:12
#define write(a, b, c)
Definition: win32.h:14
#define read(a, b, c)
Definition: win32.h:13
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:77
void AcceptInvalidationMessages(void)
Definition: inval.c:746
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
void on_exit_reset(void)
Definition: ipc.c:412
void InitializeLatchWaitSet(void)
Definition: latch.c:321
void InitializeLatchSupport(void)
Definition: latch.c:207
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1008
void SetLatch(Latch *latch)
Definition: latch.c:607
void InitLatch(Latch *latch)
Definition: latch.c:369
#define WL_LATCH_SET
Definition: latch.h:125
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lcons(void *datum, List *list)
Definition: list.c:494
void list_free_deep(List *list)
Definition: list.c:1559
char * pstrdup(const char *in)
Definition: mcxt.c:1624
void pfree(void *pointer)
Definition: mcxt.c:1436
MemoryContext TopMemoryContext
Definition: mcxt.c:141
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1611
ProcessingMode
Definition: miscadmin.h:397
@ InitProcessing
Definition: miscadmin.h:399
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:405
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:306
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:305
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:304
BackendType
Definition: miscadmin.h:318
@ B_WAL_WRITER
Definition: miscadmin.h:332
@ B_WAL_RECEIVER
Definition: miscadmin.h:330
@ B_CHECKPOINTER
Definition: miscadmin.h:326
@ B_WAL_SENDER
Definition: miscadmin.h:331
@ B_LOGGER
Definition: miscadmin.h:327
@ B_STARTUP
Definition: miscadmin.h:329
@ B_BG_WORKER
Definition: miscadmin.h:324
@ B_INVALID
Definition: miscadmin.h:319
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:328
@ B_BG_WRITER
Definition: miscadmin.h:325
@ B_BACKEND
Definition: miscadmin.h:323
@ B_ARCHIVER
Definition: miscadmin.h:320
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:321
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:322
void(* shmem_request_hook_type)(void)
Definition: miscadmin.h:488
struct SerializedClientConnectionInfo SerializedClientConnectionInfo
void ChangeToDataDir(void)
Definition: miscinit.c:449
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition: miscinit.c:984
Oid GetOuterUserId(void)
Definition: miscinit.c:521
bool process_shared_preload_libraries_done
Definition: miscinit.c:1783
void process_shmem_requests(void)
Definition: miscinit.c:1875
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:529
static List * lock_files
Definition: miscinit.c:66
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void SerializeClientConnectionInfo(Size maxsize, char *start_address)
Definition: miscinit.c:1047
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:855
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:832
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1515
void InitProcessLocalLatch(void)
Definition: miscinit.c:242
static bool AuthenticatedUserIsSuperuser
Definition: miscinit.c:496
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:631
void SetSessionAuthorization(Oid userid, bool is_superuser)
Definition: miscinit.c:903
void process_session_preload_libraries(void)
Definition: miscinit.c:1861
static bool SessionUserIsSuperuser
Definition: miscinit.c:497
bool process_shmem_requests_in_progress
Definition: miscinit.c:1786
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:658
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:59
Oid GetUserId(void)
Definition: miscinit.c:510
static const char * SystemUser
Definition: miscinit.c:493
static Oid OuterUserId
Definition: miscinit.c:491
static int SecurityRestrictionContext
Definition: miscinit.c:499
Size EstimateClientConnectionInfoSpace(void)
Definition: miscinit.c:1031
const char * GetSystemUser(void)
Definition: miscinit.c:570
Oid GetSessionUserId(void)
Definition: miscinit.c:544
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:949
bool IgnoreSystemIndexes
Definition: miscinit.c:80
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:579
static Oid SessionUserId
Definition: miscinit.c:490
bool InLocalUserIdChange(void)
Definition: miscinit.c:649
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:879
void SetDatabasePath(const char *path)
Definition: miscinit.c:323
void InitPostmasterChild(void)
Definition: miscinit.c:95
void InitializeSessionUserId(const char *rolename, Oid roleid)
Definition: miscinit.c:729
char * shared_preload_libraries_string
Definition: miscinit.c:1778
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1014
void process_shared_preload_libraries(void)
Definition: miscinit.c:1847
char * session_preload_libraries_string
Definition: miscinit.c:1777
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:552
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1785
char * local_preload_libraries_string
Definition: miscinit.c:1779
static Latch LocalLatchData
Definition: miscinit.c:68
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:264
void TouchSocketLockFiles(void)
Definition: miscinit.c:1486
void RestoreClientConnectionInfo(char *conninfo)
Definition: miscinit.c:1079
static Oid CurrentUserId
Definition: miscinit.c:492
static bool SetRoleIsActive
Definition: miscinit.c:502
bool InNoForceRLSOperation(void)
Definition: miscinit.c:667
static Oid AuthenticatedUserId
Definition: miscinit.c:489
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1795
ProcessingMode Mode
Definition: miscinit.c:61
Oid GetCurrentRoleId(void)
Definition: miscinit.c:928
void checkDataDir(void)
Definition: miscinit.c:336
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:1119
void SwitchToSharedLatch(void)
Definition: miscinit.c:222
BackendType MyBackendType
Definition: miscinit.c:63
void GetUserIdAndContext(Oid *userid, bool *sec_def_context)
Definition: miscinit.c:680
void SetDataDir(const char *dir)
Definition: miscinit.c:429
void SetUserIdAndContext(Oid userid, bool sec_def_context)
Definition: miscinit.c:687
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1782
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1884
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:707
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1154
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1714
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:638
bool RecheckDataDirLockFile(void)
Definition: miscinit.c:1642
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1459
void SwitchBackToLocalLatch(void)
Definition: miscinit.c:249
void CreateSocketLockFile(const char *socketfile, bool amPostmaster, const char *socketDir)
Definition: miscinit.c:1468
NameData rolname
Definition: pg_authid.h:34
FormData_pg_authid * Form_pg_authid
Definition: pg_authid.h:56
bool rolreplication
Definition: pg_authid.h:40
void * arg
#define MAXPGPATH
const void size_t len
static char * argv0
Definition: pg_ctl.c:92
static bool is_superuser(Archive *fout)
Definition: pg_dump.c:4574
static char * filename
Definition: pg_dumpall.c:119
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define LOCK_FILE_LINE_SHMEM_KEY
Definition: pidfile.h:43
void PostmasterDeathSignalInit(void)
Definition: pmsignal.c:437
void get_pkglib_path(const char *my_exec_path, char *ret_path)
Definition: path.c:879
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:888
char * make_absolute_path(const char *path)
Definition: path.c:729
char * first_dir_separator(const char *filename)
Definition: path.c:104
#define pg_pwrite
Definition: port.h:226
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define snprintf
Definition: port.h:238
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
pg_stack_base_t set_stack_base(void)
Definition: postgres.c:3411
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void InitProcessGlobals(void)
Definition: postmaster.c:2645
int PostPortNumber
Definition: postmaster.c:198
int postmaster_alive_fds[2]
Definition: postmaster.c:576
#define POSTMASTER_FD_WATCH
Definition: postmaster.h:46
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:164
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int CountUserBackends(Oid roleid)
Definition: procarray.c:3689
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
void pgwin32_signal_initialize(void)
Definition: signal.c:79
PGPROC * MyProc
Definition: proc.c:66
const char * authn_id
Definition: libpq-be.h:113
UserAuth auth_method
Definition: libpq-be.h:119
Definition: latch.h:111
Definition: pg_list.h:54
Oid roleId
Definition: proc.h:199
Latch procLatch
Definition: proc.h:170
unsigned short st_mode
Definition: win32_port.h:270
short st_uid
Definition: win32_port.h:272
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:866
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:818
@ AUTHOID
Definition: syscache.h:45
@ AUTHNAME
Definition: syscache.h:44
bool PGSharedMemoryIsInUse(unsigned long id1, unsigned long id2)
Definition: sysv_shmem.c:316
bool SplitDirectoriesString(char *rawstring, char separator, List **namelist)
Definition: varlena.c:3582
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE
Definition: wait_event.h:189
@ WAIT_EVENT_LOCK_FILE_CREATE_SYNC
Definition: wait_event.h:191
@ WAIT_EVENT_LOCK_FILE_CREATE_READ
Definition: wait_event.h:190
@ WAIT_EVENT_LOCK_FILE_CREATE_WRITE
Definition: wait_event.h:192
@ WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ
Definition: wait_event.h:193
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ
Definition: wait_event.h:187
@ WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC
Definition: wait_event.h:188
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:271
static void pgstat_report_wait_end(void)
Definition: wait_event.h:287
#define stat
Definition: win32_port.h:286
#define SIGQUIT
Definition: win32_port.h:177
#define S_ISDIR(m)
Definition: win32_port.h:327
#define kill(pid, sig)
Definition: win32_port.h:489