-
Notifications
You must be signed in to change notification settings - Fork 3
/
spamc.hsl
89 lines (78 loc) · 2.52 KB
/
spamc.hsl
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
function spamc($fp, $opts = [])
{
$path = $opts["path"];
$address = $opts["address"] ?? "127.0.0.1";
$port = $opts["port"] ?? 783;
$timeout = $opts["timeout"] ?? 30;
$tls = $opts["tls"] ?? ["enabled" => false];
$user = $opts["user"] ?? none;
$sender = $opts["sender"] ?? none;
$sizelimit = $opts["size_limit"] ?? 500 * 1024;
$report = $opts["report"] ?? false;
$symbols_unparsed = $opts["symbols_unparsed"] ?? false;
$s = $fp->seek(0, "SEEK_END");
$fp->seek(0, "SEEK_SET");
if ($sender)
$s += length("Return-Path: <".$sender.">\r\n");
if ($s > $sizelimit) return ["error" => "Content too large"];
$conn = $socket = Socket($path ? "AF_UNIX" : Socket::AF($address), "SOCK_STREAM");
if (!$socket->settimeout($timeout)) return ["error" => "Could not set timeout"];
if (!$socket->connect(...($path ? [$path] : [$address, $port]))) return ["error" => "Could not connect"];
if ($tls["enabled"])
{
$socket = TLSSocket($socket, $tls["opts"] ?? []);
if (!$socket->handshake()) return ["error" => "Could not perform TLS handshake"];
}
if ($report)
$str = "REPORT SPAMC/1.5\r\n";
else
$str = "SYMBOLS SPAMC/1.5\r\n";
$str .= "Content-length: $s\r\n";
if ($user) $str .= "User: ".$user."\r\n";
$str .= "\r\n";
if (!$socket->send($str)) return ["error" => "Could not send request"];
if ($sender)
$socket->send("Return-Path: <".$sender.">\r\n");
$fp->seek(0, "SEEK_SET");
while ($str = $fp->read(8192))
if (!$socket->send($str))
return ["error" => "Could not send content"];
$conn->shutdown("SHUT_WR");
$result = "";
while ($resp = $socket->recv(8192))
$result .= $resp;
$conn->shutdown("SHUT_RDWR");
$conn->close();
if (!$result) return ["error" => "No scan result"];
if (!pcre_match("EX_OK", $result)) return ["error" => "Bad scan result"];
[$header, $body] = str_split($result, "\r\n\r\n", 2);
foreach (str_split($header, "\r\n") as $headerline)
{
$sa_result = pcre_match(#/Spam: (.*) ; (.*) \/ (.*)/, $headerline);
if ($sa_result)
break;
}
if ($symbols_unparsed)
{
$symbols = [$body ?? ""];
}
else if ($report)
{
$symbols = [];
if ($body and ($symbol_section = str_find($body, "\n---")) != -1 and
($match = pcre_match_all(#/^\s*(-?\d+(?:\.\d+)?) ([^\s]+)/m, $body[$symbol_section:])))
{
$symbols = array_map(number, array_combine(...array_reverse($match[1:])));
}
}
else
{
$symbols = $body ? str_split($body, ",") : [];
}
return [
"spam" => $sa_result[1] == "True" ? true : false,
"score" => number($sa_result[2]),
"threshold" => number($sa_result[3]),
"symbols" => $symbols
];
}