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