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