-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate-limiter-shmop.php
More file actions
72 lines (56 loc) · 1.7 KB
/
rate-limiter-shmop.php
File metadata and controls
72 lines (56 loc) · 1.7 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
<?php
/**
* Rate limiter with shmop driver
*
* @author Viktor Szépe <viktor@szepe.net>
* @link https://github.com/szepeviktor/php-rate-limiter
*/
namespace SzepeViktor\WordPress\Waf;
rate_limit([
'id' => getenv('RATE_LIMIT_ID'),
'interval' => getenv('RATE_LIMIT_INTERVAL'),
'prefix' => 'ratelimit:waf:',
]);
/**
* @param array{id?: string|false, interval?: string|false, prefix?: string} $options
*/
function rate_limit(array $options): void
{
if (!extension_loaded('shmop') || !function_exists('shmop_write')) {
error_log('shmop PHP extension (Shared Memory Operations) is not available. Install/enable the shmop extension.');
return;
}
$key = (string)($options['id'] ?? false);
$interval = (int)($options['interval'] ?? false);
$prefix = $options['prefix'] ?? 'ratelimit:';
if ($key === '' || $interval <= 0) {
return;
}
$now = time();
$shm = @shmop_open(crc32($prefix . $key), 'c', 0600, 4);
if ($shm === false) {
error_log('Unable to open shared memory segment.');
return;
}
$data = shmop_read($shm, 0, 4);
if (strlen($data) !== 4) {
error_log('Unexpected shared memory content length. Expected 4 bytes.');
return;
}
$last = unpack('N', $data);
if ($last === false) {
error_log('Failed to unpack data from shared memory.');
return;
}
$is_request_allowed = $now - $last[1] >= $interval;
if ($is_request_allowed) {
shmop_write($shm, pack('N', $now), 0);
}
shmop_close($shm);
if (!$is_request_allowed) {
http_response_code(429);
header('Retry-After: ' . $interval);
echo 'Too Many Requests';
exit;
}
}