Files
ipass/rust/crates/ipass-core/src/http.rs
T
admin 74aeefee58 refactor(plugin): P0-P2 插件化落地 —— workspace 化 + ipass-core + plugin-domain
- P0: rust/ 改 workspace(ipass-core 内核 + gateway 唯一 cdylib),
  [profile.release] 上移根、依赖收敛 workspace.dependencies;
  users::delete 的 stats::forget 依赖改为 on_delete 钩子注册表
- P1: 契约层 core/plugin.rs(Plugin trait)+ core/loc.rs(Switch 并集 +
  set_switch_fn,未实现变体保守 false);gateway PLUGINS 分发循环,
  不认领统一 404(插件绝不自行 404)
- P2: 身份端点下沉 core/api.rs(CorePlugin + CoreExt 扩展注册表,
  gateway 作装配根回填域名数/用量/连带回收/白名单校验);
  plugin-domain crate(domains + DomainEntry + sub: 前缀 + ResolveHandler
  + $proxy_backend_addr + 域名类端点含 purge)
- 行为等价:conf/nginx.conf、Dockerfile、tests 零改动,262 回归全绿
- 方案文档 docs/plugin/PLUGINIZATION_PLAN.md
2026-09-13 11:43:22 +08:00

224 lines
7.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 请求/响应辅助:参数解析、请求体读取、JSON 响应输出。
//!
//! 这一层承担旧版 `util.params` / `util.respond` 的职责,但有一处本质差异:
//! **ngx crate 没有暴露请求体读取**,必须直接走
//! `ngx_http_read_client_request_body` 的两段式异步接口。
use std::collections::HashMap;
use std::ptr;
use ngx::core::{Buffer, Status};
use ngx::ffi::{ngx_chain_t, ngx_http_request_t};
use ngx::http::{HTTPStatus, Request};
use serde_json::{Value, json};
use crate::util;
// ===========================================================================
// 取请求信息
// ===========================================================================
pub fn uri(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 由 nginx 保证有效;uri 是请求内存池中的字符串
unsafe { String::from_utf8_lossy((*r).uri.as_bytes()).into_owned() }
}
/// HTTP 方法名。直接读 nginx 已解析好的 `method_name`,
/// 避免依赖 Method 枚举的全部变体名(少一个就编译不过)。
pub fn method_str(r: *mut ngx_http_request_t) -> String {
// SAFETY: 同上
unsafe { String::from_utf8_lossy((*r).method_name.as_bytes()).into_owned() }
}
pub fn args_raw(r: *mut ngx_http_request_t) -> Vec<u8> {
// SAFETY: 同上
unsafe { (*r).args.as_bytes().to_vec() }
}
/// 请求头(大小写不敏感)
pub fn header(r: *mut ngx_http_request_t, name: &str) -> Option<String> {
// SAFETY: 迭代器只在本函数存续期内使用
let request = unsafe { Request::from_ngx_http_request(r) };
for (k, v) in request.headers_in_iterator() {
if k.as_bytes().eq_ignore_ascii_case(name.as_bytes()) {
return Some(String::from_utf8_lossy(v.as_bytes()).into_owned());
}
}
None
}
/// 请求 Host 里的端口后缀(`:88` / 空串)。
///
/// 对外三个域名(`mdm` 管理台 / `lm` LLM / `*.dm` 企业)**共用同一个端口**,
/// 所以「管理接口从哪个端口进来,LLM 就该从哪个端口出去」。回显用的 `base_url`
/// 用它拼:写死端口在换端口部署时失效,完全不写则在非 443 部署时指向别处。
pub fn host_port(r: *mut ngx_http_request_t) -> String {
let host = match header(r, "Host") {
Some(h) => h,
None => return String::new(),
};
// IPv6 字面量形如 `[::1]:88`,rsplit 后 `[::1]` / `88` 仍然正确;
// 纯 `[::1]` 会切出非全数字的尾巴,被下面判掉。
match host.rsplit_once(':') {
Some((_, p)) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => format!(":{p}"),
_ => String::new(),
}
}
/// 客户端地址(登录限速的分组键)
pub fn remote_addr(r: *mut ngx_http_request_t) -> String {
// SAFETY: r 有效;connection 在请求生命周期内必然存在
unsafe {
let conn = (*r).connection;
if conn.is_null() {
return "-".to_owned();
}
String::from_utf8_lossy((*conn).addr_text.as_bytes()).into_owned()
}
}
// ===========================================================================
// 请求体
// ===========================================================================
/// 收集已读入的请求体。
///
/// **调用前提**:本函数只应在 `ngx_http_read_client_request_body` 的
/// post_handler 里调用(见 `api::read_body_then`)。
///
/// 请求体可能跨越多个 `ngx_buf_t`(chain)。被刷写到临时文件的大请求体
/// 这里直接忽略——管理台 API 的请求体都是几百字节的小 JSON,
/// 且管理 server 已把 `client_body_buffer_size` 调到 1m 覆盖边界。
pub unsafe fn collect_body(r: *mut ngx_http_request_t) -> Vec<u8> {
let mut out = Vec::new();
let rb = unsafe { (*r).request_body };
if rb.is_null() {
return out;
}
let mut chain = unsafe { (*rb).bufs };
while !chain.is_null() {
// SAFETY: chain 由 nginx 构建,节点与 buf 均有效
unsafe {
let buf = (*chain).buf;
if !buf.is_null() && (*buf).in_file() == 0 {
let (pos, last) = ((*buf).pos, (*buf).last);
if !pos.is_null() && !last.is_null() && last > pos {
let len = last.offset_from(pos) as usize;
out.extend_from_slice(std::slice::from_raw_parts(pos, len));
}
}
chain = (*chain).next;
}
}
out
}
/// 合并 query string 与请求体参数。
///
/// 优先级与旧版一致:**请求体覆盖 query**(同名时以 body 为准)。
pub fn params(r: *mut ngx_http_request_t) -> HashMap<String, String> {
let mut map = HashMap::new();
for (k, v) in util::parse_kv(&args_raw(r)) {
map.insert(k, v);
}
let body = unsafe { collect_body(r) };
if body.is_empty() {
return map;
}
let ctype = header(r, "content-type").unwrap_or_default();
if ctype.to_ascii_lowercase().contains("application/json") {
if let Ok(Value::Object(obj)) = serde_json::from_slice::<Value>(&body) {
for (k, v) in obj {
let s = match v {
Value::String(s) => s,
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
_ => continue,
};
map.insert(k, s);
}
}
} else {
for (k, v) in util::parse_kv(&body) {
map.insert(k, v);
}
}
map
}
// ===========================================================================
// 响应
// ===========================================================================
/// 发送 JSON 响应体(含额外响应头,如 Set-Cookie)。
///
/// `body` 的字节会被复制进 nginx 的请求内存池,随请求自动回收。
pub fn send_with(
r: *mut ngx_http_request_t,
status: HTTPStatus,
body: &str,
extra_headers: &[(&str, &str)],
) -> Status {
// SAFETY: r 有效
unsafe {
let request = Request::from_ngx_http_request(r);
let pool = request.pool();
let mut buf = match pool.create_buffer_from_str(body) {
Some(b) => b,
None => return Status::NGX_ERROR,
};
buf.set_last_buf(true);
let mut chain = ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: ptr::null_mut() };
request.set_status(status);
request.add_header_out("Content-Type", "application/json; charset=utf-8");
request.add_header_out("Cache-Control", "no-store");
for (name, value) in extra_headers {
request.add_header_out(name, value);
}
request.set_content_length_n(body.len());
let st = request.send_header();
if st != Status::NGX_OK {
return st;
}
request.output_filter(&mut chain)
}
}
pub fn send(r: *mut ngx_http_request_t, status: HTTPStatus, body: &str) -> Status {
send_with(r, status, body, &[])
}
/// 统一成功响应:`{code:200, msg, data}`
pub fn ok(r: *mut ngx_http_request_t, data: Value, msg: &str) -> Status {
let body = json!({ "code": 200, "msg": msg, "data": data }).to_string();
send(r, HTTPStatus::OK, &body)
}
pub fn ok_with(
r: *mut ngx_http_request_t,
data: Value,
msg: &str,
extra_headers: &[(&str, &str)],
) -> Status {
let body = json!({ "code": 200, "msg": msg, "data": data }).to_string();
send_with(r, HTTPStatus::OK, &body, extra_headers)
}
/// 统一失败响应:`{code:<status>, msg}`(与旧版 `util.fail` 一致)
pub fn fail(r: *mut ngx_http_request_t, status: HTTPStatus, msg: &str) -> Status {
// HTTPStatus 是 newtype(`pub struct HTTPStatus(pub ngx_uint_t)`),直接取内层值
let code = status.0 as u16;
let body = json!({ "code": code, "msg": msg }).to_string();
send(r, status, &body)
}