Header And Logo

PostgreSQL
| The world's most advanced open source database.

postinit.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * postinit.c
00004  *    postgres initialization utilities
00005  *
00006  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00007  * Portions Copyright (c) 1994, Regents of the University of California
00008  *
00009  *
00010  * IDENTIFICATION
00011  *    src/backend/utils/init/postinit.c
00012  *
00013  *
00014  *-------------------------------------------------------------------------
00015  */
00016 #include "postgres.h"
00017 
00018 #include <ctype.h>
00019 #include <fcntl.h>
00020 #include <unistd.h>
00021 
00022 #include "access/heapam.h"
00023 #include "access/htup_details.h"
00024 #include "access/sysattr.h"
00025 #include "access/xact.h"
00026 #include "catalog/catalog.h"
00027 #include "catalog/indexing.h"
00028 #include "catalog/namespace.h"
00029 #include "catalog/pg_authid.h"
00030 #include "catalog/pg_database.h"
00031 #include "catalog/pg_db_role_setting.h"
00032 #include "catalog/pg_tablespace.h"
00033 #include "libpq/auth.h"
00034 #include "libpq/libpq-be.h"
00035 #include "mb/pg_wchar.h"
00036 #include "miscadmin.h"
00037 #include "pgstat.h"
00038 #include "postmaster/autovacuum.h"
00039 #include "postmaster/postmaster.h"
00040 #include "replication/walsender.h"
00041 #include "storage/bufmgr.h"
00042 #include "storage/fd.h"
00043 #include "storage/ipc.h"
00044 #include "storage/lmgr.h"
00045 #include "storage/procarray.h"
00046 #include "storage/procsignal.h"
00047 #include "storage/proc.h"
00048 #include "storage/sinvaladt.h"
00049 #include "storage/smgr.h"
00050 #include "tcop/tcopprot.h"
00051 #include "utils/acl.h"
00052 #include "utils/fmgroids.h"
00053 #include "utils/guc.h"
00054 #include "utils/pg_locale.h"
00055 #include "utils/portal.h"
00056 #include "utils/ps_status.h"
00057 #include "utils/snapmgr.h"
00058 #include "utils/syscache.h"
00059 #include "utils/timeout.h"
00060 #include "utils/tqual.h"
00061 
00062 
00063 static HeapTuple GetDatabaseTuple(const char *dbname);
00064 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
00065 static void PerformAuthentication(Port *port);
00066 static void CheckMyDatabase(const char *name, bool am_superuser);
00067 static void InitCommunication(void);
00068 static void ShutdownPostgres(int code, Datum arg);
00069 static void StatementTimeoutHandler(void);
00070 static void LockTimeoutHandler(void);
00071 static bool ThereIsAtLeastOneRole(void);
00072 static void process_startup_options(Port *port, bool am_superuser);
00073 static void process_settings(Oid databaseid, Oid roleid);
00074 
00075 
00076 /*** InitPostgres support ***/
00077 
00078 
00079 /*
00080  * GetDatabaseTuple -- fetch the pg_database row for a database
00081  *
00082  * This is used during backend startup when we don't yet have any access to
00083  * system catalogs in general.  In the worst case, we can seqscan pg_database
00084  * using nothing but the hard-wired descriptor that relcache.c creates for
00085  * pg_database.  In more typical cases, relcache.c was able to load
00086  * descriptors for both pg_database and its indexes from the shared relcache
00087  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
00088  * tells whether we got the cached descriptors.
00089  */
00090 static HeapTuple
00091 GetDatabaseTuple(const char *dbname)
00092 {
00093     HeapTuple   tuple;
00094     Relation    relation;
00095     SysScanDesc scan;
00096     ScanKeyData key[1];
00097 
00098     /*
00099      * form a scan key
00100      */
00101     ScanKeyInit(&key[0],
00102                 Anum_pg_database_datname,
00103                 BTEqualStrategyNumber, F_NAMEEQ,
00104                 CStringGetDatum(dbname));
00105 
00106     /*
00107      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
00108      * built the critical shared relcache entries (i.e., we're starting up
00109      * without a shared relcache cache file).
00110      */
00111     relation = heap_open(DatabaseRelationId, AccessShareLock);
00112     scan = systable_beginscan(relation, DatabaseNameIndexId,
00113                               criticalSharedRelcachesBuilt,
00114                               SnapshotNow,
00115                               1, key);
00116 
00117     tuple = systable_getnext(scan);
00118 
00119     /* Must copy tuple before releasing buffer */
00120     if (HeapTupleIsValid(tuple))
00121         tuple = heap_copytuple(tuple);
00122 
00123     /* all done */
00124     systable_endscan(scan);
00125     heap_close(relation, AccessShareLock);
00126 
00127     return tuple;
00128 }
00129 
00130 /*
00131  * GetDatabaseTupleByOid -- as above, but search by database OID
00132  */
00133 static HeapTuple
00134 GetDatabaseTupleByOid(Oid dboid)
00135 {
00136     HeapTuple   tuple;
00137     Relation    relation;
00138     SysScanDesc scan;
00139     ScanKeyData key[1];
00140 
00141     /*
00142      * form a scan key
00143      */
00144     ScanKeyInit(&key[0],
00145                 ObjectIdAttributeNumber,
00146                 BTEqualStrategyNumber, F_OIDEQ,
00147                 ObjectIdGetDatum(dboid));
00148 
00149     /*
00150      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
00151      * built the critical shared relcache entries (i.e., we're starting up
00152      * without a shared relcache cache file).
00153      */
00154     relation = heap_open(DatabaseRelationId, AccessShareLock);
00155     scan = systable_beginscan(relation, DatabaseOidIndexId,
00156                               criticalSharedRelcachesBuilt,
00157                               SnapshotNow,
00158                               1, key);
00159 
00160     tuple = systable_getnext(scan);
00161 
00162     /* Must copy tuple before releasing buffer */
00163     if (HeapTupleIsValid(tuple))
00164         tuple = heap_copytuple(tuple);
00165 
00166     /* all done */
00167     systable_endscan(scan);
00168     heap_close(relation, AccessShareLock);
00169 
00170     return tuple;
00171 }
00172 
00173 
00174 /*
00175  * PerformAuthentication -- authenticate a remote client
00176  *
00177  * returns: nothing.  Will not return at all if there's any failure.
00178  */
00179 static void
00180 PerformAuthentication(Port *port)
00181 {
00182     /* This should be set already, but let's make sure */
00183     ClientAuthInProgress = true;    /* limit visibility of log messages */
00184 
00185     /*
00186      * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
00187      * etcetera from the postmaster, and have to load them ourselves.
00188      *
00189      * FIXME: [fork/exec] Ugh.  Is there a way around this overhead?
00190      */
00191 #ifdef EXEC_BACKEND
00192     if (!load_hba())
00193     {
00194         /*
00195          * It makes no sense to continue if we fail to load the HBA file,
00196          * since there is no way to connect to the database in this case.
00197          */
00198         ereport(FATAL,
00199                 (errmsg("could not load pg_hba.conf")));
00200     }
00201 
00202     if (!load_ident())
00203     {
00204         /*
00205          * It is ok to continue if we fail to load the IDENT file, although it
00206          * means that you cannot log in using any of the authentication methods
00207          * that need a user name mapping. load_ident() already logged the
00208          * details of error to the log.
00209          */
00210     }
00211 #endif
00212 
00213     /*
00214      * Set up a timeout in case a buggy or malicious client fails to respond
00215      * during authentication.  Since we're inside a transaction and might do
00216      * database access, we have to use the statement_timeout infrastructure.
00217      */
00218     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
00219 
00220     /*
00221      * Now perform authentication exchange.
00222      */
00223     ClientAuthentication(port); /* might not return, if failure */
00224 
00225     /*
00226      * Done with authentication.  Disable the timeout, and log if needed.
00227      */
00228     disable_timeout(STATEMENT_TIMEOUT, false);
00229 
00230     if (Log_connections)
00231     {
00232         if (am_walsender)
00233             ereport(LOG,
00234                     (errmsg("replication connection authorized: user=%s",
00235                             port->user_name)));
00236         else
00237             ereport(LOG,
00238                     (errmsg("connection authorized: user=%s database=%s",
00239                             port->user_name, port->database_name)));
00240     }
00241 
00242     set_ps_display("startup", false);
00243 
00244     ClientAuthInProgress = false;       /* client_min_messages is active now */
00245 }
00246 
00247 
00248 /*
00249  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
00250  */
00251 static void
00252 CheckMyDatabase(const char *name, bool am_superuser)
00253 {
00254     HeapTuple   tup;
00255     Form_pg_database dbform;
00256     char       *collate;
00257     char       *ctype;
00258 
00259     /* Fetch our pg_database row normally, via syscache */
00260     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
00261     if (!HeapTupleIsValid(tup))
00262         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
00263     dbform = (Form_pg_database) GETSTRUCT(tup);
00264 
00265     /* This recheck is strictly paranoia */
00266     if (strcmp(name, NameStr(dbform->datname)) != 0)
00267         ereport(FATAL,
00268                 (errcode(ERRCODE_UNDEFINED_DATABASE),
00269                  errmsg("database \"%s\" has disappeared from pg_database",
00270                         name),
00271                  errdetail("Database OID %u now seems to belong to \"%s\".",
00272                            MyDatabaseId, NameStr(dbform->datname))));
00273 
00274     /*
00275      * Check permissions to connect to the database.
00276      *
00277      * These checks are not enforced when in standalone mode, so that there is
00278      * a way to recover from disabling all access to all databases, for
00279      * example "UPDATE pg_database SET datallowconn = false;".
00280      *
00281      * We do not enforce them for autovacuum worker processes either.
00282      */
00283     if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
00284     {
00285         /*
00286          * Check that the database is currently allowing connections.
00287          */
00288         if (!dbform->datallowconn)
00289             ereport(FATAL,
00290                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
00291              errmsg("database \"%s\" is not currently accepting connections",
00292                     name)));
00293 
00294         /*
00295          * Check privilege to connect to the database.  (The am_superuser test
00296          * is redundant, but since we have the flag, might as well check it
00297          * and save a few cycles.)
00298          */
00299         if (!am_superuser &&
00300             pg_database_aclcheck(MyDatabaseId, GetUserId(),
00301                                  ACL_CONNECT) != ACLCHECK_OK)
00302             ereport(FATAL,
00303                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
00304                      errmsg("permission denied for database \"%s\"", name),
00305                      errdetail("User does not have CONNECT privilege.")));
00306 
00307         /*
00308          * Check connection limit for this database.
00309          *
00310          * There is a race condition here --- we create our PGPROC before
00311          * checking for other PGPROCs.  If two backends did this at about the
00312          * same time, they might both think they were over the limit, while
00313          * ideally one should succeed and one fail.  Getting that to work
00314          * exactly seems more trouble than it is worth, however; instead we
00315          * just document that the connection limit is approximate.
00316          */
00317         if (dbform->datconnlimit >= 0 &&
00318             !am_superuser &&
00319             CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
00320             ereport(FATAL,
00321                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
00322                      errmsg("too many connections for database \"%s\"",
00323                             name)));
00324     }
00325 
00326     /*
00327      * OK, we're golden.  Next to-do item is to save the encoding info out of
00328      * the pg_database tuple.
00329      */
00330     SetDatabaseEncoding(dbform->encoding);
00331     /* Record it as a GUC internal option, too */
00332     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
00333                     PGC_INTERNAL, PGC_S_OVERRIDE);
00334     /* If we have no other source of client_encoding, use server encoding */
00335     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
00336                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
00337 
00338     /* assign locale variables */
00339     collate = NameStr(dbform->datcollate);
00340     ctype = NameStr(dbform->datctype);
00341 
00342     if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
00343         ereport(FATAL,
00344             (errmsg("database locale is incompatible with operating system"),
00345              errdetail("The database was initialized with LC_COLLATE \"%s\", "
00346                        " which is not recognized by setlocale().", collate),
00347              errhint("Recreate the database with another locale or install the missing locale.")));
00348 
00349     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
00350         ereport(FATAL,
00351             (errmsg("database locale is incompatible with operating system"),
00352              errdetail("The database was initialized with LC_CTYPE \"%s\", "
00353                        " which is not recognized by setlocale().", ctype),
00354              errhint("Recreate the database with another locale or install the missing locale.")));
00355 
00356     /* Make the locale settings visible as GUC variables, too */
00357     SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
00358     SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
00359 
00360     /* Use the right encoding in translated messages */
00361 #ifdef ENABLE_NLS
00362     pg_bind_textdomain_codeset(textdomain(NULL));
00363 #endif
00364 
00365     ReleaseSysCache(tup);
00366 }
00367 
00368 
00369 
00370 /* --------------------------------
00371  *      InitCommunication
00372  *
00373  *      This routine initializes stuff needed for ipc, locking, etc.
00374  *      it should be called something more informative.
00375  * --------------------------------
00376  */
00377 static void
00378 InitCommunication(void)
00379 {
00380     /*
00381      * initialize shared memory and semaphores appropriately.
00382      */
00383     if (!IsUnderPostmaster)     /* postmaster already did this */
00384     {
00385         /*
00386          * We're running a postgres bootstrap process or a standalone backend.
00387          * Create private "shmem" and semaphores.
00388          */
00389         CreateSharedMemoryAndSemaphores(true, 0);
00390     }
00391 }
00392 
00393 
00394 /*
00395  * pg_split_opts -- split a string of options and append it to an argv array
00396  *
00397  * NB: the input string is destructively modified!  Also, caller is responsible
00398  * for ensuring the argv array is large enough.  The maximum possible number
00399  * of arguments added by this routine is (strlen(optstr) + 1) / 2.
00400  *
00401  * Since no current POSTGRES arguments require any quoting characters,
00402  * we can use the simple-minded tactic of assuming each set of space-
00403  * delimited characters is a separate argv element.
00404  *
00405  * If you don't like that, well, we *used* to pass the whole option string
00406  * as ONE argument to execl(), which was even less intelligent...
00407  */
00408 void
00409 pg_split_opts(char **argv, int *argcp, char *optstr)
00410 {
00411     while (*optstr)
00412     {
00413         while (isspace((unsigned char) *optstr))
00414             optstr++;
00415         if (*optstr == '\0')
00416             break;
00417         argv[(*argcp)++] = optstr;
00418         while (*optstr && !isspace((unsigned char) *optstr))
00419             optstr++;
00420         if (*optstr)
00421             *optstr++ = '\0';
00422     }
00423 }
00424 
00425 /*
00426  * Initialize MaxBackends value from config options.
00427  *
00428  * This must be called after modules have had the chance to register background
00429  * workers in shared_preload_libraries, and before shared memory size is
00430  * determined.
00431  *
00432  * Note that in EXEC_BACKEND environment, the value is passed down from
00433  * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
00434  * postmaster itself and processes not under postmaster control should call
00435  * this.
00436  */
00437 void
00438 InitializeMaxBackends(void)
00439 {
00440     Assert(MaxBackends == 0);
00441 
00442     /* the extra unit accounts for the autovacuum launcher */
00443     MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
00444         GetNumShmemAttachedBgworkers();
00445 
00446     /* internal error because the values were all checked previously */
00447     if (MaxBackends > MAX_BACKENDS)
00448         elog(ERROR, "too many backends configured");
00449 }
00450 
00451 /*
00452  * Early initialization of a backend (either standalone or under postmaster).
00453  * This happens even before InitPostgres.
00454  *
00455  * This is separate from InitPostgres because it is also called by auxiliary
00456  * processes, such as the background writer process, which may not call
00457  * InitPostgres at all.
00458  */
00459 void
00460 BaseInit(void)
00461 {
00462     /*
00463      * Attach to shared memory and semaphores, and initialize our
00464      * input/output/debugging file descriptors.
00465      */
00466     InitCommunication();
00467     DebugFileOpen();
00468 
00469     /* Do local initialization of file, storage and buffer managers */
00470     InitFileAccess();
00471     smgrinit();
00472     InitBufferPoolAccess();
00473 }
00474 
00475 
00476 /* --------------------------------
00477  * InitPostgres
00478  *      Initialize POSTGRES.
00479  *
00480  * The database can be specified by name, using the in_dbname parameter, or by
00481  * OID, using the dboid parameter.  In the latter case, the actual database
00482  * name can be returned to the caller in out_dbname.  If out_dbname isn't
00483  * NULL, it must point to a buffer of size NAMEDATALEN.
00484  *
00485  * In bootstrap mode no parameters are used.  The autovacuum launcher process
00486  * doesn't use any parameters either, because it only goes far enough to be
00487  * able to read pg_database; it doesn't connect to any particular database.
00488  * In walsender mode only username is used.
00489  *
00490  * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
00491  * already have a PGPROC struct ... but it's not completely filled in yet.
00492  *
00493  * Note:
00494  *      Be very careful with the order of calls in the InitPostgres function.
00495  * --------------------------------
00496  */
00497 void
00498 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
00499              char *out_dbname)
00500 {
00501     bool        bootstrap = IsBootstrapProcessingMode();
00502     bool        am_superuser;
00503     char       *fullpath;
00504     char        dbname[NAMEDATALEN];
00505 
00506     elog(DEBUG3, "InitPostgres");
00507 
00508     /*
00509      * Add my PGPROC struct to the ProcArray.
00510      *
00511      * Once I have done this, I am visible to other backends!
00512      */
00513     InitProcessPhase2();
00514 
00515     /*
00516      * Initialize my entry in the shared-invalidation manager's array of
00517      * per-backend data.
00518      *
00519      * Sets up MyBackendId, a unique backend identifier.
00520      */
00521     MyBackendId = InvalidBackendId;
00522 
00523     SharedInvalBackendInit(false);
00524 
00525     if (MyBackendId > MaxBackends || MyBackendId <= 0)
00526         elog(FATAL, "bad backend ID: %d", MyBackendId);
00527 
00528     /* Now that we have a BackendId, we can participate in ProcSignal */
00529     ProcSignalInit(MyBackendId);
00530 
00531     /*
00532      * Also set up timeout handlers needed for backend operation.  We need
00533      * these in every case except bootstrap.
00534      */
00535     if (!bootstrap)
00536     {
00537         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLock);
00538         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
00539         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
00540     }
00541 
00542     /*
00543      * bufmgr needs another initialization call too
00544      */
00545     InitBufferPoolBackend();
00546 
00547     /*
00548      * Initialize local process's access to XLOG.
00549      */
00550     if (IsUnderPostmaster)
00551     {
00552         /*
00553          * The postmaster already started the XLOG machinery, but we need to
00554          * call InitXLOGAccess(), if the system isn't in hot-standby mode.
00555          * This is handled by calling RecoveryInProgress and ignoring the
00556          * result.
00557          */
00558         (void) RecoveryInProgress();
00559     }
00560     else
00561     {
00562         /*
00563          * We are either a bootstrap process or a standalone backend. Either
00564          * way, start up the XLOG machinery, and register to have it closed
00565          * down at exit.
00566          */
00567         StartupXLOG();
00568         on_shmem_exit(ShutdownXLOG, 0);
00569     }
00570 
00571     /*
00572      * Initialize the relation cache and the system catalog caches.  Note that
00573      * no catalog access happens here; we only set up the hashtable structure.
00574      * We must do this before starting a transaction because transaction abort
00575      * would try to touch these hashtables.
00576      */
00577     RelationCacheInitialize();
00578     InitCatalogCache();
00579     InitPlanCache();
00580 
00581     /* Initialize portal manager */
00582     EnablePortalManager();
00583 
00584     /* Initialize stats collection --- must happen before first xact */
00585     if (!bootstrap)
00586         pgstat_initialize();
00587 
00588     /*
00589      * Load relcache entries for the shared system catalogs.  This must create
00590      * at least entries for pg_database and catalogs used for authentication.
00591      */
00592     RelationCacheInitializePhase2();
00593 
00594     /*
00595      * Set up process-exit callback to do pre-shutdown cleanup.  This has to
00596      * be after we've initialized all the low-level modules like the buffer
00597      * manager, because during shutdown this has to run before the low-level
00598      * modules start to close down.  On the other hand, we want it in place
00599      * before we begin our first transaction --- if we fail during the
00600      * initialization transaction, as is entirely possible, we need the
00601      * AbortTransaction call to clean up.
00602      */
00603     on_shmem_exit(ShutdownPostgres, 0);
00604 
00605     /* The autovacuum launcher is done here */
00606     if (IsAutoVacuumLauncherProcess())
00607         return;
00608 
00609     /*
00610      * Start a new transaction here before first access to db, and get a
00611      * snapshot.  We don't have a use for the snapshot itself, but we're
00612      * interested in the secondary effect that it sets RecentGlobalXmin. (This
00613      * is critical for anything that reads heap pages, because HOT may decide
00614      * to prune them even if the process doesn't attempt to modify any
00615      * tuples.)
00616      */
00617     if (!bootstrap)
00618     {
00619         /* statement_timestamp must be set for timeouts to work correctly */
00620         SetCurrentStatementStartTimestamp();
00621         StartTransactionCommand();
00622 
00623         /*
00624          * transaction_isolation will have been set to the default by the
00625          * above.  If the default is "serializable", and we are in hot
00626          * standby, we will fail if we don't change it to something lower.
00627          * Fortunately, "read committed" is plenty good enough.
00628          */
00629         XactIsoLevel = XACT_READ_COMMITTED;
00630 
00631         (void) GetTransactionSnapshot();
00632     }
00633 
00634     /*
00635      * Perform client authentication if necessary, then figure out our
00636      * postgres user ID, and see if we are a superuser.
00637      *
00638      * In standalone mode and in autovacuum worker processes, we use a fixed
00639      * ID, otherwise we figure it out from the authenticated user name.
00640      */
00641     if (bootstrap || IsAutoVacuumWorkerProcess())
00642     {
00643         InitializeSessionUserIdStandalone();
00644         am_superuser = true;
00645     }
00646     else if (!IsUnderPostmaster)
00647     {
00648         InitializeSessionUserIdStandalone();
00649         am_superuser = true;
00650         if (!ThereIsAtLeastOneRole())
00651             ereport(WARNING,
00652                     (errcode(ERRCODE_UNDEFINED_OBJECT),
00653                      errmsg("no roles are defined in this database system"),
00654                      errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
00655                              username)));
00656     }
00657     else if (IsBackgroundWorker)
00658     {
00659         if (username == NULL)
00660         {
00661             InitializeSessionUserIdStandalone();
00662             am_superuser = true;
00663         }
00664         else
00665         {
00666             InitializeSessionUserId(username);
00667             am_superuser = superuser();
00668         }
00669     }
00670     else
00671     {
00672         /* normal multiuser case */
00673         Assert(MyProcPort != NULL);
00674         PerformAuthentication(MyProcPort);
00675         InitializeSessionUserId(username);
00676         am_superuser = superuser();
00677     }
00678 
00679     /*
00680      * If we're trying to shut down, only superusers can connect, and new
00681      * replication connections are not allowed.
00682      */
00683     if ((!am_superuser || am_walsender) &&
00684         MyProcPort != NULL &&
00685         MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
00686     {
00687         if (am_walsender)
00688             ereport(FATAL,
00689                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
00690                      errmsg("new replication connections are not allowed during database shutdown")));
00691         else
00692             ereport(FATAL,
00693                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
00694             errmsg("must be superuser to connect during database shutdown")));
00695     }
00696 
00697     /*
00698      * Binary upgrades only allowed super-user connections
00699      */
00700     if (IsBinaryUpgrade && !am_superuser)
00701     {
00702         ereport(FATAL,
00703                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
00704              errmsg("must be superuser to connect in binary upgrade mode")));
00705     }
00706 
00707     /*
00708      * The last few connections slots are reserved for superusers. Although
00709      * replication connections currently require superuser privileges, we
00710      * don't allow them to consume the reserved slots, which are intended for
00711      * interactive use.
00712      */
00713     if ((!am_superuser || am_walsender) &&
00714         ReservedBackends > 0 &&
00715         !HaveNFreeProcs(ReservedBackends))
00716         ereport(FATAL,
00717                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
00718                  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
00719 
00720     /*
00721      * If walsender, we don't want to connect to any particular database. Just
00722      * finish the backend startup by processing any options from the startup
00723      * packet, and we're done.
00724      */
00725     if (am_walsender)
00726     {
00727         Assert(!bootstrap);
00728 
00729         if (!superuser() && !has_rolreplication(GetUserId()))
00730             ereport(FATAL,
00731                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
00732                      errmsg("must be superuser or replication role to start walsender")));
00733 
00734         /* process any options passed in the startup packet */
00735         if (MyProcPort != NULL)
00736             process_startup_options(MyProcPort, am_superuser);
00737 
00738         /* Apply PostAuthDelay as soon as we've read all options */
00739         if (PostAuthDelay > 0)
00740             pg_usleep(PostAuthDelay * 1000000L);
00741 
00742         /* initialize client encoding */
00743         InitializeClientEncoding();
00744 
00745         /* report this backend in the PgBackendStatus array */
00746         pgstat_bestart();
00747 
00748         /* close the transaction we started above */
00749         CommitTransactionCommand();
00750 
00751         return;
00752     }
00753 
00754     /*
00755      * Set up the global variables holding database id and default tablespace.
00756      * But note we won't actually try to touch the database just yet.
00757      *
00758      * We take a shortcut in the bootstrap case, otherwise we have to look up
00759      * the db's entry in pg_database.
00760      */
00761     if (bootstrap)
00762     {
00763         MyDatabaseId = TemplateDbOid;
00764         MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
00765     }
00766     else if (in_dbname != NULL)
00767     {
00768         HeapTuple   tuple;
00769         Form_pg_database dbform;
00770 
00771         tuple = GetDatabaseTuple(in_dbname);
00772         if (!HeapTupleIsValid(tuple))
00773             ereport(FATAL,
00774                     (errcode(ERRCODE_UNDEFINED_DATABASE),
00775                      errmsg("database \"%s\" does not exist", in_dbname)));
00776         dbform = (Form_pg_database) GETSTRUCT(tuple);
00777         MyDatabaseId = HeapTupleGetOid(tuple);
00778         MyDatabaseTableSpace = dbform->dattablespace;
00779         /* take database name from the caller, just for paranoia */
00780         strlcpy(dbname, in_dbname, sizeof(dbname));
00781     }
00782     else
00783     {
00784         /* caller specified database by OID */
00785         HeapTuple   tuple;
00786         Form_pg_database dbform;
00787 
00788         tuple = GetDatabaseTupleByOid(dboid);
00789         if (!HeapTupleIsValid(tuple))
00790             ereport(FATAL,
00791                     (errcode(ERRCODE_UNDEFINED_DATABASE),
00792                      errmsg("database %u does not exist", dboid)));
00793         dbform = (Form_pg_database) GETSTRUCT(tuple);
00794         MyDatabaseId = HeapTupleGetOid(tuple);
00795         MyDatabaseTableSpace = dbform->dattablespace;
00796         Assert(MyDatabaseId == dboid);
00797         strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
00798         /* pass the database name back to the caller */
00799         if (out_dbname)
00800             strcpy(out_dbname, dbname);
00801     }
00802 
00803     /* Now we can mark our PGPROC entry with the database ID */
00804     /* (We assume this is an atomic store so no lock is needed) */
00805     MyProc->databaseId = MyDatabaseId;
00806 
00807     /*
00808      * Now, take a writer's lock on the database we are trying to connect to.
00809      * If there is a concurrently running DROP DATABASE on that database, this
00810      * will block us until it finishes (and has committed its update of
00811      * pg_database).
00812      *
00813      * Note that the lock is not held long, only until the end of this startup
00814      * transaction.  This is OK since we are already advertising our use of
00815      * the database in the PGPROC array; anyone trying a DROP DATABASE after
00816      * this point will see us there.
00817      *
00818      * Note: use of RowExclusiveLock here is reasonable because we envision
00819      * our session as being a concurrent writer of the database.  If we had a
00820      * way of declaring a session as being guaranteed-read-only, we could use
00821      * AccessShareLock for such sessions and thereby not conflict against
00822      * CREATE DATABASE.
00823      */
00824     if (!bootstrap)
00825         LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
00826                          RowExclusiveLock);
00827 
00828     /*
00829      * Recheck pg_database to make sure the target database hasn't gone away.
00830      * If there was a concurrent DROP DATABASE, this ensures we will die
00831      * cleanly without creating a mess.
00832      */
00833     if (!bootstrap)
00834     {
00835         HeapTuple   tuple;
00836 
00837         tuple = GetDatabaseTuple(dbname);
00838         if (!HeapTupleIsValid(tuple) ||
00839             MyDatabaseId != HeapTupleGetOid(tuple) ||
00840             MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
00841             ereport(FATAL,
00842                     (errcode(ERRCODE_UNDEFINED_DATABASE),
00843                      errmsg("database \"%s\" does not exist", dbname),
00844                errdetail("It seems to have just been dropped or renamed.")));
00845     }
00846 
00847     /*
00848      * Now we should be able to access the database directory safely. Verify
00849      * it's there and looks reasonable.
00850      */
00851     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
00852 
00853     if (!bootstrap)
00854     {
00855         if (access(fullpath, F_OK) == -1)
00856         {
00857             if (errno == ENOENT)
00858                 ereport(FATAL,
00859                         (errcode(ERRCODE_UNDEFINED_DATABASE),
00860                          errmsg("database \"%s\" does not exist",
00861                                 dbname),
00862                     errdetail("The database subdirectory \"%s\" is missing.",
00863                               fullpath)));
00864             else
00865                 ereport(FATAL,
00866                         (errcode_for_file_access(),
00867                          errmsg("could not access directory \"%s\": %m",
00868                                 fullpath)));
00869         }
00870 
00871         ValidatePgVersion(fullpath);
00872     }
00873 
00874     SetDatabasePath(fullpath);
00875 
00876     /*
00877      * It's now possible to do real access to the system catalogs.
00878      *
00879      * Load relcache entries for the system catalogs.  This must create at
00880      * least the minimum set of "nailed-in" cache entries.
00881      */
00882     RelationCacheInitializePhase3();
00883 
00884     /* set up ACL framework (so CheckMyDatabase can check permissions) */
00885     initialize_acl();
00886 
00887     /*
00888      * Re-read the pg_database row for our database, check permissions and set
00889      * up database-specific GUC settings.  We can't do this until all the
00890      * database-access infrastructure is up.  (Also, it wants to know if the
00891      * user is a superuser, so the above stuff has to happen first.)
00892      */
00893     if (!bootstrap)
00894         CheckMyDatabase(dbname, am_superuser);
00895 
00896     /*
00897      * Now process any command-line switches and any additional GUC variable
00898      * settings passed in the startup packet.   We couldn't do this before
00899      * because we didn't know if client is a superuser.
00900      */
00901     if (MyProcPort != NULL)
00902         process_startup_options(MyProcPort, am_superuser);
00903 
00904     /* Process pg_db_role_setting options */
00905     process_settings(MyDatabaseId, GetSessionUserId());
00906 
00907     /* Apply PostAuthDelay as soon as we've read all options */
00908     if (PostAuthDelay > 0)
00909         pg_usleep(PostAuthDelay * 1000000L);
00910 
00911     /*
00912      * Initialize various default states that can't be set up until we've
00913      * selected the active user and gotten the right GUC settings.
00914      */
00915 
00916     /* set default namespace search path */
00917     InitializeSearchPath();
00918 
00919     /* initialize client encoding */
00920     InitializeClientEncoding();
00921 
00922     /* report this backend in the PgBackendStatus array */
00923     if (!bootstrap)
00924         pgstat_bestart();
00925 
00926     /* close the transaction we started above */
00927     if (!bootstrap)
00928         CommitTransactionCommand();
00929 }
00930 
00931 /*
00932  * Process any command-line switches and any additional GUC variable
00933  * settings passed in the startup packet.
00934  */
00935 static void
00936 process_startup_options(Port *port, bool am_superuser)
00937 {
00938     GucContext  gucctx;
00939     ListCell   *gucopts;
00940 
00941     gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
00942 
00943     /*
00944      * First process any command-line switches that were included in the
00945      * startup packet, if we are in a regular backend.
00946      */
00947     if (port->cmdline_options != NULL)
00948     {
00949         /*
00950          * The maximum possible number of commandline arguments that could
00951          * come from port->cmdline_options is (strlen + 1) / 2; see
00952          * pg_split_opts().
00953          */
00954         char      **av;
00955         int         maxac;
00956         int         ac;
00957 
00958         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
00959 
00960         av = (char **) palloc(maxac * sizeof(char *));
00961         ac = 0;
00962 
00963         av[ac++] = "postgres";
00964 
00965         /* Note this mangles port->cmdline_options */
00966         pg_split_opts(av, &ac, port->cmdline_options);
00967 
00968         av[ac] = NULL;
00969 
00970         Assert(ac < maxac);
00971 
00972         (void) process_postgres_switches(ac, av, gucctx, NULL);
00973     }
00974 
00975     /*
00976      * Process any additional GUC variable settings passed in startup packet.
00977      * These are handled exactly like command-line variables.
00978      */
00979     gucopts = list_head(port->guc_options);
00980     while (gucopts)
00981     {
00982         char       *name;
00983         char       *value;
00984 
00985         name = lfirst(gucopts);
00986         gucopts = lnext(gucopts);
00987 
00988         value = lfirst(gucopts);
00989         gucopts = lnext(gucopts);
00990 
00991         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
00992     }
00993 }
00994 
00995 /*
00996  * Load GUC settings from pg_db_role_setting.
00997  *
00998  * We try specific settings for the database/role combination, as well as
00999  * general for this database and for this user.
01000  */
01001 static void
01002 process_settings(Oid databaseid, Oid roleid)
01003 {
01004     Relation    relsetting;
01005 
01006     if (!IsUnderPostmaster)
01007         return;
01008 
01009     relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
01010 
01011     /* Later settings are ignored if set earlier. */
01012     ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
01013     ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
01014     ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
01015     ApplySetting(InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
01016 
01017     heap_close(relsetting, AccessShareLock);
01018 }
01019 
01020 /*
01021  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
01022  * before all the supporting modules begin to nail their doors shut via
01023  * their own callbacks.
01024  *
01025  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
01026  * via separate callbacks that execute before this one.  We don't combine the
01027  * callbacks because we still want this one to happen if the user-level
01028  * cleanup fails.
01029  */
01030 static void
01031 ShutdownPostgres(int code, Datum arg)
01032 {
01033     /* Make sure we've killed any active transaction */
01034     AbortOutOfAnyTransaction();
01035 
01036     /*
01037      * User locks are not released by transaction end, so be sure to release
01038      * them explicitly.
01039      */
01040     LockReleaseAll(USER_LOCKMETHOD, true);
01041 }
01042 
01043 
01044 /*
01045  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
01046  */
01047 static void
01048 StatementTimeoutHandler(void)
01049 {
01050 #ifdef HAVE_SETSID
01051     /* try to signal whole process group */
01052     kill(-MyProcPid, SIGINT);
01053 #endif
01054     kill(MyProcPid, SIGINT);
01055 }
01056 
01057 /*
01058  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
01059  *
01060  * This is identical to StatementTimeoutHandler, but since it's so short,
01061  * we might as well keep the two functions separate for clarity.
01062  */
01063 static void
01064 LockTimeoutHandler(void)
01065 {
01066 #ifdef HAVE_SETSID
01067     /* try to signal whole process group */
01068     kill(-MyProcPid, SIGINT);
01069 #endif
01070     kill(MyProcPid, SIGINT);
01071 }
01072 
01073 
01074 /*
01075  * Returns true if at least one role is defined in this database cluster.
01076  */
01077 static bool
01078 ThereIsAtLeastOneRole(void)
01079 {
01080     Relation    pg_authid_rel;
01081     HeapScanDesc scan;
01082     bool        result;
01083 
01084     pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
01085 
01086     scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
01087     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
01088 
01089     heap_endscan(scan);
01090     heap_close(pg_authid_rel, AccessShareLock);
01091 
01092     return result;
01093 }