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