]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
94f92dd7343af74c37b7efe9f5f57a44f42c3d9e
[postgresql] / src / backend / utils / init / postinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c
4  *        postgres initialization utilities
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/init/postinit.c
12  *
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21
22 #include "access/heapam.h"
23 #include "access/sysattr.h"
24 #include "access/xact.h"
25 #include "catalog/catalog.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_database.h"
30 #include "catalog/pg_db_role_setting.h"
31 #include "catalog/pg_tablespace.h"
32 #include "libpq/auth.h"
33 #include "libpq/libpq-be.h"
34 #include "mb/pg_wchar.h"
35 #include "miscadmin.h"
36 #include "pgstat.h"
37 #include "postmaster/autovacuum.h"
38 #include "postmaster/postmaster.h"
39 #include "replication/walsender.h"
40 #include "storage/bufmgr.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/lmgr.h"
44 #include "storage/proc.h"
45 #include "storage/procarray.h"
46 #include "storage/procsignal.h"
47 #include "storage/sinvaladt.h"
48 #include "storage/smgr.h"
49 #include "tcop/tcopprot.h"
50 #include "utils/acl.h"
51 #include "utils/fmgroids.h"
52 #include "utils/guc.h"
53 #include "utils/pg_locale.h"
54 #include "utils/portal.h"
55 #include "utils/ps_status.h"
56 #include "utils/snapmgr.h"
57 #include "utils/syscache.h"
58 #include "utils/tqual.h"
59
60
61 static HeapTuple GetDatabaseTuple(const char *dbname);
62 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
63 static void PerformAuthentication(Port *port);
64 static void CheckMyDatabase(const char *name, bool am_superuser);
65 static void InitCommunication(void);
66 static void ShutdownPostgres(int code, Datum arg);
67 static bool ThereIsAtLeastOneRole(void);
68 static void process_startup_options(Port *port, bool am_superuser);
69 static void process_settings(Oid databaseid, Oid roleid);
70
71
72 /*** InitPostgres support ***/
73
74
75 /*
76  * GetDatabaseTuple -- fetch the pg_database row for a database
77  *
78  * This is used during backend startup when we don't yet have any access to
79  * system catalogs in general.  In the worst case, we can seqscan pg_database
80  * using nothing but the hard-wired descriptor that relcache.c creates for
81  * pg_database.  In more typical cases, relcache.c was able to load
82  * descriptors for both pg_database and its indexes from the shared relcache
83  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
84  * tells whether we got the cached descriptors.
85  */
86 static HeapTuple
87 GetDatabaseTuple(const char *dbname)
88 {
89         HeapTuple       tuple;
90         Relation        relation;
91         SysScanDesc scan;
92         ScanKeyData key[1];
93
94         /*
95          * form a scan key
96          */
97         ScanKeyInit(&key[0],
98                                 Anum_pg_database_datname,
99                                 BTEqualStrategyNumber, F_NAMEEQ,
100                                 CStringGetDatum(dbname));
101
102         /*
103          * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
104          * built the critical shared relcache entries (i.e., we're starting up
105          * without a shared relcache cache file).
106          */
107         relation = heap_open(DatabaseRelationId, AccessShareLock);
108         scan = systable_beginscan(relation, DatabaseNameIndexId,
109                                                           criticalSharedRelcachesBuilt,
110                                                           SnapshotNow,
111                                                           1, key);
112
113         tuple = systable_getnext(scan);
114
115         /* Must copy tuple before releasing buffer */
116         if (HeapTupleIsValid(tuple))
117                 tuple = heap_copytuple(tuple);
118
119         /* all done */
120         systable_endscan(scan);
121         heap_close(relation, AccessShareLock);
122
123         return tuple;
124 }
125
126 /*
127  * GetDatabaseTupleByOid -- as above, but search by database OID
128  */
129 static HeapTuple
130 GetDatabaseTupleByOid(Oid dboid)
131 {
132         HeapTuple       tuple;
133         Relation        relation;
134         SysScanDesc scan;
135         ScanKeyData key[1];
136
137         /*
138          * form a scan key
139          */
140         ScanKeyInit(&key[0],
141                                 ObjectIdAttributeNumber,
142                                 BTEqualStrategyNumber, F_OIDEQ,
143                                 ObjectIdGetDatum(dboid));
144
145         /*
146          * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
147          * built the critical shared relcache entries (i.e., we're starting up
148          * without a shared relcache cache file).
149          */
150         relation = heap_open(DatabaseRelationId, AccessShareLock);
151         scan = systable_beginscan(relation, DatabaseOidIndexId,
152                                                           criticalSharedRelcachesBuilt,
153                                                           SnapshotNow,
154                                                           1, key);
155
156         tuple = systable_getnext(scan);
157
158         /* Must copy tuple before releasing buffer */
159         if (HeapTupleIsValid(tuple))
160                 tuple = heap_copytuple(tuple);
161
162         /* all done */
163         systable_endscan(scan);
164         heap_close(relation, AccessShareLock);
165
166         return tuple;
167 }
168
169
170 /*
171  * PerformAuthentication -- authenticate a remote client
172  *
173  * returns: nothing.  Will not return at all if there's any failure.
174  */
175 static void
176 PerformAuthentication(Port *port)
177 {
178         /* This should be set already, but let's make sure */
179         ClientAuthInProgress = true;    /* limit visibility of log messages */
180
181         /*
182          * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
183          * etcetera from the postmaster, and have to load them ourselves.  Note we
184          * are loading them into the startup transaction's memory context, not
185          * PostmasterContext, but that shouldn't matter.
186          *
187          * FIXME: [fork/exec] Ugh.      Is there a way around this overhead?
188          */
189 #ifdef EXEC_BACKEND
190         if (!load_hba())
191         {
192                 /*
193                  * It makes no sense to continue if we fail to load the HBA file,
194                  * since there is no way to connect to the database in this case.
195                  */
196                 ereport(FATAL,
197                                 (errmsg("could not load pg_hba.conf")));
198         }
199         load_ident();
200 #endif
201
202         /*
203          * Set up a timeout in case a buggy or malicious client fails to respond
204          * during authentication.  Since we're inside a transaction and might do
205          * database access, we have to use the statement_timeout infrastructure.
206          */
207         if (!enable_sig_alarm(AuthenticationTimeout * 1000, true))
208                 elog(FATAL, "could not set timer for authorization timeout");
209
210         /*
211          * Now perform authentication exchange.
212          */
213         ClientAuthentication(port); /* might not return, if failure */
214
215         /*
216          * Done with authentication.  Disable the timeout, and log if needed.
217          */
218         if (!disable_sig_alarm(true))
219                 elog(FATAL, "could not disable timer for authorization timeout");
220
221         if (Log_connections)
222         {
223                 if (am_walsender)
224                         ereport(LOG,
225                                         (errmsg("replication connection authorized: user=%s",
226                                                         port->user_name)));
227                 else
228                         ereport(LOG,
229                                         (errmsg("connection authorized: user=%s database=%s",
230                                                         port->user_name, port->database_name)));
231         }
232
233         set_ps_display("startup", false);
234
235         ClientAuthInProgress = false;           /* client_min_messages is active now */
236 }
237
238
239 /*
240  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
241  */
242 static void
243 CheckMyDatabase(const char *name, bool am_superuser)
244 {
245         HeapTuple       tup;
246         Form_pg_database dbform;
247         char       *collate;
248         char       *ctype;
249
250         /* Fetch our pg_database row normally, via syscache */
251         tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
252         if (!HeapTupleIsValid(tup))
253                 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
254         dbform = (Form_pg_database) GETSTRUCT(tup);
255
256         /* This recheck is strictly paranoia */
257         if (strcmp(name, NameStr(dbform->datname)) != 0)
258                 ereport(FATAL,
259                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
260                                  errmsg("database \"%s\" has disappeared from pg_database",
261                                                 name),
262                                  errdetail("Database OID %u now seems to belong to \"%s\".",
263                                                    MyDatabaseId, NameStr(dbform->datname))));
264
265         /*
266          * Check permissions to connect to the database.
267          *
268          * These checks are not enforced when in standalone mode, so that there is
269          * a way to recover from disabling all access to all databases, for
270          * example "UPDATE pg_database SET datallowconn = false;".
271          *
272          * We do not enforce them for autovacuum worker processes either.
273          */
274         if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
275         {
276                 /*
277                  * Check that the database is currently allowing connections.
278                  */
279                 if (!dbform->datallowconn)
280                         ereport(FATAL,
281                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
282                          errmsg("database \"%s\" is not currently accepting connections",
283                                         name)));
284
285                 /*
286                  * Check privilege to connect to the database.  (The am_superuser test
287                  * is redundant, but since we have the flag, might as well check it
288                  * and save a few cycles.)
289                  */
290                 if (!am_superuser &&
291                         pg_database_aclcheck(MyDatabaseId, GetUserId(),
292                                                                  ACL_CONNECT) != ACLCHECK_OK)
293                         ereport(FATAL,
294                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
295                                          errmsg("permission denied for database \"%s\"", name),
296                                          errdetail("User does not have CONNECT privilege.")));
297
298                 /*
299                  * Check connection limit for this database.
300                  *
301                  * There is a race condition here --- we create our PGPROC before
302                  * checking for other PGPROCs.  If two backends did this at about the
303                  * same time, they might both think they were over the limit, while
304                  * ideally one should succeed and one fail.  Getting that to work
305                  * exactly seems more trouble than it is worth, however; instead we
306                  * just document that the connection limit is approximate.
307                  */
308                 if (dbform->datconnlimit >= 0 &&
309                         !am_superuser &&
310                         CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
311                         ereport(FATAL,
312                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
313                                          errmsg("too many connections for database \"%s\"",
314                                                         name)));
315         }
316
317         /*
318          * OK, we're golden.  Next to-do item is to save the encoding info out of
319          * the pg_database tuple.
320          */
321         SetDatabaseEncoding(dbform->encoding);
322         /* Record it as a GUC internal option, too */
323         SetConfigOption("server_encoding", GetDatabaseEncodingName(),
324                                         PGC_INTERNAL, PGC_S_OVERRIDE);
325         /* If we have no other source of client_encoding, use server encoding */
326         SetConfigOption("client_encoding", GetDatabaseEncodingName(),
327                                         PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
328
329         /* assign locale variables */
330         collate = NameStr(dbform->datcollate);
331         ctype = NameStr(dbform->datctype);
332
333         if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
334                 ereport(FATAL,
335                         (errmsg("database locale is incompatible with operating system"),
336                          errdetail("The database was initialized with LC_COLLATE \"%s\", "
337                                            " which is not recognized by setlocale().", collate),
338                          errhint("Recreate the database with another locale or install the missing locale.")));
339
340         if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
341                 ereport(FATAL,
342                         (errmsg("database locale is incompatible with operating system"),
343                          errdetail("The database was initialized with LC_CTYPE \"%s\", "
344                                            " which is not recognized by setlocale().", ctype),
345                          errhint("Recreate the database with another locale or install the missing locale.")));
346
347         /* Make the locale settings visible as GUC variables, too */
348         SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
349         SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
350
351         /* Use the right encoding in translated messages */
352 #ifdef ENABLE_NLS
353         pg_bind_textdomain_codeset(textdomain(NULL));
354 #endif
355
356         ReleaseSysCache(tup);
357 }
358
359
360
361 /* --------------------------------
362  *              InitCommunication
363  *
364  *              This routine initializes stuff needed for ipc, locking, etc.
365  *              it should be called something more informative.
366  * --------------------------------
367  */
368 static void
369 InitCommunication(void)
370 {
371         /*
372          * initialize shared memory and semaphores appropriately.
373          */
374         if (!IsUnderPostmaster)         /* postmaster already did this */
375         {
376                 /*
377                  * We're running a postgres bootstrap process or a standalone backend.
378                  * Create private "shmem" and semaphores.
379                  */
380                 CreateSharedMemoryAndSemaphores(true, 0);
381         }
382 }
383
384
385 /*
386  * pg_split_opts -- split a string of options and append it to an argv array
387  *
388  * NB: the input string is destructively modified!      Also, caller is responsible
389  * for ensuring the argv array is large enough.  The maximum possible number
390  * of arguments added by this routine is (strlen(optstr) + 1) / 2.
391  *
392  * Since no current POSTGRES arguments require any quoting characters,
393  * we can use the simple-minded tactic of assuming each set of space-
394  * delimited characters is a separate argv element.
395  *
396  * If you don't like that, well, we *used* to pass the whole option string
397  * as ONE argument to execl(), which was even less intelligent...
398  */
399 void
400 pg_split_opts(char **argv, int *argcp, char *optstr)
401 {
402         while (*optstr)
403         {
404                 while (isspace((unsigned char) *optstr))
405                         optstr++;
406                 if (*optstr == '\0')
407                         break;
408                 argv[(*argcp)++] = optstr;
409                 while (*optstr && !isspace((unsigned char) *optstr))
410                         optstr++;
411                 if (*optstr)
412                         *optstr++ = '\0';
413         }
414 }
415
416
417 /*
418  * Early initialization of a backend (either standalone or under postmaster).
419  * This happens even before InitPostgres.
420  *
421  * This is separate from InitPostgres because it is also called by auxiliary
422  * processes, such as the background writer process, which may not call
423  * InitPostgres at all.
424  */
425 void
426 BaseInit(void)
427 {
428         /*
429          * Attach to shared memory and semaphores, and initialize our
430          * input/output/debugging file descriptors.
431          */
432         InitCommunication();
433         DebugFileOpen();
434
435         /* Do local initialization of file, storage and buffer managers */
436         InitFileAccess();
437         smgrinit();
438         InitBufferPoolAccess();
439 }
440
441
442 /* --------------------------------
443  * InitPostgres
444  *              Initialize POSTGRES.
445  *
446  * The database can be specified by name, using the in_dbname parameter, or by
447  * OID, using the dboid parameter.      In the latter case, the actual database
448  * name can be returned to the caller in out_dbname.  If out_dbname isn't
449  * NULL, it must point to a buffer of size NAMEDATALEN.
450  *
451  * In bootstrap mode no parameters are used.  The autovacuum launcher process
452  * doesn't use any parameters either, because it only goes far enough to be
453  * able to read pg_database; it doesn't connect to any particular database.
454  * In walsender mode only username is used.
455  *
456  * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
457  * already have a PGPROC struct ... but it's not completely filled in yet.
458  *
459  * Note:
460  *              Be very careful with the order of calls in the InitPostgres function.
461  * --------------------------------
462  */
463 void
464 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
465                          char *out_dbname)
466 {
467         bool            bootstrap = IsBootstrapProcessingMode();
468         bool            am_superuser;
469         char       *fullpath;
470         char            dbname[NAMEDATALEN];
471
472         elog(DEBUG3, "InitPostgres");
473
474         /*
475          * Add my PGPROC struct to the ProcArray.
476          *
477          * Once I have done this, I am visible to other backends!
478          */
479         InitProcessPhase2();
480
481         /*
482          * Initialize my entry in the shared-invalidation manager's array of
483          * per-backend data.
484          *
485          * Sets up MyBackendId, a unique backend identifier.
486          */
487         MyBackendId = InvalidBackendId;
488
489         SharedInvalBackendInit(false);
490
491         if (MyBackendId > MaxBackends || MyBackendId <= 0)
492                 elog(FATAL, "bad backend ID: %d", MyBackendId);
493
494         /* Now that we have a BackendId, we can participate in ProcSignal */
495         ProcSignalInit(MyBackendId);
496
497         /*
498          * bufmgr needs another initialization call too
499          */
500         InitBufferPoolBackend();
501
502         /*
503          * Initialize local process's access to XLOG.
504          */
505         if (IsUnderPostmaster)
506         {
507                 /*
508                  * The postmaster already started the XLOG machinery, but we need to
509                  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
510                  * This is handled by calling RecoveryInProgress and ignoring the
511                  * result.
512                  */
513                 (void) RecoveryInProgress();
514         }
515         else
516         {
517                 /*
518                  * We are either a bootstrap process or a standalone backend. Either
519                  * way, start up the XLOG machinery, and register to have it closed
520                  * down at exit.
521                  */
522                 StartupXLOG();
523                 on_shmem_exit(ShutdownXLOG, 0);
524         }
525
526         /*
527          * Initialize the relation cache and the system catalog caches.  Note that
528          * no catalog access happens here; we only set up the hashtable structure.
529          * We must do this before starting a transaction because transaction abort
530          * would try to touch these hashtables.
531          */
532         RelationCacheInitialize();
533         InitCatalogCache();
534         InitPlanCache();
535
536         /* Initialize portal manager */
537         EnablePortalManager();
538
539         /* Initialize stats collection --- must happen before first xact */
540         if (!bootstrap)
541                 pgstat_initialize();
542
543         /*
544          * Load relcache entries for the shared system catalogs.  This must create
545          * at least entries for pg_database and catalogs used for authentication.
546          */
547         RelationCacheInitializePhase2();
548
549         /*
550          * Set up process-exit callback to do pre-shutdown cleanup.  This has to
551          * be after we've initialized all the low-level modules like the buffer
552          * manager, because during shutdown this has to run before the low-level
553          * modules start to close down.  On the other hand, we want it in place
554          * before we begin our first transaction --- if we fail during the
555          * initialization transaction, as is entirely possible, we need the
556          * AbortTransaction call to clean up.
557          */
558         on_shmem_exit(ShutdownPostgres, 0);
559
560         /* The autovacuum launcher is done here */
561         if (IsAutoVacuumLauncherProcess())
562                 return;
563
564         /*
565          * Start a new transaction here before first access to db, and get a
566          * snapshot.  We don't have a use for the snapshot itself, but we're
567          * interested in the secondary effect that it sets RecentGlobalXmin. (This
568          * is critical for anything that reads heap pages, because HOT may decide
569          * to prune them even if the process doesn't attempt to modify any
570          * tuples.)
571          */
572         if (!bootstrap)
573         {
574                 /* statement_timestamp must be set for timeouts to work correctly */
575                 SetCurrentStatementStartTimestamp();
576                 StartTransactionCommand();
577                 (void) GetTransactionSnapshot();
578         }
579
580         /*
581          * Perform client authentication if necessary, then figure out our
582          * postgres user ID, and see if we are a superuser.
583          *
584          * In standalone mode and in autovacuum worker processes, we use a fixed
585          * ID, otherwise we figure it out from the authenticated user name.
586          */
587         if (bootstrap || IsAutoVacuumWorkerProcess())
588         {
589                 InitializeSessionUserIdStandalone();
590                 am_superuser = true;
591         }
592         else if (!IsUnderPostmaster)
593         {
594                 InitializeSessionUserIdStandalone();
595                 am_superuser = true;
596                 if (!ThereIsAtLeastOneRole())
597                         ereport(WARNING,
598                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
599                                          errmsg("no roles are defined in this database system"),
600                                          errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
601                                                          username)));
602         }
603         else
604         {
605                 /* normal multiuser case */
606                 Assert(MyProcPort != NULL);
607                 PerformAuthentication(MyProcPort);
608                 InitializeSessionUserId(username);
609                 am_superuser = superuser();
610         }
611
612         /*
613          * If we're trying to shut down, only superusers can connect, and new
614          * replication connections are not allowed.
615          */
616         if ((!am_superuser || am_walsender) &&
617                 MyProcPort != NULL &&
618                 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
619         {
620                 if (am_walsender)
621                         ereport(FATAL,
622                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
623                                          errmsg("new replication connections are not allowed during database shutdown")));
624                 else
625                         ereport(FATAL,
626                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
627                         errmsg("must be superuser to connect during database shutdown")));
628         }
629
630         /*
631          * Binary upgrades only allowed super-user connections
632          */
633         if (IsBinaryUpgrade && !am_superuser)
634         {
635                 ereport(FATAL,
636                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
637                          errmsg("must be superuser to connect in binary upgrade mode")));
638         }
639
640         /*
641          * The last few connections slots are reserved for superusers. Although
642          * replication connections currently require superuser privileges, we
643          * don't allow them to consume the reserved slots, which are intended for
644          * interactive use.
645          */
646         if ((!am_superuser || am_walsender) &&
647                 ReservedBackends > 0 &&
648                 !HaveNFreeProcs(ReservedBackends))
649                 ereport(FATAL,
650                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
651                                  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
652
653         /*
654          * If walsender, we don't want to connect to any particular database. Just
655          * finish the backend startup by processing any options from the startup
656          * packet, and we're done.
657          */
658         if (am_walsender)
659         {
660                 Assert(!bootstrap);
661
662                 /* must have authenticated as a replication role */
663                 if (!is_authenticated_user_replication_role())
664                         ereport(FATAL,
665                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
666                                          errmsg("must be replication role to start walsender")));
667
668                 /* process any options passed in the startup packet */
669                 if (MyProcPort != NULL)
670                         process_startup_options(MyProcPort, am_superuser);
671
672                 /* Apply PostAuthDelay as soon as we've read all options */
673                 if (PostAuthDelay > 0)
674                         pg_usleep(PostAuthDelay * 1000000L);
675
676                 /* initialize client encoding */
677                 InitializeClientEncoding();
678
679                 /* report this backend in the PgBackendStatus array */
680                 pgstat_bestart();
681
682                 /* close the transaction we started above */
683                 CommitTransactionCommand();
684
685                 return;
686         }
687
688         /*
689          * Set up the global variables holding database id and default tablespace.
690          * But note we won't actually try to touch the database just yet.
691          *
692          * We take a shortcut in the bootstrap case, otherwise we have to look up
693          * the db's entry in pg_database.
694          */
695         if (bootstrap)
696         {
697                 MyDatabaseId = TemplateDbOid;
698                 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
699         }
700         else if (in_dbname != NULL)
701         {
702                 HeapTuple       tuple;
703                 Form_pg_database dbform;
704
705                 tuple = GetDatabaseTuple(in_dbname);
706                 if (!HeapTupleIsValid(tuple))
707                         ereport(FATAL,
708                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
709                                          errmsg("database \"%s\" does not exist", in_dbname)));
710                 dbform = (Form_pg_database) GETSTRUCT(tuple);
711                 MyDatabaseId = HeapTupleGetOid(tuple);
712                 MyDatabaseTableSpace = dbform->dattablespace;
713                 /* take database name from the caller, just for paranoia */
714                 strlcpy(dbname, in_dbname, sizeof(dbname));
715         }
716         else
717         {
718                 /* caller specified database by OID */
719                 HeapTuple       tuple;
720                 Form_pg_database dbform;
721
722                 tuple = GetDatabaseTupleByOid(dboid);
723                 if (!HeapTupleIsValid(tuple))
724                         ereport(FATAL,
725                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
726                                          errmsg("database %u does not exist", dboid)));
727                 dbform = (Form_pg_database) GETSTRUCT(tuple);
728                 MyDatabaseId = HeapTupleGetOid(tuple);
729                 MyDatabaseTableSpace = dbform->dattablespace;
730                 Assert(MyDatabaseId == dboid);
731                 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
732                 /* pass the database name back to the caller */
733                 if (out_dbname)
734                         strcpy(out_dbname, dbname);
735         }
736
737         /* Now we can mark our PGPROC entry with the database ID */
738         /* (We assume this is an atomic store so no lock is needed) */
739         MyProc->databaseId = MyDatabaseId;
740
741         /*
742          * Now, take a writer's lock on the database we are trying to connect to.
743          * If there is a concurrently running DROP DATABASE on that database, this
744          * will block us until it finishes (and has committed its update of
745          * pg_database).
746          *
747          * Note that the lock is not held long, only until the end of this startup
748          * transaction.  This is OK since we are already advertising our use of
749          * the database in the PGPROC array; anyone trying a DROP DATABASE after
750          * this point will see us there.
751          *
752          * Note: use of RowExclusiveLock here is reasonable because we envision
753          * our session as being a concurrent writer of the database.  If we had a
754          * way of declaring a session as being guaranteed-read-only, we could use
755          * AccessShareLock for such sessions and thereby not conflict against
756          * CREATE DATABASE.
757          */
758         if (!bootstrap)
759                 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
760                                                  RowExclusiveLock);
761
762         /*
763          * Recheck pg_database to make sure the target database hasn't gone away.
764          * If there was a concurrent DROP DATABASE, this ensures we will die
765          * cleanly without creating a mess.
766          */
767         if (!bootstrap)
768         {
769                 HeapTuple       tuple;
770
771                 tuple = GetDatabaseTuple(dbname);
772                 if (!HeapTupleIsValid(tuple) ||
773                         MyDatabaseId != HeapTupleGetOid(tuple) ||
774                         MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
775                         ereport(FATAL,
776                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
777                                          errmsg("database \"%s\" does not exist", dbname),
778                            errdetail("It seems to have just been dropped or renamed.")));
779         }
780
781         /*
782          * Now we should be able to access the database directory safely. Verify
783          * it's there and looks reasonable.
784          */
785         fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
786
787         if (!bootstrap)
788         {
789                 if (access(fullpath, F_OK) == -1)
790                 {
791                         if (errno == ENOENT)
792                                 ereport(FATAL,
793                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
794                                                  errmsg("database \"%s\" does not exist",
795                                                                 dbname),
796                                         errdetail("The database subdirectory \"%s\" is missing.",
797                                                           fullpath)));
798                         else
799                                 ereport(FATAL,
800                                                 (errcode_for_file_access(),
801                                                  errmsg("could not access directory \"%s\": %m",
802                                                                 fullpath)));
803                 }
804
805                 ValidatePgVersion(fullpath);
806         }
807
808         SetDatabasePath(fullpath);
809
810         /*
811          * It's now possible to do real access to the system catalogs.
812          *
813          * Load relcache entries for the system catalogs.  This must create at
814          * least the minimum set of "nailed-in" cache entries.
815          */
816         RelationCacheInitializePhase3();
817
818         /* set up ACL framework (so CheckMyDatabase can check permissions) */
819         initialize_acl();
820
821         /*
822          * Re-read the pg_database row for our database, check permissions and set
823          * up database-specific GUC settings.  We can't do this until all the
824          * database-access infrastructure is up.  (Also, it wants to know if the
825          * user is a superuser, so the above stuff has to happen first.)
826          */
827         if (!bootstrap)
828                 CheckMyDatabase(dbname, am_superuser);
829
830         /*
831          * Now process any command-line switches and any additional GUC variable
832          * settings passed in the startup packet.       We couldn't do this before
833          * because we didn't know if client is a superuser.
834          */
835         if (MyProcPort != NULL)
836                 process_startup_options(MyProcPort, am_superuser);
837
838         /* Process pg_db_role_setting options */
839         process_settings(MyDatabaseId, GetSessionUserId());
840
841         /* Apply PostAuthDelay as soon as we've read all options */
842         if (PostAuthDelay > 0)
843                 pg_usleep(PostAuthDelay * 1000000L);
844
845         /*
846          * Initialize various default states that can't be set up until we've
847          * selected the active user and gotten the right GUC settings.
848          */
849
850         /* set default namespace search path */
851         InitializeSearchPath();
852
853         /* initialize client encoding */
854         InitializeClientEncoding();
855
856         /* report this backend in the PgBackendStatus array */
857         if (!bootstrap)
858                 pgstat_bestart();
859
860         /* close the transaction we started above */
861         if (!bootstrap)
862                 CommitTransactionCommand();
863 }
864
865 /*
866  * Process any command-line switches and any additional GUC variable
867  * settings passed in the startup packet.
868  */
869 static void
870 process_startup_options(Port *port, bool am_superuser)
871 {
872         GucContext      gucctx;
873         ListCell   *gucopts;
874
875         gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
876
877         /*
878          * First process any command-line switches that were included in the
879          * startup packet, if we are in a regular backend.
880          */
881         if (port->cmdline_options != NULL)
882         {
883                 /*
884                  * The maximum possible number of commandline arguments that could
885                  * come from port->cmdline_options is (strlen + 1) / 2; see
886                  * pg_split_opts().
887                  */
888                 char      **av;
889                 int                     maxac;
890                 int                     ac;
891
892                 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
893
894                 av = (char **) palloc(maxac * sizeof(char *));
895                 ac = 0;
896
897                 av[ac++] = "postgres";
898
899                 /* Note this mangles port->cmdline_options */
900                 pg_split_opts(av, &ac, port->cmdline_options);
901
902                 av[ac] = NULL;
903
904                 Assert(ac < maxac);
905
906                 (void) process_postgres_switches(ac, av, gucctx);
907         }
908
909         /*
910          * Process any additional GUC variable settings passed in startup packet.
911          * These are handled exactly like command-line variables.
912          */
913         gucopts = list_head(port->guc_options);
914         while (gucopts)
915         {
916                 char       *name;
917                 char       *value;
918
919                 name = lfirst(gucopts);
920                 gucopts = lnext(gucopts);
921
922                 value = lfirst(gucopts);
923                 gucopts = lnext(gucopts);
924
925                 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
926         }
927 }
928
929 /*
930  * Load GUC settings from pg_db_role_setting.
931  *
932  * We try specific settings for the database/role combination, as well as
933  * general for this database and for this user.
934  */
935 static void
936 process_settings(Oid databaseid, Oid roleid)
937 {
938         Relation        relsetting;
939
940         if (!IsUnderPostmaster)
941                 return;
942
943         relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
944
945         /* Later settings are ignored if set earlier. */
946         ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
947         ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
948         ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
949
950         heap_close(relsetting, AccessShareLock);
951 }
952
953 /*
954  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
955  * before all the supporting modules begin to nail their doors shut via
956  * their own callbacks.
957  *
958  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
959  * via separate callbacks that execute before this one.  We don't combine the
960  * callbacks because we still want this one to happen if the user-level
961  * cleanup fails.
962  */
963 static void
964 ShutdownPostgres(int code, Datum arg)
965 {
966         /* Make sure we've killed any active transaction */
967         AbortOutOfAnyTransaction();
968
969         /*
970          * User locks are not released by transaction end, so be sure to release
971          * them explicitly.
972          */
973         LockReleaseAll(USER_LOCKMETHOD, true);
974 }
975
976
977 /*
978  * Returns true if at least one role is defined in this database cluster.
979  */
980 static bool
981 ThereIsAtLeastOneRole(void)
982 {
983         Relation        pg_authid_rel;
984         HeapScanDesc scan;
985         bool            result;
986
987         pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
988
989         scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
990         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
991
992         heap_endscan(scan);
993         heap_close(pg_authid_rel, AccessShareLock);
994
995         return result;
996 }