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