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