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