LCOV - differential code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 86.2 % 384 331 9 13 25 6 6 202 30 93 41 217 8
Current Date: 2023-04-08 15:15:32 Functions: 86.4 % 22 19 3 12 5 2 3 16
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a