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