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