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