fix(cache): 修 read_failed_slot 的未初始化读,补解析失败告警

This commit is contained in:
admin committed 2026-10-30 23:45:17 +08:00
1 parent c43ad3749e
commit 1ab8a84901
2 files changed
+85 -19

No files matched your search

+19
View File
@@ -667,6 +667,25 @@ pub fn upstream_configured(r: *mut ngx_http_request_t, route: &str) -> bool {
unsafe { memo_for(r, route) }.is_some()
}
/// 取本请求 memo 里的**有效源个数**(log 阶段用)。
///
/// `pub(crate)`:Task 5 的 `handlers::cool_down_failed` 要用它做
/// 「顺位下标 → 源下标」的边界检查。走 memo ⇒ **不再查一次上游表**、
/// **不再 clone 整份源列表**(log 阶段多一次 shm 读 + 逐行解码 +
/// String 分配的纯浪费)。
///
/// ⚠️ memo 里的源列表**就是**本次请求选源时用的那一份 ⇒ 顺位下标
/// (`$cache_pick`)与它是**同一个下标空间** ⇒ 边界检查恒成立
/// (保留检查是为了「越界就跳过」这条防御语义不变)。
///
/// `r` 必须是 nginx 传入的有效请求指针。
pub(crate) fn memo_source_count(r: *mut ngx_http_request_t, route: &str) -> Option<usize> {
// SAFETY: r 有效;memo 的路由必须与本路由一致
let m = unsafe { memo_for(r, route) }?;
// SAFETY: 指针指向请求池里的 Memo,请求存活期间有效
Some(unsafe { (*m).sources.len() })
}
/// 读 `$cache_pick` 的字符串值(空串 = 还没有)。
///
/// ⚠️ **不能用 `ngx_http_get_variable(r, name, 0)`**。
+66 -19
View File
@@ -35,7 +35,6 @@ use ipass_core::{auth, http, plugin_registry, util};
use crate::cache;
use crate::config;
use crate::stats;
use crate::upstreams;
/// `$upstream_cache_status` 的变量索引(postconfig 解析一次,log 阶段复用)
static CACHE_STATUS_IDX: AtomicIsize = AtomicIsize::new(-1);
@@ -169,13 +168,33 @@ pub fn read_failed_slot(r: *mut ngx_http_request_t) -> Option<usize> {
if v.is_null() {
return None;
}
// SAFETY: v 非空 ⇒ 可读它的字段;not_found 为真时 data 未定义
// (nginx 只置 not_found,不清 data)⇒ 先判 not_found 再碰 data。
let (not_found, data, len) = unsafe { ((*v).not_found() != 0, (*v).data, (*v).len() as usize) };
if not_found || data.is_null() || len == 0 {
// ⚠️ **先判 not_found,再碰 data / len**(两步走,别合成一个元组):
// nginx 的「未找到」分支(ngx_http_variables.c:998-1001)**只置 not_found**,
// **不动 data / len**;而这个值槽是 `ngx_palloc` 分配的(同文件 :725)
// ⇒ **不清零** ⇒ not_found 为真时 data / len 是**未初始化**的。
// 元组/逗号表达式会**按顺序求值全部元素** ⇒ 把 data/len 提到 not_found
// 之前读 ⇒ 未初始化读(UB)。故这里**提前 return**。
//
// ⚠️ 本函数走的是**按名查**(`ngx_http_get_variable`)⇒ 值槽是
// `ngx_palloc` 的**未清零**内存。
// 对比 `cache.rs::read_indexed_var`(按索引查):值槽在
// `r->variables[]` 里,是 `ngx_pcalloc` 的**清零**内存 ⇒ 那边没这个问题。
// SAFETY: v 非空 ⇒ 可读它的字段;nginx 保证了 not_found 已被写过
if unsafe { (*v).not_found() != 0 } {
return None;
}
// SAFETY: not_found 为假且 data 非空 ⇒ data 指向 len 字节的有效内存
// SAFETY: not_found 为假 ⇒ nginx 走的是 unknown_header 的**成功分支**
// (ngx_http_variables.c:1003-1011 / 1017-1029)⇒ data / len 都被写好了
let data = unsafe { (*v).data };
if data.is_null() {
return None;
}
// SAFETY: 同上 ⇒ len 也已被 nginx 写好
let len = unsafe { (*v).len() as usize };
if len == 0 {
return None;
}
// SAFETY: data 非空 ⇒ data 指向 len 字节的有效内存
let s = unsafe { core::slice::from_raw_parts(data, len) };
let s = String::from_utf8_lossy(s);
let s = s.trim();
@@ -184,8 +203,28 @@ pub fn read_failed_slot(r: *mut ngx_http_request_t) -> Option<usize> {
// 契约是「一个整数」,但若 conf 在**同一层**写了两次该头,
// 拿到的就是 "1, 2" ⇒ 直接 parse 会失败 ⇒ **静默地一个源都不冷却**。
// ⇒ 取**最后一段**(内层/后写的那次最贴近真实失败顺位)再解析。
let s = s.rsplit(',').next().unwrap_or(s).trim();
s.parse::<usize>().ok()
let last = s.rsplit(',').next().unwrap_or(s).trim();
match last.parse::<usize>() {
Ok(v) => Some(v),
Err(_) => {
// ⚠️ **只在「有值但解析不出来」时告警**(D4):
// 之前这里是 `.ok()` ⇒ 静默吞掉 ⇒ 排障时看不到任何线索
// (换源链写坏了头 / conf 写了两次 / 上游塞了脏值,都表现为
// 「一个源都不冷却」,无从判断是「没失败」还是「解析失败」)。
// 「头不存在」走的是上面的 not_found 早退、「值为空」走 len==0
// 早退 ⇒ **都不在这里打**,避免正常请求(没失败过)在热路径上
// 无脑刷日志。
//
// ⚠️ 头值**可能来自上游**(`sent_http_` 读的是响应头全集)
// ⇒ 截断到 64 字符再打(免得灌日志);`{:?}` 会转义控制字符
// (免得伪造日志行)。
let shown: String = s.chars().take(64).collect();
util::log_warn(&format!(
"[cache] 响应头 X-Cache-Failed-Slot 的值无法解析为顺位号:{shown:?} —— 本次不冷却任何源"
));
None
}
}
}
/// 把失败的源打入冷却(`cache::cool_down`,60 秒)。
@@ -202,8 +241,8 @@ pub fn read_failed_slot(r: *mut ngx_http_request_t) -> Option<usize> {
/// 顺位 → 源下标的映射**必须**走 `$cache_pick`(R-T5-5):它是**请求内缓存**
/// 的(Task 4 的 memo)⇒ 与本次请求**实际用的源**严格一致;
/// 另查一次上游表拿到的是**此刻**的池子 ⇒ 管理员在请求中途改了池子就错位。
/// 另查的那一次**只**用来取 `sources.len()` 做**边界检查**
/// (防止池子缩小后下标越界)——这条检查必须保留。
/// 另查的那一次**只**用来取「源个数」做**边界检查**
/// (防止下标越界)——这条检查必须保留。
///
/// ⚠️ 调用点必须在 log handler 的 `status.is_empty()` **早退之后**
/// (R-T5-1):没过缓存层的请求(401 无效 Key / 429 超配额 / 503 未配上游)
@@ -212,14 +251,6 @@ fn cool_down_failed(r: *mut ngx_http_request_t) {
let Some(route) = config::route_of_uri(&http::uri(r)) else {
return;
};
// 只用来取 sources.len() 做边界检查(真相源是 $cache_pick,见上)
let Some(up) = upstreams::lookup_upstream(route) else {
return;
};
let sources = upstreams::effective_sources(&up);
if sources.is_empty() {
return;
}
// SAFETY: r 由 nginx 传入且有效;只读响应状态码
let final_status = unsafe { (*r).headers_out.status as u16 };
let all_failed = matches!(final_status, 403 | 500 | 502 | 503 | 504);
@@ -232,9 +263,25 @@ fn cool_down_failed(r: *mut ngx_http_request_t) {
let Some(slots) = cache::parse_pick(&raw) else {
return;
};
// 源个数(**只**用于边界检查;真相源是 $cache_pick,见上)
//
// ⚠️ **走请求级 memo**(Task 4 建的那份快照,D3):
// memo 里装的就是**本次请求选源时用的那份源列表** ⇒ 顺位下标
// (`$cache_pick`)与它是**同一个下标空间** ⇒ 边界检查天然成立。
// 这样 log 阶段**不必再查一次上游表、也不必 clone 整份源列表**
// (每次多一次 shm 读 + 逐行解码 + 一批 String 分配)。
//
// ⚠️ memo 拿不到 ⇒ 本请求**没有选过源** ⇒ `$cache_pick` 也拿不到
// (两者同源)⇒ 直接返回,不冷却任何源。
let Some(n_sources) = cache::memo_source_count(r, route) else {
return;
};
if n_sources == 0 {
return;
}
for slot in failed {
let Some(idx) = slots.get(slot) else { continue };
if *idx >= sources.len() {
if *idx >= n_sources {
continue;
}
cache::cool_down(route, *idx);