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