1 /*-------------------------------------------------------------------------
2 *
3 * postinit.c
4 * postgres initialization utilities
5 *
6 * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/utils/init/postinit.c
12 *
13 *
14 *-------------------------------------------------------------------------
15 */
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21
22 #include "access/heapam.h"
23 #include "access/htup_details.h"
24 #include "access/session.h"
25 #include "access/sysattr.h"
26 #include "access/xact.h"
27 #include "access/xlog.h"
28 #include "catalog/catalog.h"
29 #include "catalog/indexing.h"
30 #include "catalog/namespace.h"
31 #include "catalog/pg_authid.h"
32 #include "catalog/pg_database.h"
33 #include "catalog/pg_db_role_setting.h"
34 #include "catalog/pg_tablespace.h"
35 #include "libpq/auth.h"
36 #include "libpq/libpq-be.h"
37 #include "mb/pg_wchar.h"
38 #include "miscadmin.h"
39 #include "pgstat.h"
40 #include "postmaster/autovacuum.h"
41 #include "postmaster/postmaster.h"
42 #include "replication/walsender.h"
43 #include "storage/bufmgr.h"
44 #include "storage/fd.h"
45 #include "storage/ipc.h"
46 #include "storage/lmgr.h"
47 #include "storage/procarray.h"
48 #include "storage/procsignal.h"
49 #include "storage/proc.h"
50 #include "storage/sinvaladt.h"
51 #include "storage/smgr.h"
52 #include "tcop/tcopprot.h"
53 #include "utils/acl.h"
54 #include "utils/fmgroids.h"
55 #include "utils/guc.h"
56 #include "utils/memutils.h"
57 #include "utils/pg_locale.h"
58 #include "utils/portal.h"
59 #include "utils/ps_status.h"
60 #include "utils/snapmgr.h"
61 #include "utils/syscache.h"
62 #include "utils/timeout.h"
63 #include "utils/tqual.h"
64
65
66 static HeapTuple GetDatabaseTuple(const char *dbname);
67 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
68 static void PerformAuthentication(Port *port);
69 static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
70 static void InitCommunication(void);
71 static void ShutdownPostgres(int code, Datum arg);
72 static void StatementTimeoutHandler(void);
73 static void LockTimeoutHandler(void);
74 static void IdleInTransactionSessionTimeoutHandler(void);
75 static bool ThereIsAtLeastOneRole(void);
76 static void process_startup_options(Port *port, bool am_superuser);
77 static void process_settings(Oid databaseid, Oid roleid);
78
79
80 /*** InitPostgres support ***/
81
82
83 /*
84 * GetDatabaseTuple -- fetch the pg_database row for a database
85 *
86 * This is used during backend startup when we don't yet have any access to
87 * system catalogs in general. In the worst case, we can seqscan pg_database
88 * using nothing but the hard-wired descriptor that relcache.c creates for
89 * pg_database. In more typical cases, relcache.c was able to load
90 * descriptors for both pg_database and its indexes from the shared relcache
91 * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
92 * tells whether we got the cached descriptors.
93 */
94 static HeapTuple
GetDatabaseTuple(const char * dbname)95 GetDatabaseTuple(const char *dbname)
96 {
97 HeapTuple tuple;
98 Relation relation;
99 SysScanDesc scan;
100 ScanKeyData key[1];
101
102 /*
103 * form a scan key
104 */
105 ScanKeyInit(&key[0],
106 Anum_pg_database_datname,
107 BTEqualStrategyNumber, F_NAMEEQ,
108 CStringGetDatum(dbname));
109
110 /*
111 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
112 * built the critical shared relcache entries (i.e., we're starting up
113 * without a shared relcache cache file).
114 */
115 relation = heap_open(DatabaseRelationId, AccessShareLock);
116 scan = systable_beginscan(relation, DatabaseNameIndexId,
117 criticalSharedRelcachesBuilt,
118 NULL,
119 1, key);
120
121 tuple = systable_getnext(scan);
122
123 /* Must copy tuple before releasing buffer */
124 if (HeapTupleIsValid(tuple))
125 tuple = heap_copytuple(tuple);
126
127 /* all done */
128 systable_endscan(scan);
129 heap_close(relation, AccessShareLock);
130
131 return tuple;
132 }
133
134 /*
135 * GetDatabaseTupleByOid -- as above, but search by database OID
136 */
137 static HeapTuple
GetDatabaseTupleByOid(Oid dboid)138 GetDatabaseTupleByOid(Oid dboid)
139 {
140 HeapTuple tuple;
141 Relation relation;
142 SysScanDesc scan;
143 ScanKeyData key[1];
144
145 /*
146 * form a scan key
147 */
148 ScanKeyInit(&key[0],
149 ObjectIdAttributeNumber,
150 BTEqualStrategyNumber, F_OIDEQ,
151 ObjectIdGetDatum(dboid));
152
153 /*
154 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
155 * built the critical shared relcache entries (i.e., we're starting up
156 * without a shared relcache cache file).
157 */
158 relation = heap_open(DatabaseRelationId, AccessShareLock);
159 scan = systable_beginscan(relation, DatabaseOidIndexId,
160 criticalSharedRelcachesBuilt,
161 NULL,
162 1, key);
163
164 tuple = systable_getnext(scan);
165
166 /* Must copy tuple before releasing buffer */
167 if (HeapTupleIsValid(tuple))
168 tuple = heap_copytuple(tuple);
169
170 /* all done */
171 systable_endscan(scan);
172 heap_close(relation, AccessShareLock);
173
174 return tuple;
175 }
176
177
178 /*
179 * PerformAuthentication -- authenticate a remote client
180 *
181 * returns: nothing. Will not return at all if there's any failure.
182 */
183 static void
PerformAuthentication(Port * port)184 PerformAuthentication(Port *port)
185 {
186 /* This should be set already, but let's make sure */
187 ClientAuthInProgress = true; /* limit visibility of log messages */
188
189 /*
190 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
191 * etcetera from the postmaster, and have to load them ourselves.
192 *
193 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
194 */
195 #ifdef EXEC_BACKEND
196
197 /*
198 * load_hba() and load_ident() want to work within the PostmasterContext,
199 * so create that if it doesn't exist (which it won't). We'll delete it
200 * again later, in PostgresMain.
201 */
202 if (PostmasterContext == NULL)
203 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
204 "Postmaster",
205 ALLOCSET_DEFAULT_SIZES);
206
207 if (!load_hba())
208 {
209 /*
210 * It makes no sense to continue if we fail to load the HBA file,
211 * since there is no way to connect to the database in this case.
212 */
213 ereport(FATAL,
214 (errmsg("could not load pg_hba.conf")));
215 }
216
217 if (!load_ident())
218 {
219 /*
220 * It is ok to continue if we fail to load the IDENT file, although it
221 * means that you cannot log in using any of the authentication
222 * methods that need a user name mapping. load_ident() already logged
223 * the details of error to the log.
224 */
225 }
226 #endif
227
228 /*
229 * Set up a timeout in case a buggy or malicious client fails to respond
230 * during authentication. Since we're inside a transaction and might do
231 * database access, we have to use the statement_timeout infrastructure.
232 */
233 enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
234
235 /*
236 * Now perform authentication exchange.
237 */
238 ClientAuthentication(port); /* might not return, if failure */
239
240 /*
241 * Done with authentication. Disable the timeout, and log if needed.
242 */
243 disable_timeout(STATEMENT_TIMEOUT, false);
244
245 if (Log_connections)
246 {
247 if (am_walsender)
248 {
249 #ifdef USE_SSL
250 if (port->ssl_in_use)
251 ereport(LOG,
252 (errmsg("replication connection authorized: user=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
253 port->user_name,
254 be_tls_get_version(port),
255 be_tls_get_cipher(port),
256 be_tls_get_cipher_bits(port),
257 be_tls_get_compression(port) ? _("on") : _("off"))));
258 else
259 #endif
260 ereport(LOG,
261 (errmsg("replication connection authorized: user=%s",
262 port->user_name)));
263 }
264 else
265 {
266 #ifdef USE_SSL
267 if (port->ssl_in_use)
268 ereport(LOG,
269 (errmsg("connection authorized: user=%s database=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
270 port->user_name, port->database_name,
271 be_tls_get_version(port),
272 be_tls_get_cipher(port),
273 be_tls_get_cipher_bits(port),
274 be_tls_get_compression(port) ? _("on") : _("off"))));
275 else
276 #endif
277 ereport(LOG,
278 (errmsg("connection authorized: user=%s database=%s",
279 port->user_name, port->database_name)));
280 }
281 }
282
283 set_ps_display("startup", false);
284
285 ClientAuthInProgress = false; /* client_min_messages is active now */
286 }
287
288
289 /*
290 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
291 */
292 static void
CheckMyDatabase(const char * name,bool am_superuser,bool override_allow_connections)293 CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
294 {
295 HeapTuple tup;
296 Form_pg_database dbform;
297 char *collate;
298 char *ctype;
299
300 /* Fetch our pg_database row normally, via syscache */
301 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
302 if (!HeapTupleIsValid(tup))
303 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
304 dbform = (Form_pg_database) GETSTRUCT(tup);
305
306 /* This recheck is strictly paranoia */
307 if (strcmp(name, NameStr(dbform->datname)) != 0)
308 ereport(FATAL,
309 (errcode(ERRCODE_UNDEFINED_DATABASE),
310 errmsg("database \"%s\" has disappeared from pg_database",
311 name),
312 errdetail("Database OID %u now seems to belong to \"%s\".",
313 MyDatabaseId, NameStr(dbform->datname))));
314
315 /*
316 * Check permissions to connect to the database.
317 *
318 * These checks are not enforced when in standalone mode, so that there is
319 * a way to recover from disabling all access to all databases, for
320 * example "UPDATE pg_database SET datallowconn = false;".
321 *
322 * We do not enforce them for autovacuum worker processes either.
323 */
324 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
325 {
326 /*
327 * Check that the database is currently allowing connections.
328 */
329 if (!dbform->datallowconn && !override_allow_connections)
330 ereport(FATAL,
331 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
332 errmsg("database \"%s\" is not currently accepting connections",
333 name)));
334
335 /*
336 * Check privilege to connect to the database. (The am_superuser test
337 * is redundant, but since we have the flag, might as well check it
338 * and save a few cycles.)
339 */
340 if (!am_superuser &&
341 pg_database_aclcheck(MyDatabaseId, GetUserId(),
342 ACL_CONNECT) != ACLCHECK_OK)
343 ereport(FATAL,
344 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
345 errmsg("permission denied for database \"%s\"", name),
346 errdetail("User does not have CONNECT privilege.")));
347
348 /*
349 * Check connection limit for this database.
350 *
351 * There is a race condition here --- we create our PGPROC before
352 * checking for other PGPROCs. If two backends did this at about the
353 * same time, they might both think they were over the limit, while
354 * ideally one should succeed and one fail. Getting that to work
355 * exactly seems more trouble than it is worth, however; instead we
356 * just document that the connection limit is approximate.
357 */
358 if (dbform->datconnlimit >= 0 &&
359 !am_superuser &&
360 CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
361 ereport(FATAL,
362 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
363 errmsg("too many connections for database \"%s\"",
364 name)));
365 }
366
367 /*
368 * OK, we're golden. Next to-do item is to save the encoding info out of
369 * the pg_database tuple.
370 */
371 SetDatabaseEncoding(dbform->encoding);
372 /* Record it as a GUC internal option, too */
373 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
374 PGC_INTERNAL, PGC_S_OVERRIDE);
375 /* If we have no other source of client_encoding, use server encoding */
376 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
377 PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
378
379 /* assign locale variables */
380 collate = NameStr(dbform->datcollate);
381 ctype = NameStr(dbform->datctype);
382
383 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
384 ereport(FATAL,
385 (errmsg("database locale is incompatible with operating system"),
386 errdetail("The database was initialized with LC_COLLATE \"%s\", "
387 " which is not recognized by setlocale().", collate),
388 errhint("Recreate the database with another locale or install the missing locale.")));
389
390 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
391 ereport(FATAL,
392 (errmsg("database locale is incompatible with operating system"),
393 errdetail("The database was initialized with LC_CTYPE \"%s\", "
394 " which is not recognized by setlocale().", ctype),
395 errhint("Recreate the database with another locale or install the missing locale.")));
396
397 /* Make the locale settings visible as GUC variables, too */
398 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
399 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
400
401 check_strxfrm_bug();
402
403 ReleaseSysCache(tup);
404 }
405
406
407
408 /* --------------------------------
409 * InitCommunication
410 *
411 * This routine initializes stuff needed for ipc, locking, etc.
412 * it should be called something more informative.
413 * --------------------------------
414 */
415 static void
InitCommunication(void)416 InitCommunication(void)
417 {
418 /*
419 * initialize shared memory and semaphores appropriately.
420 */
421 if (!IsUnderPostmaster) /* postmaster already did this */
422 {
423 /*
424 * We're running a postgres bootstrap process or a standalone backend.
425 * Though we won't listen on PostPortNumber, use it to select a shmem
426 * key. This increases the chance of detecting a leftover live
427 * backend of this DataDir.
428 */
429 CreateSharedMemoryAndSemaphores(PostPortNumber);
430 }
431 }
432
433
434 /*
435 * pg_split_opts -- split a string of options and append it to an argv array
436 *
437 * The caller is responsible for ensuring the argv array is large enough. The
438 * maximum possible number of arguments added by this routine is
439 * (strlen(optstr) + 1) / 2.
440 *
441 * Because some option values can contain spaces we allow escaping using
442 * backslashes, with \\ representing a literal backslash.
443 */
444 void
pg_split_opts(char ** argv,int * argcp,const char * optstr)445 pg_split_opts(char **argv, int *argcp, const char *optstr)
446 {
447 StringInfoData s;
448
449 initStringInfo(&s);
450
451 while (*optstr)
452 {
453 bool last_was_escape = false;
454
455 resetStringInfo(&s);
456
457 /* skip over leading space */
458 while (isspace((unsigned char) *optstr))
459 optstr++;
460
461 if (*optstr == '\0')
462 break;
463
464 /*
465 * Parse a single option, stopping at the first space, unless it's
466 * escaped.
467 */
468 while (*optstr)
469 {
470 if (isspace((unsigned char) *optstr) && !last_was_escape)
471 break;
472
473 if (!last_was_escape && *optstr == '\\')
474 last_was_escape = true;
475 else
476 {
477 last_was_escape = false;
478 appendStringInfoChar(&s, *optstr);
479 }
480
481 optstr++;
482 }
483
484 /* now store the option in the next argv[] position */
485 argv[(*argcp)++] = pstrdup(s.data);
486 }
487
488 pfree(s.data);
489 }
490
491 /*
492 * Initialize MaxBackends value from config options.
493 *
494 * This must be called after modules have had the chance to register background
495 * workers in shared_preload_libraries, and before shared memory size is
496 * determined.
497 *
498 * Note that in EXEC_BACKEND environment, the value is passed down from
499 * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
500 * postmaster itself and processes not under postmaster control should call
501 * this.
502 */
503 void
InitializeMaxBackends(void)504 InitializeMaxBackends(void)
505 {
506 Assert(MaxBackends == 0);
507
508 /* the extra unit accounts for the autovacuum launcher */
509 MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
510 max_worker_processes;
511
512 /* internal error because the values were all checked previously */
513 if (MaxBackends > MAX_BACKENDS)
514 elog(ERROR, "too many backends configured");
515 }
516
517 /*
518 * Early initialization of a backend (either standalone or under postmaster).
519 * This happens even before InitPostgres.
520 *
521 * This is separate from InitPostgres because it is also called by auxiliary
522 * processes, such as the background writer process, which may not call
523 * InitPostgres at all.
524 */
525 void
BaseInit(void)526 BaseInit(void)
527 {
528 /*
529 * Attach to shared memory and semaphores, and initialize our
530 * input/output/debugging file descriptors.
531 */
532 InitCommunication();
533 DebugFileOpen();
534
535 /* Do local initialization of file, storage and buffer managers */
536 InitFileAccess();
537 smgrinit();
538 InitBufferPoolAccess();
539 }
540
541
542 /* --------------------------------
543 * InitPostgres
544 * Initialize POSTGRES.
545 *
546 * The database can be specified by name, using the in_dbname parameter, or by
547 * OID, using the dboid parameter. In the latter case, the actual database
548 * name can be returned to the caller in out_dbname. If out_dbname isn't
549 * NULL, it must point to a buffer of size NAMEDATALEN.
550 *
551 * Similarly, the username can be passed by name, using the username parameter,
552 * or by OID using the useroid parameter.
553 *
554 * In bootstrap mode no parameters are used. The autovacuum launcher process
555 * doesn't use any parameters either, because it only goes far enough to be
556 * able to read pg_database; it doesn't connect to any particular database.
557 * In walsender mode only username is used.
558 *
559 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
560 * already have a PGPROC struct ... but it's not completely filled in yet.
561 *
562 * Note:
563 * Be very careful with the order of calls in the InitPostgres function.
564 * --------------------------------
565 */
566 void
InitPostgres(const char * in_dbname,Oid dboid,const char * username,Oid useroid,char * out_dbname,bool override_allow_connections)567 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
568 Oid useroid, char *out_dbname, bool override_allow_connections)
569 {
570 bool bootstrap = IsBootstrapProcessingMode();
571 bool am_superuser;
572 char *fullpath;
573 char dbname[NAMEDATALEN];
574
575 elog(DEBUG3, "InitPostgres");
576
577 /*
578 * Add my PGPROC struct to the ProcArray.
579 *
580 * Once I have done this, I am visible to other backends!
581 */
582 InitProcessPhase2();
583
584 /*
585 * Initialize my entry in the shared-invalidation manager's array of
586 * per-backend data.
587 *
588 * Sets up MyBackendId, a unique backend identifier.
589 */
590 MyBackendId = InvalidBackendId;
591
592 SharedInvalBackendInit(false);
593
594 if (MyBackendId > MaxBackends || MyBackendId <= 0)
595 elog(FATAL, "bad backend ID: %d", MyBackendId);
596
597 /* Now that we have a BackendId, we can participate in ProcSignal */
598 ProcSignalInit(MyBackendId);
599
600 /*
601 * Also set up timeout handlers needed for backend operation. We need
602 * these in every case except bootstrap.
603 */
604 if (!bootstrap)
605 {
606 RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
607 RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
608 RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
609 RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
610 IdleInTransactionSessionTimeoutHandler);
611 }
612
613 /*
614 * bufmgr needs another initialization call too
615 */
616 InitBufferPoolBackend();
617
618 /*
619 * Initialize local process's access to XLOG.
620 */
621 if (IsUnderPostmaster)
622 {
623 /*
624 * The postmaster already started the XLOG machinery, but we need to
625 * call InitXLOGAccess(), if the system isn't in hot-standby mode.
626 * This is handled by calling RecoveryInProgress and ignoring the
627 * result.
628 */
629 (void) RecoveryInProgress();
630 }
631 else
632 {
633 /*
634 * We are either a bootstrap process or a standalone backend. Either
635 * way, start up the XLOG machinery, and register to have it closed
636 * down at exit.
637 */
638 StartupXLOG();
639 on_shmem_exit(ShutdownXLOG, 0);
640 }
641
642 /*
643 * Initialize the relation cache and the system catalog caches. Note that
644 * no catalog access happens here; we only set up the hashtable structure.
645 * We must do this before starting a transaction because transaction abort
646 * would try to touch these hashtables.
647 */
648 RelationCacheInitialize();
649 InitCatalogCache();
650 InitPlanCache();
651
652 /* Initialize portal manager */
653 EnablePortalManager();
654
655 /* Initialize stats collection --- must happen before first xact */
656 if (!bootstrap)
657 pgstat_initialize();
658
659 /*
660 * Load relcache entries for the shared system catalogs. This must create
661 * at least entries for pg_database and catalogs used for authentication.
662 */
663 RelationCacheInitializePhase2();
664
665 /*
666 * Set up process-exit callback to do pre-shutdown cleanup. This is the
667 * first before_shmem_exit callback we register; thus, this will be the
668 * last thing we do before low-level modules like the buffer manager begin
669 * to close down. We need to have this in place before we begin our first
670 * transaction --- if we fail during the initialization transaction, as is
671 * entirely possible, we need the AbortTransaction call to clean up.
672 */
673 before_shmem_exit(ShutdownPostgres, 0);
674
675 /* The autovacuum launcher is done here */
676 if (IsAutoVacuumLauncherProcess())
677 {
678 /* report this backend in the PgBackendStatus array */
679 pgstat_bestart();
680
681 return;
682 }
683
684 /*
685 * Start a new transaction here before first access to db, and get a
686 * snapshot. We don't have a use for the snapshot itself, but we're
687 * interested in the secondary effect that it sets RecentGlobalXmin. (This
688 * is critical for anything that reads heap pages, because HOT may decide
689 * to prune them even if the process doesn't attempt to modify any
690 * tuples.)
691 */
692 if (!bootstrap)
693 {
694 /* statement_timestamp must be set for timeouts to work correctly */
695 SetCurrentStatementStartTimestamp();
696 StartTransactionCommand();
697
698 /*
699 * transaction_isolation will have been set to the default by the
700 * above. If the default is "serializable", and we are in hot
701 * standby, we will fail if we don't change it to something lower.
702 * Fortunately, "read committed" is plenty good enough.
703 */
704 XactIsoLevel = XACT_READ_COMMITTED;
705
706 (void) GetTransactionSnapshot();
707 }
708
709 /*
710 * Perform client authentication if necessary, then figure out our
711 * postgres user ID, and see if we are a superuser.
712 *
713 * In standalone mode and in autovacuum worker processes, we use a fixed
714 * ID, otherwise we figure it out from the authenticated user name.
715 */
716 if (bootstrap || IsAutoVacuumWorkerProcess())
717 {
718 InitializeSessionUserIdStandalone();
719 am_superuser = true;
720 }
721 else if (!IsUnderPostmaster)
722 {
723 InitializeSessionUserIdStandalone();
724 am_superuser = true;
725 if (!ThereIsAtLeastOneRole())
726 ereport(WARNING,
727 (errcode(ERRCODE_UNDEFINED_OBJECT),
728 errmsg("no roles are defined in this database system"),
729 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
730 username != NULL ? username : "postgres")));
731 }
732 else if (IsBackgroundWorker)
733 {
734 if (username == NULL && !OidIsValid(useroid))
735 {
736 InitializeSessionUserIdStandalone();
737 am_superuser = true;
738 }
739 else
740 {
741 InitializeSessionUserId(username, useroid);
742 am_superuser = superuser();
743 }
744 }
745 else
746 {
747 /* normal multiuser case */
748 Assert(MyProcPort != NULL);
749 PerformAuthentication(MyProcPort);
750 InitializeSessionUserId(username, useroid);
751 am_superuser = superuser();
752 }
753
754 /*
755 * If we're trying to shut down, only superusers can connect, and new
756 * replication connections are not allowed.
757 */
758 if ((!am_superuser || am_walsender) &&
759 MyProcPort != NULL &&
760 MyProcPort->canAcceptConnections == CAC_SUPERUSER)
761 {
762 if (am_walsender)
763 ereport(FATAL,
764 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
765 errmsg("new replication connections are not allowed during database shutdown")));
766 else
767 ereport(FATAL,
768 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
769 errmsg("must be superuser to connect during database shutdown")));
770 }
771
772 /*
773 * Binary upgrades only allowed super-user connections
774 */
775 if (IsBinaryUpgrade && !am_superuser)
776 {
777 ereport(FATAL,
778 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
779 errmsg("must be superuser to connect in binary upgrade mode")));
780 }
781
782 /*
783 * The last few connection slots are reserved for superusers. Although
784 * replication connections currently require superuser privileges, we
785 * don't allow them to consume the reserved slots, which are intended for
786 * interactive use.
787 */
788 if ((!am_superuser || am_walsender) &&
789 ReservedBackends > 0 &&
790 !HaveNFreeProcs(ReservedBackends))
791 ereport(FATAL,
792 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
793 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
794
795 /* Check replication permissions needed for walsender processes. */
796 if (am_walsender)
797 {
798 Assert(!bootstrap);
799
800 if (!superuser() && !has_rolreplication(GetUserId()))
801 ereport(FATAL,
802 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
803 errmsg("must be superuser or replication role to start walsender")));
804 }
805
806 /*
807 * If this is a plain walsender only supporting physical replication, we
808 * don't want to connect to any particular database. Just finish the
809 * backend startup by processing any options from the startup packet, and
810 * we're done.
811 */
812 if (am_walsender && !am_db_walsender)
813 {
814 /* process any options passed in the startup packet */
815 if (MyProcPort != NULL)
816 process_startup_options(MyProcPort, am_superuser);
817
818 /* Apply PostAuthDelay as soon as we've read all options */
819 if (PostAuthDelay > 0)
820 pg_usleep(PostAuthDelay * 1000000L);
821
822 /* initialize client encoding */
823 InitializeClientEncoding();
824
825 /* report this backend in the PgBackendStatus array */
826 pgstat_bestart();
827
828 /* close the transaction we started above */
829 CommitTransactionCommand();
830
831 return;
832 }
833
834 /*
835 * Set up the global variables holding database id and default tablespace.
836 * But note we won't actually try to touch the database just yet.
837 *
838 * We take a shortcut in the bootstrap case, otherwise we have to look up
839 * the db's entry in pg_database.
840 */
841 if (bootstrap)
842 {
843 MyDatabaseId = TemplateDbOid;
844 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
845 }
846 else if (in_dbname != NULL)
847 {
848 HeapTuple tuple;
849 Form_pg_database dbform;
850
851 tuple = GetDatabaseTuple(in_dbname);
852 if (!HeapTupleIsValid(tuple))
853 ereport(FATAL,
854 (errcode(ERRCODE_UNDEFINED_DATABASE),
855 errmsg("database \"%s\" does not exist", in_dbname)));
856 dbform = (Form_pg_database) GETSTRUCT(tuple);
857 MyDatabaseId = HeapTupleGetOid(tuple);
858 MyDatabaseTableSpace = dbform->dattablespace;
859 /* take database name from the caller, just for paranoia */
860 strlcpy(dbname, in_dbname, sizeof(dbname));
861 }
862 else if (OidIsValid(dboid))
863 {
864 /* caller specified database by OID */
865 HeapTuple tuple;
866 Form_pg_database dbform;
867
868 tuple = GetDatabaseTupleByOid(dboid);
869 if (!HeapTupleIsValid(tuple))
870 ereport(FATAL,
871 (errcode(ERRCODE_UNDEFINED_DATABASE),
872 errmsg("database %u does not exist", dboid)));
873 dbform = (Form_pg_database) GETSTRUCT(tuple);
874 MyDatabaseId = HeapTupleGetOid(tuple);
875 MyDatabaseTableSpace = dbform->dattablespace;
876 Assert(MyDatabaseId == dboid);
877 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
878 /* pass the database name back to the caller */
879 if (out_dbname)
880 strcpy(out_dbname, dbname);
881 }
882 else
883 {
884 /*
885 * If this is a background worker not bound to any particular
886 * database, we're done now. Everything that follows only makes sense
887 * if we are bound to a specific database. We do need to close the
888 * transaction we started before returning.
889 */
890 if (!bootstrap)
891 {
892 pgstat_bestart();
893 CommitTransactionCommand();
894 }
895 return;
896 }
897
898 /*
899 * Now, take a writer's lock on the database we are trying to connect to.
900 * If there is a concurrently running DROP DATABASE on that database, this
901 * will block us until it finishes (and has committed its update of
902 * pg_database).
903 *
904 * Note that the lock is not held long, only until the end of this startup
905 * transaction. This is OK since we will advertise our use of the
906 * database in the ProcArray before dropping the lock (in fact, that's the
907 * next thing to do). Anyone trying a DROP DATABASE after this point will
908 * see us in the array once they have the lock. Ordering is important for
909 * this because we don't want to advertise ourselves as being in this
910 * database until we have the lock; otherwise we create what amounts to a
911 * deadlock with CountOtherDBBackends().
912 *
913 * Note: use of RowExclusiveLock here is reasonable because we envision
914 * our session as being a concurrent writer of the database. If we had a
915 * way of declaring a session as being guaranteed-read-only, we could use
916 * AccessShareLock for such sessions and thereby not conflict against
917 * CREATE DATABASE.
918 */
919 if (!bootstrap)
920 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
921 RowExclusiveLock);
922
923 /*
924 * Now we can mark our PGPROC entry with the database ID.
925 *
926 * We assume this is an atomic store so no lock is needed; though actually
927 * things would work fine even if it weren't atomic. Anyone searching the
928 * ProcArray for this database's ID should hold the database lock, so they
929 * would not be executing concurrently with this store. A process looking
930 * for another database's ID could in theory see a chance match if it read
931 * a partially-updated databaseId value; but as long as all such searches
932 * wait and retry, as in CountOtherDBBackends(), they will certainly see
933 * the correct value on their next try.
934 */
935 MyProc->databaseId = MyDatabaseId;
936
937 /*
938 * We established a catalog snapshot while reading pg_authid and/or
939 * pg_database; but until we have set up MyDatabaseId, we won't react to
940 * incoming sinval messages for unshared catalogs, so we won't realize it
941 * if the snapshot has been invalidated. Assume it's no good anymore.
942 */
943 InvalidateCatalogSnapshot();
944
945 /*
946 * Recheck pg_database to make sure the target database hasn't gone away.
947 * If there was a concurrent DROP DATABASE, this ensures we will die
948 * cleanly without creating a mess.
949 */
950 if (!bootstrap)
951 {
952 HeapTuple tuple;
953
954 tuple = GetDatabaseTuple(dbname);
955 if (!HeapTupleIsValid(tuple) ||
956 MyDatabaseId != HeapTupleGetOid(tuple) ||
957 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
958 ereport(FATAL,
959 (errcode(ERRCODE_UNDEFINED_DATABASE),
960 errmsg("database \"%s\" does not exist", dbname),
961 errdetail("It seems to have just been dropped or renamed.")));
962 }
963
964 /*
965 * Now we should be able to access the database directory safely. Verify
966 * it's there and looks reasonable.
967 */
968 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
969
970 if (!bootstrap)
971 {
972 if (access(fullpath, F_OK) == -1)
973 {
974 if (errno == ENOENT)
975 ereport(FATAL,
976 (errcode(ERRCODE_UNDEFINED_DATABASE),
977 errmsg("database \"%s\" does not exist",
978 dbname),
979 errdetail("The database subdirectory \"%s\" is missing.",
980 fullpath)));
981 else
982 ereport(FATAL,
983 (errcode_for_file_access(),
984 errmsg("could not access directory \"%s\": %m",
985 fullpath)));
986 }
987
988 ValidatePgVersion(fullpath);
989 }
990
991 SetDatabasePath(fullpath);
992
993 /*
994 * It's now possible to do real access to the system catalogs.
995 *
996 * Load relcache entries for the system catalogs. This must create at
997 * least the minimum set of "nailed-in" cache entries.
998 */
999 RelationCacheInitializePhase3();
1000
1001 /* set up ACL framework (so CheckMyDatabase can check permissions) */
1002 initialize_acl();
1003
1004 /*
1005 * Re-read the pg_database row for our database, check permissions and set
1006 * up database-specific GUC settings. We can't do this until all the
1007 * database-access infrastructure is up. (Also, it wants to know if the
1008 * user is a superuser, so the above stuff has to happen first.)
1009 */
1010 if (!bootstrap)
1011 CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1012
1013 /*
1014 * Now process any command-line switches and any additional GUC variable
1015 * settings passed in the startup packet. We couldn't do this before
1016 * because we didn't know if client is a superuser.
1017 */
1018 if (MyProcPort != NULL)
1019 process_startup_options(MyProcPort, am_superuser);
1020
1021 /* Process pg_db_role_setting options */
1022 process_settings(MyDatabaseId, GetSessionUserId());
1023
1024 /* Apply PostAuthDelay as soon as we've read all options */
1025 if (PostAuthDelay > 0)
1026 pg_usleep(PostAuthDelay * 1000000L);
1027
1028 /*
1029 * Initialize various default states that can't be set up until we've
1030 * selected the active user and gotten the right GUC settings.
1031 */
1032
1033 /* set default namespace search path */
1034 InitializeSearchPath();
1035
1036 /* initialize client encoding */
1037 InitializeClientEncoding();
1038
1039 /* Initialize this backend's session state. */
1040 InitializeSession();
1041
1042 /* report this backend in the PgBackendStatus array */
1043 if (!bootstrap)
1044 pgstat_bestart();
1045
1046 /* close the transaction we started above */
1047 if (!bootstrap)
1048 CommitTransactionCommand();
1049 }
1050
1051 /*
1052 * Process any command-line switches and any additional GUC variable
1053 * settings passed in the startup packet.
1054 */
1055 static void
process_startup_options(Port * port,bool am_superuser)1056 process_startup_options(Port *port, bool am_superuser)
1057 {
1058 GucContext gucctx;
1059 ListCell *gucopts;
1060
1061 gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1062
1063 /*
1064 * First process any command-line switches that were included in the
1065 * startup packet, if we are in a regular backend.
1066 */
1067 if (port->cmdline_options != NULL)
1068 {
1069 /*
1070 * The maximum possible number of commandline arguments that could
1071 * come from port->cmdline_options is (strlen + 1) / 2; see
1072 * pg_split_opts().
1073 */
1074 char **av;
1075 int maxac;
1076 int ac;
1077
1078 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1079
1080 av = (char **) palloc(maxac * sizeof(char *));
1081 ac = 0;
1082
1083 av[ac++] = "postgres";
1084
1085 pg_split_opts(av, &ac, port->cmdline_options);
1086
1087 av[ac] = NULL;
1088
1089 Assert(ac < maxac);
1090
1091 (void) process_postgres_switches(ac, av, gucctx, NULL);
1092 }
1093
1094 /*
1095 * Process any additional GUC variable settings passed in startup packet.
1096 * These are handled exactly like command-line variables.
1097 */
1098 gucopts = list_head(port->guc_options);
1099 while (gucopts)
1100 {
1101 char *name;
1102 char *value;
1103
1104 name = lfirst(gucopts);
1105 gucopts = lnext(gucopts);
1106
1107 value = lfirst(gucopts);
1108 gucopts = lnext(gucopts);
1109
1110 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1111 }
1112 }
1113
1114 /*
1115 * Load GUC settings from pg_db_role_setting.
1116 *
1117 * We try specific settings for the database/role combination, as well as
1118 * general for this database and for this user.
1119 */
1120 static void
process_settings(Oid databaseid,Oid roleid)1121 process_settings(Oid databaseid, Oid roleid)
1122 {
1123 Relation relsetting;
1124 Snapshot snapshot;
1125
1126 if (!IsUnderPostmaster)
1127 return;
1128
1129 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
1130
1131 /* read all the settings under the same snapshot for efficiency */
1132 snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1133
1134 /* Later settings are ignored if set earlier. */
1135 ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1136 ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1137 ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1138 ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1139
1140 UnregisterSnapshot(snapshot);
1141 heap_close(relsetting, AccessShareLock);
1142 }
1143
1144 /*
1145 * Backend-shutdown callback. Do cleanup that we want to be sure happens
1146 * before all the supporting modules begin to nail their doors shut via
1147 * their own callbacks.
1148 *
1149 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1150 * via separate callbacks that execute before this one. We don't combine the
1151 * callbacks because we still want this one to happen if the user-level
1152 * cleanup fails.
1153 */
1154 static void
ShutdownPostgres(int code,Datum arg)1155 ShutdownPostgres(int code, Datum arg)
1156 {
1157 /* Make sure we've killed any active transaction */
1158 AbortOutOfAnyTransaction();
1159
1160 /*
1161 * User locks are not released by transaction end, so be sure to release
1162 * them explicitly.
1163 */
1164 LockReleaseAll(USER_LOCKMETHOD, true);
1165 }
1166
1167
1168 /*
1169 * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1170 */
1171 static void
StatementTimeoutHandler(void)1172 StatementTimeoutHandler(void)
1173 {
1174 int sig = SIGINT;
1175
1176 /*
1177 * During authentication the timeout is used to deal with
1178 * authentication_timeout - we want to quit in response to such timeouts.
1179 */
1180 if (ClientAuthInProgress)
1181 sig = SIGTERM;
1182
1183 #ifdef HAVE_SETSID
1184 /* try to signal whole process group */
1185 kill(-MyProcPid, sig);
1186 #endif
1187 kill(MyProcPid, sig);
1188 }
1189
1190 /*
1191 * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1192 */
1193 static void
LockTimeoutHandler(void)1194 LockTimeoutHandler(void)
1195 {
1196 #ifdef HAVE_SETSID
1197 /* try to signal whole process group */
1198 kill(-MyProcPid, SIGINT);
1199 #endif
1200 kill(MyProcPid, SIGINT);
1201 }
1202
1203 static void
IdleInTransactionSessionTimeoutHandler(void)1204 IdleInTransactionSessionTimeoutHandler(void)
1205 {
1206 IdleInTransactionSessionTimeoutPending = true;
1207 InterruptPending = true;
1208 SetLatch(MyLatch);
1209 }
1210
1211 /*
1212 * Returns true if at least one role is defined in this database cluster.
1213 */
1214 static bool
ThereIsAtLeastOneRole(void)1215 ThereIsAtLeastOneRole(void)
1216 {
1217 Relation pg_authid_rel;
1218 HeapScanDesc scan;
1219 bool result;
1220
1221 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1222
1223 scan = heap_beginscan_catalog(pg_authid_rel, 0, NULL);
1224 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1225
1226 heap_endscan(scan);
1227 heap_close(pg_authid_rel, AccessShareLock);
1228
1229 return result;
1230 }
1231