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