-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart_scribe.php
More file actions
483 lines (419 loc) · 16.2 KB
/
Copy pathstart_scribe.php
File metadata and controls
483 lines (419 loc) · 16.2 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
<?php
/**
* Argora Scribe
*
* @package Scribe
* @version 1.0.0
* @author (c) 2025 Taras Kondratyuk
* @email help@namingo.org
* @license Apache-2.0 license
* @description A lightweight PHP catch-all email server that silently records all incoming messages into a database. Built for logging, archiving, and listening. Based on the Simple-SMTP-Server package created by 青石 (www@qs5.org) in 2017. (https://github.com/imdong/Simple-SMTP-Server)
*/
require_once __DIR__ . '/vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
use PhpMimeMailParser\Parser;
/**
* Database Configuration
*/
$db_info = [
"hostname" => "127.0.0.1",
"username" => "root",
"password" => "",
"dbname" => "",
];
// Server
class SMTP_Server
{
private $debug = false; // Debug mode
private $serv; // Server object
private $cli_pool; // Client user pool
private $db_info; // Database connection
private $link; // Database connectivity
private $logger; // Logger instance
public function __construct($db_info, $logger, $is_run = false)
{
$is_run && ($this->debug = false);
$this->serv = new Swoole\Server("0.0.0.0", 25, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);
$this->serv->set([
"daemonize" => $is_run,
"log_file" => "log_file.log",
"log_level" => SWOOLE_LOG_INFO,
"worker_num" => swoole_cpu_num() * 2,
"pid_file" => "/var/run/scribe.pid",
"debug_mode" => 1,
"max_conn" => 1000,
"max_request" => 10000,
"dispatch_mode" => 2,
"open_eof_check" => true,
"package_eof" => "\r\n",
"heartbeat_check_interval" => 30,
"heartbeat_idle_time" => 60,
]);
$this->logger = $logger;
// Database Connection
$this->db_info = $db_info;
$this->mysqlConnect();
// Event Preparation
$this->serv->on("Start", [$this, "onStart"]);
$this->serv->on("WorkerStart", [$this, "onWorkerStart"]);
$this->serv->on("Connect", [$this, "onConnect"]);
$this->serv->on("Receive", [$this, "onReceive"]);
$this->serv->on("Close", [$this, "onClose"]);
// Server Start
$this->serv->start();
}
public function mysqlConnect()
{
// Connect to the database using PDO
$dsn = "mysql:host={$this->db_info["hostname"]};dbname={$this->db_info["dbname"]}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->link = new PDO(
$dsn,
$this->db_info["username"],
$this->db_info["password"],
$options
);
} catch (PDOException $e) {
die("PDO Connect Error: " . $e->getMessage() . "\n");
}
}
public function tickOnMysqlPing($serv)
{
// Ping check to verify the connection status
$serverInfo = $this->link->getAttribute(PDO::ATTR_SERVER_INFO);
if ($serverInfo === false) {
// Reconnect to the database
$this->mysqlConnect();
// Display reconnection success message
$this->logger->info("[tick] Reload Link OK!");
}
}
public function onStart($serv)
{
$this->logger->info("[Scribe 1.0 Start] master_pid: {$serv->master_pid}");
}
public function onWorkerStart($serv, $worker_id)
{
// Check database every 5 seconds
if ($worker_id == 1) {
swoole_timer_tick(5000, function () use ($serv) {
$this->tickOnMysqlPing($serv);
});
}
$this->logger->info("[WorkerStart:{$worker_id}] master_pid: {$serv->master_pid}");
}
public function onConnect($serv, $fd, $from_id)
{
// Get client details
$cliInfo = $serv->connection_info($fd, $from_id);
// Create an array of message records
$this->cli_pool[$fd] = [
"username" => "u_{$fd}",
"status" => "init",
"client_ip" => $cliInfo["remote_ip"],
"client_port" => $cliInfo["remote_port"],
"client_from" => "",
"mail_from" => "",
"mail_rect" => [],
];
// Output information to client
$this->logger->info("[Connect] {$this->cli_pool[$fd]["username"]} {$this->cli_pool[$fd]["client_ip"]}:{$this->cli_pool[$fd]["client_port"]}");
// Reply to client
$serv->send(
$fd,
"220 Hello {$this->cli_pool[$fd]["username"]}, Welcome - Scribe\r\n"
);
}
public function onReceive(\Swoole\Server $serv, $fd, $from_id, $datas)
{
// Always assume multiple rows of data from the user
$dataArr = explode("\r\n", rtrim($datas, "\r\n"));
// Loop through each row of data
$isClose = false;
foreach ($dataArr as $data) {
if ($data == "" || $isClose) {
continue;
}
// Hand over to the mail processor
$retInfo = $this->mailResolve($serv, $fd, "{$data}\r\n");
// Return results
$retInfo["status"] &&
$serv->send($fd, "{$retInfo["code"]} {$retInfo["msg"]}\r\n");
// Disconnect
if (!empty($retInfo["close"])) {
$isClose = true;
$serv->close($fd);
}
}
return;
}
public function onClose($serv, $fd, $from_id)
{
$this->logger->info("[Close] {$fd}");
unset($this->cli_pool[$fd]);
}
public function mailResolve(\Swoole\Server $serv, $fd, $data)
{
// Determine the phase
if ($this->cli_pool[$fd]["status"] == "getData") {
$this->cli_pool[$fd]["buffer"] .= $data;
// If the message does not reach a new line, continue to receive
if (!preg_match("#\r\n\.\r\n$#", $this->cli_pool[$fd]["buffer"])) {
return ["status" => false];
}
$this->cli_pool[$fd]["status"] = "";
// Get data and clear cache
$dataBody = $this->cli_pool[$fd]["buffer"];
$this->cli_pool[$fd]["buffer"] = "";
//echo "[Data:{$fd}]\n{$dataBody}\n==============\n";
// Get the boundary string of the email
$matches = [];
preg_match('/--(.*?)\n/s', $dataBody, $matches);
$boundary = $matches[1] ?? "";
// Split the email into parts
$parts = explode("--" . $boundary, $dataBody);
// If there's only one part, save it to $emailBody
if (count($parts) == 1) {
$emailBody = $parts[0];
$attachment = NULL;
} else {
// Join the first two parts and save to $emailBody
$emailBody = $parts[0] . "--" . $boundary . $parts[1];
// Process the attachment to find out about filename and type
$parser = new Parser();
$attachmentDetails = [];
// Create a separate file counter
$fileCounter = 1;
// Start processing from the third part to the end
for ($i = 2; $i < count($parts); $i++) {
// Set the content of the attachment
$parser->setText("--".$boundary.$parts[$i]);
$attachments = $parser->getAttachments();
// Calculate the approximate size in kilobytes (KB)
$sizeKB = round(strlen($parts[$i]) / 1024);
// Check if there are really any attachments
if (!empty($attachments)) {
foreach ($attachments as $attachment_loop) {
$filename = $attachment_loop->getFilename();
$filetype = $attachment_loop->getContentType();
$attachmentDetails[] = 'File '.$fileCounter.': '.$filename.', Type: '.$filetype.', Size: '.$sizeKB.' KB';
// Increment the file counter for each file
$fileCounter++;
}
}
}
// If no attachments found, set $attachment to NULL
if (empty($attachmentDetails)) {
$attachment = NULL;
} else {
$attachment = implode("\n", $attachmentDetails);
}
}
// Save email message
$saveRet = $this->mailSave(
$this->cli_pool[$fd]["mail_from"],
$this->cli_pool[$fd]["mail_rect"],
$emailBody,
$this->cli_pool[$fd]["client_ip"],
$this->cli_pool[$fd]["client_from"],
$attachment
);
// Output result
if ($saveRet) {
$this->logger->info("[mailSave:{$fd}] Ok!");
} else {
$this->logger->info("[mailSave:{$fd}] Error!");
}
// Return result
$ret_info = [
"status" => true,
"code" => $saveRet ? 250 : 554,
"msg" => $saveRet ? "Ok" : "Error",
];
} else {
// Get data and clear cache
$msgBody = rtrim($data, "\r\n");
// Output the obtained message content
if ($this->debug) {
$this->logger->info("[Get:{$fd}] {$msgBody}");
}
// Get message format
if (
!preg_match(
'#^(?<cmd>[^\s]+)(\s(?<msg>.*?))?$#',
$msgBody,
$msgInfo
)
) {
return [
"status" => true,
"code" => 500,
"msg" => "Msg Error!",
];
}
$cmd = strtoupper(trim($msgInfo["cmd"]));
switch ($cmd) {
case "NOOP":
$ret_info = [
"status" => true,
"code" => 250,
"msg" => "Ok",
];
break;
case "HELO":
$this->cli_pool[$fd]["client_from"] = $msgInfo["msg"];
$this->logger->info("[HELO] {$msgInfo["msg"]}");
$ret_info = [
"status" => true,
"code" => 250,
"msg" => "{$this->cli_pool[$fd]["username"]}",
];
break;
case "MAIL":
if (
!preg_match(
"#^FROM:\s*<(?<mail>[^>]+)>#i",
$msgInfo["msg"],
$mailAddr
)
) {
$ret_info = [
"status" => true,
"code" => 501,
"msg" => "Error!",
];
} else {
$this->logger->info("[Mail From] {$mailAddr["mail"]}");
$this->cli_pool[$fd]["mail_from"] = trim(
$mailAddr["mail"]
);
$this->cli_pool[$fd]["mail_rect"] = [];
$ret_info = [
"status" => true,
"code" => 250,
"msg" => "Ok",
];
}
break;
case "RCPT":
if (
!preg_match(
"#^TO:\s*<(?<mail>[^>]+)>#i",
$msgInfo["msg"],
$mailAddr
)
) {
$ret_info = [
"status" => true,
"code" => 501,
"msg" => "Error!",
];
} else {
$this->logger->info("[Rect To] {$mailAddr["mail"]}");
$this->cli_pool[$fd]["mail_rect"][] = trim(
$mailAddr["mail"]
);
$ret_info = [
"status" => true,
"code" => 250,
"msg" => "Ok",
];
}
break;
case "DATA":
$this->cli_pool[$fd]["status"] = "getData";
$this->cli_pool[$fd]["buffer"] = "";
$ret_info = [
"status" => true,
"code" => 354,
"msg" => "End data with <CR><LF>.<CR><LF>",
];
break;
case "QUIT":
$ret_info = [
"status" => true,
"close" => true,
"code" => 221,
"msg" => "Bye",
];
break;
default:
$ret_info = [
"status" => true,
"code" => 502,
"msg" => "Error: command \"{$cmd}\" not implemented",
];
break;
}
}
return $ret_info;
}
// Save mail to database
public function mailSave($mail_from, $mail_rect, $mail_data, $client_ip, $client_from, $attachment)
{
// Get the current timestamp
$timeStr = date("Ymd");
// SQL statement
$sql = "INSERT INTO `scribe` (`mail_id`, `from`, `from_ip`,`client_from`, `rect`, `body`, `attachment`) VALUES \n";
$sql_value = [];
foreach ($mail_rect as $rect) {
$mail_hash = substr(md5("{$mail_from}_{$rect}"), 6, 16);
$randid = substr(md5(uniqid(mt_rand(), true)), 10, 16);
$mail_id = "d{$timeStr}_{$mail_hash}_{$randid}";
$sql_value[] = "(:mail_id, :mail_from, :client_ip, :client_from, :rect, :mail_data, :attachment)";
}
$sql_valueStr = implode(",\n", $sql_value);
$sql .= $sql_valueStr . ";";
// Prepare SQL statement
$stmt = $this->link->prepare($sql);
if (!$stmt) {
die("PDO Prepare Error: " . $this->link->errorInfo()[2] . "\n");
}
// Bind parameters and execute prepared statements
foreach ($mail_rect as $rect) {
$mail_hash = substr(md5("{$mail_from}_{$rect}"), 6, 16);
$randid = substr(md5(uniqid(mt_rand(), true)), 10, 16);
$mail_id = "d{$timeStr}_{$mail_hash}_{$randid}";
$stmt->bindValue(":mail_id", $mail_id);
$stmt->bindValue(":mail_from", $mail_from);
$stmt->bindValue(":client_ip", $client_ip);
$stmt->bindValue(":client_from", $client_from);
$stmt->bindValue(":rect", $rect);
$stmt->bindValue(":mail_data", $mail_data);
$stmt->bindValue(":attachment", $attachment);
if (!$stmt->execute()) {
die("PDO Execute Error: " . $stmt->errorInfo()[2] . "\n");
}
}
// Return status
return $stmt->rowCount();
}
}
if (php_sapi_name() != "cli") {
die("Is cli Run!");
}
$isRun = !empty($argv["1"]) && $argv["1"] == "run";
/**
* Log Configuration
*/
// Create a logger instance
$logger = new Logger('Scribe');
// Create a formatter for log messages
$formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n");
// Create a terminal log handler
$terminalHandler = new StreamHandler("php://stdout", Logger::DEBUG);
$terminalHandler->setFormatter($formatter);
// Create a file log handler
$fileHandler = new StreamHandler("scribe.log", Logger::DEBUG);
$fileHandler->setFormatter($formatter);
// Add handlers to the logger
$logger->pushHandler($terminalHandler);
$logger->pushHandler($fileHandler);
// Start server
$server = new SMTP_Server($db_info, $logger, $isRun);