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 AuthenticatedUserId is a
471  * superuser). 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 the session user */
496 static bool SessionUserIsSuperuser = false;
497 
499 
500 /* We also remember if a SET ROLE is currently active */
501 static bool SetRoleIsActive = false;
502 
503 /*
504  * GetUserId - get the current effective user ID.
505  *
506  * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
507  */
508 Oid
510 {
512  return CurrentUserId;
513 }
514 
515 
516 /*
517  * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
518  */
519 Oid
521 {
523  return OuterUserId;
524 }
525 
526 
527 static void
529 {
531  Assert(OidIsValid(userid));
532  OuterUserId = userid;
533 
534  /* We force the effective user ID to match, too */
535  CurrentUserId = userid;
536 }
537 
538 
539 /*
540  * GetSessionUserId/SetSessionUserId - get/set the session user ID.
541  */
542 Oid
544 {
546  return SessionUserId;
547 }
548 
549 
550 static void
552 {
554  Assert(OidIsValid(userid));
555  SessionUserId = userid;
557  SetRoleIsActive = false;
558 
559  /* We force the effective user IDs to match, too */
560  OuterUserId = userid;
561  CurrentUserId = userid;
562 }
563 
564 /*
565  * Return the system user representing the authenticated identity.
566  * It is defined in InitializeSystemUser() as auth_method:authn_id.
567  */
568 const char *
570 {
571  return SystemUser;
572 }
573 
574 /*
575  * GetAuthenticatedUserId - get the authenticated user ID
576  */
577 Oid
579 {
581  return AuthenticatedUserId;
582 }
583 
584 
585 /*
586  * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
587  * and the SecurityRestrictionContext flags.
588  *
589  * Currently there are three valid bits in SecurityRestrictionContext:
590  *
591  * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
592  * that is temporarily changing CurrentUserId via these functions. This is
593  * needed to indicate that the actual value of CurrentUserId is not in sync
594  * with guc.c's internal state, so SET ROLE has to be disallowed.
595  *
596  * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
597  * that does not wish to trust called user-defined functions at all. The
598  * policy is to use this before operations, e.g. autovacuum and REINDEX, that
599  * enumerate relations of a database or schema and run functions associated
600  * with each found relation. The relation owner is the new user ID. Set this
601  * as soon as possible after locking the relation. Restore the old user ID as
602  * late as possible before closing the relation; restoring it shortly after
603  * close is also tolerable. If a command has both relation-enumerating and
604  * non-enumerating modes, e.g. ANALYZE, both modes set this bit. This bit
605  * prevents not only SET ROLE, but various other changes of session state that
606  * normally is unprotected but might possibly be used to subvert the calling
607  * session later. An example is replacing an existing prepared statement with
608  * new code, which will then be executed with the outer session's permissions
609  * when the prepared statement is next used. These restrictions are fairly
610  * draconian, but the functions called in relation-enumerating operations are
611  * really supposed to be side-effect-free anyway.
612  *
613  * SECURITY_NOFORCE_RLS indicates that we are inside an operation which should
614  * ignore the FORCE ROW LEVEL SECURITY per-table indication. This is used to
615  * ensure that FORCE RLS does not mistakenly break referential integrity
616  * checks. Note that this is intentionally only checked when running as the
617  * owner of the table (which should always be the case for referential
618  * integrity checks).
619  *
620  * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
621  * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
622  * the new value to be valid. In fact, these routines had better not
623  * ever throw any kind of error. This is because they are used by
624  * StartTransaction and AbortTransaction to save/restore the settings,
625  * and during the first transaction within a backend, the value to be saved
626  * and perhaps restored is indeed invalid. We have to be able to get
627  * through AbortTransaction without asserting in case InitPostgres fails.
628  */
629 void
630 GetUserIdAndSecContext(Oid *userid, int *sec_context)
631 {
632  *userid = CurrentUserId;
633  *sec_context = SecurityRestrictionContext;
634 }
635 
636 void
637 SetUserIdAndSecContext(Oid userid, int sec_context)
638 {
639  CurrentUserId = userid;
640  SecurityRestrictionContext = sec_context;
641 }
642 
643 
644 /*
645  * InLocalUserIdChange - are we inside a local change of CurrentUserId?
646  */
647 bool
649 {
651 }
652 
653 /*
654  * InSecurityRestrictedOperation - are we inside a security-restricted command?
655  */
656 bool
658 {
660 }
661 
662 /*
663  * InNoForceRLSOperation - are we ignoring FORCE ROW LEVEL SECURITY ?
664  */
665 bool
667 {
669 }
670 
671 
672 /*
673  * These are obsolete versions of Get/SetUserIdAndSecContext that are
674  * only provided for bug-compatibility with some rather dubious code in
675  * pljava. We allow the userid to be set, but only when not inside a
676  * security restriction context.
677  */
678 void
679 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
680 {
681  *userid = CurrentUserId;
682  *sec_def_context = InLocalUserIdChange();
683 }
684 
685 void
686 SetUserIdAndContext(Oid userid, bool sec_def_context)
687 {
688  /* We throw the same error SET ROLE would. */
690  ereport(ERROR,
691  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
692  errmsg("cannot set parameter \"%s\" within security-restricted operation",
693  "role")));
694  CurrentUserId = userid;
695  if (sec_def_context)
697  else
699 }
700 
701 
702 /*
703  * Check whether specified role has explicit REPLICATION privilege
704  */
705 bool
707 {
708  bool result = false;
709  HeapTuple utup;
710 
711  /* Superusers bypass all permission checking. */
712  if (superuser_arg(roleid))
713  return true;
714 
715  utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
716  if (HeapTupleIsValid(utup))
717  {
718  result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
719  ReleaseSysCache(utup);
720  }
721  return result;
722 }
723 
724 /*
725  * Initialize user identity during normal backend startup
726  */
727 void
728 InitializeSessionUserId(const char *rolename, Oid roleid, bool bypass_login_check)
729 {
730  HeapTuple roleTup;
731  Form_pg_authid rform;
732  char *rname;
733  bool is_superuser;
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  is_superuser = 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 (!bypass_login_check && !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 &&
809  !is_superuser &&
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  is_superuser ? "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;
844  SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
845 
846  /*
847  * XXX This should set SetConfigOption("session_authorization"), too.
848  * Since we don't, C code will get NULL, and current_setting() will get an
849  * empty string.
850  */
851  SetConfigOption("is_superuser", "on",
853 }
854 
855 /*
856  * Initialize the system user.
857  *
858  * This is built as auth_method:authn_id.
859  */
860 void
861 InitializeSystemUser(const char *authn_id, const char *auth_method)
862 {
863  char *system_user;
864 
865  /* call only once */
866  Assert(SystemUser == NULL);
867 
868  /*
869  * InitializeSystemUser should be called only when authn_id is not NULL,
870  * meaning that auth_method is valid.
871  */
872  Assert(authn_id != NULL);
873 
874  system_user = psprintf("%s:%s", auth_method, authn_id);
875 
876  /* Store SystemUser in long-lived storage */
879 }
880 
881 /*
882  * SQL-function SYSTEM_USER
883  */
884 Datum
886 {
887  const char *sysuser = GetSystemUser();
888 
889  if (sysuser)
891  else
892  PG_RETURN_NULL();
893 }
894 
895 /*
896  * Change session auth ID while running
897  *
898  * Note that we set the GUC variable is_superuser to indicate whether the
899  * current role is a superuser.
900  */
901 void
903 {
905 
906  SetConfigOption("is_superuser",
907  is_superuser ? "on" : "off",
909 }
910 
911 /*
912  * Report current role id
913  * This follows the semantics of SET ROLE, ie return the outer-level ID
914  * not the current effective ID, and return InvalidOid when the setting
915  * is logically SET ROLE NONE.
916  */
917 Oid
919 {
920  if (SetRoleIsActive)
921  return OuterUserId;
922  else
923  return InvalidOid;
924 }
925 
926 /*
927  * Change Role ID while running (SET ROLE)
928  *
929  * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
930  * session user authorization. In this case the is_superuser argument
931  * is ignored.
932  *
933  * When roleid is not InvalidOid, the caller must have checked whether
934  * the session user has permission to become that role. (We cannot check
935  * here because this routine must be able to execute in a failed transaction
936  * to restore a prior value of the ROLE GUC variable.)
937  */
938 void
940 {
941  /*
942  * Get correct info if it's SET ROLE NONE
943  *
944  * If SessionUserId hasn't been set yet, just do nothing --- the eventual
945  * SetSessionUserId call will fix everything. This is needed since we
946  * will get called during GUC initialization.
947  */
948  if (!OidIsValid(roleid))
949  {
951  return;
952 
953  roleid = SessionUserId;
955 
956  SetRoleIsActive = false;
957  }
958  else
959  SetRoleIsActive = true;
960 
961  SetOuterUserId(roleid);
962 
963  SetConfigOption("is_superuser",
964  is_superuser ? "on" : "off",
966 }
967 
968 
969 /*
970  * Get user name from user oid, returns NULL for nonexistent roleid if noerr
971  * is true.
972  */
973 char *
974 GetUserNameFromId(Oid roleid, bool noerr)
975 {
976  HeapTuple tuple;
977  char *result;
978 
979  tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
980  if (!HeapTupleIsValid(tuple))
981  {
982  if (!noerr)
983  ereport(ERROR,
984  (errcode(ERRCODE_UNDEFINED_OBJECT),
985  errmsg("invalid role OID: %u", roleid)));
986  result = NULL;
987  }
988  else
989  {
990  result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
991  ReleaseSysCache(tuple);
992  }
993  return result;
994 }
995 
996 /* ------------------------------------------------------------------------
997  * Client connection state shared with parallel workers
998  *
999  * ClientConnectionInfo contains pieces of information about the client that
1000  * need to be synced to parallel workers when they initialize.
1001  *-------------------------------------------------------------------------
1002  */
1003 
1005 
1006 /*
1007  * Intermediate representation of ClientConnectionInfo for easier
1008  * serialization. Variable-length fields are allocated right after this
1009  * header.
1010  */
1012 {
1013  int32 authn_id_len; /* strlen(authn_id), or -1 if NULL */
1016 
1017 /*
1018  * Calculate the space needed to serialize MyClientConnectionInfo.
1019  */
1020 Size
1022 {
1023  Size size = 0;
1024 
1025  size = add_size(size, sizeof(SerializedClientConnectionInfo));
1026 
1028  size = add_size(size, strlen(MyClientConnectionInfo.authn_id) + 1);
1029 
1030  return size;
1031 }
1032 
1033 /*
1034  * Serialize MyClientConnectionInfo for use by parallel workers.
1035  */
1036 void
1037 SerializeClientConnectionInfo(Size maxsize, char *start_address)
1038 {
1039  SerializedClientConnectionInfo serialized = {0};
1040 
1041  serialized.authn_id_len = -1;
1043 
1045  serialized.authn_id_len = strlen(MyClientConnectionInfo.authn_id);
1046 
1047  /* Copy serialized representation to buffer */
1048  Assert(maxsize >= sizeof(serialized));
1049  memcpy(start_address, &serialized, sizeof(serialized));
1050 
1051  maxsize -= sizeof(serialized);
1052  start_address += sizeof(serialized);
1053 
1054  /* Copy authn_id into the space after the struct */
1055  if (serialized.authn_id_len >= 0)
1056  {
1057  Assert(maxsize >= (serialized.authn_id_len + 1));
1058  memcpy(start_address,
1060  /* include the NULL terminator to ease deserialization */
1061  serialized.authn_id_len + 1);
1062  }
1063 }
1064 
1065 /*
1066  * Restore MyClientConnectionInfo from its serialized representation.
1067  */
1068 void
1070 {
1071  SerializedClientConnectionInfo serialized;
1072 
1073  memcpy(&serialized, conninfo, sizeof(serialized));
1074 
1075  /* Copy the fields back into place */
1078 
1079  if (serialized.authn_id_len >= 0)
1080  {
1081  char *authn_id;
1082 
1083  authn_id = conninfo + sizeof(serialized);
1085  authn_id);
1086  }
1087 }
1088 
1089 
1090 /*-------------------------------------------------------------------------
1091  * Interlock-file support
1092  *
1093  * These routines are used to create both a data-directory lockfile
1094  * ($DATADIR/postmaster.pid) and Unix-socket-file lockfiles ($SOCKFILE.lock).
1095  * Both kinds of files contain the same info initially, although we can add
1096  * more information to a data-directory lockfile after it's created, using
1097  * AddToDataDirLockFile(). See pidfile.h for documentation of the contents
1098  * of these lockfiles.
1099  *
1100  * On successful lockfile creation, a proc_exit callback to remove the
1101  * lockfile is automatically created.
1102  *-------------------------------------------------------------------------
1103  */
1104 
1105 /*
1106  * proc_exit callback to remove lockfiles.
1107  */
1108 static void
1110 {
1111  ListCell *l;
1112 
1113  foreach(l, lock_files)
1114  {
1115  char *curfile = (char *) lfirst(l);
1116 
1117  unlink(curfile);
1118  /* Should we complain if the unlink fails? */
1119  }
1120  /* Since we're about to exit, no need to reclaim storage */
1121  lock_files = NIL;
1122 
1123  /*
1124  * Lock file removal should always be the last externally visible action
1125  * of a postmaster or standalone backend, while we won't come here at all
1126  * when exiting postmaster child processes. Therefore, this is a good
1127  * place to log completion of shutdown. We could alternatively teach
1128  * proc_exit() to do it, but that seems uglier. In a standalone backend,
1129  * use NOTICE elevel to be less chatty.
1130  */
1132  (errmsg("database system is shut down")));
1133 }
1134 
1135 /*
1136  * Create a lockfile.
1137  *
1138  * filename is the path name of the lockfile to create.
1139  * amPostmaster is used to determine how to encode the output PID.
1140  * socketDir is the Unix socket directory path to include (possibly empty).
1141  * isDDLock and refName are used to determine what error message to produce.
1142  */
1143 static void
1144 CreateLockFile(const char *filename, bool amPostmaster,
1145  const char *socketDir,
1146  bool isDDLock, const char *refName)
1147 {
1148  int fd;
1149  char buffer[MAXPGPATH * 2 + 256];
1150  int ntries;
1151  int len;
1152  int encoded_pid;
1153  pid_t other_pid;
1154  pid_t my_pid,
1155  my_p_pid,
1156  my_gp_pid;
1157  const char *envvar;
1158 
1159  /*
1160  * If the PID in the lockfile is our own PID or our parent's or
1161  * grandparent's PID, then the file must be stale (probably left over from
1162  * a previous system boot cycle). We need to check this because of the
1163  * likelihood that a reboot will assign exactly the same PID as we had in
1164  * the previous reboot, or one that's only one or two counts larger and
1165  * hence the lockfile's PID now refers to an ancestor shell process. We
1166  * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
1167  * via the environment variable PG_GRANDPARENT_PID; this is so that
1168  * launching the postmaster via pg_ctl can be just as reliable as
1169  * launching it directly. There is no provision for detecting
1170  * further-removed ancestor processes, but if the init script is written
1171  * carefully then all but the immediate parent shell will be root-owned
1172  * processes and so the kill test will fail with EPERM. Note that we
1173  * cannot get a false negative this way, because an existing postmaster
1174  * would surely never launch a competing postmaster or pg_ctl process
1175  * directly.
1176  */
1177  my_pid = getpid();
1178 
1179 #ifndef WIN32
1180  my_p_pid = getppid();
1181 #else
1182 
1183  /*
1184  * Windows hasn't got getppid(), but doesn't need it since it's not using
1185  * real kill() either...
1186  */
1187  my_p_pid = 0;
1188 #endif
1189 
1190  envvar = getenv("PG_GRANDPARENT_PID");
1191  if (envvar)
1192  my_gp_pid = atoi(envvar);
1193  else
1194  my_gp_pid = 0;
1195 
1196  /*
1197  * We need a loop here because of race conditions. But don't loop forever
1198  * (for example, a non-writable $PGDATA directory might cause a failure
1199  * that won't go away). 100 tries seems like plenty.
1200  */
1201  for (ntries = 0;; ntries++)
1202  {
1203  /*
1204  * Try to create the lock file --- O_EXCL makes this atomic.
1205  *
1206  * Think not to make the file protection weaker than 0600/0640. See
1207  * comments below.
1208  */
1209  fd = open(filename, O_RDWR | O_CREAT | O_EXCL, pg_file_create_mode);
1210  if (fd >= 0)
1211  break; /* Success; exit the retry loop */
1212 
1213  /*
1214  * Couldn't create the pid file. Probably it already exists.
1215  */
1216  if ((errno != EEXIST && errno != EACCES) || ntries > 100)
1217  ereport(FATAL,
1219  errmsg("could not create lock file \"%s\": %m",
1220  filename)));
1221 
1222  /*
1223  * Read the file to get the old owner's PID. Note race condition
1224  * here: file might have been deleted since we tried to create it.
1225  */
1226  fd = open(filename, O_RDONLY, pg_file_create_mode);
1227  if (fd < 0)
1228  {
1229  if (errno == ENOENT)
1230  continue; /* race condition; try again */
1231  ereport(FATAL,
1233  errmsg("could not open lock file \"%s\": %m",
1234  filename)));
1235  }
1236  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_CREATE_READ);
1237  if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
1238  ereport(FATAL,
1240  errmsg("could not read lock file \"%s\": %m",
1241  filename)));
1243  close(fd);
1244 
1245  if (len == 0)
1246  {
1247  ereport(FATAL,
1248  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1249  errmsg("lock file \"%s\" is empty", filename),
1250  errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
1251  }
1252 
1253  buffer[len] = '\0';
1254  encoded_pid = atoi(buffer);
1255 
1256  /* if pid < 0, the pid is for postgres, not postmaster */
1257  other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
1258 
1259  if (other_pid <= 0)
1260  elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
1261  filename, buffer);
1262 
1263  /*
1264  * Check to see if the other process still exists
1265  *
1266  * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
1267  * ignored as false matches.
1268  *
1269  * Normally kill() will fail with ESRCH if the given PID doesn't
1270  * exist.
1271  *
1272  * We can treat the EPERM-error case as okay because that error
1273  * implies that the existing process has a different userid than we
1274  * do, which means it cannot be a competing postmaster. A postmaster
1275  * cannot successfully attach to a data directory owned by a userid
1276  * other than its own, as enforced in checkDataDir(). Also, since we
1277  * create the lockfiles mode 0600/0640, we'd have failed above if the
1278  * lockfile belonged to another userid --- which means that whatever
1279  * process kill() is reporting about isn't the one that made the
1280  * lockfile. (NOTE: this last consideration is the only one that
1281  * keeps us from blowing away a Unix socket file belonging to an
1282  * instance of Postgres being run by someone else, at least on
1283  * machines where /tmp hasn't got a stickybit.)
1284  */
1285  if (other_pid != my_pid && other_pid != my_p_pid &&
1286  other_pid != my_gp_pid)
1287  {
1288  if (kill(other_pid, 0) == 0 ||
1289  (errno != ESRCH && errno != EPERM))
1290  {
1291  /* lockfile belongs to a live process */
1292  ereport(FATAL,
1293  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1294  errmsg("lock file \"%s\" already exists",
1295  filename),
1296  isDDLock ?
1297  (encoded_pid < 0 ?
1298  errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
1299  (int) other_pid, refName) :
1300  errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
1301  (int) other_pid, refName)) :
1302  (encoded_pid < 0 ?
1303  errhint("Is another postgres (PID %d) using socket file \"%s\"?",
1304  (int) other_pid, refName) :
1305  errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
1306  (int) other_pid, refName))));
1307  }
1308  }
1309 
1310  /*
1311  * No, the creating process did not exist. However, it could be that
1312  * the postmaster crashed (or more likely was kill -9'd by a clueless
1313  * admin) but has left orphan backends behind. Check for this by
1314  * looking to see if there is an associated shmem segment that is
1315  * still in use.
1316  *
1317  * Note: because postmaster.pid is written in multiple steps, we might
1318  * not find the shmem ID values in it; we can't treat that as an
1319  * error.
1320  */
1321  if (isDDLock)
1322  {
1323  char *ptr = buffer;
1324  unsigned long id1,
1325  id2;
1326  int lineno;
1327 
1328  for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
1329  {
1330  if ((ptr = strchr(ptr, '\n')) == NULL)
1331  break;
1332  ptr++;
1333  }
1334 
1335  if (ptr != NULL &&
1336  sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
1337  {
1338  if (PGSharedMemoryIsInUse(id1, id2))
1339  ereport(FATAL,
1340  (errcode(ERRCODE_LOCK_FILE_EXISTS),
1341  errmsg("pre-existing shared memory block (key %lu, ID %lu) is still in use",
1342  id1, id2),
1343  errhint("Terminate any old server processes associated with data directory \"%s\".",
1344  refName)));
1345  }
1346  }
1347 
1348  /*
1349  * Looks like nobody's home. Unlink the file and try again to create
1350  * it. Need a loop because of possible race condition against other
1351  * would-be creators.
1352  */
1353  if (unlink(filename) < 0)
1354  ereport(FATAL,
1356  errmsg("could not remove old lock file \"%s\": %m",
1357  filename),
1358  errhint("The file seems accidentally left over, but "
1359  "it could not be removed. Please remove the file "
1360  "by hand and try again.")));
1361  }
1362 
1363  /*
1364  * Successfully created the file, now fill it. See comment in pidfile.h
1365  * about the contents. Note that we write the same first five lines into
1366  * both datadir and socket lockfiles; although more stuff may get added to
1367  * the datadir lockfile later.
1368  */
1369  snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
1370  amPostmaster ? (int) my_pid : -((int) my_pid),
1371  DataDir,
1372  (long) MyStartTime,
1374  socketDir);
1375 
1376  /*
1377  * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
1378  * will never receive data, so fill it in as empty now.
1379  */
1380  if (isDDLock && !amPostmaster)
1381  strlcat(buffer, "\n", sizeof(buffer));
1382 
1383  errno = 0;
1384  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_CREATE_WRITE);
1385  if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
1386  {
1387  int save_errno = errno;
1388 
1389  close(fd);
1390  unlink(filename);
1391  /* if write didn't set errno, assume problem is no disk space */
1392  errno = save_errno ? save_errno : ENOSPC;
1393  ereport(FATAL,
1395  errmsg("could not write lock file \"%s\": %m", filename)));
1396  }
1398 
1399  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_CREATE_SYNC);
1400  if (pg_fsync(fd) != 0)
1401  {
1402  int save_errno = errno;
1403 
1404  close(fd);
1405  unlink(filename);
1406  errno = save_errno;
1407  ereport(FATAL,
1409  errmsg("could not write lock file \"%s\": %m", filename)));
1410  }
1412  if (close(fd) != 0)
1413  {
1414  int save_errno = errno;
1415 
1416  unlink(filename);
1417  errno = save_errno;
1418  ereport(FATAL,
1420  errmsg("could not write lock file \"%s\": %m", filename)));
1421  }
1422 
1423  /*
1424  * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1425  * one, set up the on_proc_exit function to do it; then add this lock file
1426  * to the list of files to unlink.
1427  */
1428  if (lock_files == NIL)
1430 
1431  /*
1432  * Use lcons so that the lock files are unlinked in reverse order of
1433  * creation; this is critical!
1434  */
1436 }
1437 
1438 /*
1439  * Create the data directory lockfile.
1440  *
1441  * When this is called, we must have already switched the working
1442  * directory to DataDir, so we can just use a relative path. This
1443  * helps ensure that we are locking the directory we should be.
1444  *
1445  * Note that the socket directory path line is initially written as empty.
1446  * postmaster.c will rewrite it upon creating the first Unix socket.
1447  */
1448 void
1449 CreateDataDirLockFile(bool amPostmaster)
1450 {
1451  CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1452 }
1453 
1454 /*
1455  * Create a lockfile for the specified Unix socket file.
1456  */
1457 void
1458 CreateSocketLockFile(const char *socketfile, bool amPostmaster,
1459  const char *socketDir)
1460 {
1461  char lockfile[MAXPGPATH];
1462 
1463  snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1464  CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1465 }
1466 
1467 /*
1468  * TouchSocketLockFiles -- mark socket lock files as recently accessed
1469  *
1470  * This routine should be called every so often to ensure that the socket
1471  * lock files have a recent mod or access date. That saves them
1472  * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
1473  * (Another reason we should never have put the socket file in /tmp...)
1474  */
1475 void
1477 {
1478  ListCell *l;
1479 
1480  foreach(l, lock_files)
1481  {
1482  char *socketLockFile = (char *) lfirst(l);
1483 
1484  /* No need to touch the data directory lock file, we trust */
1485  if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1486  continue;
1487 
1488  /* we just ignore any error here */
1489  (void) utime(socketLockFile, NULL);
1490  }
1491 }
1492 
1493 
1494 /*
1495  * Add (or replace) a line in the data directory lock file.
1496  * The given string should not include a trailing newline.
1497  *
1498  * Note: because we don't truncate the file, if we were to rewrite a line
1499  * with less data than it had before, there would be garbage after the last
1500  * line. While we could fix that by adding a truncate call, that would make
1501  * the file update non-atomic, which we'd rather avoid. Therefore, callers
1502  * should endeavor never to shorten a line once it's been written.
1503  */
1504 void
1505 AddToDataDirLockFile(int target_line, const char *str)
1506 {
1507  int fd;
1508  int len;
1509  int lineno;
1510  char *srcptr;
1511  char *destptr;
1512  char srcbuffer[BLCKSZ];
1513  char destbuffer[BLCKSZ];
1514 
1515  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1516  if (fd < 0)
1517  {
1518  ereport(LOG,
1520  errmsg("could not open file \"%s\": %m",
1522  return;
1523  }
1524  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_READ);
1525  len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1527  if (len < 0)
1528  {
1529  ereport(LOG,
1531  errmsg("could not read from file \"%s\": %m",
1533  close(fd);
1534  return;
1535  }
1536  srcbuffer[len] = '\0';
1537 
1538  /*
1539  * Advance over lines we are not supposed to rewrite, then copy them to
1540  * destbuffer.
1541  */
1542  srcptr = srcbuffer;
1543  for (lineno = 1; lineno < target_line; lineno++)
1544  {
1545  char *eol = strchr(srcptr, '\n');
1546 
1547  if (eol == NULL)
1548  break; /* not enough lines in file yet */
1549  srcptr = eol + 1;
1550  }
1551  memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1552  destptr = destbuffer + (srcptr - srcbuffer);
1553 
1554  /*
1555  * Fill in any missing lines before the target line, in case lines are
1556  * added to the file out of order.
1557  */
1558  for (; lineno < target_line; lineno++)
1559  {
1560  if (destptr < destbuffer + sizeof(destbuffer))
1561  *destptr++ = '\n';
1562  }
1563 
1564  /*
1565  * Write or rewrite the target line.
1566  */
1567  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1568  destptr += strlen(destptr);
1569 
1570  /*
1571  * If there are more lines in the old file, append them to destbuffer.
1572  */
1573  if ((srcptr = strchr(srcptr, '\n')) != NULL)
1574  {
1575  srcptr++;
1576  snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1577  srcptr);
1578  }
1579 
1580  /*
1581  * And rewrite the data. Since we write in a single kernel call, this
1582  * update should appear atomic to onlookers.
1583  */
1584  len = strlen(destbuffer);
1585  errno = 0;
1586  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_WRITE);
1587  if (pg_pwrite(fd, destbuffer, len, 0) != len)
1588  {
1590  /* if write didn't set errno, assume problem is no disk space */
1591  if (errno == 0)
1592  errno = ENOSPC;
1593  ereport(LOG,
1595  errmsg("could not write to file \"%s\": %m",
1597  close(fd);
1598  return;
1599  }
1601  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_ADDTODATADIR_SYNC);
1602  if (pg_fsync(fd) != 0)
1603  {
1604  ereport(LOG,
1606  errmsg("could not write to file \"%s\": %m",
1608  }
1610  if (close(fd) != 0)
1611  {
1612  ereport(LOG,
1614  errmsg("could not write to file \"%s\": %m",
1616  }
1617 }
1618 
1619 
1620 /*
1621  * Recheck that the data directory lock file still exists with expected
1622  * content. Return true if the lock file appears OK, false if it isn't.
1623  *
1624  * We call this periodically in the postmaster. The idea is that if the
1625  * lock file has been removed or replaced by another postmaster, we should
1626  * do a panic database shutdown. Therefore, we should return true if there
1627  * is any doubt: we do not want to cause a panic shutdown unnecessarily.
1628  * Transient failures like EINTR or ENFILE should not cause us to fail.
1629  * (If there really is something wrong, we'll detect it on a future recheck.)
1630  */
1631 bool
1633 {
1634  int fd;
1635  int len;
1636  long file_pid;
1637  char buffer[BLCKSZ];
1638 
1639  fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1640  if (fd < 0)
1641  {
1642  /*
1643  * There are many foreseeable false-positive error conditions. For
1644  * safety, fail only on enumerated clearly-something-is-wrong
1645  * conditions.
1646  */
1647  switch (errno)
1648  {
1649  case ENOENT:
1650  case ENOTDIR:
1651  /* disaster */
1652  ereport(LOG,
1654  errmsg("could not open file \"%s\": %m",
1656  return false;
1657  default:
1658  /* non-fatal, at least for now */
1659  ereport(LOG,
1661  errmsg("could not open file \"%s\": %m; continuing anyway",
1663  return true;
1664  }
1665  }
1666  pgstat_report_wait_start(WAIT_EVENT_LOCK_FILE_RECHECKDATADIR_READ);
1667  len = read(fd, buffer, sizeof(buffer) - 1);
1669  if (len < 0)
1670  {
1671  ereport(LOG,
1673  errmsg("could not read from file \"%s\": %m",
1675  close(fd);
1676  return true; /* treat read failure as nonfatal */
1677  }
1678  buffer[len] = '\0';
1679  close(fd);
1680  file_pid = atol(buffer);
1681  if (file_pid == getpid())
1682  return true; /* all is well */
1683 
1684  /* Trouble: someone's overwritten the lock file */
1685  ereport(LOG,
1686  (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1687  DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1688  return false;
1689 }
1690 
1691 
1692 /*-------------------------------------------------------------------------
1693  * Version checking support
1694  *-------------------------------------------------------------------------
1695  */
1696 
1697 /*
1698  * Determine whether the PG_VERSION file in directory `path' indicates
1699  * a data version compatible with the version of this program.
1700  *
1701  * If compatible, return. Otherwise, ereport(FATAL).
1702  */
1703 void
1704 ValidatePgVersion(const char *path)
1705 {
1706  char full_path[MAXPGPATH];
1707  FILE *file;
1708  int ret;
1709  long file_major;
1710  long my_major;
1711  char *endptr;
1712  char file_version_string[64];
1713  const char *my_version_string = PG_VERSION;
1714 
1715  my_major = strtol(my_version_string, &endptr, 10);
1716 
1717  snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1718 
1719  file = AllocateFile(full_path, "r");
1720  if (!file)
1721  {
1722  if (errno == ENOENT)
1723  ereport(FATAL,
1724  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1725  errmsg("\"%s\" is not a valid data directory",
1726  path),
1727  errdetail("File \"%s\" is missing.", full_path)));
1728  else
1729  ereport(FATAL,
1731  errmsg("could not open file \"%s\": %m", full_path)));
1732  }
1733 
1734  file_version_string[0] = '\0';
1735  ret = fscanf(file, "%63s", file_version_string);
1736  file_major = strtol(file_version_string, &endptr, 10);
1737 
1738  if (ret != 1 || endptr == file_version_string)
1739  ereport(FATAL,
1740  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1741  errmsg("\"%s\" is not a valid data directory",
1742  path),
1743  errdetail("File \"%s\" does not contain valid data.",
1744  full_path),
1745  errhint("You might need to initdb.")));
1746 
1747  FreeFile(file);
1748 
1749  if (my_major != file_major)
1750  ereport(FATAL,
1751  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1752  errmsg("database files are incompatible with server"),
1753  errdetail("The data directory was initialized by PostgreSQL version %s, "
1754  "which is not compatible with this version %s.",
1755  file_version_string, my_version_string)));
1756 }
1757 
1758 /*-------------------------------------------------------------------------
1759  * Library preload support
1760  *-------------------------------------------------------------------------
1761  */
1762 
1763 /*
1764  * GUC variables: lists of library names to be preloaded at postmaster
1765  * start and at backend start
1766  */
1770 
1771 /* Flag telling that we are loading shared_preload_libraries */
1774 
1777 
1778 /*
1779  * load the shared libraries listed in 'libraries'
1780  *
1781  * 'gucname': name of GUC variable, for error reports
1782  * 'restricted': if true, force libraries to be in $libdir/plugins/
1783  */
1784 static void
1785 load_libraries(const char *libraries, const char *gucname, bool restricted)
1786 {
1787  char *rawstring;
1788  List *elemlist;
1789  ListCell *l;
1790 
1791  if (libraries == NULL || libraries[0] == '\0')
1792  return; /* nothing to do */
1793 
1794  /* Need a modifiable copy of string */
1795  rawstring = pstrdup(libraries);
1796 
1797  /* Parse string into list of filename paths */
1798  if (!SplitDirectoriesString(rawstring, ',', &elemlist))
1799  {
1800  /* syntax error in list */
1801  list_free_deep(elemlist);
1802  pfree(rawstring);
1803  ereport(LOG,
1804  (errcode(ERRCODE_SYNTAX_ERROR),
1805  errmsg("invalid list syntax in parameter \"%s\"",
1806  gucname)));
1807  return;
1808  }
1809 
1810  foreach(l, elemlist)
1811  {
1812  /* Note that filename was already canonicalized */
1813  char *filename = (char *) lfirst(l);
1814  char *expanded = NULL;
1815 
1816  /* If restricting, insert $libdir/plugins if not mentioned already */
1817  if (restricted && first_dir_separator(filename) == NULL)
1818  {
1819  expanded = psprintf("$libdir/plugins/%s", filename);
1820  filename = expanded;
1821  }
1822  load_file(filename, restricted);
1823  ereport(DEBUG1,
1824  (errmsg_internal("loaded library \"%s\"", filename)));
1825  if (expanded)
1826  pfree(expanded);
1827  }
1828 
1829  list_free_deep(elemlist);
1830  pfree(rawstring);
1831 }
1832 
1833 /*
1834  * process any libraries that should be preloaded at postmaster start
1835  */
1836 void
1838 {
1841  "shared_preload_libraries",
1842  false);
1845 }
1846 
1847 /*
1848  * process any libraries that should be preloaded at backend start
1849  */
1850 void
1852 {
1854  "session_preload_libraries",
1855  false);
1857  "local_preload_libraries",
1858  true);
1859 }
1860 
1861 /*
1862  * process any shared memory requests from preloaded libraries
1863  */
1864 void
1866 {
1868  if (shmem_request_hook)
1871 }
1872 
1873 void
1874 pg_bindtextdomain(const char *domain)
1875 {
1876 #ifdef ENABLE_NLS
1877  if (my_exec_path[0] != '\0')
1878  {
1879  char locale_path[MAXPGPATH];
1880 
1881  get_locale_path(my_exec_path, locale_path);
1882  bindtextdomain(domain, locale_path);
1883  pg_bind_textdomain_codeset(domain);
1884  }
1885 #endif
1886 }
bool IsAutoVacuumWorkerProcess(void)
Definition: autovacuum.c:3396
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:735
signed int int32
Definition: c.h:483
#define PG_BINARY
Definition: c.h:1283
#define OidIsValid(objectId)
Definition: c.h:764
size_t Size
Definition: c.h:594
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:2553
int FreeFile(FILE *file)
Definition: fd.c:2751
int pg_fsync(int fd)
Definition: fd.c:386
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:115
int data_directory_mode
Definition: globals.c:72
bool IsBackgroundWorker
Definition: globals.c:117
char * DataDir
Definition: globals.c:66
bool IsPostmasterEnvironment
Definition: globals.c:114
pg_time_t MyStartTime
Definition: globals.c:45
struct Latch * MyLatch
Definition: globals.c:58
char * DatabasePath
Definition: globals.c:99
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:4206
@ 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:807
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
void on_exit_reset(void)
Definition: ipc.c:416
void InitializeLatchWaitSet(void)
Definition: latch.c:347
void InitializeLatchSupport(void)
Definition: latch.c:233
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:1050
void SetLatch(Latch *latch)
Definition: latch.c:633
void InitLatch(Latch *latch)
Definition: latch.c:395
#define WL_LATCH_SET
Definition: latch.h:127
#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:1644
void pfree(void *pointer)
Definition: mcxt.c:1456
MemoryContext TopMemoryContext
Definition: mcxt.c:141
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1631
ProcessingMode
Definition: miscadmin.h:409
@ InitProcessing
Definition: miscadmin.h:411
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:417
#define SECURITY_NOFORCE_RLS
Definition: miscadmin.h:317
#define SECURITY_RESTRICTED_OPERATION
Definition: miscadmin.h:316
#define SECURITY_LOCAL_USERID_CHANGE
Definition: miscadmin.h:315
BackendType
Definition: miscadmin.h:329
@ B_WAL_WRITER
Definition: miscadmin.h:343
@ B_WAL_RECEIVER
Definition: miscadmin.h:341
@ B_CHECKPOINTER
Definition: miscadmin.h:337
@ B_WAL_SENDER
Definition: miscadmin.h:342
@ B_LOGGER
Definition: miscadmin.h:338
@ B_STARTUP
Definition: miscadmin.h:340
@ B_BG_WORKER
Definition: miscadmin.h:335
@ B_INVALID
Definition: miscadmin.h:330
@ B_STANDALONE_BACKEND
Definition: miscadmin.h:339
@ B_BG_WRITER
Definition: miscadmin.h:336
@ B_BACKEND
Definition: miscadmin.h:334
@ B_ARCHIVER
Definition: miscadmin.h:331
@ B_AUTOVAC_LAUNCHER
Definition: miscadmin.h:332
@ B_AUTOVAC_WORKER
Definition: miscadmin.h:333
void(* shmem_request_hook_type)(void)
Definition: miscadmin.h:503
struct SerializedClientConnectionInfo SerializedClientConnectionInfo
void ChangeToDataDir(void)
Definition: miscinit.c:449
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition: miscinit.c:974
Oid GetOuterUserId(void)
Definition: miscinit.c:520
bool process_shared_preload_libraries_done
Definition: miscinit.c:1773
void process_shmem_requests(void)
Definition: miscinit.c:1865
static void SetOuterUserId(Oid userid)
Definition: miscinit.c:528
static List * lock_files
Definition: miscinit.c:66
void InitializeSessionUserId(const char *rolename, Oid roleid, bool bypass_login_check)
Definition: miscinit.c:728
void InitStandaloneProcess(const char *argv0)
Definition: miscinit.c:182
void SerializeClientConnectionInfo(Size maxsize, char *start_address)
Definition: miscinit.c:1037
void InitializeSystemUser(const char *authn_id, const char *auth_method)
Definition: miscinit.c:861
void InitializeSessionUserIdStandalone(void)
Definition: miscinit.c:832
void AddToDataDirLockFile(int target_line, const char *str)
Definition: miscinit.c:1505
void InitProcessLocalLatch(void)
Definition: miscinit.c:242
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:630
void SetSessionAuthorization(Oid userid, bool is_superuser)
Definition: miscinit.c:902
void process_session_preload_libraries(void)
Definition: miscinit.c:1851
static bool SessionUserIsSuperuser
Definition: miscinit.c:496
bool process_shmem_requests_in_progress
Definition: miscinit.c:1776
bool InSecurityRestrictedOperation(void)
Definition: miscinit.c:657
#define DIRECTORY_LOCK_FILE
Definition: miscinit.c:59
Oid GetUserId(void)
Definition: miscinit.c:509
static const char * SystemUser
Definition: miscinit.c:493
static Oid OuterUserId
Definition: miscinit.c:491
static int SecurityRestrictionContext
Definition: miscinit.c:498
Size EstimateClientConnectionInfoSpace(void)
Definition: miscinit.c:1021
const char * GetSystemUser(void)
Definition: miscinit.c:569
Oid GetSessionUserId(void)
Definition: miscinit.c:543
void SetCurrentRoleId(Oid roleid, bool is_superuser)
Definition: miscinit.c:939
bool IgnoreSystemIndexes
Definition: miscinit.c:80
Oid GetAuthenticatedUserId(void)
Definition: miscinit.c:578
static Oid SessionUserId
Definition: miscinit.c:490
bool InLocalUserIdChange(void)
Definition: miscinit.c:648
Datum system_user(PG_FUNCTION_ARGS)
Definition: miscinit.c:885
void SetDatabasePath(const char *path)
Definition: miscinit.c:323
void InitPostmasterChild(void)
Definition: miscinit.c:95
char * shared_preload_libraries_string
Definition: miscinit.c:1768
ClientConnectionInfo MyClientConnectionInfo
Definition: miscinit.c:1004
void process_shared_preload_libraries(void)
Definition: miscinit.c:1837
char * session_preload_libraries_string
Definition: miscinit.c:1767
static void SetSessionUserId(Oid userid, bool is_superuser)
Definition: miscinit.c:551
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1775
char * local_preload_libraries_string
Definition: miscinit.c:1769
static Latch LocalLatchData
Definition: miscinit.c:68
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:264
void TouchSocketLockFiles(void)
Definition: miscinit.c:1476
void RestoreClientConnectionInfo(char *conninfo)
Definition: miscinit.c:1069
static Oid CurrentUserId
Definition: miscinit.c:492
static bool SetRoleIsActive
Definition: miscinit.c:501
bool InNoForceRLSOperation(void)
Definition: miscinit.c:666
static Oid AuthenticatedUserId
Definition: miscinit.c:489
static void load_libraries(const char *libraries, const char *gucname, bool restricted)
Definition: miscinit.c:1785
ProcessingMode Mode
Definition: miscinit.c:61
Oid GetCurrentRoleId(void)
Definition: miscinit.c:918
void checkDataDir(void)
Definition: miscinit.c:336
static void UnlinkLockFiles(int status, Datum arg)
Definition: miscinit.c:1109
void SwitchToSharedLatch(void)
Definition: miscinit.c:222
BackendType MyBackendType
Definition: miscinit.c:63
void GetUserIdAndContext(Oid *userid, bool *sec_def_context)
Definition: miscinit.c:679
void SetDataDir(const char *dir)
Definition: miscinit.c:429
void SetUserIdAndContext(Oid userid, bool sec_def_context)
Definition: miscinit.c:686
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1772
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1874
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:706
static void CreateLockFile(const char *filename, bool amPostmaster, const char *socketDir, bool isDDLock, const char *refName)
Definition: miscinit.c:1144
void ValidatePgVersion(const char *path)
Definition: miscinit.c:1704
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:637
bool RecheckDataDirLockFile(void)
Definition: miscinit.c:1632
void CreateDataDirLockFile(bool amPostmaster)
Definition: miscinit.c:1449
void SwitchBackToLocalLatch(void)
Definition: miscinit.c:249
void CreateSocketLockFile(const char *socketfile, bool amPostmaster, const char *socketDir)
Definition: miscinit.c:1458
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:4573
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:3470
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:2566
int PostPortNumber
Definition: postmaster.c:199
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:3606
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:114
UserAuth auth_method
Definition: libpq-be.h:120
Definition: latch.h:113
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:268
short st_uid
Definition: win32_port.h:270
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:820
@ 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:3583
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:88
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
#define stat
Definition: win32_port.h:284
#define SIGQUIT
Definition: win32_port.h:169
#define S_ISDIR(m)
Definition: win32_port.h:325
#define kill(pid, sig)
Definition: win32_port.h:485