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