LCOV - code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 318 372 85.5 %
Date: 2024-02-28 23:11:08 Functions: 19 23 82.6 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * postinit.c
       4             :  *    postgres initialization utilities
       5             :  *
       6             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/utils/init/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/genam.h"
      23             : #include "access/heapam.h"
      24             : #include "access/htup_details.h"
      25             : #include "access/session.h"
      26             : #include "access/sysattr.h"
      27             : #include "access/tableam.h"
      28             : #include "access/xact.h"
      29             : #include "access/xlog.h"
      30             : #include "access/xloginsert.h"
      31             : #include "catalog/catalog.h"
      32             : #include "catalog/namespace.h"
      33             : #include "catalog/pg_authid.h"
      34             : #include "catalog/pg_collation.h"
      35             : #include "catalog/pg_database.h"
      36             : #include "catalog/pg_db_role_setting.h"
      37             : #include "catalog/pg_tablespace.h"
      38             : #include "libpq/auth.h"
      39             : #include "libpq/libpq-be.h"
      40             : #include "mb/pg_wchar.h"
      41             : #include "miscadmin.h"
      42             : #include "pgstat.h"
      43             : #include "postmaster/autovacuum.h"
      44             : #include "postmaster/postmaster.h"
      45             : #include "replication/slot.h"
      46             : #include "replication/slotsync.h"
      47             : #include "replication/walsender.h"
      48             : #include "storage/bufmgr.h"
      49             : #include "storage/fd.h"
      50             : #include "storage/ipc.h"
      51             : #include "storage/lmgr.h"
      52             : #include "storage/proc.h"
      53             : #include "storage/procarray.h"
      54             : #include "storage/procsignal.h"
      55             : #include "storage/sinvaladt.h"
      56             : #include "storage/smgr.h"
      57             : #include "storage/sync.h"
      58             : #include "tcop/tcopprot.h"
      59             : #include "utils/acl.h"
      60             : #include "utils/builtins.h"
      61             : #include "utils/fmgroids.h"
      62             : #include "utils/guc_hooks.h"
      63             : #include "utils/memutils.h"
      64             : #include "utils/pg_locale.h"
      65             : #include "utils/portal.h"
      66             : #include "utils/ps_status.h"
      67             : #include "utils/snapmgr.h"
      68             : #include "utils/syscache.h"
      69             : #include "utils/timeout.h"
      70             : 
      71             : static HeapTuple GetDatabaseTuple(const char *dbname);
      72             : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
      73             : static void PerformAuthentication(Port *port);
      74             : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
      75             : static void ShutdownPostgres(int code, Datum arg);
      76             : static void StatementTimeoutHandler(void);
      77             : static void LockTimeoutHandler(void);
      78             : static void IdleInTransactionSessionTimeoutHandler(void);
      79             : static void TransactionTimeoutHandler(void);
      80             : static void IdleSessionTimeoutHandler(void);
      81             : static void IdleStatsUpdateTimeoutHandler(void);
      82             : static void ClientCheckTimeoutHandler(void);
      83             : static bool ThereIsAtLeastOneRole(void);
      84             : static void process_startup_options(Port *port, bool am_superuser);
      85             : static void process_settings(Oid databaseid, Oid roleid);
      86             : 
      87             : 
      88             : /*** InitPostgres support ***/
      89             : 
      90             : 
      91             : /*
      92             :  * GetDatabaseTuple -- fetch the pg_database row for a database
      93             :  *
      94             :  * This is used during backend startup when we don't yet have any access to
      95             :  * system catalogs in general.  In the worst case, we can seqscan pg_database
      96             :  * using nothing but the hard-wired descriptor that relcache.c creates for
      97             :  * pg_database.  In more typical cases, relcache.c was able to load
      98             :  * descriptors for both pg_database and its indexes from the shared relcache
      99             :  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
     100             :  * tells whether we got the cached descriptors.
     101             :  */
     102             : static HeapTuple
     103       19626 : GetDatabaseTuple(const char *dbname)
     104             : {
     105             :     HeapTuple   tuple;
     106             :     Relation    relation;
     107             :     SysScanDesc scan;
     108             :     ScanKeyData key[1];
     109             : 
     110             :     /*
     111             :      * form a scan key
     112             :      */
     113       19626 :     ScanKeyInit(&key[0],
     114             :                 Anum_pg_database_datname,
     115             :                 BTEqualStrategyNumber, F_NAMEEQ,
     116             :                 CStringGetDatum(dbname));
     117             : 
     118             :     /*
     119             :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     120             :      * built the critical shared relcache entries (i.e., we're starting up
     121             :      * without a shared relcache cache file).
     122             :      */
     123       19626 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     124       19626 :     scan = systable_beginscan(relation, DatabaseNameIndexId,
     125             :                               criticalSharedRelcachesBuilt,
     126             :                               NULL,
     127             :                               1, key);
     128             : 
     129       19626 :     tuple = systable_getnext(scan);
     130             : 
     131             :     /* Must copy tuple before releasing buffer */
     132       19626 :     if (HeapTupleIsValid(tuple))
     133       19608 :         tuple = heap_copytuple(tuple);
     134             : 
     135             :     /* all done */
     136       19626 :     systable_endscan(scan);
     137       19626 :     table_close(relation, AccessShareLock);
     138             : 
     139       19626 :     return tuple;
     140             : }
     141             : 
     142             : /*
     143             :  * GetDatabaseTupleByOid -- as above, but search by database OID
     144             :  */
     145             : static HeapTuple
     146       22944 : GetDatabaseTupleByOid(Oid dboid)
     147             : {
     148             :     HeapTuple   tuple;
     149             :     Relation    relation;
     150             :     SysScanDesc scan;
     151             :     ScanKeyData key[1];
     152             : 
     153             :     /*
     154             :      * form a scan key
     155             :      */
     156       22944 :     ScanKeyInit(&key[0],
     157             :                 Anum_pg_database_oid,
     158             :                 BTEqualStrategyNumber, F_OIDEQ,
     159             :                 ObjectIdGetDatum(dboid));
     160             : 
     161             :     /*
     162             :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     163             :      * built the critical shared relcache entries (i.e., we're starting up
     164             :      * without a shared relcache cache file).
     165             :      */
     166       22944 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     167       22944 :     scan = systable_beginscan(relation, DatabaseOidIndexId,
     168             :                               criticalSharedRelcachesBuilt,
     169             :                               NULL,
     170             :                               1, key);
     171             : 
     172       22944 :     tuple = systable_getnext(scan);
     173             : 
     174             :     /* Must copy tuple before releasing buffer */
     175       22944 :     if (HeapTupleIsValid(tuple))
     176       22944 :         tuple = heap_copytuple(tuple);
     177             : 
     178             :     /* all done */
     179       22944 :     systable_endscan(scan);
     180       22944 :     table_close(relation, AccessShareLock);
     181             : 
     182       22944 :     return tuple;
     183             : }
     184             : 
     185             : 
     186             : /*
     187             :  * PerformAuthentication -- authenticate a remote client
     188             :  *
     189             :  * returns: nothing.  Will not return at all if there's any failure.
     190             :  */
     191             : static void
     192       20404 : PerformAuthentication(Port *port)
     193             : {
     194             :     /* This should be set already, but let's make sure */
     195       20404 :     ClientAuthInProgress = true;    /* limit visibility of log messages */
     196             : 
     197             :     /*
     198             :      * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
     199             :      * etcetera from the postmaster, and have to load them ourselves.
     200             :      *
     201             :      * FIXME: [fork/exec] Ugh.  Is there a way around this overhead?
     202             :      */
     203             : #ifdef EXEC_BACKEND
     204             : 
     205             :     /*
     206             :      * load_hba() and load_ident() want to work within the PostmasterContext,
     207             :      * so create that if it doesn't exist (which it won't).  We'll delete it
     208             :      * again later, in PostgresMain.
     209             :      */
     210             :     if (PostmasterContext == NULL)
     211             :         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
     212             :                                                   "Postmaster",
     213             :                                                   ALLOCSET_DEFAULT_SIZES);
     214             : 
     215             :     if (!load_hba())
     216             :     {
     217             :         /*
     218             :          * It makes no sense to continue if we fail to load the HBA file,
     219             :          * since there is no way to connect to the database in this case.
     220             :          */
     221             :         ereport(FATAL,
     222             :         /* translator: %s is a configuration file */
     223             :                 (errmsg("could not load %s", HbaFileName)));
     224             :     }
     225             : 
     226             :     if (!load_ident())
     227             :     {
     228             :         /*
     229             :          * It is ok to continue if we fail to load the IDENT file, although it
     230             :          * means that you cannot log in using any of the authentication
     231             :          * methods that need a user name mapping. load_ident() already logged
     232             :          * the details of error to the log.
     233             :          */
     234             :     }
     235             : #endif
     236             : 
     237             :     /*
     238             :      * Set up a timeout in case a buggy or malicious client fails to respond
     239             :      * during authentication.  Since we're inside a transaction and might do
     240             :      * database access, we have to use the statement_timeout infrastructure.
     241             :      */
     242       20404 :     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
     243             : 
     244             :     /*
     245             :      * Now perform authentication exchange.
     246             :      */
     247       20404 :     set_ps_display("authentication");
     248       20404 :     ClientAuthentication(port); /* might not return, if failure */
     249             : 
     250             :     /*
     251             :      * Done with authentication.  Disable the timeout, and log if needed.
     252             :      */
     253       20288 :     disable_timeout(STATEMENT_TIMEOUT, false);
     254             : 
     255       20288 :     if (Log_connections)
     256             :     {
     257             :         StringInfoData logmsg;
     258             : 
     259         518 :         initStringInfo(&logmsg);
     260         518 :         if (am_walsender)
     261           6 :             appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
     262             :                              port->user_name);
     263             :         else
     264         512 :             appendStringInfo(&logmsg, _("connection authorized: user=%s"),
     265             :                              port->user_name);
     266         518 :         if (!am_walsender)
     267         512 :             appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
     268             : 
     269         518 :         if (port->application_name != NULL)
     270         518 :             appendStringInfo(&logmsg, _(" application_name=%s"),
     271             :                              port->application_name);
     272             : 
     273             : #ifdef USE_SSL
     274         518 :         if (port->ssl_in_use)
     275         156 :             appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
     276             :                              be_tls_get_version(port),
     277             :                              be_tls_get_cipher(port),
     278             :                              be_tls_get_cipher_bits(port));
     279             : #endif
     280             : #ifdef ENABLE_GSS
     281             :         if (port->gss)
     282             :         {
     283             :             const char *princ = be_gssapi_get_princ(port);
     284             : 
     285             :             if (princ)
     286             :                 appendStringInfo(&logmsg,
     287             :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
     288             :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
     289             :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
     290             :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"),
     291             :                                  princ);
     292             :             else
     293             :                 appendStringInfo(&logmsg,
     294             :                                  _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
     295             :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
     296             :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
     297             :                                  be_gssapi_get_delegation(port) ? _("yes") : _("no"));
     298             :         }
     299             : #endif
     300             : 
     301         518 :         ereport(LOG, errmsg_internal("%s", logmsg.data));
     302         518 :         pfree(logmsg.data);
     303             :     }
     304             : 
     305       20288 :     set_ps_display("startup");
     306             : 
     307       20288 :     ClientAuthInProgress = false;   /* client_min_messages is active now */
     308       20288 : }
     309             : 
     310             : 
     311             : /*
     312             :  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
     313             :  */
     314             : static void
     315       22924 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
     316             : {
     317             :     HeapTuple   tup;
     318             :     Form_pg_database dbform;
     319             :     Datum       datum;
     320             :     bool        isnull;
     321             :     char       *collate;
     322             :     char       *ctype;
     323             :     char       *iculocale;
     324             : 
     325             :     /* Fetch our pg_database row normally, via syscache */
     326       22924 :     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
     327       22924 :     if (!HeapTupleIsValid(tup))
     328           0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
     329       22924 :     dbform = (Form_pg_database) GETSTRUCT(tup);
     330             : 
     331             :     /* This recheck is strictly paranoia */
     332       22924 :     if (strcmp(name, NameStr(dbform->datname)) != 0)
     333           0 :         ereport(FATAL,
     334             :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
     335             :                  errmsg("database \"%s\" has disappeared from pg_database",
     336             :                         name),
     337             :                  errdetail("Database OID %u now seems to belong to \"%s\".",
     338             :                            MyDatabaseId, NameStr(dbform->datname))));
     339             : 
     340             :     /*
     341             :      * Check permissions to connect to the database.
     342             :      *
     343             :      * These checks are not enforced when in standalone mode, so that there is
     344             :      * a way to recover from disabling all access to all databases, for
     345             :      * example "UPDATE pg_database SET datallowconn = false;".
     346             :      *
     347             :      * We do not enforce them for autovacuum worker processes either.
     348             :      */
     349       22924 :     if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
     350             :     {
     351             :         /*
     352             :          * Check that the database is currently allowing connections.
     353             :          */
     354       22820 :         if (!dbform->datallowconn && !override_allow_connections)
     355           2 :             ereport(FATAL,
     356             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     357             :                      errmsg("database \"%s\" is not currently accepting connections",
     358             :                             name)));
     359             : 
     360             :         /*
     361             :          * Check privilege to connect to the database.  (The am_superuser test
     362             :          * is redundant, but since we have the flag, might as well check it
     363             :          * and save a few cycles.)
     364             :          */
     365       23238 :         if (!am_superuser &&
     366         420 :             object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
     367             :                             ACL_CONNECT) != ACLCHECK_OK)
     368           0 :             ereport(FATAL,
     369             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     370             :                      errmsg("permission denied for database \"%s\"", name),
     371             :                      errdetail("User does not have CONNECT privilege.")));
     372             : 
     373             :         /*
     374             :          * Check connection limit for this database.
     375             :          *
     376             :          * There is a race condition here --- we create our PGPROC before
     377             :          * checking for other PGPROCs.  If two backends did this at about the
     378             :          * same time, they might both think they were over the limit, while
     379             :          * ideally one should succeed and one fail.  Getting that to work
     380             :          * exactly seems more trouble than it is worth, however; instead we
     381             :          * just document that the connection limit is approximate.
     382             :          */
     383       22818 :         if (dbform->datconnlimit >= 0 &&
     384           0 :             !am_superuser &&
     385           0 :             CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
     386           0 :             ereport(FATAL,
     387             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     388             :                      errmsg("too many connections for database \"%s\"",
     389             :                             name)));
     390             :     }
     391             : 
     392             :     /*
     393             :      * OK, we're golden.  Next to-do item is to save the encoding info out of
     394             :      * the pg_database tuple.
     395             :      */
     396       22922 :     SetDatabaseEncoding(dbform->encoding);
     397             :     /* Record it as a GUC internal option, too */
     398       22922 :     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
     399             :                     PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
     400             :     /* If we have no other source of client_encoding, use server encoding */
     401       22922 :     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
     402             :                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
     403             : 
     404             :     /* assign locale variables */
     405       22922 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
     406       22922 :     collate = TextDatumGetCString(datum);
     407       22922 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
     408       22922 :     ctype = TextDatumGetCString(datum);
     409             : 
     410       22922 :     if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
     411           0 :         ereport(FATAL,
     412             :                 (errmsg("database locale is incompatible with operating system"),
     413             :                  errdetail("The database was initialized with LC_COLLATE \"%s\", "
     414             :                            " which is not recognized by setlocale().", collate),
     415             :                  errhint("Recreate the database with another locale or install the missing locale.")));
     416             : 
     417       22922 :     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
     418           0 :         ereport(FATAL,
     419             :                 (errmsg("database locale is incompatible with operating system"),
     420             :                  errdetail("The database was initialized with LC_CTYPE \"%s\", "
     421             :                            " which is not recognized by setlocale().", ctype),
     422             :                  errhint("Recreate the database with another locale or install the missing locale.")));
     423             : 
     424       22922 :     if (strcmp(ctype, "C") == 0 ||
     425       20146 :         strcmp(ctype, "POSIX") == 0)
     426        2776 :         database_ctype_is_c = true;
     427             : 
     428       22922 :     if (dbform->datlocprovider == COLLPROVIDER_ICU)
     429             :     {
     430             :         char       *icurules;
     431             : 
     432        1756 :         datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_daticulocale);
     433        1756 :         iculocale = TextDatumGetCString(datum);
     434             : 
     435        1756 :         datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_daticurules, &isnull);
     436        1756 :         if (!isnull)
     437           0 :             icurules = TextDatumGetCString(datum);
     438             :         else
     439        1756 :             icurules = NULL;
     440             : 
     441        1756 :         make_icu_collator(iculocale, icurules, &default_locale);
     442             :     }
     443             :     else
     444       21166 :         iculocale = NULL;
     445             : 
     446       22918 :     default_locale.provider = dbform->datlocprovider;
     447             : 
     448             :     /*
     449             :      * Default locale is currently always deterministic.  Nondeterministic
     450             :      * locales currently don't support pattern matching, which would break a
     451             :      * lot of things if applied globally.
     452             :      */
     453       22918 :     default_locale.deterministic = true;
     454             : 
     455             :     /*
     456             :      * Check collation version.  See similar code in
     457             :      * pg_newlocale_from_collation().  Note that here we warn instead of error
     458             :      * in any case, so that we don't prevent connecting.
     459             :      */
     460       22918 :     datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
     461             :                             &isnull);
     462       22918 :     if (!isnull)
     463             :     {
     464             :         char       *actual_versionstr;
     465             :         char       *collversionstr;
     466             : 
     467       21844 :         collversionstr = TextDatumGetCString(datum);
     468             : 
     469       21844 :         actual_versionstr = get_collation_actual_version(dbform->datlocprovider, dbform->datlocprovider == COLLPROVIDER_ICU ? iculocale : collate);
     470       21844 :         if (!actual_versionstr)
     471             :             /* should not happen */
     472           0 :             elog(WARNING,
     473             :                  "database \"%s\" has no actual collation version, but a version was recorded",
     474             :                  name);
     475       21844 :         else if (strcmp(actual_versionstr, collversionstr) != 0)
     476           0 :             ereport(WARNING,
     477             :                     (errmsg("database \"%s\" has a collation version mismatch",
     478             :                             name),
     479             :                      errdetail("The database was created using collation version %s, "
     480             :                                "but the operating system provides version %s.",
     481             :                                collversionstr, actual_versionstr),
     482             :                      errhint("Rebuild all objects in this database that use the default collation and run "
     483             :                              "ALTER DATABASE %s REFRESH COLLATION VERSION, "
     484             :                              "or build PostgreSQL with the right library version.",
     485             :                              quote_identifier(name))));
     486             :     }
     487             : 
     488       22918 :     ReleaseSysCache(tup);
     489       22918 : }
     490             : 
     491             : 
     492             : /*
     493             :  * pg_split_opts -- split a string of options and append it to an argv array
     494             :  *
     495             :  * The caller is responsible for ensuring the argv array is large enough.  The
     496             :  * maximum possible number of arguments added by this routine is
     497             :  * (strlen(optstr) + 1) / 2.
     498             :  *
     499             :  * Because some option values can contain spaces we allow escaping using
     500             :  * backslashes, with \\ representing a literal backslash.
     501             :  */
     502             : void
     503        6010 : pg_split_opts(char **argv, int *argcp, const char *optstr)
     504             : {
     505             :     StringInfoData s;
     506             : 
     507        6010 :     initStringInfo(&s);
     508             : 
     509       21914 :     while (*optstr)
     510             :     {
     511       15904 :         bool        last_was_escape = false;
     512             : 
     513       15904 :         resetStringInfo(&s);
     514             : 
     515             :         /* skip over leading space */
     516       29858 :         while (isspace((unsigned char) *optstr))
     517       13954 :             optstr++;
     518             : 
     519       15904 :         if (*optstr == '\0')
     520           0 :             break;
     521             : 
     522             :         /*
     523             :          * Parse a single option, stopping at the first space, unless it's
     524             :          * escaped.
     525             :          */
     526      241352 :         while (*optstr)
     527             :         {
     528      235342 :             if (isspace((unsigned char) *optstr) && !last_was_escape)
     529        9894 :                 break;
     530             : 
     531      225448 :             if (!last_was_escape && *optstr == '\\')
     532          28 :                 last_was_escape = true;
     533             :             else
     534             :             {
     535      225420 :                 last_was_escape = false;
     536      225420 :                 appendStringInfoChar(&s, *optstr);
     537             :             }
     538             : 
     539      225448 :             optstr++;
     540             :         }
     541             : 
     542             :         /* now store the option in the next argv[] position */
     543       15904 :         argv[(*argcp)++] = pstrdup(s.data);
     544             :     }
     545             : 
     546        6010 :     pfree(s.data);
     547        6010 : }
     548             : 
     549             : /*
     550             :  * Initialize MaxBackends value from config options.
     551             :  *
     552             :  * This must be called after modules have had the chance to alter GUCs in
     553             :  * shared_preload_libraries and before shared memory size is determined.
     554             :  *
     555             :  * Note that in EXEC_BACKEND environment, the value is passed down from
     556             :  * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
     557             :  * postmaster itself and processes not under postmaster control should call
     558             :  * this.
     559             :  */
     560             : void
     561        1636 : InitializeMaxBackends(void)
     562             : {
     563             :     Assert(MaxBackends == 0);
     564             : 
     565             :     /* the extra unit accounts for the autovacuum launcher */
     566        1636 :     MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
     567        1636 :         max_worker_processes + max_wal_senders;
     568             : 
     569             :     /* internal error because the values were all checked previously */
     570        1636 :     if (MaxBackends > MAX_BACKENDS)
     571           0 :         elog(ERROR, "too many backends configured");
     572        1636 : }
     573             : 
     574             : /*
     575             :  * GUC check_hook for max_connections
     576             :  */
     577             : bool
     578        4122 : check_max_connections(int *newval, void **extra, GucSource source)
     579             : {
     580        4122 :     if (*newval + autovacuum_max_workers + 1 +
     581        4122 :         max_worker_processes + max_wal_senders > MAX_BACKENDS)
     582           0 :         return false;
     583        4122 :     return true;
     584             : }
     585             : 
     586             : /*
     587             :  * GUC check_hook for autovacuum_max_workers
     588             :  */
     589             : bool
     590        1700 : check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
     591             : {
     592        1700 :     if (MaxConnections + *newval + 1 +
     593        1700 :         max_worker_processes + max_wal_senders > MAX_BACKENDS)
     594           0 :         return false;
     595        1700 :     return true;
     596             : }
     597             : 
     598             : /*
     599             :  * GUC check_hook for max_worker_processes
     600             :  */
     601             : bool
     602        1702 : check_max_worker_processes(int *newval, void **extra, GucSource source)
     603             : {
     604        1702 :     if (MaxConnections + autovacuum_max_workers + 1 +
     605        1702 :         *newval + max_wal_senders > MAX_BACKENDS)
     606           0 :         return false;
     607        1702 :     return true;
     608             : }
     609             : 
     610             : /*
     611             :  * GUC check_hook for max_wal_senders
     612             :  */
     613             : bool
     614        3620 : check_max_wal_senders(int *newval, void **extra, GucSource source)
     615             : {
     616        3620 :     if (MaxConnections + autovacuum_max_workers + 1 +
     617        3620 :         max_worker_processes + *newval > MAX_BACKENDS)
     618           0 :         return false;
     619        3620 :     return true;
     620             : }
     621             : 
     622             : /*
     623             :  * Early initialization of a backend (either standalone or under postmaster).
     624             :  * This happens even before InitPostgres.
     625             :  *
     626             :  * This is separate from InitPostgres because it is also called by auxiliary
     627             :  * processes, such as the background writer process, which may not call
     628             :  * InitPostgres at all.
     629             :  */
     630             : void
     631       29100 : BaseInit(void)
     632             : {
     633             :     Assert(MyProc != NULL);
     634             : 
     635             :     /*
     636             :      * Initialize our input/output/debugging file descriptors.
     637             :      */
     638       29100 :     DebugFileOpen();
     639             : 
     640             :     /*
     641             :      * Initialize file access. Done early so other subsystems can access
     642             :      * files.
     643             :      */
     644       29100 :     InitFileAccess();
     645             : 
     646             :     /*
     647             :      * Initialize statistics reporting. This needs to happen early to ensure
     648             :      * that pgstat's shutdown callback runs after the shutdown callbacks of
     649             :      * all subsystems that can produce stats (like e.g. transaction commits
     650             :      * can).
     651             :      */
     652       29100 :     pgstat_initialize();
     653             : 
     654             :     /* Do local initialization of storage and buffer managers */
     655       29100 :     InitSync();
     656       29100 :     smgrinit();
     657       29100 :     InitBufferPoolAccess();
     658             : 
     659             :     /*
     660             :      * Initialize temporary file access after pgstat, so that the temporary
     661             :      * file shutdown hook can report temporary file statistics.
     662             :      */
     663       29100 :     InitTemporaryFileAccess();
     664             : 
     665             :     /*
     666             :      * Initialize local buffers for WAL record construction, in case we ever
     667             :      * try to insert XLOG.
     668             :      */
     669       29100 :     InitXLogInsert();
     670             : 
     671             :     /*
     672             :      * Initialize replication slots after pgstat. The exit hook might need to
     673             :      * drop ephemeral slots, which in turn triggers stats reporting.
     674             :      */
     675       29100 :     ReplicationSlotInitialize();
     676       29100 : }
     677             : 
     678             : 
     679             : /* --------------------------------
     680             :  * InitPostgres
     681             :  *      Initialize POSTGRES.
     682             :  *
     683             :  * Parameters:
     684             :  *  in_dbname, dboid: specify database to connect to, as described below
     685             :  *  username, useroid: specify role to connect as, as described below
     686             :  *  flags:
     687             :  *    - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
     688             :  *    - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
     689             :  *    - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
     690             :  *  out_dbname: optional output parameter, see below; pass NULL if not used
     691             :  *
     692             :  * The database can be specified by name, using the in_dbname parameter, or by
     693             :  * OID, using the dboid parameter.  Specify NULL or InvalidOid respectively
     694             :  * for the unused parameter.  If dboid is provided, the actual database
     695             :  * name can be returned to the caller in out_dbname.  If out_dbname isn't
     696             :  * NULL, it must point to a buffer of size NAMEDATALEN.
     697             :  *
     698             :  * Similarly, the role can be passed by name, using the username parameter,
     699             :  * or by OID using the useroid parameter.
     700             :  *
     701             :  * In bootstrap mode the database and username parameters are NULL/InvalidOid.
     702             :  * The autovacuum launcher process doesn't specify these parameters either,
     703             :  * because it only goes far enough to be able to read pg_database; it doesn't
     704             :  * connect to any particular database.  An autovacuum worker specifies a
     705             :  * database but not a username; conversely, a physical walsender specifies
     706             :  * username but not database.
     707             :  *
     708             :  * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
     709             :  * "interactive" sessions (including standalone backends), but not in
     710             :  * background processes such as autovacuum.  Note in particular that it
     711             :  * shouldn't be true in parallel worker processes; those have another
     712             :  * mechanism for replicating their leader's set of loaded libraries.
     713             :  *
     714             :  * We expect that InitProcess() was already called, so we already have a
     715             :  * PGPROC struct ... but it's not completely filled in yet.
     716             :  *
     717             :  * Note:
     718             :  *      Be very careful with the order of calls in the InitPostgres function.
     719             :  * --------------------------------
     720             :  */
     721             : void
     722       25186 : InitPostgres(const char *in_dbname, Oid dboid,
     723             :              const char *username, Oid useroid,
     724             :              bits32 flags,
     725             :              char *out_dbname)
     726             : {
     727       25186 :     bool        bootstrap = IsBootstrapProcessingMode();
     728             :     bool        am_superuser;
     729             :     char       *fullpath;
     730             :     char        dbname[NAMEDATALEN];
     731       25186 :     int         nfree = 0;
     732             : 
     733       25186 :     elog(DEBUG3, "InitPostgres");
     734             : 
     735             :     /*
     736             :      * Add my PGPROC struct to the ProcArray.
     737             :      *
     738             :      * Once I have done this, I am visible to other backends!
     739             :      */
     740       25186 :     InitProcessPhase2();
     741             : 
     742             :     /*
     743             :      * Initialize my entry in the shared-invalidation manager's array of
     744             :      * per-backend data.
     745             :      *
     746             :      * Sets up MyBackendId, a unique backend identifier.
     747             :      */
     748       25186 :     MyBackendId = InvalidBackendId;
     749             : 
     750       25186 :     SharedInvalBackendInit(false);
     751             : 
     752       25186 :     if (MyBackendId > MaxBackends || MyBackendId <= 0)
     753           0 :         elog(FATAL, "bad backend ID: %d", MyBackendId);
     754             : 
     755             :     /* Now that we have a BackendId, we can participate in ProcSignal */
     756       25186 :     ProcSignalInit(MyBackendId);
     757             : 
     758             :     /*
     759             :      * Also set up timeout handlers needed for backend operation.  We need
     760             :      * these in every case except bootstrap.
     761             :      */
     762       25186 :     if (!bootstrap)
     763             :     {
     764       25120 :         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
     765       25120 :         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
     766       25120 :         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
     767       25120 :         RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
     768             :                         IdleInTransactionSessionTimeoutHandler);
     769       25120 :         RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
     770       25120 :         RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
     771       25120 :         RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
     772       25120 :         RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
     773             :                         IdleStatsUpdateTimeoutHandler);
     774             :     }
     775             : 
     776             :     /*
     777             :      * If this is either a bootstrap process or a standalone backend, start up
     778             :      * the XLOG machinery, and register to have it closed down at exit. In
     779             :      * other cases, the startup process is responsible for starting up the
     780             :      * XLOG machinery, and the checkpointer for closing it down.
     781             :      */
     782       25186 :     if (!IsUnderPostmaster)
     783             :     {
     784             :         /*
     785             :          * We don't yet have an aux-process resource owner, but StartupXLOG
     786             :          * and ShutdownXLOG will need one.  Hence, create said resource owner
     787             :          * (and register a callback to clean it up after ShutdownXLOG runs).
     788             :          */
     789         150 :         CreateAuxProcessResourceOwner();
     790             : 
     791         150 :         StartupXLOG();
     792             :         /* Release (and warn about) any buffer pins leaked in StartupXLOG */
     793         150 :         ReleaseAuxProcessResources(true);
     794             :         /* Reset CurrentResourceOwner to nothing for the moment */
     795         150 :         CurrentResourceOwner = NULL;
     796             : 
     797             :         /*
     798             :          * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
     799             :          * segments etc to work (which in turn is required for pgstats).
     800             :          */
     801         150 :         before_shmem_exit(pgstat_before_server_shutdown, 0);
     802         150 :         before_shmem_exit(ShutdownXLOG, 0);
     803             :     }
     804             : 
     805             :     /*
     806             :      * Initialize the relation cache and the system catalog caches.  Note that
     807             :      * no catalog access happens here; we only set up the hashtable structure.
     808             :      * We must do this before starting a transaction because transaction abort
     809             :      * would try to touch these hashtables.
     810             :      */
     811       25186 :     RelationCacheInitialize();
     812       25186 :     InitCatalogCache();
     813       25186 :     InitPlanCache();
     814             : 
     815             :     /* Initialize portal manager */
     816       25186 :     EnablePortalManager();
     817             : 
     818             :     /* Initialize status reporting */
     819       25186 :     pgstat_beinit();
     820             : 
     821             :     /*
     822             :      * Load relcache entries for the shared system catalogs.  This must create
     823             :      * at least entries for pg_database and catalogs used for authentication.
     824             :      */
     825       25186 :     RelationCacheInitializePhase2();
     826             : 
     827             :     /*
     828             :      * Set up process-exit callback to do pre-shutdown cleanup.  This is the
     829             :      * one of the first before_shmem_exit callbacks we register; thus, this
     830             :      * will be one the last things we do before low-level modules like the
     831             :      * buffer manager begin to close down.  We need to have this in place
     832             :      * before we begin our first transaction --- if we fail during the
     833             :      * initialization transaction, as is entirely possible, we need the
     834             :      * AbortTransaction call to clean up.
     835             :      */
     836       25186 :     before_shmem_exit(ShutdownPostgres, 0);
     837             : 
     838             :     /* The autovacuum launcher is done here */
     839       25186 :     if (IsAutoVacuumLauncherProcess())
     840             :     {
     841             :         /* report this backend in the PgBackendStatus array */
     842         628 :         pgstat_bestart();
     843             : 
     844        2032 :         return;
     845             :     }
     846             : 
     847             :     /*
     848             :      * Start a new transaction here before first access to db, and get a
     849             :      * snapshot.  We don't have a use for the snapshot itself, but we're
     850             :      * interested in the secondary effect that it sets RecentGlobalXmin. (This
     851             :      * is critical for anything that reads heap pages, because HOT may decide
     852             :      * to prune them even if the process doesn't attempt to modify any
     853             :      * tuples.)
     854             :      *
     855             :      * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
     856             :      * not pushed/active does not reliably prevent HOT pruning (->xmin could
     857             :      * e.g. be cleared when cache invalidations are processed).
     858             :      */
     859       24558 :     if (!bootstrap)
     860             :     {
     861             :         /* statement_timestamp must be set for timeouts to work correctly */
     862       24492 :         SetCurrentStatementStartTimestamp();
     863       24492 :         StartTransactionCommand();
     864             : 
     865             :         /*
     866             :          * transaction_isolation will have been set to the default by the
     867             :          * above.  If the default is "serializable", and we are in hot
     868             :          * standby, we will fail if we don't change it to something lower.
     869             :          * Fortunately, "read committed" is plenty good enough.
     870             :          */
     871       24492 :         XactIsoLevel = XACT_READ_COMMITTED;
     872             : 
     873       24492 :         (void) GetTransactionSnapshot();
     874             :     }
     875             : 
     876             :     /*
     877             :      * Perform client authentication if necessary, then figure out our
     878             :      * postgres user ID, and see if we are a superuser.
     879             :      *
     880             :      * In standalone mode, autovacuum worker processes and slot sync worker
     881             :      * process, we use a fixed ID, otherwise we figure it out from the
     882             :      * authenticated user name.
     883             :      */
     884       24558 :     if (bootstrap || IsAutoVacuumWorkerProcess() || IsLogicalSlotSyncWorker())
     885             :     {
     886          90 :         InitializeSessionUserIdStandalone();
     887          90 :         am_superuser = true;
     888             :     }
     889       24468 :     else if (!IsUnderPostmaster)
     890             :     {
     891          84 :         InitializeSessionUserIdStandalone();
     892          84 :         am_superuser = true;
     893          84 :         if (!ThereIsAtLeastOneRole())
     894           0 :             ereport(WARNING,
     895             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     896             :                      errmsg("no roles are defined in this database system"),
     897             :                      errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
     898             :                              username != NULL ? username : "postgres")));
     899             :     }
     900       24384 :     else if (IsBackgroundWorker)
     901             :     {
     902        3980 :         if (username == NULL && !OidIsValid(useroid))
     903             :         {
     904         666 :             InitializeSessionUserIdStandalone();
     905         666 :             am_superuser = true;
     906             :         }
     907             :         else
     908             :         {
     909        3314 :             InitializeSessionUserId(username, useroid,
     910        3314 :                                     (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
     911        3312 :             am_superuser = superuser();
     912             :         }
     913             :     }
     914             :     else
     915             :     {
     916             :         /* normal multiuser case */
     917             :         Assert(MyProcPort != NULL);
     918       20404 :         PerformAuthentication(MyProcPort);
     919       20288 :         InitializeSessionUserId(username, useroid, false);
     920             :         /* ensure that auth_method is actually valid, aka authn_id is not NULL */
     921       20280 :         if (MyClientConnectionInfo.authn_id)
     922         206 :             InitializeSystemUser(MyClientConnectionInfo.authn_id,
     923             :                                  hba_authname(MyClientConnectionInfo.auth_method));
     924       20280 :         am_superuser = superuser();
     925             :     }
     926             : 
     927             :     /*
     928             :      * Binary upgrades only allowed super-user connections
     929             :      */
     930       24432 :     if (IsBinaryUpgrade && !am_superuser)
     931             :     {
     932           0 :         ereport(FATAL,
     933             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     934             :                  errmsg("must be superuser to connect in binary upgrade mode")));
     935             :     }
     936             : 
     937             :     /*
     938             :      * The last few connection slots are reserved for superusers and roles
     939             :      * with privileges of pg_use_reserved_connections.  Replication
     940             :      * connections are drawn from slots reserved with max_wal_senders and are
     941             :      * not limited by max_connections, superuser_reserved_connections, or
     942             :      * reserved_connections.
     943             :      *
     944             :      * Note: At this point, the new backend has already claimed a proc struct,
     945             :      * so we must check whether the number of free slots is strictly less than
     946             :      * the reserved connection limits.
     947             :      */
     948       24432 :     if (!am_superuser && !am_walsender &&
     949         418 :         (SuperuserReservedConnections + ReservedConnections) > 0 &&
     950         418 :         !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
     951             :     {
     952           0 :         if (nfree < SuperuserReservedConnections)
     953           0 :             ereport(FATAL,
     954             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     955             :                      errmsg("remaining connection slots are reserved for roles with the %s attribute",
     956             :                             "SUPERUSER")));
     957             : 
     958           0 :         if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
     959           0 :             ereport(FATAL,
     960             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     961             :                      errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
     962             :                             "pg_use_reserved_connections")));
     963             :     }
     964             : 
     965             :     /* Check replication permissions needed for walsender processes. */
     966       24432 :     if (am_walsender)
     967             :     {
     968             :         Assert(!bootstrap);
     969             : 
     970        1856 :         if (!has_rolreplication(GetUserId()))
     971           0 :             ereport(FATAL,
     972             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     973             :                      errmsg("permission denied to start WAL sender"),
     974             :                      errdetail("Only roles with the %s attribute may start a WAL sender process.",
     975             :                                "REPLICATION")));
     976             :     }
     977             : 
     978             :     /*
     979             :      * If this is a plain walsender only supporting physical replication, we
     980             :      * don't want to connect to any particular database. Just finish the
     981             :      * backend startup by processing any options from the startup packet, and
     982             :      * we're done.
     983             :      */
     984       24432 :     if (am_walsender && !am_db_walsender)
     985             :     {
     986             :         /* process any options passed in the startup packet */
     987         742 :         if (MyProcPort != NULL)
     988         742 :             process_startup_options(MyProcPort, am_superuser);
     989             : 
     990             :         /* Apply PostAuthDelay as soon as we've read all options */
     991         742 :         if (PostAuthDelay > 0)
     992           0 :             pg_usleep(PostAuthDelay * 1000000L);
     993             : 
     994             :         /* initialize client encoding */
     995         742 :         InitializeClientEncoding();
     996             : 
     997             :         /* report this backend in the PgBackendStatus array */
     998         742 :         pgstat_bestart();
     999             : 
    1000             :         /* close the transaction we started above */
    1001         742 :         CommitTransactionCommand();
    1002             : 
    1003         742 :         return;
    1004             :     }
    1005             : 
    1006             :     /*
    1007             :      * Set up the global variables holding database id and default tablespace.
    1008             :      * But note we won't actually try to touch the database just yet.
    1009             :      *
    1010             :      * We take a shortcut in the bootstrap case, otherwise we have to look up
    1011             :      * the db's entry in pg_database.
    1012             :      */
    1013       23690 :     if (bootstrap)
    1014             :     {
    1015          66 :         dboid = Template1DbOid;
    1016          66 :         MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
    1017             :     }
    1018       23624 :     else if (in_dbname != NULL)
    1019             :     {
    1020             :         HeapTuple   tuple;
    1021             :         Form_pg_database dbform;
    1022             : 
    1023       19626 :         tuple = GetDatabaseTuple(in_dbname);
    1024       19626 :         if (!HeapTupleIsValid(tuple))
    1025          18 :             ereport(FATAL,
    1026             :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
    1027             :                      errmsg("database \"%s\" does not exist", in_dbname)));
    1028       19608 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
    1029       19608 :         dboid = dbform->oid;
    1030             :     }
    1031        3998 :     else if (!OidIsValid(dboid))
    1032             :     {
    1033             :         /*
    1034             :          * If this is a background worker not bound to any particular
    1035             :          * database, we're done now.  Everything that follows only makes sense
    1036             :          * if we are bound to a specific database.  We do need to close the
    1037             :          * transaction we started before returning.
    1038             :          */
    1039         662 :         if (!bootstrap)
    1040             :         {
    1041         662 :             pgstat_bestart();
    1042         662 :             CommitTransactionCommand();
    1043             :         }
    1044         662 :         return;
    1045             :     }
    1046             : 
    1047             :     /*
    1048             :      * Now, take a writer's lock on the database we are trying to connect to.
    1049             :      * If there is a concurrently running DROP DATABASE on that database, this
    1050             :      * will block us until it finishes (and has committed its update of
    1051             :      * pg_database).
    1052             :      *
    1053             :      * Note that the lock is not held long, only until the end of this startup
    1054             :      * transaction.  This is OK since we will advertise our use of the
    1055             :      * database in the ProcArray before dropping the lock (in fact, that's the
    1056             :      * next thing to do).  Anyone trying a DROP DATABASE after this point will
    1057             :      * see us in the array once they have the lock.  Ordering is important for
    1058             :      * this because we don't want to advertise ourselves as being in this
    1059             :      * database until we have the lock; otherwise we create what amounts to a
    1060             :      * deadlock with CountOtherDBBackends().
    1061             :      *
    1062             :      * Note: use of RowExclusiveLock here is reasonable because we envision
    1063             :      * our session as being a concurrent writer of the database.  If we had a
    1064             :      * way of declaring a session as being guaranteed-read-only, we could use
    1065             :      * AccessShareLock for such sessions and thereby not conflict against
    1066             :      * CREATE DATABASE.
    1067             :      */
    1068       23010 :     if (!bootstrap)
    1069       22944 :         LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
    1070             : 
    1071             :     /*
    1072             :      * Recheck pg_database to make sure the target database hasn't gone away.
    1073             :      * If there was a concurrent DROP DATABASE, this ensures we will die
    1074             :      * cleanly without creating a mess.
    1075             :      */
    1076       23010 :     if (!bootstrap)
    1077             :     {
    1078             :         HeapTuple   tuple;
    1079             :         Form_pg_database datform;
    1080             : 
    1081       22944 :         tuple = GetDatabaseTupleByOid(dboid);
    1082       22944 :         if (HeapTupleIsValid(tuple))
    1083       22944 :             datform = (Form_pg_database) GETSTRUCT(tuple);
    1084             : 
    1085       22944 :         if (!HeapTupleIsValid(tuple) ||
    1086       19608 :             (in_dbname && namestrcmp(&datform->datname, in_dbname)))
    1087             :         {
    1088           0 :             if (in_dbname)
    1089           0 :                 ereport(FATAL,
    1090             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1091             :                          errmsg("database \"%s\" does not exist", in_dbname),
    1092             :                          errdetail("It seems to have just been dropped or renamed.")));
    1093             :             else
    1094           0 :                 ereport(FATAL,
    1095             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1096             :                          errmsg("database %u does not exist", dboid)));
    1097             :         }
    1098             : 
    1099       22944 :         strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
    1100             : 
    1101       22944 :         if (database_is_invalid_form(datform))
    1102             :         {
    1103          14 :             ereport(FATAL,
    1104             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1105             :                     errmsg("cannot connect to invalid database \"%s\"", dbname),
    1106             :                     errhint("Use DROP DATABASE to drop invalid databases."));
    1107             :         }
    1108             : 
    1109       22930 :         MyDatabaseTableSpace = datform->dattablespace;
    1110       22930 :         MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
    1111             :         /* pass the database name back to the caller */
    1112       22930 :         if (out_dbname)
    1113          20 :             strcpy(out_dbname, dbname);
    1114             :     }
    1115             : 
    1116             :     /*
    1117             :      * Now that we rechecked, we are certain to be connected to a database and
    1118             :      * thus can set MyDatabaseId.
    1119             :      *
    1120             :      * It is important that MyDatabaseId only be set once we are sure that the
    1121             :      * target database can no longer be concurrently dropped or renamed.  For
    1122             :      * example, without this guarantee, pgstat_update_dbstats() could create
    1123             :      * entries for databases that were just dropped in the pgstat shutdown
    1124             :      * callback, which could confuse other code paths like the autovacuum
    1125             :      * scheduler.
    1126             :      */
    1127       22996 :     MyDatabaseId = dboid;
    1128             : 
    1129             :     /*
    1130             :      * Now we can mark our PGPROC entry with the database ID.
    1131             :      *
    1132             :      * We assume this is an atomic store so no lock is needed; though actually
    1133             :      * things would work fine even if it weren't atomic.  Anyone searching the
    1134             :      * ProcArray for this database's ID should hold the database lock, so they
    1135             :      * would not be executing concurrently with this store.  A process looking
    1136             :      * for another database's ID could in theory see a chance match if it read
    1137             :      * a partially-updated databaseId value; but as long as all such searches
    1138             :      * wait and retry, as in CountOtherDBBackends(), they will certainly see
    1139             :      * the correct value on their next try.
    1140             :      */
    1141       22996 :     MyProc->databaseId = MyDatabaseId;
    1142             : 
    1143             :     /*
    1144             :      * We established a catalog snapshot while reading pg_authid and/or
    1145             :      * pg_database; but until we have set up MyDatabaseId, we won't react to
    1146             :      * incoming sinval messages for unshared catalogs, so we won't realize it
    1147             :      * if the snapshot has been invalidated.  Assume it's no good anymore.
    1148             :      */
    1149       22996 :     InvalidateCatalogSnapshot();
    1150             : 
    1151             :     /*
    1152             :      * Now we should be able to access the database directory safely. Verify
    1153             :      * it's there and looks reasonable.
    1154             :      */
    1155       22996 :     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
    1156             : 
    1157       22996 :     if (!bootstrap)
    1158             :     {
    1159       22930 :         if (access(fullpath, F_OK) == -1)
    1160             :         {
    1161           0 :             if (errno == ENOENT)
    1162           0 :                 ereport(FATAL,
    1163             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1164             :                          errmsg("database \"%s\" does not exist",
    1165             :                                 dbname),
    1166             :                          errdetail("The database subdirectory \"%s\" is missing.",
    1167             :                                    fullpath)));
    1168             :             else
    1169           0 :                 ereport(FATAL,
    1170             :                         (errcode_for_file_access(),
    1171             :                          errmsg("could not access directory \"%s\": %m",
    1172             :                                 fullpath)));
    1173             :         }
    1174             : 
    1175       22930 :         ValidatePgVersion(fullpath);
    1176             :     }
    1177             : 
    1178       22996 :     SetDatabasePath(fullpath);
    1179       22996 :     pfree(fullpath);
    1180             : 
    1181             :     /*
    1182             :      * It's now possible to do real access to the system catalogs.
    1183             :      *
    1184             :      * Load relcache entries for the system catalogs.  This must create at
    1185             :      * least the minimum set of "nailed-in" cache entries.
    1186             :      */
    1187       22996 :     RelationCacheInitializePhase3();
    1188             : 
    1189             :     /* set up ACL framework (so CheckMyDatabase can check permissions) */
    1190       22990 :     initialize_acl();
    1191             : 
    1192             :     /*
    1193             :      * Re-read the pg_database row for our database, check permissions and set
    1194             :      * up database-specific GUC settings.  We can't do this until all the
    1195             :      * database-access infrastructure is up.  (Also, it wants to know if the
    1196             :      * user is a superuser, so the above stuff has to happen first.)
    1197             :      */
    1198       22990 :     if (!bootstrap)
    1199       22924 :         CheckMyDatabase(dbname, am_superuser,
    1200       22924 :                         (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
    1201             : 
    1202             :     /*
    1203             :      * Now process any command-line switches and any additional GUC variable
    1204             :      * settings passed in the startup packet.   We couldn't do this before
    1205             :      * because we didn't know if client is a superuser.
    1206             :      */
    1207       22984 :     if (MyProcPort != NULL)
    1208       19506 :         process_startup_options(MyProcPort, am_superuser);
    1209             : 
    1210             :     /* Process pg_db_role_setting options */
    1211       22984 :     process_settings(MyDatabaseId, GetSessionUserId());
    1212             : 
    1213             :     /* Apply PostAuthDelay as soon as we've read all options */
    1214       22980 :     if (PostAuthDelay > 0)
    1215           0 :         pg_usleep(PostAuthDelay * 1000000L);
    1216             : 
    1217             :     /*
    1218             :      * Initialize various default states that can't be set up until we've
    1219             :      * selected the active user and gotten the right GUC settings.
    1220             :      */
    1221             : 
    1222             :     /* set default namespace search path */
    1223       22980 :     InitializeSearchPath();
    1224             : 
    1225             :     /* initialize client encoding */
    1226       22980 :     InitializeClientEncoding();
    1227             : 
    1228             :     /* Initialize this backend's session state. */
    1229       22980 :     InitializeSession();
    1230             : 
    1231             :     /*
    1232             :      * If this is an interactive session, load any libraries that should be
    1233             :      * preloaded at backend start.  Since those are determined by GUCs, this
    1234             :      * can't happen until GUC settings are complete, but we want it to happen
    1235             :      * during the initial transaction in case anything that requires database
    1236             :      * access needs to be done.
    1237             :      */
    1238       22980 :     if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
    1239       18472 :         process_session_preload_libraries();
    1240             : 
    1241             :     /* report this backend in the PgBackendStatus array */
    1242       22980 :     if (!bootstrap)
    1243       22914 :         pgstat_bestart();
    1244             : 
    1245             :     /* close the transaction we started above */
    1246       22980 :     if (!bootstrap)
    1247       22914 :         CommitTransactionCommand();
    1248             : }
    1249             : 
    1250             : /*
    1251             :  * Process any command-line switches and any additional GUC variable
    1252             :  * settings passed in the startup packet.
    1253             :  */
    1254             : static void
    1255       20248 : process_startup_options(Port *port, bool am_superuser)
    1256             : {
    1257             :     GucContext  gucctx;
    1258             :     ListCell   *gucopts;
    1259             : 
    1260       20248 :     gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
    1261             : 
    1262             :     /*
    1263             :      * First process any command-line switches that were included in the
    1264             :      * startup packet, if we are in a regular backend.
    1265             :      */
    1266       20248 :     if (port->cmdline_options != NULL)
    1267             :     {
    1268             :         /*
    1269             :          * The maximum possible number of commandline arguments that could
    1270             :          * come from port->cmdline_options is (strlen + 1) / 2; see
    1271             :          * pg_split_opts().
    1272             :          */
    1273             :         char      **av;
    1274             :         int         maxac;
    1275             :         int         ac;
    1276             : 
    1277        6010 :         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
    1278             : 
    1279        6010 :         av = (char **) palloc(maxac * sizeof(char *));
    1280        6010 :         ac = 0;
    1281             : 
    1282        6010 :         av[ac++] = "postgres";
    1283             : 
    1284        6010 :         pg_split_opts(av, &ac, port->cmdline_options);
    1285             : 
    1286        6010 :         av[ac] = NULL;
    1287             : 
    1288             :         Assert(ac < maxac);
    1289             : 
    1290        6010 :         (void) process_postgres_switches(ac, av, gucctx, NULL);
    1291             :     }
    1292             : 
    1293             :     /*
    1294             :      * Process any additional GUC variable settings passed in startup packet.
    1295             :      * These are handled exactly like command-line variables.
    1296             :      */
    1297       20248 :     gucopts = list_head(port->guc_options);
    1298       49910 :     while (gucopts)
    1299             :     {
    1300             :         char       *name;
    1301             :         char       *value;
    1302             : 
    1303       29662 :         name = lfirst(gucopts);
    1304       29662 :         gucopts = lnext(port->guc_options, gucopts);
    1305             : 
    1306       29662 :         value = lfirst(gucopts);
    1307       29662 :         gucopts = lnext(port->guc_options, gucopts);
    1308             : 
    1309       29662 :         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
    1310             :     }
    1311       20248 : }
    1312             : 
    1313             : /*
    1314             :  * Load GUC settings from pg_db_role_setting.
    1315             :  *
    1316             :  * We try specific settings for the database/role combination, as well as
    1317             :  * general for this database and for this user.
    1318             :  */
    1319             : static void
    1320       22984 : process_settings(Oid databaseid, Oid roleid)
    1321             : {
    1322             :     Relation    relsetting;
    1323             :     Snapshot    snapshot;
    1324             : 
    1325       22984 :     if (!IsUnderPostmaster)
    1326         146 :         return;
    1327             : 
    1328       22838 :     relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
    1329             : 
    1330             :     /* read all the settings under the same snapshot for efficiency */
    1331       22838 :     snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
    1332             : 
    1333             :     /* Later settings are ignored if set earlier. */
    1334       22838 :     ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
    1335       22834 :     ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
    1336       22834 :     ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
    1337       22834 :     ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
    1338             : 
    1339       22834 :     UnregisterSnapshot(snapshot);
    1340       22834 :     table_close(relsetting, AccessShareLock);
    1341             : }
    1342             : 
    1343             : /*
    1344             :  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
    1345             :  * before all the supporting modules begin to nail their doors shut via
    1346             :  * their own callbacks.
    1347             :  *
    1348             :  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
    1349             :  * via separate callbacks that execute before this one.  We don't combine the
    1350             :  * callbacks because we still want this one to happen if the user-level
    1351             :  * cleanup fails.
    1352             :  */
    1353             : static void
    1354       25186 : ShutdownPostgres(int code, Datum arg)
    1355             : {
    1356             :     /* Make sure we've killed any active transaction */
    1357       25186 :     AbortOutOfAnyTransaction();
    1358             : 
    1359             :     /*
    1360             :      * User locks are not released by transaction end, so be sure to release
    1361             :      * them explicitly.
    1362             :      */
    1363       25186 :     LockReleaseAll(USER_LOCKMETHOD, true);
    1364       25186 : }
    1365             : 
    1366             : 
    1367             : /*
    1368             :  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
    1369             :  */
    1370             : static void
    1371          10 : StatementTimeoutHandler(void)
    1372             : {
    1373          10 :     int         sig = SIGINT;
    1374             : 
    1375             :     /*
    1376             :      * During authentication the timeout is used to deal with
    1377             :      * authentication_timeout - we want to quit in response to such timeouts.
    1378             :      */
    1379          10 :     if (ClientAuthInProgress)
    1380           0 :         sig = SIGTERM;
    1381             : 
    1382             : #ifdef HAVE_SETSID
    1383             :     /* try to signal whole process group */
    1384          10 :     kill(-MyProcPid, sig);
    1385             : #endif
    1386          10 :     kill(MyProcPid, sig);
    1387          10 : }
    1388             : 
    1389             : /*
    1390             :  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
    1391             :  */
    1392             : static void
    1393           8 : LockTimeoutHandler(void)
    1394             : {
    1395             : #ifdef HAVE_SETSID
    1396             :     /* try to signal whole process group */
    1397           8 :     kill(-MyProcPid, SIGINT);
    1398             : #endif
    1399           8 :     kill(MyProcPid, SIGINT);
    1400           8 : }
    1401             : 
    1402             : static void
    1403           0 : TransactionTimeoutHandler(void)
    1404             : {
    1405           0 :     TransactionTimeoutPending = true;
    1406           0 :     InterruptPending = true;
    1407           0 :     SetLatch(MyLatch);
    1408           0 : }
    1409             : 
    1410             : static void
    1411           0 : IdleInTransactionSessionTimeoutHandler(void)
    1412             : {
    1413           0 :     IdleInTransactionSessionTimeoutPending = true;
    1414           0 :     InterruptPending = true;
    1415           0 :     SetLatch(MyLatch);
    1416           0 : }
    1417             : 
    1418             : static void
    1419           0 : IdleSessionTimeoutHandler(void)
    1420             : {
    1421           0 :     IdleSessionTimeoutPending = true;
    1422           0 :     InterruptPending = true;
    1423           0 :     SetLatch(MyLatch);
    1424           0 : }
    1425             : 
    1426             : static void
    1427          20 : IdleStatsUpdateTimeoutHandler(void)
    1428             : {
    1429          20 :     IdleStatsUpdateTimeoutPending = true;
    1430          20 :     InterruptPending = true;
    1431          20 :     SetLatch(MyLatch);
    1432          20 : }
    1433             : 
    1434             : static void
    1435           0 : ClientCheckTimeoutHandler(void)
    1436             : {
    1437           0 :     CheckClientConnectionPending = true;
    1438           0 :     InterruptPending = true;
    1439           0 :     SetLatch(MyLatch);
    1440           0 : }
    1441             : 
    1442             : /*
    1443             :  * Returns true if at least one role is defined in this database cluster.
    1444             :  */
    1445             : static bool
    1446          84 : ThereIsAtLeastOneRole(void)
    1447             : {
    1448             :     Relation    pg_authid_rel;
    1449             :     TableScanDesc scan;
    1450             :     bool        result;
    1451             : 
    1452          84 :     pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
    1453             : 
    1454          84 :     scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
    1455          84 :     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
    1456             : 
    1457          84 :     table_endscan(scan);
    1458          84 :     table_close(pg_authid_rel, AccessShareLock);
    1459             : 
    1460          84 :     return result;
    1461             : }

Generated by: LCOV version 1.14