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