Repository navigation
Expand file tree
/
Copy pathclass-wp-sqlite-storage.php
More file actions
600 lines (532 loc) · 19.6 KB
/
Copy pathclass-wp-sqlite-storage.php
File metadata and controls
600 lines (532 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
<?php
/**
* Manages the storage for the WordPress SQLite database.
*
* The storage handles the path of the SQLite database:
* - An explicit database path is used as is.
* - A database with a secret path is stored in a randomized protected directory.
* - A database in a legacy path is migrated to a secret path.
*
* The storage implements a locking mechanism for initialization and maintenance.
* Locking uses a dedicated empty SQLite database and a maintenance file:
* 1. An exclusive lock is acquired on the locking database at ".ht.sqlite.lock".
* 2. A maintenance marker file is created at ".ht.sqlite.maintenance":
* - When requests see the file, they use the locking database.
* - Its absence provides a fast path for normal traffic.
* 3. When the lock is released, the maintenance file is automatically removed.
*
* Database locking uses a PDO SQLite connection:
* phpcs:disable WordPress.DB.RestrictedClasses.mysql__PDO
*
* Filesystem warnings are suppressed to avoid exposing database paths:
* phpcs:disable WordPress.PHP.NoSilencedErrors.Discouraged
*/
class WP_SQLite_Storage {
/**
* Filename of a script that returns the path to the database file.
*/
private const DATABASE_PATH_FILENAME = 'db-path.php';
/**
* Filename of the database file.
*/
private const DATABASE_FILENAME = '.ht.sqlite';
/**
* Filename of the SQLite locking database.
*/
private const LOCK_FILENAME = '.ht.sqlite.lock';
/**
* Filename of the marker that makes requests check the storage lock.
*/
private const MAINTENANCE_FILENAME = '.ht.sqlite.maintenance';
/**
* Number of bytes in a generated random token.
*/
private const TOKEN_BYTE_LENGTH = 16;
/**
* Directory with the storage lock files and, for a secret path, the database.
* Null for an in-memory database.
*
* @var string|null
*/
private $database_root;
/**
* Explicitly configured database path, if any.
*
* @var string|null
*/
private $database_path;
/**
* Absolute path of the database path file.
*
* @var string|null
*/
private $database_path_file;
/**
* Absolute path of the SQLite locking database.
*
* @var string|null
*/
private $lock_path;
/**
* Absolute path of the storage maintenance marker.
*
* @var string|null
*/
private $maintenance_path;
/**
* Connection holding the exclusive transaction on the SQLite locking database.
*
* @var PDO|null
*/
private $storage_lock_connection;
/**
* Connection holding the exclusive transaction on the WordPress SQLite database.
*
* @var PDO|null
*/
private $database_lock_connection;
/**
* Time to wait for existing database connections, in milliseconds.
*
* @var int
*/
private $database_lock_timeout = 10000;
/**
* Create a storage manager for a database with a secret path.
*
* The database is stored in a randomized directory inside the root directory.
* Legacy databases in the root directory are migrated to it.
*
* @param string $root Root directory of the database storage.
* @return self The storage manager.
* @throws RuntimeException When the root directory is not an absolute path.
*/
public static function with_secret_path( string $root ): self {
if ( ! self::is_absolute_path( $root ) ) {
throw new RuntimeException( 'The SQLite database directory must be an absolute filesystem path.' );
}
$storage = new self();
$storage->set_database_root( $root );
return $storage;
}
/**
* Create a storage manager for an explicit database path.
*
* @param string $path Absolute database path or ":memory:".
* @return self The storage manager.
* @throws RuntimeException When the database path is invalid.
*/
public static function with_explicit_path( string $path ): self {
if ( ':memory:' !== $path ) {
if ( ! self::is_absolute_path( $path ) ) {
throw new RuntimeException( 'The SQLite database path must be an absolute filesystem path or ":memory:".' );
}
if ( is_dir( $path ) || in_array( substr( $path, -1 ), array( '/', DIRECTORY_SEPARATOR ), true ) ) {
throw new RuntimeException( 'The SQLite database path must point to a file, not a directory.' );
}
}
$storage = new self();
$storage->database_path = $path;
if ( ':memory:' !== $path ) {
$storage->set_database_root( dirname( $path ) );
}
return $storage;
}
/**
* Initialize the SQLite database storage.
*
* Uses an explicit file path or ":memory:" as configured. Otherwise, initializes
* a secret randomized path and migrates legacy databases as needed.
*
* @return string Absolute path to the SQLite database file, or ":memory:".
* @throws RuntimeException When the storage cannot be initialized.
*/
public function initialize(): string {
// An in-memory database has no files.
if ( ':memory:' === $this->database_path ) {
return $this->database_path;
}
// Never resolve a database path while storage maintenance is in progress.
$this->wait_until_unlocked();
// Check if we're already holding a lock.
$was_locked = null !== $this->storage_lock_connection;
// Explicitly configured database path.
if ( null !== $this->database_path ) {
$this->ensure_database( $this->database_path );
if ( $was_locked ) {
// If the storage was locked, ensure the database is locked as well.
$this->lock();
}
return $this->database_path;
}
// Initialized secret database path.
$database_path = $this->read_recorded_database_path();
if ( null !== $database_path && @is_file( $database_path ) ) {
return $database_path;
}
// Initialize or repair the secret path under the storage lock.
// Preserve a lock already held by this instance for a larger operation.
$this->lock();
try {
// Another process may have completed the initialization meanwhile.
$database_path = $this->read_recorded_database_path();
if ( null !== $database_path && @is_file( $database_path ) ) {
return $database_path;
}
if ( null === $database_path ) {
$database_path = $this->publish_database_path();
}
// Migrate legacy database paths.
$legacy_path = $this->database_root . self::DATABASE_FILENAME;
if ( ! @is_file( $legacy_path ) ) {
$legacy_path = $this->database_root . self::DATABASE_FILENAME . '.php';
}
if ( @is_file( $legacy_path ) ) {
$this->move_legacy_database( $legacy_path, $database_path );
} else {
$this->ensure_database( $database_path );
// The earlier lock() call only locked the storage because the database
// did not exist yet. Lock the new database too, so callers that already
// held the storage lock retain both locks after initialization.
$this->lock();
}
return $database_path;
} finally {
if ( ! $was_locked ) {
$this->unlock();
}
}
}
/**
* Lock the database storage for maintenance.
*
* The locking mechanism does the following:
* - Waits for a lock held by another process, up to the database lock timeout.
* - Marks maintenance as active so new requests wait.
* - When a database exists, also acquires an exclusive database lock.
*
* Existing database connections must be closed first to avoid blocking the lock.
*
* The lock is released when unlock() is called or the process ends.
*
* @throws RuntimeException When the lock cannot be acquired.
*/
public function lock(): void {
// An in-memory database has no files to lock.
if ( ':memory:' === $this->database_path ) {
return;
}
$was_locked = null !== $this->storage_lock_connection;
// Serialize maintenance through the dedicated locking database.
if ( ! $was_locked ) {
try {
$this->ensure_database( $this->lock_path );
$connection = new PDO( 'sqlite:' . $this->lock_path );
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$connection->exec( 'PRAGMA busy_timeout = ' . $this->database_lock_timeout );
$connection->exec( 'BEGIN EXCLUSIVE' );
$this->storage_lock_connection = $connection;
} catch ( Throwable $exception ) {
throw new RuntimeException( 'Failed to acquire the SQLite storage lock.', 0, $exception );
}
}
try {
// Ensure the maintenance marker exists so new requests use the locking database.
if ( ! @is_file( $this->maintenance_path ) ) {
if ( false === @file_put_contents( $this->maintenance_path, '' ) ) {
throw new RuntimeException( 'Failed to create the SQLite storage maintenance marker.' );
}
@chmod( $this->maintenance_path, 0600 );
}
// Reuse a database lock already held by this instance.
if ( null !== $this->database_lock_connection ) {
return;
}
// Look for an existing database so that it can be locked as well.
$database_path = $this->database_path;
if ( null === $database_path ) {
$database_path = $this->read_recorded_database_path();
// The database may still be at a legacy path.
if ( null === $database_path || ! @is_file( $database_path ) ) {
$database_path = $this->database_root . self::DATABASE_FILENAME;
}
if ( ! @is_file( $database_path ) ) {
$database_path = $this->database_root . self::DATABASE_FILENAME . '.php';
}
}
// Lock the existing database when found.
if ( @is_file( $database_path ) ) {
try {
$this->database_lock_connection = $this->lock_database( $database_path );
} catch ( Throwable $exception ) {
throw new RuntimeException( 'Failed to lock the SQLite database.', 0, $exception );
}
}
} catch ( Throwable $exception ) {
if ( ! $was_locked ) {
$this->unlock();
}
throw $exception;
}
}
/**
* Unlock the storage.
*/
public function unlock(): void {
$this->database_lock_connection = null;
if ( null !== $this->storage_lock_connection ) {
// Remove the marker before releasing the lock that protects it.
@unlink( $this->maintenance_path );
$this->storage_lock_connection = null;
}
}
/**
* Create a storage manager. Use with_secret_path() or with_explicit_path().
*/
private function __construct() {
}
/**
* Set the storage root directory and the paths derived from it.
*
* @param string $database_root Storage root directory.
*/
private function set_database_root( string $database_root ): void {
$this->database_root = rtrim( $database_root, '/\\' ) . '/';
$this->database_path_file = $this->database_root . self::DATABASE_PATH_FILENAME;
$this->lock_path = $this->database_root . self::LOCK_FILENAME;
$this->maintenance_path = $this->database_root . self::MAINTENANCE_FILENAME;
}
/**
* Check whether a path is an absolute filesystem path.
*
* @param string $path Filesystem path.
* @return bool Whether the path is absolute.
*/
private static function is_absolute_path( string $path ): bool {
if ( '' === $path || false !== strpos( $path, "\0" ) ) {
return false;
}
if ( '/' === DIRECTORY_SEPARATOR ) {
return '/' === $path[0];
} else {
// Match Windows absolute path with a drive letter or UNC share.
return 1 === preg_match(
'~^(?:[a-zA-Z]:/|//[^/]+/[^/]+/)~',
str_replace( '\\', '/', $path )
);
}
}
/**
* Wait until no maintenance process holds an active storage lock.
*/
private function wait_until_unlocked(): void {
// A lock held by this instance must not block its own work.
if ( null !== $this->storage_lock_connection || ! @is_file( $this->maintenance_path ) ) {
return;
}
try {
$this->ensure_database( $this->lock_path );
$connection = new PDO( 'sqlite:' . $this->lock_path );
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$connection->exec( 'PRAGMA busy_timeout = ' . $this->database_lock_timeout );
$connection->exec( 'BEGIN EXCLUSIVE' );
// Clear a stale marker while the transaction prevents new maintenance from starting.
@unlink( $this->maintenance_path );
} catch ( Throwable $exception ) {
throw new RuntimeException( 'Failed to check the SQLite storage lock.', 0, $exception );
}
}
/**
* Reads the recorded database path.
*
* @return string|null Absolute database path, or null when none is recorded.
*/
private function read_recorded_database_path(): ?string {
if ( ! @is_file( $this->database_path_file ) ) {
return null;
}
try {
// Use include so an unreadable file can be handled without terminating on PHP 7.
$database_path = @include $this->database_path_file;
} catch ( Throwable $exception ) {
throw new RuntimeException( 'Failed to read the SQLite database path file.', 0, $exception );
}
if ( false === $database_path ) {
throw new RuntimeException( 'Failed to read the SQLite database path file.' );
}
if ( ! is_string( $database_path ) || '' === $database_path ) {
throw new RuntimeException( 'The SQLite database path file is invalid.' );
}
return $database_path;
}
/**
* Generate a randomized database path and publish it atomically.
*
* @return string Absolute path to the published SQLite database file.
*/
private function publish_database_path(): string {
$directory_name = '.ht.' . bin2hex( random_bytes( self::TOKEN_BYTE_LENGTH ) );
$temporary_path = $this->database_root . 'tmp.' . self::DATABASE_PATH_FILENAME;
$database_path_contents = sprintf(
"<?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",
$directory_name,
self::DATABASE_FILENAME
);
// Publish the complete file atomically.
if ( false === @file_put_contents( $temporary_path, $database_path_contents ) ) {
throw new RuntimeException( 'Failed to write the SQLite database path file.' );
}
@chmod( $temporary_path, 0600 );
if ( ! @rename( $temporary_path, $this->database_path_file ) ) {
@unlink( $temporary_path );
throw new RuntimeException( 'Failed to publish the SQLite database path file.' );
}
// This runs before wp_opcache_invalidate() is available.
$opcache_restrict_api = ini_get( 'opcache.restrict_api' );
$script_filename = isset( $_SERVER['SCRIPT_FILENAME'] ) ? realpath( $_SERVER['SCRIPT_FILENAME'] ) : false;
if (
function_exists( 'opcache_invalidate' )
&& ( ! $opcache_restrict_api || ( $script_filename && 0 === stripos( $script_filename, $opcache_restrict_api ) ) )
) {
opcache_invalidate( $this->database_path_file, true );
}
return $this->database_root . $directory_name . '/' . self::DATABASE_FILENAME;
}
/**
* Move a legacy database into a secret path.
*
* @param string $legacy_path Absolute path of the legacy database file.
* @param string $database_path Absolute destination path.
*/
private function move_legacy_database( string $legacy_path, string $database_path ): void {
$this->ensure_protected_directory( dirname( $database_path ) );
/*
* Close the connection just before moving the database. SQLite considers
* renaming an open database undefined, and Windows generally prevents it.
* We cannot fully prevent race conditions, but this makes them unlikely.
*
* See: https://www.sqlite.org/howtocorrupt.html#unlink
*/
$this->database_lock_connection = null;
if ( ! @rename( $legacy_path, $database_path ) ) {
throw new RuntimeException( 'Failed to move the SQLite database file.' );
}
@chmod( $database_path, 0600 );
try {
$this->database_lock_connection = $this->lock_database( $database_path );
} catch ( Throwable $exception ) {
throw new RuntimeException( 'Failed to lock the migrated SQLite database.', 0, $exception );
}
}
/**
* Ensure that a database and its protected directory exist.
*
* @param string $database_path Absolute database path.
*/
private function ensure_database( string $database_path ): void {
$this->ensure_protected_directory( dirname( $database_path ) );
if ( ! @is_file( $database_path ) ) {
// Create an empty database file with restricted permissions.
$database_handle = @fopen( $database_path, 'c' );
if ( false === $database_handle ) {
throw new RuntimeException( 'Failed to create the SQLite database file.' );
}
fclose( $database_handle );
@chmod( $database_path, 0600 );
}
}
/**
* Ensure that a database directory exists and deny direct access.
*
* @param string $directory Absolute directory path.
*/
private function ensure_protected_directory( string $directory ): void {
if ( ! @is_dir( $directory ) ) {
// Create the path one directory at a time to avoid changing the process-wide umask.
$missing_directories = array();
for ( $path = rtrim( $directory, '/\\' ); ! @is_dir( $path ); $path = dirname( $path ) ) {
$missing_directories[] = $path;
if ( dirname( $path ) === $path ) {
break;
}
}
foreach ( array_reverse( $missing_directories ) as $path ) {
if ( ! @mkdir( $path, 0700 ) && ! @is_dir( $path ) ) {
throw new RuntimeException( 'Failed to create the SQLite database directory.' );
}
@chmod( $path, 0700 );
}
}
$this->ensure_file( rtrim( $directory, '/\\' ) . '/.htaccess', 'DENY FROM ALL' );
$this->ensure_file( rtrim( $directory, '/\\' ) . '/index.php', '<?php // Silence is golden.' );
}
/**
* Create a protected file when it does not already exist.
*
* @param string $path Absolute file path.
* @param string $contents File contents.
*/
private function ensure_file( string $path, string $contents ): void {
if ( @is_file( $path ) ) {
return;
}
if ( false === @file_put_contents( $path, $contents ) ) {
throw new RuntimeException( 'Failed to create SQLite database protection file.' );
}
@chmod( $path, 0600 );
}
/**
* Acquire an exclusive transaction on an SQLite database.
*
* @param string $database_path Absolute database path.
* @return PDO Connection holding the transaction.
*/
private function lock_database( string $database_path ): PDO {
// Do not silently create an empty database if the expected file is missing.
$pdo_options = array();
if ( defined( 'Pdo\Sqlite::ATTR_OPEN_FLAGS' ) ) {
$pdo_options[ Pdo\Sqlite::ATTR_OPEN_FLAGS ] = Pdo\Sqlite::OPEN_READWRITE;
} elseif ( defined( 'PDO::SQLITE_ATTR_OPEN_FLAGS' ) ) {
$pdo_options[ PDO::SQLITE_ATTR_OPEN_FLAGS ] = PDO::SQLITE_OPEN_READWRITE;
}
$connection = null;
$deadline = microtime( true ) + ( $this->database_lock_timeout / 1000 );
do {
if ( microtime( true ) >= $deadline ) {
throw new RuntimeException( 'Failed to acquire an exclusive SQLite database lock.' );
}
if ( null === $connection ) {
$connection = new PDO( 'sqlite:' . $database_path, null, null, $pdo_options );
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$connection->exec( 'PRAGMA busy_timeout = ' . $this->database_lock_timeout );
}
try {
// Disable WAL so we can acquire a truly exclusive READ/WRITE lock.
$journal_mode = $connection->query( 'PRAGMA journal_mode = DELETE' )->fetchColumn();
if ( 'delete' === strtolower( (string) $journal_mode ) ) {
// Acquire exclusive lock.
$connection->exec( 'BEGIN EXCLUSIVE' );
// Another connection may have restored WAL before the transaction started.
// If that's the case, release the lock and retry in the next iteration.
$journal_mode = $connection->query( 'PRAGMA journal_mode' )->fetchColumn();
if ( 'delete' !== strtolower( (string) $journal_mode ) ) {
$connection->exec( 'ROLLBACK' );
} else {
// Connection lock successfully acquired.
return $connection;
}
}
} catch ( PDOException $exception ) {
$error_info = $connection->errorInfo();
$sqlite_busy = 5;
$database_busy = isset( $error_info[1] ) && ( (int) $error_info[1] & 0xff ) === $sqlite_busy;
if ( ! $database_busy ) {
throw $exception;
}
// Close the connection so any raw transaction is rolled back before retrying.
$connection = null;
}
usleep( 100000 ); // 100 milliseconds.
} while ( true );
}
}