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