]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
Add connection messages for streaming replication. log_connections
[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.205 2010/03/19 19:19:38 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("connection authorized: user=%s database=replication",
226                                                 port->user_name)));
227         else if (Log_connections)
228                 ereport(LOG,
229                                 (errmsg("connection authorized: user=%s database=%s",
230                                                 port->user_name, port->database_name)));
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_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  * If you're wondering why this is separate from InitPostgres at all:
421  * the critical distinction is that this stuff has to happen before we can
422  * run XLOG-related initialization, which is done before InitPostgres --- in
423  * fact, for cases such as the background writer process, InitPostgres may
424  * never be done at all.
425  */
426 void
427 BaseInit(void)
428 {
429         /*
430          * Attach to shared memory and semaphores, and initialize our
431          * input/output/debugging file descriptors.
432          */
433         InitCommunication();
434         DebugFileOpen();
435
436         /* Do local initialization of file, storage and buffer managers */
437         InitFileAccess();
438         smgrinit();
439         InitBufferPoolAccess();
440 }
441
442
443 /* --------------------------------
444  * InitPostgres
445  *              Initialize POSTGRES.
446  *
447  * The database can be specified by name, using the in_dbname parameter, or by
448  * OID, using the dboid parameter.      In the latter case, the actual database
449  * name can be returned to the caller in out_dbname.  If out_dbname isn't
450  * NULL, it must point to a buffer of size NAMEDATALEN.
451  *
452  * In bootstrap mode no parameters are used.  The autovacuum launcher process
453  * doesn't use any parameters either, because it only goes far enough to be
454  * able to read pg_database; it doesn't connect to any particular database.
455  * In walsender mode only username is used.
456  *
457  * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
458  * already have a PGPROC struct ... but it's not completely filled in yet.
459  *
460  * Note:
461  *              Be very careful with the order of calls in the InitPostgres function.
462  * --------------------------------
463  */
464 void
465 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
466                          char *out_dbname)
467 {
468         bool            bootstrap = IsBootstrapProcessingMode();
469         bool            am_superuser;
470         GucContext      gucctx;
471         char       *fullpath;
472         char            dbname[NAMEDATALEN];
473
474         elog(DEBUG3, "InitPostgres");
475
476         /*
477          * Add my PGPROC struct to the ProcArray.
478          *
479          * Once I have done this, I am visible to other backends!
480          */
481         InitProcessPhase2();
482
483         /*
484          * Initialize my entry in the shared-invalidation manager's array of
485          * per-backend data.
486          *
487          * Sets up MyBackendId, a unique backend identifier.
488          */
489         MyBackendId = InvalidBackendId;
490
491         SharedInvalBackendInit(false);
492
493         if (MyBackendId > MaxBackends || MyBackendId <= 0)
494                 elog(FATAL, "bad backend id: %d", MyBackendId);
495
496         /* Now that we have a BackendId, we can participate in ProcSignal */
497         ProcSignalInit(MyBackendId);
498
499         /*
500          * bufmgr needs another initialization call too
501          */
502         InitBufferPoolBackend();
503
504         /*
505          * Initialize local process's access to XLOG, if appropriate.  In
506          * bootstrap case we skip this since StartupXLOG() was run instead.
507          */
508         if (!bootstrap)
509                 (void) RecoveryInProgress();
510
511         /*
512          * Initialize the relation cache and the system catalog caches.  Note that
513          * no catalog access happens here; we only set up the hashtable structure.
514          * We must do this before starting a transaction because transaction abort
515          * would try to touch these hashtables.
516          */
517         RelationCacheInitialize();
518         InitCatalogCache();
519         InitPlanCache();
520
521         /* Initialize portal manager */
522         EnablePortalManager();
523
524         /* Initialize stats collection --- must happen before first xact */
525         if (!bootstrap)
526                 pgstat_initialize();
527
528         /*
529          * Load relcache entries for the shared system catalogs.  This must create
530          * at least an entry for pg_database.
531          */
532         RelationCacheInitializePhase2();
533
534         /*
535          * Set up process-exit callback to do pre-shutdown cleanup.  This has to
536          * be after we've initialized all the low-level modules like the buffer
537          * manager, because during shutdown this has to run before the low-level
538          * modules start to close down.  On the other hand, we want it in place
539          * before we begin our first transaction --- if we fail during the
540          * initialization transaction, as is entirely possible, we need the
541          * AbortTransaction call to clean up.
542          */
543         on_shmem_exit(ShutdownPostgres, 0);
544
545         /* The autovacuum launcher is done here */
546         if (IsAutoVacuumLauncherProcess())
547                 return;
548
549         /*
550          * Start a new transaction here before first access to db, and get a
551          * snapshot.  We don't have a use for the snapshot itself, but we're
552          * interested in the secondary effect that it sets RecentGlobalXmin. (This
553          * is critical for anything that reads heap pages, because HOT may decide
554          * to prune them even if the process doesn't attempt to modify any
555          * tuples.)
556          */
557         if (!bootstrap)
558         {
559                 StartTransactionCommand();
560                 (void) GetTransactionSnapshot();
561         }
562
563         /*
564          * Set up the global variables holding database id and default tablespace.
565          * But note we won't actually try to touch the database just yet.
566          *
567          * We take a shortcut in the bootstrap and walsender case, otherwise we
568          * have to look up the db's entry in pg_database.
569          */
570         if (bootstrap || am_walsender)
571         {
572                 MyDatabaseId = TemplateDbOid;
573                 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
574         }
575         else if (in_dbname != NULL)
576         {
577                 HeapTuple       tuple;
578                 Form_pg_database dbform;
579
580                 tuple = GetDatabaseTuple(in_dbname);
581                 if (!HeapTupleIsValid(tuple))
582                         ereport(FATAL,
583                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
584                                          errmsg("database \"%s\" does not exist", in_dbname)));
585                 dbform = (Form_pg_database) GETSTRUCT(tuple);
586                 MyDatabaseId = HeapTupleGetOid(tuple);
587                 MyDatabaseTableSpace = dbform->dattablespace;
588                 /* take database name from the caller, just for paranoia */
589                 strlcpy(dbname, in_dbname, sizeof(dbname));
590         }
591         else
592         {
593                 /* caller specified database by OID */
594                 HeapTuple       tuple;
595                 Form_pg_database dbform;
596
597                 tuple = GetDatabaseTupleByOid(dboid);
598                 if (!HeapTupleIsValid(tuple))
599                         ereport(FATAL,
600                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
601                                          errmsg("database %u does not exist", dboid)));
602                 dbform = (Form_pg_database) GETSTRUCT(tuple);
603                 MyDatabaseId = HeapTupleGetOid(tuple);
604                 MyDatabaseTableSpace = dbform->dattablespace;
605                 Assert(MyDatabaseId == dboid);
606                 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
607                 /* pass the database name back to the caller */
608                 if (out_dbname)
609                         strcpy(out_dbname, dbname);
610         }
611
612         /* Now we can mark our PGPROC entry with the database ID */
613         /* (We assume this is an atomic store so no lock is needed) */
614         MyProc->databaseId = MyDatabaseId;
615
616         /*
617          * Now, take a writer's lock on the database we are trying to connect to.
618          * If there is a concurrently running DROP DATABASE on that database, this
619          * will block us until it finishes (and has committed its update of
620          * pg_database).
621          *
622          * Note that the lock is not held long, only until the end of this startup
623          * transaction.  This is OK since we are already advertising our use of
624          * the database in the PGPROC array; anyone trying a DROP DATABASE after
625          * this point will see us there.
626          *
627          * Note: use of RowExclusiveLock here is reasonable because we envision
628          * our session as being a concurrent writer of the database.  If we had a
629          * way of declaring a session as being guaranteed-read-only, we could use
630          * AccessShareLock for such sessions and thereby not conflict against
631          * CREATE DATABASE.
632          */
633         if (!bootstrap && !am_walsender)
634                 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
635                                                  RowExclusiveLock);
636
637         /*
638          * Recheck pg_database to make sure the target database hasn't gone away.
639          * If there was a concurrent DROP DATABASE, this ensures we will die
640          * cleanly without creating a mess.
641          */
642         if (!bootstrap && !am_walsender)
643         {
644                 HeapTuple       tuple;
645
646                 tuple = GetDatabaseTuple(dbname);
647                 if (!HeapTupleIsValid(tuple) ||
648                         MyDatabaseId != HeapTupleGetOid(tuple) ||
649                         MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
650                         ereport(FATAL,
651                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
652                                          errmsg("database \"%s\" does not exist", dbname),
653                            errdetail("It seems to have just been dropped or renamed.")));
654         }
655
656         /*
657          * Now we should be able to access the database directory safely. Verify
658          * it's there and looks reasonable.
659          */
660         fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
661
662         if (!bootstrap && !am_walsender)
663         {
664                 if (access(fullpath, F_OK) == -1)
665                 {
666                         if (errno == ENOENT)
667                                 ereport(FATAL,
668                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
669                                                  errmsg("database \"%s\" does not exist",
670                                                                 dbname),
671                                         errdetail("The database subdirectory \"%s\" is missing.",
672                                                           fullpath)));
673                         else
674                                 ereport(FATAL,
675                                                 (errcode_for_file_access(),
676                                                  errmsg("could not access directory \"%s\": %m",
677                                                                 fullpath)));
678                 }
679
680                 ValidatePgVersion(fullpath);
681         }
682
683         SetDatabasePath(fullpath);
684
685         /*
686          * It's now possible to do real access to the system catalogs.
687          *
688          * Load relcache entries for the system catalogs.  This must create at
689          * least the minimum set of "nailed-in" cache entries.
690          */
691         RelationCacheInitializePhase3();
692
693         /*
694          * Perform client authentication if necessary, then figure out our
695          * postgres user ID, and see if we are a superuser.
696          *
697          * In standalone mode and in autovacuum worker processes, we use a fixed
698          * ID, otherwise we figure it out from the authenticated user name.
699          */
700         if (bootstrap || IsAutoVacuumWorkerProcess())
701         {
702                 InitializeSessionUserIdStandalone();
703                 am_superuser = true;
704         }
705         else if (!IsUnderPostmaster)
706         {
707                 InitializeSessionUserIdStandalone();
708                 am_superuser = true;
709                 if (!ThereIsAtLeastOneRole())
710                         ereport(WARNING,
711                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
712                                          errmsg("no roles are defined in this database system"),
713                                          errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
714                                                          username)));
715         }
716         else
717         {
718                 /* normal multiuser case */
719                 Assert(MyProcPort != NULL);
720                 PerformAuthentication(MyProcPort);
721                 InitializeSessionUserId(username);
722                 am_superuser = superuser();
723         }
724
725         /* set up ACL framework (so CheckMyDatabase can check permissions) */
726         initialize_acl();
727
728         /* Process pg_db_role_setting options */
729         process_settings(MyDatabaseId, GetSessionUserId());
730
731         /*
732          * Re-read the pg_database row for our database, check permissions and set
733          * up database-specific GUC settings.  We can't do this until all the
734          * database-access infrastructure is up.  (Also, it wants to know if the
735          * user is a superuser, so the above stuff has to happen first.)
736          */
737         if (!bootstrap && !am_walsender)
738                 CheckMyDatabase(dbname, am_superuser);
739
740         /*
741          * If we're trying to shut down, only superusers can connect.
742          */
743         if (!am_superuser &&
744                 MyProcPort != NULL &&
745                 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
746                 ereport(FATAL,
747                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
748                    errmsg("must be superuser to connect during database shutdown")));
749
750         /*
751          * Check a normal user hasn't connected to a superuser reserved slot.
752          */
753         if (!am_superuser &&
754                 ReservedBackends > 0 &&
755                 !HaveNFreeProcs(ReservedBackends))
756                 ereport(FATAL,
757                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
758                                  errmsg("connection limit exceeded for non-superusers")));
759
760         /*
761          * Now process any command-line switches that were included in the startup
762          * packet, if we are in a regular backend.      We couldn't do this before
763          * because we didn't know if client is a superuser.
764          */
765         gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
766
767         if (MyProcPort != NULL &&
768                 MyProcPort->cmdline_options != NULL)
769         {
770                 /*
771                  * The maximum possible number of commandline arguments that could
772                  * come from MyProcPort->cmdline_options is (strlen + 1) / 2; see
773                  * pg_split_opts().
774                  */
775                 char      **av;
776                 int                     maxac;
777                 int                     ac;
778
779                 maxac = 2 + (strlen(MyProcPort->cmdline_options) + 1) / 2;
780
781                 av = (char **) palloc(maxac * sizeof(char *));
782                 ac = 0;
783
784                 av[ac++] = "postgres";
785
786                 /* Note this mangles MyProcPort->cmdline_options */
787                 pg_split_opts(av, &ac, MyProcPort->cmdline_options);
788
789                 av[ac] = NULL;
790
791                 Assert(ac < maxac);
792
793                 (void) process_postgres_switches(ac, av, gucctx);
794         }
795
796         /*
797          * Process any additional GUC variable settings passed in startup packet.
798          * These are handled exactly like command-line variables.
799          */
800         if (MyProcPort != NULL)
801         {
802                 ListCell   *gucopts = list_head(MyProcPort->guc_options);
803
804                 while (gucopts)
805                 {
806                         char       *name;
807                         char       *value;
808
809                         name = lfirst(gucopts);
810                         gucopts = lnext(gucopts);
811
812                         value = lfirst(gucopts);
813                         gucopts = lnext(gucopts);
814
815                         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
816                 }
817         }
818
819         /* Apply PostAuthDelay as soon as we've read all options */
820         if (PostAuthDelay > 0)
821                 pg_usleep(PostAuthDelay * 1000000L);
822
823         /*
824          * Initialize various default states that can't be set up until we've
825          * selected the active user and gotten the right GUC settings.
826          */
827
828         /* set default namespace search path */
829         InitializeSearchPath();
830
831         /* initialize client encoding */
832         InitializeClientEncoding();
833
834         /* reset the database for walsender */
835         if (am_walsender)
836                 MyProc->databaseId = MyDatabaseId = InvalidOid;
837
838         /* report this backend in the PgBackendStatus array */
839         if (!bootstrap)
840                 pgstat_bestart();
841
842         /* close the transaction we started above */
843         if (!bootstrap)
844                 CommitTransactionCommand();
845 }
846
847 /*
848  * Load GUC settings from pg_db_role_setting.
849  *
850  * We try specific settings for the database/role combination, as well as
851  * general for this database and for this user.
852  */
853 static void
854 process_settings(Oid databaseid, Oid roleid)
855 {
856         Relation        relsetting;
857
858         if (!IsUnderPostmaster)
859                 return;
860
861         relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
862
863         /* Later settings are ignored if set earlier. */
864         ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
865         ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
866         ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
867
868         heap_close(relsetting, AccessShareLock);
869 }
870
871 /*
872  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
873  * before all the supporting modules begin to nail their doors shut via
874  * their own callbacks.
875  *
876  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
877  * via separate callbacks that execute before this one.  We don't combine the
878  * callbacks because we still want this one to happen if the user-level
879  * cleanup fails.
880  */
881 static void
882 ShutdownPostgres(int code, Datum arg)
883 {
884         /* Make sure we've killed any active transaction */
885         AbortOutOfAnyTransaction();
886
887         /*
888          * User locks are not released by transaction end, so be sure to release
889          * them explicitly.
890          */
891         LockReleaseAll(USER_LOCKMETHOD, true);
892 }
893
894
895 /*
896  * Returns true if at least one role is defined in this database cluster.
897  */
898 static bool
899 ThereIsAtLeastOneRole(void)
900 {
901         Relation        pg_authid_rel;
902         HeapScanDesc scan;
903         bool            result;
904
905         pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
906
907         scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
908         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
909
910         heap_endscan(scan);
911         heap_close(pg_authid_rel, AccessShareLock);
912
913         return result;
914 }