Harden C2 file logging for Baota permission failures.

Swallow create_log mkdir/write errors so missing public/log ownership cannot take down requests, and document the www:www permission fix.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hashbro
2026-08-09 16:07:56 +08:00
parent 6489808fa5
commit 6bf33e2761
3 changed files with 39 additions and 21 deletions
+25 -20
View File
@@ -6,32 +6,37 @@ if (! function_exists('create_log')) {
/**
* Append a line to public/log/{type}/Ymd.log
*
* Failures are swallowed so logging never breaks the HTTP request
* (e.g. www cannot mkdir under public/ on a fresh Baota deploy).
*
* @param array|string $str
*/
function create_log($str, string $type = 'c2'): void
{
$str = is_array($str) ? json_encode($str, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : (string) $str;
$logPath = public_path('log/'.$type);
if (! is_dir($logPath)) {
$old = umask(0);
mkdir($logPath, 0777, true);
umask($old);
}
$logName = $logPath.'/'.date('Ymd').'.log';
try {
$url = request()->getRequestUri();
} catch (\Throwable) {
$url = $_SERVER['REQUEST_URI'] ?? '';
}
$logStr = date('Y-m-d H:i:s').' '.$url.' '.$str."\r\n\r\n";
$isNew = ! file_exists($logName);
file_put_contents($logName, $logStr, FILE_APPEND);
if ($isNew) {
try {
chmod($logName, 0777);
} catch (\Throwable) {
$str = is_array($str) ? json_encode($str, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : (string) $str;
$type = preg_replace('/[^a-z0-9_-]+/i', '', $type) ?: 'c2';
$logPath = public_path('log/'.$type);
if (! is_dir($logPath) && ! @mkdir($logPath, 0775, true) && ! is_dir($logPath)) {
return;
}
$logName = $logPath.'/'.date('Ymd').'.log';
try {
$url = request()->getRequestUri();
} catch (\Throwable) {
$url = $_SERVER['REQUEST_URI'] ?? '';
}
$logStr = date('Y-m-d H:i:s').' '.$url.' '.$str."\r\n\r\n";
$isNew = ! file_exists($logName);
if (@file_put_contents($logName, $logStr, FILE_APPEND) === false) {
return;
}
if ($isNew) {
@chmod($logName, 0664);
}
} catch (\Throwable) {
// never break the request for logging
}
}
}