Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * postinit.c
4 : : * postgres initialization utilities
5 : : *
6 : : * Portions Copyright (c) 1996-2025, 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/genam.h"
23 : : #include "access/heapam.h"
24 : : #include "access/htup_details.h"
25 : : #include "access/session.h"
26 : : #include "access/tableam.h"
27 : : #include "access/xact.h"
28 : : #include "access/xlog.h"
29 : : #include "access/xloginsert.h"
30 : : #include "catalog/namespace.h"
31 : : #include "catalog/pg_authid.h"
32 : : #include "catalog/pg_collation.h"
33 : : #include "catalog/pg_database.h"
34 : : #include "catalog/pg_db_role_setting.h"
35 : : #include "catalog/pg_tablespace.h"
36 : : #include "libpq/auth.h"
37 : : #include "libpq/libpq-be.h"
38 : : #include "mb/pg_wchar.h"
39 : : #include "miscadmin.h"
40 : : #include "pgstat.h"
41 : : #include "postmaster/autovacuum.h"
42 : : #include "postmaster/postmaster.h"
43 : : #include "replication/slot.h"
44 : : #include "replication/slotsync.h"
45 : : #include "replication/walsender.h"
46 : : #include "storage/aio_subsys.h"
47 : : #include "storage/bufmgr.h"
48 : : #include "storage/fd.h"
49 : : #include "storage/ipc.h"
50 : : #include "storage/lmgr.h"
51 : : #include "storage/proc.h"
52 : : #include "storage/procarray.h"
53 : : #include "storage/procnumber.h"
54 : : #include "storage/procsignal.h"
55 : : #include "storage/sinvaladt.h"
56 : : #include "storage/smgr.h"
57 : : #include "storage/sync.h"
58 : : #include "tcop/backend_startup.h"
59 : : #include "tcop/tcopprot.h"
60 : : #include "utils/acl.h"
61 : : #include "utils/builtins.h"
62 : : #include "utils/fmgroids.h"
63 : : #include "utils/guc_hooks.h"
64 : : #include "utils/injection_point.h"
65 : : #include "utils/memutils.h"
66 : : #include "utils/pg_locale.h"
67 : : #include "utils/portal.h"
68 : : #include "utils/ps_status.h"
69 : : #include "utils/snapmgr.h"
70 : : #include "utils/syscache.h"
71 : : #include "utils/timeout.h"
72 : :
73 : : static HeapTuple GetDatabaseTuple(const char *dbname);
74 : : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
75 : : static void PerformAuthentication(Port *port);
76 : : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
77 : : static void ShutdownPostgres(int code, Datum arg);
78 : : static void StatementTimeoutHandler(void);
79 : : static void LockTimeoutHandler(void);
80 : : static void IdleInTransactionSessionTimeoutHandler(void);
81 : : static void TransactionTimeoutHandler(void);
82 : : static void IdleSessionTimeoutHandler(void);
83 : : static void IdleStatsUpdateTimeoutHandler(void);
84 : : static void ClientCheckTimeoutHandler(void);
85 : : static bool ThereIsAtLeastOneRole(void);
86 : : static void process_startup_options(Port *port, bool am_superuser);
87 : : static void process_settings(Oid databaseid, Oid roleid);
88 : :
89 : :
90 : : /*** InitPostgres support ***/
91 : :
92 : :
93 : : /*
94 : : * GetDatabaseTuple -- fetch the pg_database row for a database
95 : : *
96 : : * This is used during backend startup when we don't yet have any access to
97 : : * system catalogs in general. In the worst case, we can seqscan pg_database
98 : : * using nothing but the hard-wired descriptor that relcache.c creates for
99 : : * pg_database. In more typical cases, relcache.c was able to load
100 : : * descriptors for both pg_database and its indexes from the shared relcache
101 : : * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
102 : : * tells whether we got the cached descriptors.
103 : : */
104 : : static HeapTuple
5921 tgl@sss.pgh.pa.us 105 :CBC 11682 : GetDatabaseTuple(const char *dbname)
106 : : {
107 : : HeapTuple tuple;
108 : : Relation relation;
109 : : SysScanDesc scan;
110 : : ScanKeyData key[1];
111 : :
112 : : /*
113 : : * form a scan key
114 : : */
115 : 11682 : ScanKeyInit(&key[0],
116 : : Anum_pg_database_datname,
117 : : BTEqualStrategyNumber, F_NAMEEQ,
118 : : CStringGetDatum(dbname));
119 : :
120 : : /*
121 : : * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
122 : : * built the critical shared relcache entries (i.e., we're starting up
123 : : * without a shared relcache cache file).
124 : : */
2472 andres@anarazel.de 125 : 11682 : relation = table_open(DatabaseRelationId, AccessShareLock);
5921 tgl@sss.pgh.pa.us 126 : 11682 : scan = systable_beginscan(relation, DatabaseNameIndexId,
127 : : criticalSharedRelcachesBuilt,
128 : : NULL,
129 : : 1, key);
130 : :
131 : 11682 : tuple = systable_getnext(scan);
132 : :
133 : : /* Must copy tuple before releasing buffer */
134 [ + + ]: 11682 : if (HeapTupleIsValid(tuple))
135 : 11677 : tuple = heap_copytuple(tuple);
136 : :
137 : : /* all done */
138 : 11682 : systable_endscan(scan);
2472 andres@anarazel.de 139 : 11682 : table_close(relation, AccessShareLock);
140 : :
5921 tgl@sss.pgh.pa.us 141 : 11682 : return tuple;
142 : : }
143 : :
144 : : /*
145 : : * GetDatabaseTupleByOid -- as above, but search by database OID
146 : : */
147 : : static HeapTuple
148 : 13631 : GetDatabaseTupleByOid(Oid dboid)
149 : : {
150 : : HeapTuple tuple;
151 : : Relation relation;
152 : : SysScanDesc scan;
153 : : ScanKeyData key[1];
154 : :
155 : : /*
156 : : * form a scan key
157 : : */
158 : 13631 : ScanKeyInit(&key[0],
159 : : Anum_pg_database_oid,
160 : : BTEqualStrategyNumber, F_OIDEQ,
161 : : ObjectIdGetDatum(dboid));
162 : :
163 : : /*
164 : : * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
165 : : * built the critical shared relcache entries (i.e., we're starting up
166 : : * without a shared relcache cache file).
167 : : */
2472 andres@anarazel.de 168 : 13631 : relation = table_open(DatabaseRelationId, AccessShareLock);
5921 tgl@sss.pgh.pa.us 169 : 13631 : scan = systable_beginscan(relation, DatabaseOidIndexId,
170 : : criticalSharedRelcachesBuilt,
171 : : NULL,
172 : : 1, key);
173 : :
174 : 13631 : tuple = systable_getnext(scan);
175 : :
176 : : /* Must copy tuple before releasing buffer */
177 [ + - ]: 13631 : if (HeapTupleIsValid(tuple))
178 : 13631 : tuple = heap_copytuple(tuple);
179 : :
180 : : /* all done */
181 : 13631 : systable_endscan(scan);
2472 andres@anarazel.de 182 : 13631 : table_close(relation, AccessShareLock);
183 : :
5921 tgl@sss.pgh.pa.us 184 : 13631 : return tuple;
185 : : }
186 : :
187 : :
188 : : /*
189 : : * PerformAuthentication -- authenticate a remote client
190 : : *
191 : : * returns: nothing. Will not return at all if there's any failure.
192 : : */
193 : : static void
5904 194 : 12251 : PerformAuthentication(Port *port)
195 : : {
196 : : /* This should be set already, but let's make sure */
197 : 12251 : ClientAuthInProgress = true; /* limit visibility of log messages */
198 : :
199 : : /*
200 : : * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
201 : : * etcetera from the postmaster, and have to load them ourselves.
202 : : *
203 : : * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
204 : : */
205 : : #ifdef EXEC_BACKEND
206 : :
207 : : /*
208 : : * load_hba() and load_ident() want to work within the PostmasterContext,
209 : : * so create that if it doesn't exist (which it won't). We'll delete it
210 : : * again later, in PostgresMain.
211 : : */
212 : : if (PostmasterContext == NULL)
213 : : PostmasterContext = AllocSetContextCreate(TopMemoryContext,
214 : : "Postmaster",
215 : : ALLOCSET_DEFAULT_SIZES);
216 : :
217 : : if (!load_hba())
218 : : {
219 : : /*
220 : : * It makes no sense to continue if we fail to load the HBA file,
221 : : * since there is no way to connect to the database in this case.
222 : : */
223 : : ereport(FATAL,
224 : : /* translator: %s is a configuration file */
225 : : (errmsg("could not load %s", HbaFileName)));
226 : : }
227 : :
228 : : if (!load_ident())
229 : : {
230 : : /*
231 : : * It is ok to continue if we fail to load the IDENT file, although it
232 : : * means that you cannot log in using any of the authentication
233 : : * methods that need a user name mapping. load_ident() already logged
234 : : * the details of error to the log.
235 : : */
236 : : }
237 : : #endif
238 : :
239 : : /* Capture authentication start time for logging */
230 melanieplageman@gmai 240 : 12251 : conn_timing.auth_start = GetCurrentTimestamp();
241 : :
242 : : /*
243 : : * Set up a timeout in case a buggy or malicious client fails to respond
244 : : * during authentication. Since we're inside a transaction and might do
245 : : * database access, we have to use the statement_timeout infrastructure.
246 : : */
4852 alvherre@alvh.no-ip. 247 : 12251 : enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
248 : :
249 : : /*
250 : : * Now perform authentication exchange.
251 : : */
2057 peter@eisentraut.org 252 : 12251 : set_ps_display("authentication");
5904 tgl@sss.pgh.pa.us 253 : 12251 : ClientAuthentication(port); /* might not return, if failure */
254 : :
255 : : /*
256 : : * Done with authentication. Disable the timeout, and log if needed.
257 : : */
4852 alvherre@alvh.no-ip. 258 : 12069 : disable_timeout(STATEMENT_TIMEOUT, false);
259 : :
260 : : /* Capture authentication end time for logging */
230 melanieplageman@gmai 261 : 12069 : conn_timing.auth_end = GetCurrentTimestamp();
262 : :
263 [ + + ]: 12069 : if (log_connections & LOG_CONNECTION_AUTHORIZATION)
264 : : {
265 : : StringInfoData logmsg;
266 : :
1791 sfrost@snowman.net 267 : 360 : initStringInfo(&logmsg);
5397 magnus@hagander.net 268 [ - + ]: 360 : if (am_walsender)
1791 sfrost@snowman.net 269 :UBC 0 : appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
270 : : port->user_name);
271 : : else
1791 sfrost@snowman.net 272 :CBC 360 : appendStringInfo(&logmsg, _("connection authorized: user=%s"),
273 : : port->user_name);
274 [ + - ]: 360 : if (!am_walsender)
275 : 360 : appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
276 : :
277 [ + + ]: 360 : if (port->application_name != NULL)
278 : 357 : appendStringInfo(&logmsg, _(" application_name=%s"),
279 : : port->application_name);
280 : :
281 : : #ifdef USE_SSL
282 [ + + ]: 360 : if (port->ssl_in_use)
1694 michael@paquier.xyz 283 : 104 : appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
284 : : be_tls_get_version(port),
285 : : be_tls_get_cipher(port),
286 : : be_tls_get_cipher_bits(port));
287 : : #endif
288 : : #ifdef ENABLE_GSS
1765 tgl@sss.pgh.pa.us 289 [ + + ]: 360 : if (port->gss)
290 : : {
291 : 90 : const char *princ = be_gssapi_get_princ(port);
292 : :
293 [ + + ]: 90 : if (princ)
294 [ + + + + : 117 : appendStringInfo(&logmsg,
+ - ]
891 295 : 39 : _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
1765 296 : 78 : be_gssapi_get_auth(port) ? _("yes") : _("no"),
297 : 78 : be_gssapi_get_enc(port) ? _("yes") : _("no"),
892 bruce@momjian.us 298 : 78 : be_gssapi_get_delegation(port) ? _("yes") : _("no"),
299 : : princ);
300 : : else
1765 tgl@sss.pgh.pa.us 301 [ - + + - : 153 : appendStringInfo(&logmsg,
- + ]
891 302 : 51 : _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
1765 303 : 102 : be_gssapi_get_auth(port) ? _("yes") : _("no"),
929 sfrost@snowman.net 304 : 102 : be_gssapi_get_enc(port) ? _("yes") : _("no"),
892 bruce@momjian.us 305 : 102 : be_gssapi_get_delegation(port) ? _("yes") : _("no"));
306 : : }
307 : : #endif
308 : :
1791 sfrost@snowman.net 309 [ + - ]: 360 : ereport(LOG, errmsg_internal("%s", logmsg.data));
310 : 360 : pfree(logmsg.data);
311 : : }
312 : :
2057 peter@eisentraut.org 313 : 12069 : set_ps_display("startup");
314 : :
3051 tgl@sss.pgh.pa.us 315 : 12069 : ClientAuthInProgress = false; /* client_min_messages is active now */
5904 316 : 12069 : }
317 : :
318 : :
319 : : /*
320 : : * CheckMyDatabase -- fetch information from the pg_database entry for our DB
321 : : */
322 : : static void
2763 magnus@hagander.net 323 : 13624 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
324 : : {
325 : : HeapTuple tup;
326 : : Form_pg_database dbform;
327 : : Datum datum;
328 : : bool isnull;
329 : : char *collate;
330 : : char *ctype;
331 : :
332 : : /* Fetch our pg_database row normally, via syscache */
5735 rhaas@postgresql.org 333 : 13624 : tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
7117 tgl@sss.pgh.pa.us 334 [ - + ]: 13624 : if (!HeapTupleIsValid(tup))
7117 tgl@sss.pgh.pa.us 335 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
7117 tgl@sss.pgh.pa.us 336 :CBC 13624 : dbform = (Form_pg_database) GETSTRUCT(tup);
337 : :
338 : : /* This recheck is strictly paranoia */
339 [ - + ]: 13624 : if (strcmp(name, NameStr(dbform->datname)) != 0)
8131 tgl@sss.pgh.pa.us 340 [ # # ]:UBC 0 : ereport(FATAL,
341 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
342 : : errmsg("database \"%s\" has disappeared from pg_database",
343 : : name),
344 : : errdetail("Database OID %u now seems to belong to \"%s\".",
345 : : MyDatabaseId, NameStr(dbform->datname))));
346 : :
347 : : /*
348 : : * Check permissions to connect to the database.
349 : : *
350 : : * These checks are not enforced when in standalone mode, so that there is
351 : : * a way to recover from disabling all access to all databases, for
352 : : * example "UPDATE pg_database SET datallowconn = false;".
353 : : */
304 tgl@sss.pgh.pa.us 354 [ + + ]:CBC 13624 : if (IsUnderPostmaster)
355 : : {
356 : : /*
357 : : * Check that the database is currently allowing connections.
358 : : * (Background processes can override this test and the next one by
359 : : * setting override_allow_connections.)
360 : : */
2763 magnus@hagander.net 361 [ + + + + ]: 13555 : if (!dbform->datallowconn && !override_allow_connections)
7394 tgl@sss.pgh.pa.us 362 [ + - ]: 1 : ereport(FATAL,
363 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
364 : : errmsg("database \"%s\" is not currently accepting connections",
365 : : name)));
366 : :
367 : : /*
368 : : * Check privilege to connect to the database. (The am_superuser test
369 : : * is redundant, but since we have the flag, might as well check it
370 : : * and save a few cycles.)
371 : : */
304 372 [ + + + + : 13953 : if (!am_superuser && !override_allow_connections &&
- + ]
1080 peter@eisentraut.org 373 : 399 : object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
374 : : ACL_CONNECT) != ACLCHECK_OK)
7121 tgl@sss.pgh.pa.us 375 [ # # ]:UBC 0 : ereport(FATAL,
376 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
377 : : errmsg("permission denied for database \"%s\"", name),
378 : : errdetail("User does not have CONNECT privilege.")));
379 : :
380 : : /*
381 : : * Check connection limit for this database. We enforce the limit
382 : : * only for regular backends, since other process types have their own
383 : : * PGPROC pools.
384 : : *
385 : : * There is a race condition here --- we create our PGPROC before
386 : : * checking for other PGPROCs. If two backends did this at about the
387 : : * same time, they might both think they were over the limit, while
388 : : * ideally one should succeed and one fail. Getting that to work
389 : : * exactly seems more trouble than it is worth, however; instead we
390 : : * just document that the connection limit is approximate.
391 : : */
7394 tgl@sss.pgh.pa.us 392 [ - + ]:CBC 13554 : if (dbform->datconnlimit >= 0 &&
304 tgl@sss.pgh.pa.us 393 [ # # ]:UBC 0 : AmRegularBackendProcess() &&
7121 394 [ # # ]: 0 : !am_superuser &&
3191 andrew@dunslane.net 395 [ # # ]: 0 : CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
7394 tgl@sss.pgh.pa.us 396 [ # # ]: 0 : ereport(FATAL,
397 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
398 : : errmsg("too many connections for database \"%s\"",
399 : : name)));
400 : : }
401 : :
402 : : /*
403 : : * OK, we're golden. Next to-do item is to save the encoding info out of
404 : : * the pg_database tuple.
405 : : */
9114 tgl@sss.pgh.pa.us 406 :CBC 13623 : SetDatabaseEncoding(dbform->encoding);
407 : : /* Record it as a GUC internal option, too */
8222 408 : 13623 : SetConfigOption("server_encoding", GetDatabaseEncodingName(),
409 : : PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
410 : : /* If we have no other source of client_encoding, use server encoding */
8565 411 : 13623 : SetConfigOption("client_encoding", GetDatabaseEncodingName(),
412 : : PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
413 : :
414 : : /* assign locale variables */
948 dgustafsson@postgres 415 : 13623 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
1370 peter@eisentraut.org 416 : 13623 : collate = TextDatumGetCString(datum);
948 dgustafsson@postgres 417 : 13623 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
1370 peter@eisentraut.org 418 : 13623 : ctype = TextDatumGetCString(datum);
419 : :
420 : : /*
421 : : * Historcally, we set LC_COLLATE from datcollate, as well. That's no
422 : : * longer necessary because all collation behavior is handled through
423 : : * pg_locale_t.
424 : : */
425 : :
5956 heikki.linnakangas@i 426 [ - + ]: 13623 : if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
5983 bruce@momjian.us 427 [ # # ]:UBC 0 : ereport(FATAL,
428 : : (errmsg("database locale is incompatible with operating system"),
429 : : errdetail("The database was initialized with LC_CTYPE \"%s\", "
430 : : " which is not recognized by setlocale().", ctype),
431 : : errhint("Recreate the database with another locale or install the missing locale.")));
432 : :
457 jdavis@postgresql.or 433 :CBC 13623 : init_database_collation();
434 : :
435 : : /*
436 : : * Check collation version. See similar code in
437 : : * pg_newlocale_from_collation(). Note that here we warn instead of error
438 : : * in any case, so that we don't prevent connecting.
439 : : */
1352 peter@eisentraut.org 440 : 13621 : datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
441 : : &isnull);
442 [ + + ]: 13621 : if (!isnull)
443 : : {
444 : : char *actual_versionstr;
445 : : char *collversionstr;
446 : : char *locale;
447 : :
448 : 877 : collversionstr = TextDatumGetCString(datum);
449 : :
594 jdavis@postgresql.or 450 [ - + ]: 877 : if (dbform->datlocprovider == COLLPROVIDER_LIBC)
594 jdavis@postgresql.or 451 :UBC 0 : locale = collate;
452 : : else
453 : : {
457 jdavis@postgresql.or 454 :CBC 877 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
455 : 877 : locale = TextDatumGetCString(datum);
456 : : }
457 : :
594 458 : 877 : actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
1352 peter@eisentraut.org 459 [ - + ]: 877 : if (!actual_versionstr)
460 : : /* should not happen */
1147 alvherre@alvh.no-ip. 461 [ # # ]:UBC 0 : elog(WARNING,
462 : : "database \"%s\" has no actual collation version, but a version was recorded",
463 : : name);
1345 peter@eisentraut.org 464 [ - + ]:CBC 877 : else if (strcmp(actual_versionstr, collversionstr) != 0)
1352 peter@eisentraut.org 465 [ # # ]:UBC 0 : ereport(WARNING,
466 : : (errmsg("database \"%s\" has a collation version mismatch",
467 : : name),
468 : : errdetail("The database was created using collation version %s, "
469 : : "but the operating system provides version %s.",
470 : : collversionstr, actual_versionstr),
471 : : errhint("Rebuild all objects in this database that use the default collation and run "
472 : : "ALTER DATABASE %s REFRESH COLLATION VERSION, "
473 : : "or build PostgreSQL with the right library version.",
474 : : quote_identifier(name))));
475 : : }
476 : :
7117 tgl@sss.pgh.pa.us 477 :CBC 13621 : ReleaseSysCache(tup);
9531 478 : 13621 : }
479 : :
480 : :
481 : : /*
482 : : * pg_split_opts -- split a string of options and append it to an argv array
483 : : *
484 : : * The caller is responsible for ensuring the argv array is large enough. The
485 : : * maximum possible number of arguments added by this routine is
486 : : * (strlen(optstr) + 1) / 2.
487 : : *
488 : : * Because some option values can contain spaces we allow escaping using
489 : : * backslashes, with \\ representing a literal backslash.
490 : : */
491 : : void
3774 492 : 3555 : pg_split_opts(char **argv, int *argcp, const char *optstr)
493 : : {
494 : : StringInfoData s;
495 : :
4079 andres@anarazel.de 496 : 3555 : initStringInfo(&s);
497 : :
5904 tgl@sss.pgh.pa.us 498 [ + + ]: 13151 : while (*optstr)
499 : : {
4063 500 : 9596 : bool last_was_escape = false;
501 : :
4079 andres@anarazel.de 502 : 9596 : resetStringInfo(&s);
503 : :
504 : : /* skip over leading space */
5904 tgl@sss.pgh.pa.us 505 [ + + ]: 17694 : while (isspace((unsigned char) *optstr))
506 : 8098 : optstr++;
507 : :
508 [ - + ]: 9596 : if (*optstr == '\0')
5904 tgl@sss.pgh.pa.us 509 :UBC 0 : break;
510 : :
511 : : /*
512 : : * Parse a single option, stopping at the first space, unless it's
513 : : * escaped.
514 : : */
4079 andres@anarazel.de 515 [ + + ]:CBC 145784 : while (*optstr)
516 : : {
4075 tgl@sss.pgh.pa.us 517 [ + + + + ]: 142229 : if (isspace((unsigned char) *optstr) && !last_was_escape)
4079 andres@anarazel.de 518 : 6041 : break;
519 : :
520 [ + + + + ]: 136188 : if (!last_was_escape && *optstr == '\\')
521 : 16 : last_was_escape = true;
522 : : else
523 : : {
524 : 136172 : last_was_escape = false;
525 : 136172 : appendStringInfoChar(&s, *optstr);
526 : : }
527 : :
5904 tgl@sss.pgh.pa.us 528 : 136188 : optstr++;
529 : : }
530 : :
531 : : /* now store the option in the next argv[] position */
4079 andres@anarazel.de 532 : 9596 : argv[(*argcp)++] = pstrdup(s.data);
533 : : }
534 : :
3774 tgl@sss.pgh.pa.us 535 : 3555 : pfree(s.data);
5904 536 : 3555 : }
537 : :
538 : : /*
539 : : * Initialize MaxBackends value from config options.
540 : : *
541 : : * This must be called after modules have had the chance to alter GUCs in
542 : : * shared_preload_libraries and before shared memory size is determined.
543 : : *
544 : : * Note that in EXEC_BACKEND environment, the value is passed down from
545 : : * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
546 : : * postmaster itself and processes not under postmaster control should call
547 : : * this.
548 : : */
549 : : void
4682 alvherre@alvh.no-ip. 550 : 1048 : InitializeMaxBackends(void)
551 : : {
1295 rhaas@postgresql.org 552 [ - + ]: 1048 : Assert(MaxBackends == 0);
553 : :
554 : : /* Note that this does not include "auxiliary" processes */
295 nathan@postgresql.or 555 : 1048 : MaxBackends = MaxConnections + autovacuum_worker_slots +
304 tgl@sss.pgh.pa.us 556 : 1048 : max_worker_processes + max_wal_senders + NUM_SPECIAL_WORKER_PROCS;
557 : :
1295 rhaas@postgresql.org 558 [ - + ]: 1048 : if (MaxBackends > MAX_BACKENDS)
480 nathan@postgresql.or 559 [ # # ]:UBC 0 : ereport(ERROR,
560 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
561 : : errmsg("too many server processes configured"),
562 : : errdetail("\"max_connections\" (%d) plus \"autovacuum_worker_slots\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
563 : : MaxConnections, autovacuum_worker_slots,
564 : : max_worker_processes, max_wal_senders,
565 : : MAX_BACKENDS - (NUM_SPECIAL_WORKER_PROCS - 1))));
1141 tgl@sss.pgh.pa.us 566 :CBC 1048 : }
567 : :
568 : : /*
569 : : * Initialize the number of fast-path lock slots in PGPROC.
570 : : *
571 : : * This must be called after modules have had the chance to alter GUCs in
572 : : * shared_preload_libraries and before shared memory size is determined.
573 : : */
574 : : void
402 tomas.vondra@postgre 575 : 1048 : InitializeFastPathLocks(void)
576 : : {
577 : : /* Should be initialized only once. */
578 [ - + ]: 1048 : Assert(FastPathLockGroupsPerBackend == 0);
579 : :
580 : : /*
581 : : * Based on the max_locks_per_transaction GUC, as that's a good indicator
582 : : * of the expected number of locks, figure out the value for
583 : : * FastPathLockGroupsPerBackend. This must be a power-of-two. We cap the
584 : : * value at FP_LOCK_GROUPS_PER_BACKEND_MAX and insist the value is at
585 : : * least 1.
586 : : *
587 : : * The default max_locks_per_transaction = 64 means 4 groups by default.
588 : : */
184 drowley@postgresql.o 589 : 1048 : FastPathLockGroupsPerBackend =
590 [ + - + - : 1048 : Max(Min(pg_nextpower2_32(max_locks_per_xact) / FP_LOCK_SLOTS_PER_GROUP,
+ - ]
591 : : FP_LOCK_GROUPS_PER_BACKEND_MAX), 1);
592 : :
593 : : /* Validate we did get a power-of-two */
594 [ - + ]: 1048 : Assert(FastPathLockGroupsPerBackend ==
595 : : pg_nextpower2_32(FastPathLockGroupsPerBackend));
402 tomas.vondra@postgre 596 : 1048 : }
597 : :
598 : : /*
599 : : * Early initialization of a backend (either standalone or under postmaster).
600 : : * This happens even before InitPostgres.
601 : : *
602 : : * This is separate from InitPostgres because it is also called by auxiliary
603 : : * processes, such as the background writer process, which may not call
604 : : * InitPostgres at all.
605 : : */
606 : : void
9080 tgl@sss.pgh.pa.us 607 : 19167 : BaseInit(void)
608 : : {
1545 andres@anarazel.de 609 [ - + ]: 19167 : Assert(MyProc != NULL);
610 : :
611 : : /*
612 : : * Initialize our input/output/debugging file descriptors.
613 : : */
9080 tgl@sss.pgh.pa.us 614 : 19167 : DebugFileOpen();
615 : :
616 : : /*
617 : : * Initialize file access. Done early so other subsystems can access
618 : : * files.
619 : : */
1543 andres@anarazel.de 620 : 19167 : InitFileAccess();
621 : :
622 : : /*
623 : : * Initialize statistics reporting. This needs to happen early to ensure
624 : : * that pgstat's shutdown callback runs after the shutdown callbacks of
625 : : * all subsystems that can produce stats (like e.g. transaction commits
626 : : * can).
627 : : */
1544 628 : 19167 : pgstat_initialize();
629 : :
630 : : /*
631 : : * Initialize AIO before infrastructure that might need to actually
632 : : * execute AIO.
633 : : */
225 634 : 19167 : pgaio_init_backend();
635 : :
636 : : /* Do local initialization of storage and buffer managers */
2399 tmunro@postgresql.or 637 : 19167 : InitSync();
9080 tgl@sss.pgh.pa.us 638 : 19167 : smgrinit();
425 heikki.linnakangas@i 639 : 19167 : InitBufferManagerAccess();
640 : :
641 : : /*
642 : : * Initialize temporary file access after pgstat, so that the temporary
643 : : * file shutdown hook can report temporary file statistics.
644 : : */
1543 andres@anarazel.de 645 : 19167 : InitTemporaryFileAccess();
646 : :
647 : : /*
648 : : * Initialize local buffers for WAL record construction, in case we ever
649 : : * try to insert XLOG.
650 : : */
1442 rhaas@postgresql.org 651 : 19167 : InitXLogInsert();
652 : :
653 : : /* Initialize lock manager's local structs */
425 heikki.linnakangas@i 654 : 19167 : InitLockManagerAccess();
655 : :
656 : : /*
657 : : * Initialize replication slots after pgstat. The exit hook might need to
658 : : * drop ephemeral slots, which in turn triggers stats reporting.
659 : : */
1352 andres@anarazel.de 660 : 19167 : ReplicationSlotInitialize();
9080 tgl@sss.pgh.pa.us 661 : 19167 : }
662 : :
663 : :
664 : : /* --------------------------------
665 : : * InitPostgres
666 : : * Initialize POSTGRES.
667 : : *
668 : : * Parameters:
669 : : * in_dbname, dboid: specify database to connect to, as described below
670 : : * username, useroid: specify role to connect as, as described below
671 : : * flags:
672 : : * - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
673 : : * - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
674 : : * - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
675 : : * out_dbname: optional output parameter, see below; pass NULL if not used
676 : : *
677 : : * The database can be specified by name, using the in_dbname parameter, or by
678 : : * OID, using the dboid parameter. Specify NULL or InvalidOid respectively
679 : : * for the unused parameter. If dboid is provided, the actual database
680 : : * name can be returned to the caller in out_dbname. If out_dbname isn't
681 : : * NULL, it must point to a buffer of size NAMEDATALEN.
682 : : *
683 : : * Similarly, the role can be passed by name, using the username parameter,
684 : : * or by OID using the useroid parameter.
685 : : *
686 : : * In bootstrap mode the database and username parameters are NULL/InvalidOid.
687 : : * The autovacuum launcher process doesn't specify these parameters either,
688 : : * because it only goes far enough to be able to read pg_database; it doesn't
689 : : * connect to any particular database. An autovacuum worker specifies a
690 : : * database but not a username; conversely, a physical walsender specifies
691 : : * username but not database.
692 : : *
693 : : * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
694 : : * "interactive" sessions (including standalone backends), but not in
695 : : * background processes such as autovacuum. Note in particular that it
696 : : * shouldn't be true in parallel worker processes; those have another
697 : : * mechanism for replicating their leader's set of loaded libraries.
698 : : *
699 : : * We expect that InitProcess() was already called, so we already have a
700 : : * PGPROC struct ... but it's not completely filled in yet.
701 : : *
702 : : * Note:
703 : : * Be very careful with the order of calls in the InitPostgres function.
704 : : * --------------------------------
705 : : */
706 : : void
1191 707 : 15110 : InitPostgres(const char *in_dbname, Oid dboid,
708 : : const char *username, Oid useroid,
709 : : bits32 flags,
710 : : char *out_dbname)
711 : : {
9420 peter_e@gmx.net 712 : 15110 : bool bootstrap = IsBootstrapProcessingMode();
713 : : bool am_superuser;
714 : : char *fullpath;
715 : : char dbname[NAMEDATALEN];
1012 rhaas@postgresql.org 716 : 15110 : int nfree = 0;
717 : :
5904 tgl@sss.pgh.pa.us 718 [ + + ]: 15110 : elog(DEBUG3, "InitPostgres");
719 : :
720 : : /*
721 : : * Add my PGPROC struct to the ProcArray.
722 : : *
723 : : * Once I have done this, I am visible to other backends!
724 : : */
7237 725 : 15110 : InitProcessPhase2();
726 : :
727 : : /* Initialize status reporting */
238 michael@paquier.xyz 728 : 15110 : pgstat_beinit();
729 : :
730 : : /*
731 : : * And initialize an entry in the PgBackendStatus array. That way, if
732 : : * LWLocks or third-party authentication should happen to hang, it is
733 : : * possible to retrieve some information about what is going on.
734 : : */
735 [ + + ]: 15110 : if (!bootstrap)
736 : : {
737 : 15060 : pgstat_bestart_initial();
738 : : INJECTION_POINT("init-pre-auth", NULL);
739 : : }
740 : :
741 : : /*
742 : : * Initialize my entry in the shared-invalidation manager's array of
743 : : * per-backend data.
744 : : */
5792 simon@2ndQuadrant.co 745 : 15110 : SharedInvalBackendInit(false);
746 : :
209 heikki.linnakangas@i 747 : 15110 : ProcSignalInit(MyCancelKey, MyCancelKeyLength);
748 : :
749 : : /*
750 : : * Also set up timeout handlers needed for backend operation. We need
751 : : * these in every case except bootstrap.
752 : : */
4852 alvherre@alvh.no-ip. 753 [ + + ]: 15110 : if (!bootstrap)
754 : : {
3920 andres@anarazel.de 755 : 15060 : RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
4852 alvherre@alvh.no-ip. 756 : 15060 : RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
4609 tgl@sss.pgh.pa.us 757 : 15060 : RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
3513 rhaas@postgresql.org 758 : 15060 : RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
759 : : IdleInTransactionSessionTimeoutHandler);
621 akorotkov@postgresql 760 : 15060 : RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
1756 tgl@sss.pgh.pa.us 761 : 15060 : RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
1669 tmunro@postgresql.or 762 : 15060 : RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
1301 andres@anarazel.de 763 : 15060 : RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
764 : : IdleStatsUpdateTimeoutHandler);
765 : : }
766 : :
767 : : /*
768 : : * If this is either a bootstrap process or a standalone backend, start up
769 : : * the XLOG machinery, and register to have it closed down at exit. In
770 : : * other cases, the startup process is responsible for starting up the
771 : : * XLOG machinery, and the checkpointer for closing it down.
772 : : */
1415 rhaas@postgresql.org 773 [ + + ]: 15110 : if (!IsUnderPostmaster)
774 : : {
775 : : /*
776 : : * We don't yet have an aux-process resource owner, but StartupXLOG
777 : : * and ShutdownXLOG will need one. Hence, create said resource owner
778 : : * (and register a callback to clean it up after ShutdownXLOG runs).
779 : : */
2659 tgl@sss.pgh.pa.us 780 : 119 : CreateAuxProcessResourceOwner();
781 : :
5670 782 : 119 : StartupXLOG();
783 : : /* Release (and warn about) any buffer pins leaked in StartupXLOG */
2659 784 : 119 : ReleaseAuxProcessResources(true);
785 : : /* Reset CurrentResourceOwner to nothing for the moment */
786 : 119 : CurrentResourceOwner = NULL;
787 : :
788 : : /*
789 : : * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
790 : : * segments etc to work (which in turn is required for pgstats).
791 : : */
1301 andres@anarazel.de 792 : 119 : before_shmem_exit(pgstat_before_server_shutdown, 0);
1677 793 : 119 : before_shmem_exit(ShutdownXLOG, 0);
794 : : }
795 : :
796 : : /*
797 : : * Initialize the relation cache and the system catalog caches. Note that
798 : : * no catalog access happens here; we only set up the hashtable structure.
799 : : * We must do this before starting a transaction because transaction abort
800 : : * would try to touch these hashtables.
801 : : */
8830 tgl@sss.pgh.pa.us 802 : 15110 : RelationCacheInitialize();
10278 bruce@momjian.us 803 : 15110 : InitCatalogCache();
6804 tgl@sss.pgh.pa.us 804 : 15110 : InitPlanCache();
805 : :
806 : : /* Initialize portal manager */
8900 807 : 15110 : EnablePortalManager();
808 : :
809 : : /*
810 : : * Load relcache entries for the shared system catalogs. This must create
811 : : * at least entries for pg_database and catalogs used for authentication.
812 : : */
5902 813 : 15110 : RelationCacheInitializePhase2();
814 : :
815 : : /*
816 : : * Set up process-exit callback to do pre-shutdown cleanup. This is the
817 : : * one of the first before_shmem_exit callbacks we register; thus, this
818 : : * will be one the last things we do before low-level modules like the
819 : : * buffer manager begin to close down. We need to have this in place
820 : : * before we begin our first transaction --- if we fail during the
821 : : * initialization transaction, as is entirely possible, we need the
822 : : * AbortTransaction call to clean up.
823 : : */
4332 rhaas@postgresql.org 824 : 15110 : before_shmem_exit(ShutdownPostgres, 0);
825 : :
826 : : /* The autovacuum launcher is done here */
603 heikki.linnakangas@i 827 [ + + ]: 15110 : if (AmAutoVacuumLauncherProcess())
828 : : {
829 : : /* fill in the remainder of this entry in the PgBackendStatus array */
238 michael@paquier.xyz 830 : 375 : pgstat_bestart_final();
831 : :
5901 tgl@sss.pgh.pa.us 832 : 1234 : return;
833 : : }
834 : :
835 : : /*
836 : : * Start a new transaction here before first access to db.
837 : : */
9442 inoue@tpf.co.jp 838 [ + + ]: 14735 : if (!bootstrap)
839 : : {
840 : : /* statement_timestamp must be set for timeouts to work correctly */
5190 tgl@sss.pgh.pa.us 841 : 14685 : SetCurrentStatementStartTimestamp();
8203 842 : 14685 : StartTransactionCommand();
843 : :
844 : : /*
845 : : * transaction_isolation will have been set to the default by the
846 : : * above. If the default is "serializable", and we are in hot
847 : : * standby, we will fail if we don't change it to something lower.
848 : : * Fortunately, "read committed" is plenty good enough.
849 : : */
4813 850 : 14685 : XactIsoLevel = XACT_READ_COMMITTED;
851 : : }
852 : :
853 : : /*
854 : : * Perform client authentication if necessary, then figure out our
855 : : * postgres user ID, and see if we are a superuser.
856 : : *
857 : : * In standalone mode, autovacuum worker processes and slot sync worker
858 : : * process, we use a fixed ID, otherwise we figure it out from the
859 : : * authenticated user name.
860 : : */
603 heikki.linnakangas@i 861 [ + + + + : 14735 : if (bootstrap || AmAutoVacuumWorkerProcess() || AmLogicalSlotSyncWorkerProcess())
+ + ]
862 : : {
5670 tgl@sss.pgh.pa.us 863 : 88 : InitializeSessionUserIdStandalone();
864 : 88 : am_superuser = true;
865 : : }
866 [ + + ]: 14647 : else if (!IsUnderPostmaster)
867 : : {
868 : 69 : InitializeSessionUserIdStandalone();
869 : 69 : am_superuser = true;
870 [ - + ]: 69 : if (!ThereIsAtLeastOneRole())
5670 tgl@sss.pgh.pa.us 871 [ # # # # ]:UBC 0 : ereport(WARNING,
872 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
873 : : errmsg("no roles are defined in this database system"),
874 : : errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
875 : : username != NULL ? username : "postgres")));
876 : : }
603 heikki.linnakangas@i 877 [ + + ]:CBC 14578 : else if (AmBackgroundWorkerProcess())
878 : : {
3921 rhaas@postgresql.org 879 [ + - + + ]: 2327 : if (username == NULL && !OidIsValid(useroid))
880 : : {
4709 alvherre@alvh.no-ip. 881 : 407 : InitializeSessionUserIdStandalone();
882 : 407 : am_superuser = true;
883 : : }
884 : : else
885 : : {
747 michael@paquier.xyz 886 : 1920 : InitializeSessionUserId(username, useroid,
887 : 1920 : (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
304 tgl@sss.pgh.pa.us 888 : 1918 : am_superuser = superuser();
889 : : }
890 : : }
891 : : else
892 : : {
893 : : /* normal multiuser case */
5670 894 [ - + ]: 12251 : Assert(MyProcPort != NULL);
895 : 12251 : PerformAuthentication(MyProcPort);
747 michael@paquier.xyz 896 : 12069 : InitializeSessionUserId(username, useroid, false);
897 : : /* ensure that auth_method is actually valid, aka authn_id is not NULL */
1125 898 [ + + ]: 12065 : if (MyClientConnectionInfo.authn_id)
899 : 176 : InitializeSystemUser(MyClientConnectionInfo.authn_id,
900 : : hba_authname(MyClientConnectionInfo.auth_method));
5670 tgl@sss.pgh.pa.us 901 : 12065 : am_superuser = superuser();
902 : : }
903 : :
904 : : /* Report any SSL/GSS details for the session. */
238 michael@paquier.xyz 905 [ + + ]: 14547 : if (MyProcPort != NULL)
906 : : {
907 [ - + ]: 12065 : Assert(!bootstrap);
908 : :
909 : 12065 : pgstat_bestart_security();
910 : : }
911 : :
912 : : /*
913 : : * Binary upgrades only allowed super-user connections
914 : : */
5300 bruce@momjian.us 915 [ + + - + ]: 14547 : if (IsBinaryUpgrade && !am_superuser)
916 : : {
5255 bruce@momjian.us 917 [ # # ]:UBC 0 : ereport(FATAL,
918 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
919 : : errmsg("must be superuser to connect in binary upgrade mode")));
920 : : }
921 : :
922 : : /*
923 : : * The last few regular connection slots are reserved for superusers and
924 : : * roles with privileges of pg_use_reserved_connections. We do not apply
925 : : * these limits to background processes, since they all have their own
926 : : * pools of PGPROC slots.
927 : : *
928 : : * Note: At this point, the new backend has already claimed a proc struct,
929 : : * so we must check whether the number of free slots is strictly less than
930 : : * the reserved connection limits.
931 : : */
304 tgl@sss.pgh.pa.us 932 [ + + + + ]:CBC 14547 : if (AmRegularBackendProcess() && !am_superuser &&
1012 rhaas@postgresql.org 933 [ + - ]: 367 : (SuperuserReservedConnections + ReservedConnections) > 0 &&
934 [ + + ]: 367 : !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
935 : : {
936 [ + + ]: 4 : if (nfree < SuperuserReservedConnections)
937 [ + - ]: 1 : ereport(FATAL,
938 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
939 : : errmsg("remaining connection slots are reserved for roles with the %s attribute",
940 : : "SUPERUSER")));
941 : :
942 [ + + ]: 3 : if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
943 [ + - ]: 1 : ereport(FATAL,
944 : : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
945 : : errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
946 : : "pg_use_reserved_connections")));
947 : : }
948 : :
949 : : /* Check replication permissions needed for walsender processes. */
5670 tgl@sss.pgh.pa.us 950 [ + + ]: 14545 : if (am_walsender)
951 : : {
952 [ - + ]: 1111 : Assert(!bootstrap);
953 : :
957 peter@eisentraut.org 954 [ - + ]: 1111 : if (!has_rolreplication(GetUserId()))
5669 tgl@sss.pgh.pa.us 955 [ # # ]:UBC 0 : ereport(FATAL,
956 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
957 : : errmsg("permission denied to start WAL sender"),
958 : : errdetail("Only roles with the %s attribute may start a WAL sender process.",
959 : : "REPLICATION")));
960 : : }
961 : :
962 : : /*
963 : : * If this is a plain walsender only supporting physical replication, we
964 : : * don't want to connect to any particular database. Just finish the
965 : : * backend startup by processing any options from the startup packet, and
966 : : * we're done.
967 : : */
4250 rhaas@postgresql.org 968 [ + + + + ]:CBC 14545 : if (am_walsender && !am_db_walsender)
969 : : {
970 : : /* process any options passed in the startup packet */
5524 heikki.linnakangas@i 971 [ + - ]: 454 : if (MyProcPort != NULL)
972 : 454 : process_startup_options(MyProcPort, am_superuser);
973 : :
974 : : /* Apply PostAuthDelay as soon as we've read all options */
975 [ - + ]: 454 : if (PostAuthDelay > 0)
5524 heikki.linnakangas@i 976 :UBC 0 : pg_usleep(PostAuthDelay * 1000000L);
977 : :
978 : : /* initialize client encoding */
5524 heikki.linnakangas@i 979 :CBC 454 : InitializeClientEncoding();
980 : :
981 : : /* fill in the remainder of this entry in the PgBackendStatus array */
238 michael@paquier.xyz 982 : 454 : pgstat_bestart_final();
983 : :
984 : : /* close the transaction we started above */
5670 tgl@sss.pgh.pa.us 985 : 454 : CommitTransactionCommand();
986 : :
987 : 454 : return;
988 : : }
989 : :
990 : : /*
991 : : * Set up the global variables holding database id and default tablespace.
992 : : * But note we won't actually try to touch the database just yet.
993 : : *
994 : : * We take a shortcut in the bootstrap case, otherwise we have to look up
995 : : * the db's entry in pg_database.
996 : : */
997 [ + + ]: 14091 : if (bootstrap)
998 : : {
785 michael@paquier.xyz 999 : 50 : dboid = Template1DbOid;
5921 tgl@sss.pgh.pa.us 1000 : 50 : MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
1001 : : }
1002 [ + + ]: 14041 : else if (in_dbname != NULL)
1003 : : {
1004 : : HeapTuple tuple;
1005 : : Form_pg_database dbform;
1006 : :
1007 : 11682 : tuple = GetDatabaseTuple(in_dbname);
1008 [ + + ]: 11682 : if (!HeapTupleIsValid(tuple))
1009 [ + - ]: 5 : ereport(FATAL,
1010 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1011 : : errmsg("database \"%s\" does not exist", in_dbname)));
1012 : 11677 : dbform = (Form_pg_database) GETSTRUCT(tuple);
785 michael@paquier.xyz 1013 : 11677 : dboid = dbform->oid;
1014 : : }
1015 [ + + ]: 2359 : else if (!OidIsValid(dboid))
1016 : : {
1017 : : /*
1018 : : * If this is a background worker not bound to any particular
1019 : : * database, we're done now. Everything that follows only makes sense
1020 : : * if we are bound to a specific database. We do need to close the
1021 : : * transaction we started before returning.
1022 : : */
3778 rhaas@postgresql.org 1023 [ + - ]: 405 : if (!bootstrap)
1024 : : {
238 michael@paquier.xyz 1025 : 405 : pgstat_bestart_final();
3778 rhaas@postgresql.org 1026 : 405 : CommitTransactionCommand();
1027 : : }
1028 : 405 : return;
1029 : : }
1030 : :
1031 : : /*
1032 : : * Now, take a writer's lock on the database we are trying to connect to.
1033 : : * If there is a concurrently running DROP DATABASE on that database, this
1034 : : * will block us until it finishes (and has committed its update of
1035 : : * pg_database).
1036 : : *
1037 : : * Note that the lock is not held long, only until the end of this startup
1038 : : * transaction. This is OK since we will advertise our use of the
1039 : : * database in the ProcArray before dropping the lock (in fact, that's the
1040 : : * next thing to do). Anyone trying a DROP DATABASE after this point will
1041 : : * see us in the array once they have the lock. Ordering is important for
1042 : : * this because we don't want to advertise ourselves as being in this
1043 : : * database until we have the lock; otherwise we create what amounts to a
1044 : : * deadlock with CountOtherDBBackends().
1045 : : *
1046 : : * Note: use of RowExclusiveLock here is reasonable because we envision
1047 : : * our session as being a concurrent writer of the database. If we had a
1048 : : * way of declaring a session as being guaranteed-read-only, we could use
1049 : : * AccessShareLock for such sessions and thereby not conflict against
1050 : : * CREATE DATABASE.
1051 : : */
5670 tgl@sss.pgh.pa.us 1052 [ + + ]: 13681 : if (!bootstrap)
785 michael@paquier.xyz 1053 : 13631 : LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1054 : :
1055 : : /*
1056 : : * Recheck pg_database to make sure the target database hasn't gone away.
1057 : : * If there was a concurrent DROP DATABASE, this ensures we will die
1058 : : * cleanly without creating a mess.
1059 : : */
1060 [ + + ]: 13681 : if (!bootstrap)
1061 : : {
1062 : : HeapTuple tuple;
1063 : : Form_pg_database datform;
1064 : :
1065 : 13631 : tuple = GetDatabaseTupleByOid(dboid);
1066 [ + - ]: 13631 : if (HeapTupleIsValid(tuple))
1067 : 13631 : datform = (Form_pg_database) GETSTRUCT(tuple);
1068 : :
1069 [ + - + + ]: 13631 : if (!HeapTupleIsValid(tuple) ||
1070 [ - + ]: 11677 : (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1071 : : {
785 michael@paquier.xyz 1072 [ # # ]:UBC 0 : if (in_dbname)
1073 [ # # ]: 0 : ereport(FATAL,
1074 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1075 : : errmsg("database \"%s\" does not exist", in_dbname),
1076 : : errdetail("It seems to have just been dropped or renamed.")));
1077 : : else
1078 [ # # ]: 0 : ereport(FATAL,
1079 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1080 : : errmsg("database %u does not exist", dboid)));
1081 : : }
1082 : :
785 michael@paquier.xyz 1083 :CBC 13631 : strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1084 : :
1085 [ + + ]: 13631 : if (database_is_invalid_form(datform))
1086 : : {
1087 [ + - ]: 5 : ereport(FATAL,
1088 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1089 : : errmsg("cannot connect to invalid database \"%s\"", dbname),
1090 : : errhint("Use DROP DATABASE to drop invalid databases."));
1091 : : }
1092 : :
1093 : 13626 : MyDatabaseTableSpace = datform->dattablespace;
743 akorotkov@postgresql 1094 : 13626 : MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1095 : : /* pass the database name back to the caller */
785 michael@paquier.xyz 1096 [ + + ]: 13626 : if (out_dbname)
1097 : 34 : strcpy(out_dbname, dbname);
1098 : : }
1099 : :
1100 : : /*
1101 : : * Now that we rechecked, we are certain to be connected to a database and
1102 : : * thus can set MyDatabaseId.
1103 : : *
1104 : : * It is important that MyDatabaseId only be set once we are sure that the
1105 : : * target database can no longer be concurrently dropped or renamed. For
1106 : : * example, without this guarantee, pgstat_update_dbstats() could create
1107 : : * entries for databases that were just dropped in the pgstat shutdown
1108 : : * callback, which could confuse other code paths like the autovacuum
1109 : : * scheduler.
1110 : : */
1111 : 13676 : MyDatabaseId = dboid;
1112 : :
1113 : : /*
1114 : : * Now we can mark our PGPROC entry with the database ID.
1115 : : *
1116 : : * We assume this is an atomic store so no lock is needed; though actually
1117 : : * things would work fine even if it weren't atomic. Anyone searching the
1118 : : * ProcArray for this database's ID should hold the database lock, so they
1119 : : * would not be executing concurrently with this store. A process looking
1120 : : * for another database's ID could in theory see a chance match if it read
1121 : : * a partially-updated databaseId value; but as long as all such searches
1122 : : * wait and retry, as in CountOtherDBBackends(), they will certainly see
1123 : : * the correct value on their next try.
1124 : : */
3798 tgl@sss.pgh.pa.us 1125 : 13676 : MyProc->databaseId = MyDatabaseId;
1126 : :
1127 : : /*
1128 : : * We established a catalog snapshot while reading pg_authid and/or
1129 : : * pg_database; but until we have set up MyDatabaseId, we won't react to
1130 : : * incoming sinval messages for unshared catalogs, so we won't realize it
1131 : : * if the snapshot has been invalidated. Assume it's no good anymore.
1132 : : */
1133 : 13676 : InvalidateCatalogSnapshot();
1134 : :
1135 : : /*
1136 : : * Now we should be able to access the database directory safely. Verify
1137 : : * it's there and looks reasonable.
1138 : : */
5921 1139 : 13676 : fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
1140 : :
5670 1141 [ + + ]: 13676 : if (!bootstrap)
1142 : : {
7117 1143 [ - + ]: 13626 : if (access(fullpath, F_OK) == -1)
1144 : : {
7117 tgl@sss.pgh.pa.us 1145 [ # # ]:UBC 0 : if (errno == ENOENT)
1146 [ # # ]: 0 : ereport(FATAL,
1147 : : (errcode(ERRCODE_UNDEFINED_DATABASE),
1148 : : errmsg("database \"%s\" does not exist",
1149 : : dbname),
1150 : : errdetail("The database subdirectory \"%s\" is missing.",
1151 : : fullpath)));
1152 : : else
1153 [ # # ]: 0 : ereport(FATAL,
1154 : : (errcode_for_file_access(),
1155 : : errmsg("could not access directory \"%s\": %m",
1156 : : fullpath)));
1157 : : }
1158 : :
7117 tgl@sss.pgh.pa.us 1159 :CBC 13626 : ValidatePgVersion(fullpath);
1160 : : }
1161 : :
5921 1162 : 13676 : SetDatabasePath(fullpath);
1282 alvherre@alvh.no-ip. 1163 : 13676 : pfree(fullpath);
1164 : :
1165 : : /*
1166 : : * It's now possible to do real access to the system catalogs.
1167 : : *
1168 : : * Load relcache entries for the system catalogs. This must create at
1169 : : * least the minimum set of "nailed-in" cache entries.
1170 : : */
5921 tgl@sss.pgh.pa.us 1171 : 13676 : RelationCacheInitializePhase3();
1172 : :
1173 : : /* set up ACL framework (so CheckMyDatabase can check permissions) */
7121 1174 : 13674 : initialize_acl();
1175 : :
1176 : : /*
1177 : : * Re-read the pg_database row for our database, check permissions and set
1178 : : * up database-specific GUC settings. We can't do this until all the
1179 : : * database-access infrastructure is up. (Also, it wants to know if the
1180 : : * user is a superuser, so the above stuff has to happen first.)
1181 : : */
5670 1182 [ + + ]: 13674 : if (!bootstrap)
748 michael@paquier.xyz 1183 : 13624 : CheckMyDatabase(dbname, am_superuser,
1184 : 13624 : (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1185 : :
1186 : : /*
1187 : : * Now process any command-line switches and any additional GUC variable
1188 : : * settings passed in the startup packet. We couldn't do this before
1189 : : * because we didn't know if client is a superuser.
1190 : : */
5524 heikki.linnakangas@i 1191 [ + + ]: 13671 : if (MyProcPort != NULL)
1192 : 11599 : process_startup_options(MyProcPort, am_superuser);
1193 : :
1194 : : /* Process pg_db_role_setting options */
1195 : 13671 : process_settings(MyDatabaseId, GetSessionUserId());
1196 : :
1197 : : /* Apply PostAuthDelay as soon as we've read all options */
1198 [ - + ]: 13670 : if (PostAuthDelay > 0)
5524 heikki.linnakangas@i 1199 :UBC 0 : pg_usleep(PostAuthDelay * 1000000L);
1200 : :
1201 : : /*
1202 : : * Initialize various default states that can't be set up until we've
1203 : : * selected the active user and gotten the right GUC settings.
1204 : : */
1205 : :
1206 : : /* set default namespace search path */
5524 heikki.linnakangas@i 1207 :CBC 13670 : InitializeSearchPath();
1208 : :
1209 : : /* initialize client encoding */
1210 : 13670 : InitializeClientEncoding();
1211 : :
1212 : : /* Initialize this backend's session state. */
2966 andres@anarazel.de 1213 : 13670 : InitializeSession();
1214 : :
1215 : : /*
1216 : : * If this is an interactive session, load any libraries that should be
1217 : : * preloaded at backend start. Since those are determined by GUCs, this
1218 : : * can't happen until GUC settings are complete, but we want it to happen
1219 : : * during the initial transaction in case anything that requires database
1220 : : * access needs to be done.
1221 : : */
748 michael@paquier.xyz 1222 [ + + ]: 13670 : if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1191 tgl@sss.pgh.pa.us 1223 : 11009 : process_session_preload_libraries();
1224 : :
1225 : : /* fill in the remainder of this entry in the PgBackendStatus array */
5524 heikki.linnakangas@i 1226 [ + + ]: 13670 : if (!bootstrap)
238 michael@paquier.xyz 1227 : 13620 : pgstat_bestart_final();
1228 : :
1229 : : /* close the transaction we started above */
5524 heikki.linnakangas@i 1230 [ + + ]: 13670 : if (!bootstrap)
1231 : 13620 : CommitTransactionCommand();
1232 : : }
1233 : :
1234 : : /*
1235 : : * Process any command-line switches and any additional GUC variable
1236 : : * settings passed in the startup packet.
1237 : : */
1238 : : static void
1239 : 12053 : process_startup_options(Port *port, bool am_superuser)
1240 : : {
1241 : : GucContext gucctx;
1242 : : ListCell *gucopts;
1243 : :
4063 tgl@sss.pgh.pa.us 1244 [ + + ]: 12053 : gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1245 : :
1246 : : /*
1247 : : * First process any command-line switches that were included in the
1248 : : * startup packet, if we are in a regular backend.
1249 : : */
5524 heikki.linnakangas@i 1250 [ + + ]: 12053 : if (port->cmdline_options != NULL)
1251 : : {
1252 : : /*
1253 : : * The maximum possible number of commandline arguments that could
1254 : : * come from port->cmdline_options is (strlen + 1) / 2; see
1255 : : * pg_split_opts().
1256 : : */
1257 : : char **av;
1258 : : int maxac;
1259 : : int ac;
1260 : :
1261 : 3555 : maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1262 : :
5901 tgl@sss.pgh.pa.us 1263 : 3555 : av = (char **) palloc(maxac * sizeof(char *));
1264 : 3555 : ac = 0;
1265 : :
1266 : 3555 : av[ac++] = "postgres";
1267 : :
5524 heikki.linnakangas@i 1268 : 3555 : pg_split_opts(av, &ac, port->cmdline_options);
1269 : :
5901 tgl@sss.pgh.pa.us 1270 : 3555 : av[ac] = NULL;
1271 : :
1272 [ - + ]: 3555 : Assert(ac < maxac);
1273 : :
4593 1274 : 3555 : (void) process_postgres_switches(ac, av, gucctx, NULL);
1275 : : }
1276 : :
1277 : : /*
1278 : : * Process any additional GUC variable settings passed in startup packet.
1279 : : * These are handled exactly like command-line variables.
1280 : : */
5524 heikki.linnakangas@i 1281 : 12053 : gucopts = list_head(port->guc_options);
1282 [ + + ]: 29027 : while (gucopts)
1283 : : {
1284 : : char *name;
1285 : : char *value;
1286 : :
1287 : 16974 : name = lfirst(gucopts);
2297 tgl@sss.pgh.pa.us 1288 : 16974 : gucopts = lnext(port->guc_options, gucopts);
1289 : :
5524 heikki.linnakangas@i 1290 : 16974 : value = lfirst(gucopts);
2297 tgl@sss.pgh.pa.us 1291 : 16974 : gucopts = lnext(port->guc_options, gucopts);
1292 : :
5524 heikki.linnakangas@i 1293 : 16974 : SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1294 : : }
9080 tgl@sss.pgh.pa.us 1295 : 12053 : }
1296 : :
1297 : : /*
1298 : : * Load GUC settings from pg_db_role_setting.
1299 : : *
1300 : : * We try specific settings for the database/role combination, as well as
1301 : : * general for this database and for this user.
1302 : : */
1303 : : static void
5865 alvherre@alvh.no-ip. 1304 : 13671 : process_settings(Oid databaseid, Oid roleid)
1305 : : {
1306 : : Relation relsetting;
1307 : : Snapshot snapshot;
1308 : :
1309 [ + + ]: 13671 : if (!IsUnderPostmaster)
1310 : 117 : return;
1311 : :
2472 andres@anarazel.de 1312 : 13554 : relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1313 : :
1314 : : /* read all the settings under the same snapshot for efficiency */
4501 rhaas@postgresql.org 1315 : 13554 : snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1316 : :
1317 : : /* Later settings are ignored if set earlier. */
1318 : 13554 : ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1319 : 13553 : ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1320 : 13553 : ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1321 : 13553 : ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1322 : :
1323 : 13553 : UnregisterSnapshot(snapshot);
2472 andres@anarazel.de 1324 : 13553 : table_close(relsetting, AccessShareLock);
1325 : : }
1326 : :
1327 : : /*
1328 : : * Backend-shutdown callback. Do cleanup that we want to be sure happens
1329 : : * before all the supporting modules begin to nail their doors shut via
1330 : : * their own callbacks.
1331 : : *
1332 : : * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1333 : : * via separate callbacks that execute before this one. We don't combine the
1334 : : * callbacks because we still want this one to happen if the user-level
1335 : : * cleanup fails.
1336 : : */
1337 : : static void
7991 peter_e@gmx.net 1338 : 15110 : ShutdownPostgres(int code, Datum arg)
1339 : : {
1340 : : /* Make sure we've killed any active transaction */
7386 tgl@sss.pgh.pa.us 1341 : 15110 : AbortOutOfAnyTransaction();
1342 : :
1343 : : /*
1344 : : * User locks are not released by transaction end, so be sure to release
1345 : : * them explicitly.
1346 : : */
1347 : 15110 : LockReleaseAll(USER_LOCKMETHOD, true);
9519 vadim4o@yahoo.com 1348 : 15110 : }
1349 : :
1350 : :
1351 : : /*
1352 : : * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1353 : : */
1354 : : static void
4852 alvherre@alvh.no-ip. 1355 : 6 : StatementTimeoutHandler(void)
1356 : : {
3811 bruce@momjian.us 1357 : 6 : int sig = SIGINT;
1358 : :
1359 : : /*
1360 : : * During authentication the timeout is used to deal with
1361 : : * authentication_timeout - we want to quit in response to such timeouts.
1362 : : */
3920 andres@anarazel.de 1363 [ - + ]: 6 : if (ClientAuthInProgress)
3920 andres@anarazel.de 1364 :UBC 0 : sig = SIGTERM;
1365 : :
1366 : : #ifdef HAVE_SETSID
1367 : : /* try to signal whole process group */
3920 andres@anarazel.de 1368 :CBC 6 : kill(-MyProcPid, sig);
1369 : : #endif
1370 : 6 : kill(MyProcPid, sig);
4852 alvherre@alvh.no-ip. 1371 : 6 : }
1372 : :
1373 : : /*
1374 : : * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1375 : : */
1376 : : static void
4609 tgl@sss.pgh.pa.us 1377 : 4 : LockTimeoutHandler(void)
1378 : : {
1379 : : #ifdef HAVE_SETSID
1380 : : /* try to signal whole process group */
1381 : 4 : kill(-MyProcPid, SIGINT);
1382 : : #endif
1383 : 4 : kill(MyProcPid, SIGINT);
1384 : 4 : }
1385 : :
1386 : : static void
621 akorotkov@postgresql 1387 :UBC 0 : TransactionTimeoutHandler(void)
1388 : : {
1389 : 0 : TransactionTimeoutPending = true;
1390 : 0 : InterruptPending = true;
1391 : 0 : SetLatch(MyLatch);
1392 : 0 : }
1393 : :
1394 : : static void
3513 rhaas@postgresql.org 1395 : 0 : IdleInTransactionSessionTimeoutHandler(void)
1396 : : {
1397 : 0 : IdleInTransactionSessionTimeoutPending = true;
1398 : 0 : InterruptPending = true;
1399 : 0 : SetLatch(MyLatch);
1400 : 0 : }
1401 : :
1402 : : static void
1756 tgl@sss.pgh.pa.us 1403 : 0 : IdleSessionTimeoutHandler(void)
1404 : : {
1405 : 0 : IdleSessionTimeoutPending = true;
1406 : 0 : InterruptPending = true;
1407 : 0 : SetLatch(MyLatch);
1408 : 0 : }
1409 : :
1410 : : static void
1301 andres@anarazel.de 1411 :CBC 23 : IdleStatsUpdateTimeoutHandler(void)
1412 : : {
1413 : 23 : IdleStatsUpdateTimeoutPending = true;
1414 : 23 : InterruptPending = true;
1415 : 23 : SetLatch(MyLatch);
1416 : 23 : }
1417 : :
1418 : : static void
1669 tmunro@postgresql.or 1419 :UBC 0 : ClientCheckTimeoutHandler(void)
1420 : : {
1421 : 0 : CheckClientConnectionPending = true;
1422 : 0 : InterruptPending = true;
1423 : 0 : SetLatch(MyLatch);
1424 : 0 : }
1425 : :
1426 : : /*
1427 : : * Returns true if at least one role is defined in this database cluster.
1428 : : */
1429 : : static bool
7427 tgl@sss.pgh.pa.us 1430 :CBC 69 : ThereIsAtLeastOneRole(void)
1431 : : {
1432 : : Relation pg_authid_rel;
1433 : : TableScanDesc scan;
1434 : : bool result;
1435 : :
2472 andres@anarazel.de 1436 : 69 : pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1437 : :
2423 1438 : 69 : scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
8562 tgl@sss.pgh.pa.us 1439 : 69 : result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1440 : :
2423 andres@anarazel.de 1441 : 69 : table_endscan(scan);
2472 1442 : 69 : table_close(pg_authid_rel, AccessShareLock);
1443 : :
8816 peter_e@gmx.net 1444 : 69 : return result;
1445 : : }
|