11<?php
22
33/**
4- * Manages locking for the WordPress SQLite database storage .
4+ * Manages the storage for the WordPress SQLite database.
55 *
6+ * The storage handles the path of the SQLite database:
7+ * - An explicit database path is used as is.
8+ * - A managed database is stored under a randomized protected path.
9+ * - A database in a legacy path stays in use.
10+ *
11+ * The storage implements a locking mechanism for initialization and maintenance.
612 * Locking uses a dedicated empty SQLite database and a maintenance file:
713 * 1. An exclusive lock is acquired on the locking database at ".ht.sqlite.lock".
814 * 2. A maintenance marker file is created at ".ht.sqlite.maintenance":
1723 * phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
1824 */
1925class WP_SQLite_Storage {
26+ /**
27+ * Filename of a script that returns the path to the database file.
28+ */
29+ private const DATABASE_PATH_FILENAME = 'db-path.php ' ;
30+
31+ /**
32+ * Filename of the database file.
33+ */
34+ private const DATABASE_FILENAME = '.ht.sqlite ' ;
35+
2036 /**
2137 * Filename of the SQLite locking database.
2238 */
@@ -27,13 +43,32 @@ class WP_SQLite_Storage {
2743 */
2844 private const MAINTENANCE_FILENAME = '.ht.sqlite.maintenance ' ;
2945
46+ /**
47+ * Number of bytes in a generated random token.
48+ */
49+ private const TOKEN_BYTE_LENGTH = 16 ;
50+
3051 /**
3152 * Managed database root directory.
3253 *
3354 * @var string
3455 */
3556 private $ database_root ;
3657
58+ /**
59+ * Explicitly configured database path, if any.
60+ *
61+ * @var string|null
62+ */
63+ private $ database_path ;
64+
65+ /**
66+ * Absolute path of the database path file.
67+ *
68+ * @var string
69+ */
70+ private $ database_path_file ;
71+
3772 /**
3873 * Absolute path of the SQLite locking database.
3974 *
@@ -63,14 +98,84 @@ class WP_SQLite_Storage {
6398 private $ database_lock_timeout = 10000 ;
6499
65100 /**
66- * Create a SQLite storage lock .
101+ * Create a SQLite storage manager .
67102 *
68103 * @param string|null $database_root Managed database root. Defaults to FQDBDIR.
104+ * @param string|null $database_path Explicit database path or ":memory:". Managed storage is used when null.
105+ * @throws RuntimeException When the database path is invalid.
106+ */
107+ public function __construct ( ?string $ database_root = null , ?string $ database_path = null ) {
108+ if ( '' === $ database_path ) {
109+ throw new RuntimeException ( 'The SQLite database path is invalid. ' );
110+ }
111+ $ this ->database_root = trailingslashit ( $ database_root ?? FQDBDIR );
112+ $ this ->database_path = $ database_path ;
113+ $ this ->database_path_file = $ this ->database_root . self ::DATABASE_PATH_FILENAME ;
114+ $ this ->lock_path = $ this ->database_root . self ::LOCK_FILENAME ;
115+ $ this ->maintenance_path = $ this ->database_root . self ::MAINTENANCE_FILENAME ;
116+ }
117+
118+ /**
119+ * Initialize the SQLite database storage.
120+ *
121+ * Uses an explicit file path or ":memory:" as configured. Otherwise, initializes
122+ * managed storage with a randomized path. A legacy database stays at its fixed path.
123+ *
124+ * @return string Absolute path to the SQLite database file, or ":memory:".
125+ * @throws RuntimeException When the storage cannot be initialized.
69126 */
70- public function __construct ( ?string $ database_root = null ) {
71- $ this ->database_root = trailingslashit ( $ database_root ?? FQDBDIR );
72- $ this ->lock_path = $ this ->database_root . self ::LOCK_FILENAME ;
73- $ this ->maintenance_path = $ this ->database_root . self ::MAINTENANCE_FILENAME ;
127+ public function initialize (): string {
128+ // An in-memory database has no files.
129+ if ( ':memory: ' === $ this ->database_path ) {
130+ return $ this ->database_path ;
131+ }
132+
133+ // Never resolve a database path while storage maintenance is in progress.
134+ $ this ->wait_until_unlocked ();
135+
136+ // Explicitly configured database path.
137+ if ( null !== $ this ->database_path ) {
138+ $ this ->ensure_database ( $ this ->database_path );
139+ return $ this ->database_path ;
140+ }
141+
142+ // Initialized managed database path.
143+ $ database_path = $ this ->read_recorded_database_path ();
144+ if ( null !== $ database_path && @is_file ( $ database_path ) ) {
145+ return $ database_path ;
146+ }
147+
148+ // Keep using a legacy database at its fixed path.
149+ $ legacy_path = $ this ->database_root . self ::DATABASE_FILENAME ;
150+ if ( ! @is_file ( $ legacy_path ) ) {
151+ $ legacy_path = $ this ->database_root . self ::DATABASE_FILENAME . '.php ' ;
152+ }
153+ if ( @is_file ( $ legacy_path ) ) {
154+ return $ legacy_path ;
155+ }
156+
157+ // Initialize or repair the managed storage under the storage lock.
158+ // Preserve a lock already held by this instance for a larger operation.
159+ $ keep_lock = null !== $ this ->storage_lock_connection ;
160+ $ this ->lock ();
161+ try {
162+ // Another process may have completed the initialization meanwhile.
163+ $ database_path = $ this ->read_recorded_database_path ();
164+ if ( null !== $ database_path && @is_file ( $ database_path ) ) {
165+ return $ database_path ;
166+ }
167+
168+ if ( null === $ database_path ) {
169+ $ database_path = $ this ->publish_database_path ();
170+ }
171+
172+ $ this ->ensure_database ( $ database_path );
173+ return $ database_path ;
174+ } finally {
175+ if ( ! $ keep_lock ) {
176+ $ this ->unlock ();
177+ }
178+ }
74179 }
75180
76181 /**
@@ -127,6 +232,96 @@ public function unlock(): void {
127232 }
128233 }
129234
235+ /**
236+ * Wait until no maintenance process holds an active storage lock.
237+ */
238+ private function wait_until_unlocked (): void {
239+ // A lock held by this instance must not block its own work.
240+ if ( null !== $ this ->storage_lock_connection || ! @is_file ( $ this ->maintenance_path ) ) {
241+ return ;
242+ }
243+
244+ try {
245+ $ this ->ensure_database ( $ this ->lock_path );
246+ $ connection = new PDO ( 'sqlite: ' . $ this ->lock_path );
247+ $ connection ->setAttribute ( PDO ::ATTR_ERRMODE , PDO ::ERRMODE_EXCEPTION );
248+ $ connection ->exec ( 'PRAGMA busy_timeout = ' . $ this ->database_lock_timeout );
249+ $ connection ->exec ( 'BEGIN EXCLUSIVE ' );
250+
251+ // Clear a stale marker while the transaction prevents new maintenance from starting.
252+ @unlink ( $ this ->maintenance_path );
253+ } catch ( Throwable $ exception ) {
254+ throw new RuntimeException ( 'Failed to check the SQLite storage lock. ' , 0 , $ exception );
255+ }
256+ }
257+
258+ /**
259+ * Reads the recorded database path.
260+ *
261+ * @return string|null Absolute database path, or null when none is recorded.
262+ */
263+ private function read_recorded_database_path (): ?string {
264+ if ( ! @is_file ( $ this ->database_path_file ) ) {
265+ return null ;
266+ }
267+
268+ try {
269+ // Use include so an unreadable file can be handled without terminating on PHP 7.
270+ $ database_path = @include $ this ->database_path_file ;
271+ } catch ( Throwable $ exception ) {
272+ throw new RuntimeException ( 'Failed to read the SQLite database path file. ' , 0 , $ exception );
273+ }
274+
275+ if ( false === $ database_path ) {
276+ throw new RuntimeException ( 'Failed to read the SQLite database path file. ' );
277+ }
278+
279+ if ( ! is_string ( $ database_path ) || '' === $ database_path ) {
280+ throw new RuntimeException ( 'The SQLite database path file is invalid. ' );
281+ }
282+
283+ return $ database_path ;
284+ }
285+
286+ /**
287+ * Generate a randomized database path and publish it atomically.
288+ *
289+ * @return string Absolute path to the published SQLite database file.
290+ */
291+ private function publish_database_path (): string {
292+ $ directory_name = '.ht. ' . bin2hex ( random_bytes ( self ::TOKEN_BYTE_LENGTH ) );
293+ $ temporary_path = $ this ->database_root . 'tmp. ' . self ::DATABASE_PATH_FILENAME ;
294+
295+ $ database_path_contents = sprintf (
296+ "<?php \n\n/** \n * SQLite database path. \n * \n * IMPORTANT: Keep this path secret. When possible, point it outside the document root. \n */ \nreturn __DIR__ . '/%s/%s'; \n" ,
297+ $ directory_name ,
298+ self ::DATABASE_FILENAME
299+ );
300+
301+ // Publish the complete file atomically.
302+ if ( false === @file_put_contents ( $ temporary_path , $ database_path_contents ) ) {
303+ throw new RuntimeException ( 'Failed to write the SQLite database path file. ' );
304+ }
305+ @chmod ( $ temporary_path , 0600 );
306+
307+ if ( ! @rename ( $ temporary_path , $ this ->database_path_file ) ) {
308+ @unlink ( $ temporary_path );
309+ throw new RuntimeException ( 'Failed to publish the SQLite database path file. ' );
310+ }
311+
312+ // This runs before wp_opcache_invalidate() is available.
313+ $ opcache_restrict_api = ini_get ( 'opcache.restrict_api ' );
314+ $ script_filename = isset ( $ _SERVER ['SCRIPT_FILENAME ' ] ) ? realpath ( $ _SERVER ['SCRIPT_FILENAME ' ] ) : false ;
315+ if (
316+ function_exists ( 'opcache_invalidate ' )
317+ && ( ! $ opcache_restrict_api || ( $ script_filename && 0 === stripos ( $ script_filename , $ opcache_restrict_api ) ) )
318+ ) {
319+ opcache_invalidate ( $ this ->database_path_file , true );
320+ }
321+
322+ return $ this ->database_root . $ directory_name . '/ ' . self ::DATABASE_FILENAME ;
323+ }
324+
130325 /**
131326 * Ensure that a database and its protected directory exist.
132327 *
0 commit comments