Process session_preload_libraries within InitPostgres's transaction.
authorTom Lane <[email protected]>
Mon, 25 Jul 2022 14:27:43 +0000 (10:27 -0400)
committerTom Lane <[email protected]>
Mon, 25 Jul 2022 14:27:43 +0000 (10:27 -0400)
Previously we did this after InitPostgres, at a somewhat randomly chosen
place within PostgresMain.  However, since commit a0ffa885e doing this
outside a transaction can cause a crash, if we need to check permissions
while replacing a placeholder GUC.  (Besides which, a preloaded library
could itself want to do database access within _PG_init.)

To avoid needing an additional transaction start/end in every session,
move the process_session_preload_libraries call to within InitPostgres's
transaction.  That requires teaching the code not to call it when
InitPostgres is called from somewhere other than PostgresMain, since
we don't want session_preload_libraries to affect background workers.
The most future-proof solution here seems to be to add an additional
flag parameter to InitPostgres; fortunately, we're not yet very worried
about API stability for v15.

Doing this also exposed the fact that we're currently honoring
session_preload_libraries in walsenders, even those not connected to
any database.  This seems, at minimum, a POLA violation: walsenders
are not interactive sessions.  Let's stop doing that.

(All these comments also apply to local_preload_libraries, of course.)

Per report from Gurjeet Singh (thanks also to Nathan Bossart and Kyotaro
Horiguchi for review).  Backpatch to v15 where a0ffa885e came in.

Discussion: https://postgr.es/m/CABwTF4VEpwTHhRQ+q5MiC5ucngN-whN-PdcKeufX7eLSoAfbZA@mail.gmail.com

src/backend/bootstrap/bootstrap.c
src/backend/postmaster/autovacuum.c
src/backend/postmaster/postmaster.c
src/backend/tcop/postgres.c
src/backend/utils/init/postinit.c
src/include/miscadmin.h

index 088556ab54cc5d44d684557fc546b500e670d4d6..58752368e7e333949073f029b8b78ee5db2dbf7b 100644 (file)
@@ -354,7 +354,7 @@ BootstrapModeMain(int argc, char *argv[], bool check_only)
    if (pg_link_canary_is_frontend())
        elog(ERROR, "backend is incorrectly linked to frontend functions");
 
-   InitPostgres(NULL, InvalidOid, NULL, InvalidOid, NULL, false);
+   InitPostgres(NULL, InvalidOid, NULL, InvalidOid, false, false, NULL);
 
    /* Initialize stuff for bootstrap-file processing */
    for (i = 0; i < MAXATTR; i++)
index 2e146aac93b99ae8c2af5488914a0ebdafc38b3b..70a9176c54ca944d0454f0b3d21df169271f75c4 100644 (file)
@@ -475,7 +475,7 @@ AutoVacLauncherMain(int argc, char *argv[])
    /* Early initialization */
    BaseInit();
 
-   InitPostgres(NULL, InvalidOid, NULL, InvalidOid, NULL, false);
+   InitPostgres(NULL, InvalidOid, NULL, InvalidOid, false, false, NULL);
 
    SetProcessingMode(NormalProcessing);
 
@@ -1694,12 +1694,13 @@ AutoVacWorkerMain(int argc, char *argv[])
        pgstat_report_autovac(dbid);
 
        /*
-        * Connect to the selected database
+        * Connect to the selected database, specifying no particular user
         *
         * Note: if we have selected a just-deleted database (due to using
         * stale stats info), we'll fail and exit here.
         */
-       InitPostgres(NULL, dbid, NULL, InvalidOid, dbname, false);
+       InitPostgres(NULL, dbid, NULL, InvalidOid, false, false,
+                    dbname);
        SetProcessingMode(NormalProcessing);
        set_ps_display(dbname);
        ereport(DEBUG1,
index 1c2545752666c59a6cf7e21f3f1d66ff1893d02a..e541b16bdbe11916f6287e14e93803ee0e53baa0 100644 (file)
@@ -5654,7 +5654,11 @@ BackgroundWorkerInitializeConnection(const char *dbname, const char *username, u
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("database connection requirement not indicated during registration")));
 
-   InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
+   InitPostgres(dbname, InvalidOid,    /* database to connect to */
+                username, InvalidOid,  /* role to connect as */
+                false,         /* never honor session_preload_libraries */
+                (flags & BGWORKER_BYPASS_ALLOWCONN) != 0,  /* ignore datallowconn? */
+                NULL);         /* no out_dbname */
 
    /* it had better not gotten out of "init" mode yet */
    if (!IsInitProcessingMode())
@@ -5677,7 +5681,11 @@ BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("database connection requirement not indicated during registration")));
 
-   InitPostgres(NULL, dboid, NULL, useroid, NULL, (flags & BGWORKER_BYPASS_ALLOWCONN) != 0);
+   InitPostgres(NULL, dboid,   /* database to connect to */
+                NULL, useroid, /* role to connect as */
+                false,         /* never honor session_preload_libraries */
+                (flags & BGWORKER_BYPASS_ALLOWCONN) != 0,  /* ignore datallowconn? */
+                NULL);         /* no out_dbname */
 
    /* it had better not gotten out of "init" mode yet */
    if (!IsInitProcessingMode())
index bdb11f430fd2344392e609e1f9afa0576763c7d8..d0bbd30d2b5fda5e059c850ba1a7dc8ec86b7604 100644 (file)
@@ -4076,7 +4076,11 @@ PostgresMain(const char *dbname, const char *username)
     * it inside InitPostgres() instead.  In particular, anything that
     * involves database access should be there, not here.
     */
-   InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL, false);
+   InitPostgres(dbname, InvalidOid,    /* database to connect to */
+                username, InvalidOid,  /* role to connect as */
+                !am_walsender, /* honor session_preload_libraries? */
+                false,         /* don't ignore datallowconn */
+                NULL);         /* no out_dbname */
 
    /*
     * If the PostmasterContext is still around, recycle the space; we don't
@@ -4112,12 +4116,6 @@ PostgresMain(const char *dbname, const char *username)
    if (am_walsender)
        InitWalSender();
 
-   /*
-    * process any libraries that should be preloaded at backend start (this
-    * likewise can't be done until GUC settings are complete)
-    */
-   process_session_preload_libraries();
-
    /*
     * Send this backend's cancellation info to the frontend.
     */
index a5c208a20a829da0eb9882ab41cba87814bddfe4..29f70accb22753c03078714480b02bc738ac3789 100644 (file)
@@ -622,29 +622,48 @@ BaseInit(void)
  * InitPostgres
  *     Initialize POSTGRES.
  *
+ * Parameters:
+ * in_dbname, dboid: specify database to connect to, as described below
+ * username, useroid: specify role to connect as, as described below
+ * load_session_libraries: TRUE to honor [session|local]_preload_libraries
+ * override_allow_connections: TRUE to connect despite !datallowconn
+ * out_dbname: optional output parameter, see below; pass NULL if not used
+ *
  * The database can be specified by name, using the in_dbname parameter, or by
- * OID, using the dboid parameter.  In the latter case, the actual database
+ * OID, using the dboid parameter.  Specify NULL or InvalidOid respectively
+ * for the unused parameter.  If dboid is provided, the actual database
  * name can be returned to the caller in out_dbname.  If out_dbname isn't
  * NULL, it must point to a buffer of size NAMEDATALEN.
  *
- * Similarly, the username can be passed by name, using the username parameter,
+ * Similarly, the role can be passed by name, using the username parameter,
  * or by OID using the useroid parameter.
  *
- * In bootstrap mode no parameters are used.  The autovacuum launcher process
- * doesn't use any parameters either, because it only goes far enough to be
- * able to read pg_database; it doesn't connect to any particular database.
- * In walsender mode only username is used.
+ * In bootstrap mode the database and username parameters are NULL/InvalidOid.
+ * The autovacuum launcher process doesn't specify these parameters either,
+ * because it only goes far enough to be able to read pg_database; it doesn't
+ * connect to any particular database.  An autovacuum worker specifies a
+ * database but not a username; conversely, a physical walsender specifies
+ * username but not database.
+ *
+ * By convention, load_session_libraries should be passed as true in
+ * "interactive" sessions (including standalone backends), but false in
+ * background processes such as autovacuum.  Note in particular that it
+ * shouldn't be true in parallel worker processes; those have another
+ * mechanism for replicating their leader's set of loaded libraries.
  *
- * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
- * already have a PGPROC struct ... but it's not completely filled in yet.
+ * We expect that InitProcess() was already called, so we already have a
+ * PGPROC struct ... but it's not completely filled in yet.
  *
  * Note:
  *     Be very careful with the order of calls in the InitPostgres function.
  * --------------------------------
  */
 void
-InitPostgres(const char *in_dbname, Oid dboid, const char *username,
-            Oid useroid, char *out_dbname, bool override_allow_connections)
+InitPostgres(const char *in_dbname, Oid dboid,
+            const char *username, Oid useroid,
+            bool load_session_libraries,
+            bool override_allow_connections,
+            char *out_dbname)
 {
    bool        bootstrap = IsBootstrapProcessingMode();
    bool        am_superuser;
@@ -1108,6 +1127,16 @@ InitPostgres(const char *in_dbname, Oid dboid, const char *username,
    /* Initialize this backend's session state. */
    InitializeSession();
 
+   /*
+    * If this is an interactive session, load any libraries that should be
+    * preloaded at backend start.  Since those are determined by GUCs, this
+    * can't happen until GUC settings are complete, but we want it to happen
+    * during the initial transaction in case anything that requires database
+    * access needs to be done.
+    */
+   if (load_session_libraries)
+       process_session_preload_libraries();
+
    /* report this backend in the PgBackendStatus array */
    if (!bootstrap)
        pgstat_bestart();
index ea9a56d39556c6f59832f7169b1c9aac2ca6d979..067b729d5a5cd73adadffe6e008d67d188422e5f 100644 (file)
@@ -449,8 +449,11 @@ extern PGDLLIMPORT AuxProcType MyAuxProcType;
 /* in utils/init/postinit.c */
 extern void pg_split_opts(char **argv, int *argcp, const char *optstr);
 extern void InitializeMaxBackends(void);
-extern void InitPostgres(const char *in_dbname, Oid dboid, const char *username,
-                        Oid useroid, char *out_dbname, bool override_allow_connections);
+extern void InitPostgres(const char *in_dbname, Oid dboid,
+                        const char *username, Oid useroid,
+                        bool load_session_libraries,
+                        bool override_allow_connections,
+                        char *out_dbname);
 extern void BaseInit(void);
 
 /* in utils/init/miscinit.c */