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 17:13:01 Functions: 86.4 % 22 19 3 12 5 2 3 16
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 [..60] days: 80.0 % 15 12 1 2 1 8 3 1
Legend: Lines: hit not hit (60,120] days: 42.9 % 7 3 4 3
(120,180] days: 100.0 % 1 1 1
(180,240] days: 78.3 % 23 18 4 1 18 1
(240..) days: 87.9 % 338 297 13 24 4 6 201 90 25 195
Function coverage date bins:
(180,240] days: 100.0 % 4 4 4
(240..) days: 48.4 % 31 15 3 12 1 2 13

 Age         Owner                  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
 4988 tgl                       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                 :      */
 1539 andres                    121           18805 :     relation = table_open(DatabaseRelationId, AccessShareLock);
 4988 tgl                       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);
 1539 andres                    135           18805 :     table_close(relation, AccessShareLock);
                                136                 : 
 4988 tgl                       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                 :      */
 1539 andres                    164            1632 :     relation = table_open(DatabaseRelationId, AccessShareLock);
 4988 tgl                       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);
 1539 andres                    178            1632 :     table_close(relation, AccessShareLock);
                                179                 : 
 4988 tgl                       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
 4971                           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                 :      */
 3919 alvherre                  240 GIC        8695 :     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
 4971 tgl                       241 ECB             : 
                                242                 :     /*
                                243                 :      * Now perform authentication exchange.
                                244                 :      */
 1124 peter                     245 GIC        8695 :     set_ps_display("authentication");
 4971 tgl                       246 CBC        8695 :     ClientAuthentication(port); /* might not return, if failure */
 4971 tgl                       247 ECB             : 
                                248                 :     /*
                                249                 :      * Done with authentication.  Disable the timeout, and log if needed.
                                250                 :      */
 3919 alvherre                  251 GIC        8628 :     disable_timeout(STATEMENT_TIMEOUT, false);
 4971 tgl                       252 ECB             : 
 4464 magnus                    253 GIC        8628 :     if (Log_connections)
 4763 simon                     254 ECB             :     {
                                255                 :         StringInfoData logmsg;
                                256                 : 
  858 sfrost                    257 GIC         257 :         initStringInfo(&logmsg);
 4464 magnus                    258 CBC         257 :         if (am_walsender)
  858 sfrost                    259               3 :             appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
  858 sfrost                    260 ECB             :                              port->user_name);
                                261                 :         else
  858 sfrost                    262 GIC         254 :             appendStringInfo(&logmsg, _("connection authorized: user=%s"),
  858 sfrost                    263 ECB             :                              port->user_name);
  858 sfrost                    264 GIC         257 :         if (!am_walsender)
  858 sfrost                    265 CBC         254 :             appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
  858 sfrost                    266 ECB             : 
  858 sfrost                    267 GIC         257 :         if (port->application_name != NULL)
  858 sfrost                    268 CBC         257 :             appendStringInfo(&logmsg, _(" application_name=%s"),
  858 sfrost                    269 ECB             :                              port->application_name);
                                270                 : 
                                271                 : #ifdef USE_SSL
  858 sfrost                    272 GIC         257 :         if (port->ssl_in_use)
  761 michael                   273 CBC          76 :             appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
  858 sfrost                    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
  832 tgl                       279 GIC         257 :         if (port->gss)
  832 tgl                       280 ECB             :         {
  832 tgl                       281 GIC          17 :             const char *princ = be_gssapi_get_princ(port);
  832 tgl                       282 ECB             : 
  832 tgl                       283 GIC          17 :             if (princ)
  832 tgl                       284 CBC          34 :                 appendStringInfo(&logmsg,
    1 sfrost                    285              17 :                                  _(" GSS (authenticated=%s, encrypted=%s, principal=%s)"),
  832 tgl                       286              34 :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
                                287              34 :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"),
  832 tgl                       288 ECB             :                                  princ);
                                289                 :             else
  832 tgl                       290 UIC           0 :                 appendStringInfo(&logmsg,
    1 sfrost                    291 UBC           0 :                                  _(" GSS (authenticated=%s, encrypted=%s)"),
  832 tgl                       292               0 :                                  be_gssapi_get_auth(port) ? _("yes") : _("no"),
    1 sfrost                    293               0 :                                  be_gssapi_get_enc(port) ? _("yes") : _("no"));
  832 tgl                       294 EUB             :         }
                                295                 : #endif
                                296                 : 
  858 sfrost                    297 GIC         257 :         ereport(LOG, errmsg_internal("%s", logmsg.data));
  858 sfrost                    298 CBC         257 :         pfree(logmsg.data);
 4763 simon                     299 ECB             :     }
                                300                 : 
 1124 peter                     301 GIC        8628 :     set_ps_display("startup");
 4968 tgl                       302 ECB             : 
 2118 tgl                       303 GIC        8628 :     ClientAuthInProgress = false;   /* client_min_messages is active now */
 4971 tgl                       304 CBC        8628 : }
 4971 tgl                       305 ECB             : 
                                306                 : 
                                307                 : /*
                                308                 :  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
                                309                 :  */
                                310                 : static void
 1830 magnus                    311 GIC       10213 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
 8598 tgl                       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 */
 4802 rhaas                     322 GIC       10213 :     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
 6184 tgl                       323 CBC       10213 :     if (!HeapTupleIsValid(tup))
 6184 tgl                       324 LBC           0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
 6184 tgl                       325 GBC       10213 :     dbform = (Form_pg_database) GETSTRUCT(tup);
 8397 bruce                     326 ECB             : 
                                327                 :     /* This recheck is strictly paranoia */
 6184 tgl                       328 GIC       10213 :     if (strcmp(name, NameStr(dbform->datname)) != 0)
 7198 tgl                       329 LBC           0 :         ereport(FATAL,
 7198 tgl                       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                 :      */
 5897 alvherre                  345 GIC       10213 :     if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
 6461 tgl                       346 ECB             :     {
                                347                 :         /*
                                348                 :          * Check that the database is currently allowing connections.
                                349                 :          */
 1830 magnus                    350 GIC        9883 :         if (!dbform->datallowconn && !override_allow_connections)
 6461 tgl                       351 LBC           0 :             ereport(FATAL,
 6461 tgl                       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                 :          */
 6188 tgl                       361 GIC       10090 :         if (!am_superuser &&
  147 peter                     362 GNC         207 :             object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
 6185 tgl                       363 ECB             :                                  ACL_CONNECT) != ACLCHECK_OK)
 6188 tgl                       364 UIC           0 :             ereport(FATAL,
 6188 tgl                       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                 :          */
 6461 tgl                       379 GIC        9883 :         if (dbform->datconnlimit >= 0 &&
 6188 tgl                       380 LBC           0 :             !am_superuser &&
 2258 andrew                    381 UBC           0 :             CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
 6461 tgl                       382               0 :             ereport(FATAL,
 6461 tgl                       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                 :      */
 8181 tgl                       392 GIC       10213 :     SetDatabaseEncoding(dbform->encoding);
 7289 tgl                       393 ECB             :     /* Record it as a GUC internal option, too */
 7289 tgl                       394 GIC       10213 :     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
  305 tgl                       395 ECB             :                     PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
                                396                 :     /* If we have no other source of client_encoding, use server encoding */
 7632 tgl                       397 GIC       10213 :     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
 4351 tgl                       398 ECB             :                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
                                399                 : 
                                400                 :     /* assign locale variables */
   15 dgustafsson               401 GNC       10213 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
  437 peter                     402 CBC       10213 :     collate = TextDatumGetCString(datum);
   15 dgustafsson               403 GNC       10213 :     datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
  437 peter                     404 GIC       10213 :     ctype = TextDatumGetCString(datum);
 5050 bruce                     405 ECB             : 
 5023 heikki.linnakangas        406 GBC       10213 :     if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
 5050 bruce                     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.")));
 5050 bruce                     412 ECB             : 
 5023 heikki.linnakangas        413 GBC       10213 :     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
 5050 bruce                     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.")));
 5050 bruce                     419 ECB             : 
   23 jdavis                    420 CBC       10213 :     if (strcmp(ctype, "C") == 0 ||
                                421            8931 :         strcmp(ctype, "POSIX") == 0)
   23 jdavis                    422 GIC        1282 :         database_ctype_is_c = true;
   23 jdavis                    423 ECB             : 
  388 peter                     424 GIC       10213 :     if (dbform->datlocprovider == COLLPROVIDER_ICU)
                                425                 :     {
                                426                 :         char       *icurules;
                                427                 : 
   15 dgustafsson               428 GNC       10161 :         datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_daticulocale);
  388 peter                     429 CBC       10161 :         iculocale = TextDatumGetCString(datum);
                                430                 : 
   32 peter                     431 GNC       10161 :         datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_daticurules, &isnull);
                                432           10161 :         if (!isnull)
   32 peter                     433 UNC           0 :             icurules = TextDatumGetCString(datum);
                                434                 :         else
   32 peter                     435 GNC       10161 :             icurules = NULL;
                                436                 : 
                                437           10161 :         make_icu_collator(iculocale, icurules, &default_locale);
  388 peter                     438 ECB             :     }
                                439                 :     else
  388 peter                     440 GBC          52 :         iculocale = NULL;
                                441                 : 
  388 peter                     442 CBC       10211 :     default_locale.provider = dbform->datlocprovider;
                                443                 : 
  388 peter                     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                 :      */
  388 peter                     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                 :      */
  419                           456           10211 :     datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
                                457                 :                             &isnull);
  419 peter                     458 GIC       10211 :     if (!isnull)
                                459                 :     {
                                460                 :         char       *actual_versionstr;
                                461                 :         char       *collversionstr;
                                462                 : 
  419 peter                     463 CBC        9904 :         collversionstr = TextDatumGetCString(datum);
                                464                 : 
  388                           465            9904 :         actual_versionstr = get_collation_actual_version(dbform->datlocprovider, dbform->datlocprovider == COLLPROVIDER_ICU ? iculocale : collate);
  419 peter                     466 GIC        9904 :         if (!actual_versionstr)
                                467                 :             /* should not happen */
  214 alvherre                  468 UIC           0 :             elog(WARNING,
                                469                 :                  "database \"%s\" has no actual collation version, but a version was recorded",
  214 alvherre                  470 ECB             :                  name);
  412 peter                     471 GIC        9904 :         else if (strcmp(actual_versionstr, collversionstr) != 0)
  419 peter                     472 LBC           0 :             ereport(WARNING,
  419 peter                     473 ECB             :                     (errmsg("database \"%s\" has a collation version mismatch",
                                474                 :                             name),
  419 peter                     475 EUB             :                      errdetail("The database was created using collation version %s, "
                                476                 :                                "but the operating system provides version %s.",
                                477                 :                                collversionstr, actual_versionstr),
  419 peter                     478 ECB             :                      errhint("Rebuild all objects in this database that use the default collation and run "
  419 peter                     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 */
  305 tgl                       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                 : 
 2832 noah                      488           10211 :     check_strxfrm_bug();
                                489                 : 
 6184 tgl                       490           10211 :     ReleaseSysCache(tup);
 8598                           491           10211 : }
 9644 bryanh                    492 ECB             : 
 8487 peter_e                   493                 : 
                                494                 : /*
 4971 tgl                       495                 :  * pg_split_opts -- split a string of options and append it to an argv array
                                496                 :  *
 3146 andres                    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
 2841 tgl                       505 GIC        2496 : pg_split_opts(char **argv, int *argcp, const char *optstr)
                                506                 : {
                                507                 :     StringInfoData s;
                                508                 : 
 3146 andres                    509            2496 :     initStringInfo(&s);
                                510                 : 
 4971 tgl                       511            9162 :     while (*optstr)
 4971 tgl                       512 ECB             :     {
 3130 tgl                       513 GIC        6666 :         bool        last_was_escape = false;
                                514                 : 
 3146 andres                    515            6666 :         resetStringInfo(&s);
 3146 andres                    516 ECB             : 
                                517                 :         /* skip over leading space */
 4971 tgl                       518 CBC       12714 :         while (isspace((unsigned char) *optstr))
 4971 tgl                       519 GIC        6048 :             optstr++;
 3146 andres                    520 ECB             : 
 4971 tgl                       521 GIC        6666 :         if (*optstr == '\0')
 4971 tgl                       522 LBC           0 :             break;
                                523                 : 
                                524                 :         /*
 2841 tgl                       525 ECB             :          * Parse a single option, stopping at the first space, unless it's
                                526                 :          * escaped.
                                527                 :          */
 3146 andres                    528 CBC       99667 :         while (*optstr)
 3146 andres                    529 EUB             :         {
 3142 tgl                       530 GIC       97171 :             if (isspace((unsigned char) *optstr) && !last_was_escape)
 3146 andres                    531            4170 :                 break;
                                532                 : 
                                533           93001 :             if (!last_was_escape && *optstr == '\\')
                                534               9 :                 last_was_escape = true;
 3146 andres                    535 ECB             :             else
                                536                 :             {
 3146 andres                    537 CBC       92992 :                 last_was_escape = false;
                                538           92992 :                 appendStringInfoChar(&s, *optstr);
                                539                 :             }
 3146 andres                    540 ECB             : 
 4971 tgl                       541 CBC       93001 :             optstr++;
                                542                 :         }
                                543                 : 
 2841 tgl                       544 ECB             :         /* now store the option in the next argv[] position */
 3146 andres                    545 CBC        6666 :         argv[(*argcp)++] = pstrdup(s.data);
                                546                 :     }
                                547                 : 
 2841 tgl                       548            2496 :     pfree(s.data);
 4971 tgl                       549 GIC        2496 : }
                                550                 : 
                                551                 : /*
 3749 alvherre                  552 ECB             :  * Initialize MaxBackends value from config options.
                                553                 :  *
                                554                 :  * This must be called after modules have had the chance to alter GUCs in
  338 rhaas                     555                 :  * shared_preload_libraries and before shared memory size is determined.
 3749 alvherre                  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
 3749 alvherre                  563 GIC        1825 : InitializeMaxBackends(void)
                                564                 : {
  362 rhaas                     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;
 3749 alvherre                  570 ECB             : 
                                571                 :     /* internal error because the values were all checked previously */
  362 rhaas                     572 CBC        1825 :     if (MaxBackends > MAX_BACKENDS)
 3749 alvherre                  573 UIC           0 :         elog(ERROR, "too many backends configured");
 3749 alvherre                  574 GIC        1825 : }
 4971 tgl                       575 ECB             : 
                                576                 : /*
                                577                 :  * GUC check_hook for max_connections
                                578                 :  */
                                579                 : bool
  208 tgl                       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)
  208 tgl                       584 UNC           0 :         return false;
  208 tgl                       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)
  208 tgl                       596 UNC           0 :         return false;
  208 tgl                       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)
  208 tgl                       608 UNC           0 :         return false;
  208 tgl                       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)
  208 tgl                       620 UNC           0 :         return false;
  208 tgl                       621 GNC        2714 :     return true;
                                622                 : }
                                623                 : 
 8147 tgl                       624 ECB             : /*
                                625                 :  * Early initialization of a backend (either standalone or under postmaster).
                                626                 :  * This happens even before InitPostgres.
 7967                           627                 :  *
 4737 tgl                       628 EUB             :  * This is separate from InitPostgres because it is also called by auxiliary
 4737 tgl                       629 ECB             :  * processes, such as the background writer process, which may not call
                                630                 :  * InitPostgres at all.
                                631                 :  */
                                632                 : void
 8147 tgl                       633 GIC       13373 : BaseInit(void)
                                634                 : {
  612 andres                    635 CBC       13373 :     Assert(MyProc != NULL);
                                636                 : 
 8147 tgl                       637 ECB             :     /*
  612 andres                    638                 :      * Initialize our input/output/debugging file descriptors.
 8147 tgl                       639 EUB             :      */
 8147 tgl                       640 CBC       13373 :     DebugFileOpen();
                                641                 : 
                                642                 :     /*
                                643                 :      * Initialize file access. Done early so other subsystems can access
                                644                 :      * files.
                                645                 :      */
  610 andres                    646 GIC       13373 :     InitFileAccess();
  610 andres                    647 ECB             : 
                                648                 :     /*
  611                           649                 :      * Initialize statistics reporting. This needs to happen early to ensure
                                650                 :      * that pgstat's shutdown callback runs after the shutdown callbacks of
  611 andres                    651 EUB             :      * all subsystems that can produce stats (like e.g. transaction commits
  611 andres                    652 ECB             :      * can).
                                653                 :      */
  611 andres                    654 GIC       13373 :     pgstat_initialize();
                                655                 : 
                                656                 :     /* Do local initialization of storage and buffer managers */
 1466 tmunro                    657           13373 :     InitSync();
 8147 tgl                       658           13373 :     smgrinit();
 8147 tgl                       659 CBC       13373 :     InitBufferPoolAccess();
                                660                 : 
  610 andres                    661 ECB             :     /*
  604                           662                 :      * Initialize temporary file access after pgstat, so that the temporary
  610 andres                    663 EUB             :      * file shutdown hook can report temporary file statistics.
  610 andres                    664 ECB             :      */
  610 andres                    665 GIC       13373 :     InitTemporaryFileAccess();
                                666                 : 
                                667                 :     /*
                                668                 :      * Initialize local buffers for WAL record construction, in case we ever
                                669                 :      * try to insert XLOG.
                                670                 :      */
  509 rhaas                     671 CBC       13373 :     InitXLogInsert();
                                672                 : 
  419 andres                    673 ECB             :     /*
                                674                 :      * Initialize replication slots after pgstat. The exit hook might need to
  419 andres                    675 EUB             :      * drop ephemeral slots, which in turn triggers stats reporting.
  419 andres                    676 ECB             :      */
  419 andres                    677 GIC       13373 :     ReplicationSlotInitialize();
 8147 tgl                       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
  258 tgl                       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
 4988                           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                 :  *
  258                           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.
 6720                           713                 :  *
  258                           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                 :  * --------------------------------
 9770 scrappy                   720                 :  */
                                721                 : void
  258 tgl                       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,
  258 tgl                       726 ECB             :              char *out_dbname)
                                727                 : {
 8487 peter_e                   728 GIC       11577 :     bool        bootstrap = IsBootstrapProcessingMode();
                                729                 :     bool        am_superuser;
                                730                 :     char       *fullpath;
                                731                 :     char        dbname[NAMEDATALEN];
   79 rhaas                     732 GNC       11577 :     int         nfree = 0;
 9345 bruce                     733 ECB             : 
 4971 tgl                       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                 :      */
 6304 tgl                       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                 :      */
 7967                           749           11577 :     MyBackendId = InvalidBackendId;
                                750                 : 
 4859 simon                     751           11577 :     SharedInvalBackendInit(false);
                                752                 : 
  362 rhaas                     753           11577 :     if (MyBackendId > MaxBackends || MyBackendId <= 0)
 4312 peter_e                   754 UIC           0 :         elog(FATAL, "bad backend ID: %d", MyBackendId);
                                755                 : 
                                756                 :     /* Now that we have a BackendId, we can participate in ProcSignal */
 5000 tgl                       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                 :      */
 3919 alvherre                  763           11577 :     if (!bootstrap)
                                764                 :     {
 2987 andres                    765           11272 :         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
 3919 alvherre                  766           11272 :         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
 3676 tgl                       767           11272 :         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
 2580 rhaas                     768           11272 :         RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
                                769                 :                         IdleInTransactionSessionTimeoutHandler);
  823 tgl                       770           11272 :         RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
  736 tmunro                    771           11272 :         RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
  368 andres                    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
  332 tgl                       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                 :      */
  482 rhaas                     782 GIC       11577 :     if (!IsUnderPostmaster)
                                783                 :     {
 4737 tgl                       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                 :          */
 1726 tgl                       789 GIC         619 :         CreateAuxProcessResourceOwner();
 1726 tgl                       790 ECB             : 
 4737 tgl                       791 GIC         619 :         StartupXLOG();
                                792                 :         /* Release (and warn about) any buffer pins leaked in StartupXLOG */
 1726                           793             619 :         ReleaseAuxProcessResources(true);
                                794                 :         /* Reset CurrentResourceOwner to nothing for the moment */
                                795             619 :         CurrentResourceOwner = NULL;
                                796                 : 
  744 andres                    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                 :          */
  368 andres                    801 GIC         619 :         before_shmem_exit(pgstat_before_server_shutdown, 0);
  744                           802             619 :         before_shmem_exit(ShutdownXLOG, 0);
                                803                 :     }
                                804                 : 
 9345 bruce                     805 ECB             :     /*
                                806                 :      * Initialize the relation cache and the system catalog caches.  Note that
 6184 tgl                       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
 6031 bruce                     809                 :      * would try to touch these hashtables.
 9345 bruce                     810 EUB             :      */
 7897 tgl                       811 GIC       11577 :     RelationCacheInitialize();
 9345 bruce                     812           11577 :     InitCatalogCache();
 5871 tgl                       813 CBC       11577 :     InitPlanCache();
                                814                 : 
                                815                 :     /* Initialize portal manager */
 7967 tgl                       816 GIC       11577 :     EnablePortalManager();
                                817                 : 
                                818                 :     /* Initialize status reporting */
  506 andres                    819 CBC       11577 :     pgstat_beinit();
                                820                 : 
 4969 tgl                       821 ECB             :     /*
 4790 bruce                     822                 :      * Load relcache entries for the shared system catalogs.  This must create
 4737 tgl                       823                 :      * at least entries for pg_database and catalogs used for authentication.
 4969                           824                 :      */
 4969 tgl                       825 GIC       11577 :     RelationCacheInitializePhase2();
 4969 tgl                       826 ECB             : 
 6450                           827                 :     /*
 3399 rhaas                     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                 :      */
 3399 rhaas                     836 GIC       11577 :     before_shmem_exit(ShutdownPostgres, 0);
                                837                 : 
 4969 tgl                       838 ECB             :     /* The autovacuum launcher is done here */
 4969 tgl                       839 GIC       11577 :     if (IsAutoVacuumLauncherProcess())
                                840                 :     {
                                841                 :         /* report this backend in the PgBackendStatus array */
 2205 rhaas                     842             306 :         pgstat_bestart();
                                843                 : 
 4968 tgl                       844             979 :         return;
 2205 rhaas                     845 ECB             :     }
                                846                 : 
 6184 tgl                       847                 :     /*
                                848                 :      * Start a new transaction here before first access to db, and get a
 5323 alvherre                  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
 4790 bruce                     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
  970 andres                    857                 :      * e.g. be cleared when cache invalidations are processed).
 6184 tgl                       858                 :      */
 8509 inoue                     859 GIC       11271 :     if (!bootstrap)
                                860                 :     {
                                861                 :         /* statement_timestamp must be set for timeouts to work correctly */
 4257 tgl                       862           10966 :         SetCurrentStatementStartTimestamp();
 7270                           863           10966 :         StartTransactionCommand();
                                864                 : 
                                865                 :         /*
                                866                 :          * transaction_isolation will have been set to the default by the
 3880 tgl                       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                 :          */
 3880 tgl                       871 GIC       10966 :         XactIsoLevel = XACT_READ_COMMITTED;
 3880 tgl                       872 ECB             : 
 5323 alvherre                  873 GIC       10966 :         (void) GetTransactionSnapshot();
                                874                 :     }
 8487 peter_e                   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
 4737 tgl                       881                 :      * ID, otherwise we figure it out from the authenticated user name.
                                882                 :      */
 4737 tgl                       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;
 4737 tgl                       892 CBC         314 :         if (!ThereIsAtLeastOneRole())
 4737 tgl                       893 UIC           0 :             ereport(WARNING,
                                894                 :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
 4737 tgl                       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                 :     }
 3776 alvherre                  899 GIC       10636 :     else if (IsBackgroundWorker)
 3776 alvherre                  900 ECB             :     {
 2988 rhaas                     901 GIC        1941 :         if (username == NULL && !OidIsValid(useroid))
                                902                 :         {
 3776 alvherre                  903             326 :             InitializeSessionUserIdStandalone();
                                904             326 :             am_superuser = true;
                                905                 :         }
                                906                 :         else
                                907                 :         {
 2988 rhaas                     908            1615 :             InitializeSessionUserId(username, useroid);
 3776 alvherre                  909            1615 :             am_superuser = superuser();
                                910                 :         }
                                911                 :     }
                                912                 :     else
                                913                 :     {
                                914                 :         /* normal multiuser case */
 4737 tgl                       915 CBC        8695 :         Assert(MyProcPort != NULL);
 4737 tgl                       916 GIC        8695 :         PerformAuthentication(MyProcPort);
 2988 rhaas                     917            8628 :         InitializeSessionUserId(username, useroid);
                                918                 :         /* ensure that auth_method is actually valid, aka authn_id is not NULL */
  192 michael                   919 GNC        8624 :         if (MyClientConnectionInfo.authn_id)
                                920             115 :             InitializeSystemUser(MyClientConnectionInfo.authn_id,
                                921                 :                                  hba_authname(MyClientConnectionInfo.auth_method));
 4737 tgl                       922 CBC        8624 :         am_superuser = superuser();
 4737 tgl                       923 ECB             :     }
                                924                 : 
                                925                 :     /*
                                926                 :      * Binary upgrades only allowed super-user connections
                                927                 :      */
 4367 bruce                     928 GIC       11200 :     if (IsBinaryUpgrade && !am_superuser)
                                929                 :     {
 4322 bruce                     930 UIC           0 :         ereport(FATAL,
 4322 bruce                     931 ECB             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
                                932                 :                  errmsg("must be superuser to connect in binary upgrade mode")));
 4367                           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                 :      */
 1517 michael                   946 GIC       11200 :     if (!am_superuser && !am_walsender &&
   79 rhaas                     947 GNC         205 :         (SuperuserReservedConnections + ReservedConnections) > 0 &&
                                948             205 :         !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
                                949                 :     {
   79 rhaas                     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                 :     }
 4731 rhaas                     962 ECB             : 
                                963                 :     /* Check replication permissions needed for walsender processes. */
 4737 tgl                       964 CBC       11200 :     if (am_walsender)
                                965                 :     {
                                966             835 :         Assert(!bootstrap);
 4591 heikki.linnakangas        967 ECB             : 
   24 peter                     968 GNC         835 :         if (!has_rolreplication(GetUserId()))
 4736 tgl                       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                 :     /*
 3317 rhaas                     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                 :      */
 3317 rhaas                     982 CBC       11200 :     if (am_walsender && !am_db_walsender)
                                983                 :     {
                                984                 :         /* process any options passed in the startup packet */
 4591 heikki.linnakangas        985 GIC         351 :         if (MyProcPort != NULL)
 4591 heikki.linnakangas        986 CBC         351 :             process_startup_options(MyProcPort, am_superuser);
 4591 heikki.linnakangas        987 ECB             : 
                                988                 :         /* Apply PostAuthDelay as soon as we've read all options */
 4591 heikki.linnakangas        989 GIC         351 :         if (PostAuthDelay > 0)
 4591 heikki.linnakangas        990 UIC           0 :             pg_usleep(PostAuthDelay * 1000000L);
                                991                 : 
                                992                 :         /* initialize client encoding */
 4591 heikki.linnakangas        993 CBC         351 :         InitializeClientEncoding();
 4591 heikki.linnakangas        994 ECB             : 
 4737 tgl                       995                 :         /* report this backend in the PgBackendStatus array */
 4737 tgl                       996 GIC         351 :         pgstat_bestart();
 4591 heikki.linnakangas        997 ECB             : 
 4737 tgl                       998                 :         /* close the transaction we started above */
 4737 tgl                       999 GIC         351 :         CommitTransactionCommand();
 4591 heikki.linnakangas       1000 ECB             : 
 4737 tgl                      1001 GIC         351 :         return;
                               1002                 :     }
                               1003                 : 
                               1004                 :     /*
                               1005                 :      * Set up the global variables holding database id and default tablespace.
 4988 tgl                      1006 ECB             :      * But note we won't actually try to touch the database just yet.
                               1007                 :      *
 4737 tgl                      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                 :      */
 4737 tgl                      1011 GIC       10849 :     if (bootstrap)
                               1012                 :     {
  353                          1013             305 :         MyDatabaseId = Template1DbOid;
 4988                          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,
 4988 tgl                      1024 ECB             :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
                               1025                 :                      errmsg("database \"%s\" does not exist", in_dbname)));
 4988 tgl                      1026 CBC        8583 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
 1601 andres                   1027 GIC        8583 :         MyDatabaseId = dbform->oid;
 4988 tgl                      1028 GBC        8583 :         MyDatabaseTableSpace = dbform->dattablespace;
 4988 tgl                      1029 EUB             :         /* take database name from the caller, just for paranoia */
 4988 tgl                      1030 GIC        8583 :         strlcpy(dbname, in_dbname, sizeof(dbname));
                               1031                 :     }
 2845 rhaas                    1032            1954 :     else if (OidIsValid(dboid))
                               1033                 :     {
 4988 tgl                      1034 EUB             :         /* caller specified database by OID */
 4790 bruce                    1035                 :         HeapTuple   tuple;
                               1036                 :         Form_pg_database dbform;
                               1037                 : 
 4988 tgl                      1038 GIC        1632 :         tuple = GetDatabaseTupleByOid(dboid);
                               1039            1632 :         if (!HeapTupleIsValid(tuple))
 4988 tgl                      1040 UIC           0 :             ereport(FATAL,
                               1041                 :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
 4988 tgl                      1042 ECB             :                      errmsg("database %u does not exist", dboid)));
 4988 tgl                      1043 GIC        1632 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
 1601 andres                   1044 CBC        1632 :         MyDatabaseId = dbform->oid;
 4988 tgl                      1045 GIC        1632 :         MyDatabaseTableSpace = dbform->dattablespace;
 4988 tgl                      1046 CBC        1632 :         Assert(MyDatabaseId == dboid);
 4988 tgl                      1047 GBC        1632 :         strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
                               1048                 :         /* pass the database name back to the caller */
 4988 tgl                      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                 :          */
 2845 rhaas                    1060 CBC         322 :         if (!bootstrap)
                               1061                 :         {
 2205 rhaas                    1062 GIC         322 :             pgstat_bestart();
 2845 rhaas                    1063 CBC         322 :             CommitTransactionCommand();
 2205 rhaas                    1064 ECB             :         }
 2845 rhaas                    1065 GIC         322 :         return;
                               1066                 :     }
 4988 tgl                      1067 ECB             : 
 4988 tgl                      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
 4790 bruce                    1071 ECB             :      * will block us until it finishes (and has committed its update of
                               1072                 :      * pg_database).
                               1073                 :      *
 6031                          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
 2865 tgl                      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                 :      */
 4737 tgl                      1089 CBC       10520 :     if (!bootstrap)
 6184 tgl                      1090 GIC       10215 :         LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
 6184 tgl                      1091 ECB             :                          RowExclusiveLock);
                               1092                 : 
                               1093                 :     /*
 2865                          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                 :      */
 2865 tgl                      1105 CBC       10520 :     MyProc->databaseId = MyDatabaseId;
 2865 tgl                      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                 :      */
 2865 tgl                      1113 GIC       10520 :     InvalidateCatalogSnapshot();
                               1114                 : 
                               1115                 :     /*
 4988 tgl                      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
 4988 tgl                      1118 EUB             :      * cleanly without creating a mess.
                               1119                 :      */
 4737 tgl                      1120 GIC       10520 :     if (!bootstrap)
 6184 tgl                      1121 ECB             :     {
 4790 bruce                    1122                 :         HeapTuple   tuple;
 6184 tgl                      1123                 : 
 4988 tgl                      1124 CBC       10215 :         tuple = GetDatabaseTuple(dbname);
                               1125           10215 :         if (!HeapTupleIsValid(tuple) ||
 1601 andres                   1126 GIC       10215 :             MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
 4988 tgl                      1127 CBC       10215 :             MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
 6184 tgl                      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                 :      */
 4988 tgl                      1138 CBC       10520 :     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
                               1139                 : 
 4737                          1140           10520 :     if (!bootstrap)
 6184 tgl                      1141 ECB             :     {
 6184 tgl                      1142 GIC       10215 :         if (access(fullpath, F_OK) == -1)
 6184 tgl                      1143 ECB             :         {
 6184 tgl                      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                 : 
 6184 tgl                      1158 GIC       10215 :         ValidatePgVersion(fullpath);
                               1159                 :     }
                               1160                 : 
 4988                          1161           10520 :     SetDatabasePath(fullpath);
  349 alvherre                 1162           10520 :     pfree(fullpath);
                               1163                 : 
                               1164                 :     /*
                               1165                 :      * It's now possible to do real access to the system catalogs.
                               1166                 :      *
 6184 tgl                      1167 ECB             :      * Load relcache entries for the system catalogs.  This must create at
                               1168                 :      * least the minimum set of "nailed-in" cache entries.
                               1169                 :      */
 4988 tgl                      1170 GIC       10520 :     RelationCacheInitializePhase3();
                               1171                 : 
                               1172                 :     /* set up ACL framework (so CheckMyDatabase can check permissions) */
 6188                          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                 :      */
 4737                          1181           10518 :     if (!bootstrap)
 1830 magnus                   1182           10213 :         CheckMyDatabase(dbname, am_superuser, override_allow_connections);
 8586 vadim4o                  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                 :      */
 4591 heikki.linnakangas       1189 GIC       10516 :     if (MyProcPort != NULL)
                               1190            8268 :         process_startup_options(MyProcPort, am_superuser);
 4591 heikki.linnakangas       1191 ECB             : 
                               1192                 :     /* Process pg_db_role_setting options */
 4591 heikki.linnakangas       1193 GIC       10516 :     process_settings(MyDatabaseId, GetSessionUserId());
                               1194                 : 
                               1195                 :     /* Apply PostAuthDelay as soon as we've read all options */
                               1196           10515 :     if (PostAuthDelay > 0)
 4591 heikki.linnakangas       1197 UIC           0 :         pg_usleep(PostAuthDelay * 1000000L);
 4591 heikki.linnakangas       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 */
 4591 heikki.linnakangas       1205 CBC       10515 :     InitializeSearchPath();
 4591 heikki.linnakangas       1206 EUB             : 
                               1207                 :     /* initialize client encoding */
 4591 heikki.linnakangas       1208 GIC       10515 :     InitializeClientEncoding();
                               1209                 : 
                               1210                 :     /* Initialize this backend's session state. */
 2033 andres                   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
  258 tgl                      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                 :      */
  258 tgl                      1220 CBC       10515 :     if (load_session_libraries)
  258 tgl                      1221 GIC        8096 :         process_session_preload_libraries();
  258 tgl                      1222 EUB             : 
 4591 heikki.linnakangas       1223                 :     /* report this backend in the PgBackendStatus array */
 4591 heikki.linnakangas       1224 GIC       10515 :     if (!bootstrap)
                               1225           10210 :         pgstat_bestart();
                               1226                 : 
                               1227                 :     /* close the transaction we started above */
                               1228           10515 :     if (!bootstrap)
                               1229           10210 :         CommitTransactionCommand();
 4591 heikki.linnakangas       1230 EUB             : }
                               1231                 : 
                               1232                 : /*
                               1233                 :  * Process any command-line switches and any additional GUC variable
                               1234                 :  * settings passed in the startup packet.
                               1235                 :  */
 4591 heikki.linnakangas       1236 ECB             : static void
 4591 heikki.linnakangas       1237 GIC        8619 : process_startup_options(Port *port, bool am_superuser)
                               1238                 : {
 4591 heikki.linnakangas       1239 ECB             :     GucContext  gucctx;
                               1240                 :     ListCell   *gucopts;
                               1241                 : 
 3130 tgl                      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                 :      */
 4591 heikki.linnakangas       1248 CBC        8619 :     if (port->cmdline_options != NULL)
                               1249                 :     {
                               1250                 :         /*
 4968 tgl                      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                 : 
 4591 heikki.linnakangas       1259 CBC        2496 :         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
 4968 tgl                      1260 ECB             : 
 4968 tgl                      1261 GIC        2496 :         av = (char **) palloc(maxac * sizeof(char *));
                               1262            2496 :         ac = 0;
                               1263                 : 
                               1264            2496 :         av[ac++] = "postgres";
                               1265                 : 
 4591 heikki.linnakangas       1266            2496 :         pg_split_opts(av, &ac, port->cmdline_options);
 4968 tgl                      1267 ECB             : 
 4968 tgl                      1268 CBC        2496 :         av[ac] = NULL;
                               1269                 : 
 4968 tgl                      1270 GIC        2496 :         Assert(ac < maxac);
 4968 tgl                      1271 ECB             : 
 3660 tgl                      1272 GIC        2496 :         (void) process_postgres_switches(ac, av, gucctx, NULL);
                               1273                 :     }
 4968 tgl                      1274 ECB             : 
 4968 tgl                      1275 EUB             :     /*
                               1276                 :      * Process any additional GUC variable settings passed in startup packet.
                               1277                 :      * These are handled exactly like command-line variables.
                               1278                 :      */
 4591 heikki.linnakangas       1279 GIC        8619 :     gucopts = list_head(port->guc_options);
                               1280           21573 :     while (gucopts)
                               1281                 :     {
                               1282                 :         char       *name;
 4591 heikki.linnakangas       1283 ECB             :         char       *value;
                               1284                 : 
 4591 heikki.linnakangas       1285 GIC       12954 :         name = lfirst(gucopts);
 1364 tgl                      1286 CBC       12954 :         gucopts = lnext(port->guc_options, gucopts);
                               1287                 : 
 4591 heikki.linnakangas       1288 GIC       12954 :         value = lfirst(gucopts);
 1364 tgl                      1289 CBC       12954 :         gucopts = lnext(port->guc_options, gucopts);
                               1290                 : 
 4591 heikki.linnakangas       1291 GIC       12954 :         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
                               1292                 :     }
 8147 tgl                      1293            8619 : }
                               1294                 : 
                               1295                 : /*
                               1296                 :  * Load GUC settings from pg_db_role_setting.
                               1297                 :  *
 4932 alvherre                 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
 4932 alvherre                 1302 CBC       10516 : process_settings(Oid databaseid, Oid roleid)
 4932 alvherre                 1303 ECB             : {
                               1304                 :     Relation    relsetting;
                               1305                 :     Snapshot    snapshot;
                               1306                 : 
 4932 alvherre                 1307 CBC       10516 :     if (!IsUnderPostmaster)
 4932 alvherre                 1308 GIC         617 :         return;
                               1309                 : 
 1539 andres                   1310            9899 :     relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
                               1311                 : 
                               1312                 :     /* read all the settings under the same snapshot for efficiency */
 3568 rhaas                    1313            9899 :     snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
                               1314                 : 
 4811 bruce                    1315 ECB             :     /* Later settings are ignored if set earlier. */
 3568 rhaas                    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);
 4932 alvherre                 1320 ECB             : 
 3568 rhaas                    1321 GIC        9898 :     UnregisterSnapshot(snapshot);
 1539 andres                   1322            9898 :     table_close(relsetting, AccessShareLock);
                               1323                 : }
                               1324                 : 
                               1325                 : /*
 8147 tgl                      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
 7058 peter_e                  1336 GIC       11577 : ShutdownPostgres(int code, Datum arg)
 8147 tgl                      1337 ECB             : {
                               1338                 :     /* Make sure we've killed any active transaction */
 6453 tgl                      1339 CBC       11577 :     AbortOutOfAnyTransaction();
 8053 bruce                    1340 ECB             : 
                               1341                 :     /*
 6385                          1342                 :      * User locks are not released by transaction end, so be sure to release
                               1343                 :      * them explicitly.
 8147 tgl                      1344                 :      */
 6453 tgl                      1345 GIC       11577 :     LockReleaseAll(USER_LOCKMETHOD, true);
 8586 vadim4o                  1346 CBC       11577 : }
                               1347                 : 
 7883 peter_e                  1348 ECB             : 
                               1349                 : /*
 3919 alvherre                 1350                 :  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
                               1351                 :  */
                               1352                 : static void
 3919 alvherre                 1353 GIC           5 : StatementTimeoutHandler(void)
                               1354                 : {
 2878 bruce                    1355               5 :     int         sig = SIGINT;
                               1356                 : 
 2987 andres                   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                 :      */
 2987 andres                   1361 GIC           5 :     if (ClientAuthInProgress)
 2987 andres                   1362 UIC           0 :         sig = SIGTERM;
 2987 andres                   1363 ECB             : 
 3919 alvherre                 1364                 : #ifdef HAVE_SETSID
                               1365                 :     /* try to signal whole process group */
 2987 andres                   1366 CBC           5 :     kill(-MyProcPid, sig);
 3919 alvherre                 1367 ECB             : #endif
 2987 andres                   1368 GIC           5 :     kill(MyProcPid, sig);
 3919 alvherre                 1369 CBC           5 : }
                               1370                 : 
 3676 tgl                      1371 ECB             : /*
                               1372                 :  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
                               1373                 :  */
                               1374                 : static void
 3676 tgl                      1375 GIC           4 : LockTimeoutHandler(void)
                               1376                 : {
                               1377                 : #ifdef HAVE_SETSID
                               1378                 :     /* try to signal whole process group */
                               1379               4 :     kill(-MyProcPid, SIGINT);
 3676 tgl                      1380 ECB             : #endif
 3676 tgl                      1381 GIC           4 :     kill(MyProcPid, SIGINT);
                               1382               4 : }
                               1383                 : 
                               1384                 : static void
 2580 rhaas                    1385 LBC           0 : IdleInTransactionSessionTimeoutHandler(void)
 2580 rhaas                    1386 ECB             : {
 2580 rhaas                    1387 UIC           0 :     IdleInTransactionSessionTimeoutPending = true;
 2580 rhaas                    1388 LBC           0 :     InterruptPending = true;
 2580 rhaas                    1389 UIC           0 :     SetLatch(MyLatch);
                               1390               0 : }
 3919 alvherre                 1391 ECB             : 
                               1392                 : static void
  823 tgl                      1393 UIC           0 : IdleSessionTimeoutHandler(void)
  823 tgl                      1394 ECB             : {
  823 tgl                      1395 LBC           0 :     IdleSessionTimeoutPending = true;
                               1396               0 :     InterruptPending = true;
                               1397               0 :     SetLatch(MyLatch);
  823 tgl                      1398 UIC           0 : }
  823 tgl                      1399 ECB             : 
  368 andres                   1400                 : static void
  368 andres                   1401 GIC          15 : IdleStatsUpdateTimeoutHandler(void)
                               1402                 : {
                               1403              15 :     IdleStatsUpdateTimeoutPending = true;
                               1404              15 :     InterruptPending = true;
                               1405              15 :     SetLatch(MyLatch);
                               1406              15 : }
                               1407                 : 
                               1408                 : static void
  736 tmunro                   1409 UIC           0 : ClientCheckTimeoutHandler(void)
                               1410                 : {
                               1411               0 :     CheckClientConnectionPending = true;
                               1412               0 :     InterruptPending = true;
                               1413               0 :     SetLatch(MyLatch);
  736 tmunro                   1414 LBC           0 : }
                               1415                 : 
                               1416                 : /*
 6494 tgl                      1417 ECB             :  * Returns true if at least one role is defined in this database cluster.
                               1418                 :  */
                               1419                 : static bool
 6494 tgl                      1420 GIC         314 : ThereIsAtLeastOneRole(void)
                               1421                 : {
                               1422                 :     Relation    pg_authid_rel;
 1490 andres                   1423 ECB             :     TableScanDesc scan;
 7883 peter_e                  1424                 :     bool        result;
                               1425                 : 
 1539 andres                   1426 GIC         314 :     pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
                               1427                 : 
 1490                          1428             314 :     scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
 7629 tgl                      1429             314 :     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
                               1430                 : 
 1490 andres                   1431 CBC         314 :     table_endscan(scan);
 1539 andres                   1432 GIC         314 :     table_close(pg_authid_rel, AccessShareLock);
 7883 peter_e                  1433 ECB             : 
 7883 peter_e                  1434 GIC         314 :     return result;
                               1435                 : }
        

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