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