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