PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/src/backend/utils/init/postinit.c

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