forked from csev/py4e
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrate_limit.php
More file actions
70 lines (56 loc) · 2.1 KB
/
rate_limit.php
File metadata and controls
70 lines (56 loc) · 2.1 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
<?php
function check_rate_limit($database, $ipaddr, $q) {
if ( ! is_string($ipaddr) ) return 1;
$db = false;
try {
$db = new \SQLite3($database);
$db->enableExceptions(true);
$db->exec("CREATE TABLE IF NOT EXISTS Access (ipaddr TEXT UNIQUE, retrieved_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
$db->exec("DELETE FROM Access WHERE retrieved_at <= date('now', '-1 day')");
$stm = $db->prepare("SELECT julianday('now'), julianday(retrieved_at) FROM Access WHERE ipaddr = :ip ORDER BY retrieved_at DESC LIMIT 1");
$stm->bindValue(':ip', $ipaddr, SQLITE3_TEXT);
$res = $stm->execute();
$row = $res->fetchArray(SQLITE3_NUM);
$delta = 1000;
if ( $row ) {
$now = $row[0];
$retrieved_at = $row[1];
$delta = intval(($now - $retrieved_at) * (24*60*60));
}
$stm = $db->prepare("INSERT OR REPLACE INTO Access (ipaddr, retrieved_at) VALUES (:ip, datetime('now'));");
$stm->bindValue(':ip', $ipaddr, SQLITE3_TEXT);
$res = $stm->execute();
} catch(\Exception $e) {
error_log("check_rate_limit error ".$e->getMessage());
$delta = 1;
}
if ( $db ) $db->close();
return $delta;
}
function filter_bad_things($address, $ipaddr) {
if ( strlen($address) < 1 && strlen($address) > 120 ) {
echo('{ "address": "length", "answer" : 42 }');
error_log("geo_fail_length $ipaddr $address");
return true;
}
for($i=0; $i<strlen($address); $i++) {
$ch = substr($address, $i, 1);
if ( ord($ch) < 32 ) {
echo('{ "address": "npc", "answer" : 42 }');
error_log("geo_fail_npc $ipaddr $address");
return true;
}
}
$badthings = array(
'Address', 'scrapy.org', 'HTTP',
"\r", "\n", "http", "https",
);
foreach($badthings as $badthing) {
if ( strpos($address, $badthing) !== false ) {
echo('{ "address": "fail", "answer" : 42 }');
error_log("geo_fail_hack $ipaddr $address");
return true;
}
}
return false;
}