diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..cf5f1b8 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "deps/ipass"] + path = deps/ipass + url = http://192.168.1.18:13300/ipass/ipass.git diff --git a/CLAUDE.md b/CLAUDE.md index b164950..4b98e4e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,16 +8,14 @@ **iPass 统一网关**的身份能力:nginx 动态模块(`ngx-rust`)+ Rust,单进程,无数据库 / Redis / MQ。 代码形态是**内核 + 插件**(编译期装配,产出**单个** `.so`): -| crate | 职责 | -| --- | --- | -| `ipass-core` | **内核**:共享内存状态、`users.json` 与 API Key 的**唯一读写者**、账号模型、插件契约 | -| `plugin-sso` | **身份插件**:OAuth2.0 / OIDC 授权服务器 + IAP 身份注入 | -| `plugin-domain` | **域名插件**(已迁入):企业域名「子域名 → 后端」转发 + 申请/审核。**同时是「在 `ipass-core` 之上新增一个能力插件」的完整示例** | -| ~~`plugin-llm`~~ | **不迁入**:LLM 上游代理与配额计费属于流量层,与本服务“身份层”的定位分界不变(见文末) | -| `gateway` | **装配层**:module 壳 + 插件注册表 → `libsso_gateway.so` | +| crate | 仓库内? | 职责 | +| --- | --- | --- | +| `plugin-sso` | ✅ 本仓库 | **身份插件**:OAuth2.0 / OIDC 授权服务器 + IAP 身份注入 | +| `gateway` | ✅ 本仓库 | **装配层**:module 壳 + 插件注册表 → `libsso_gateway.so` | +| `ipass-core` / `plugin-domain` / `plugin-llm` / `plugin-apix` | ⬇️ `deps/ipass` 子模块 | 网关内核与通用能力插件(见 `ipass/ipass`),本仓库不再内置 | 判据:**去掉 SSO,网关还能不能转域名、还能不能代理 LLM?** 能 → 那它就不是内核。 -所以内核是 `ipass-core`,身份只是插件之一。 +内核与通用子系统统一由 **`deps/ipass` git 子模块**(`ipass/ipass`)提供,本仓库只持有 `plugin-sso` + `gateway`。 状态 = `data/` 下两个 JSON(`users.json` / `oauth_clients.json`); **客户端注册表与会话常驻共享内存,热路径零文件 I/O**。 @@ -41,8 +39,9 @@ cargo 解析 git 依赖时会 `update_submodules` 去克隆几十 MB 的 nginx 仓库。国内网络下卡死 —— **实测 5 分钟 0% CPU、无网络活动、无产物**,`sample` 抓栈停在 `GitCheckout::update_submodules → fetch → wait4`。 -3. **正解**:源码 vendor 到 `source/rust/vendor/ngx-rust/`(已剥离 `.git`,103 个文件 / 696K), - `Cargo.toml` 用 `path` 依赖;`[workspace] exclude = ["vendor/ngx-rust"]` 处理嵌套 workspace。 +3. **正解**:内核与 `ngx-rust` 放在 `deps/ipass` git 子模块(指向 `ipass/ipass`),`source/rust` 通过 + `path` 依赖引用它;sso 自己的 `Cargo.toml` 用 `exclude = ["../../deps/ipass", "target"]` 处理嵌套 + workspace,避免重复编译(`[submodule] deps/ipass` 一节见 README「目录结构」)。 ### 为什么要 `--with-pcre=<绝对路径>`,以及路径不能随便挪 @@ -74,7 +73,7 @@ cargo build --release ### 跑测试 ```bash -bash scripts/run-local-e2e.sh # 七套 e2e 全跑(自动起停 nginx + demo 系统) +bash scripts/run-local-e2e.sh # SSO e2e 全跑(六套,自动起停 nginx + demo 系统) bash scripts/run-local-e2e.sh --keep # 保留进程手工排查 ``` @@ -87,9 +86,9 @@ bash scripts/run-local-e2e.sh --keep # 保留进程手工排查 | 路径 | 职责 | | --- | --- | | `gateway/src/lib.rs` | **装配层**:指令解析、共享内存建表(`state_zone_init`,fork 前一次)、`PLUGINS` 数组、API 的 content 阶段处理器与插件分发、`init_process` 播种 admin | -| `crates/ipass-core/src/*` | **内核**:`state`(通用共享内存原语)/ `store`(JSON 原子读写)/ `users`(账号与 Key 的唯一写入口)/ `models`(仅共性字段 + `extra` 透传)/ `config`(仅共性策略常量与键前缀)/ `session`(管理员会话)/ `audit` / `http` / `util` / `plugin`(契约)/ `loc`(location 开关)。**不含** OAuth / TOTP 等个性代码 | -| `crates/plugin-sso/src/*` | **身份插件**:`oauth`(OAuth2/OIDC 全部逻辑 + IAP 身份解析)/ `api`(路由表 + handler)/ `oauth_clients` / `oauth_keys`(OAuth/IAP 协议常量与共享内存键前缀,原属内核 `config`)/ `oauth_state`(OAuthClient 模型 + 注册表/授权码/会话状态,原属内核 `state`/`store`)/ `rsa`(手写 RS256)/ `captcha` / `otp`(TOTP 算法 + 账号侧 TOTP,数据存 `User.extra`)/ `scim`(SCIM 2.0 身份供给)/ `cas`(CAS 1.0/2.0 协议端点)/ `ldap`(LDAP/AD 认证源,零依赖手写 BER)/ `sync`(钉钉·企微·飞书同步连接器,手动触发)/ `reset`(自助密码重置)/ `geo`(登录 IP 归属地)/ `portal`(终端用户门户「我的应用」) | -| `crates/plugin-domain/src/*` | **域名插件**:`keys`(`sub:` 前缀、企业域名 zone、子域名形状与 TTL 常量)/ `models`(`DomainEntry`)/ `domains`(校验、申请/审核/删除、写穿共享内存)/ `resolve`(access 阶段解析 Host → `$proxy_backend_addr`)/ `api`(8 条管理态 + 账号态路由)/ `lib`(`DomainPlugin` 装配) | +| `crates/plugin-sso/src/*` | **身份插件**(本仓库唯一业务 crate):`oauth`(OAuth2/OIDC 全部逻辑 + IAP 身份解析)/ `api`(路由表 + handler)/ `oauth_clients` / `oauth_keys`(OAuth/IAP 协议常量与共享内存键前缀,原属内核 `config`)/ `oauth_state`(OAuthClient 模型 + 注册表/授权码/会话状态,原属内核 `state`/`store`)/ `rsa`(手写 RS256)/ `captcha` / `otp`(TOTP 算法 + 账号侧 TOTP,数据存 `User.extra`)/ `scim`(SCIM 2.0 身份供给)/ `cas`(CAS 1.0/2.0 协议端点)/ `ldap`(LDAP/AD 认证源,零依赖手写 BER)/ `sync`(钉钉·企微·飞书同步连接器,手动触发)/ `reset`(自助密码重置)/ `geo`(登录 IP 归属地)/ `portal`(终端用户门户「我的应用」)/ `compat`(内核已移除的 http 辅助 `body_object`/`json_body`/`send_ct`/`redirect` 的兼容层,避免改子模块) | +| `deps/ipass/rust/crates/ipass-core/src/*` | **内核**(子模块 `ipass/ipass`):`state`(通用共享内存原语)/ `store`(JSON 原子读写)/ `users`(账号与 Key 的唯一写入口)/ `models`(仅共性字段 + `extra` 透传)/ `config`(仅共性策略常量与键前缀)/ `session`(管理员会话)/ `audit` / `http` / `util` / `plugin`(契约)/ `loc`(location 开关)。**不含** OAuth / TOTP 等个性代码 | +| `deps/ipass/rust/crates/plugin-domain/src/*` | **域名插件**(子模块 `ipass/ipass`):`keys`(`sub:` 前缀、企业域名 zone、子域名形状与 TTL 常量)/ `models`(`DomainEntry`)/ `domains`(校验、申请/审核/删除、写穿共享内存)/ `resolve`(access 阶段解析 Host → `$proxy_backend_addr`)/ `api`(管理态 + 账号态路由)/ `lib`(`DomainPlugin` 装配) | > `models.rs` 的 `User` 只含**共性字段**(凭据 / 身份声明 / 锁定);iPass 等插件的个性字段 > (`llm_*` / TOTP 种子等)一律走 `User.extra`(内核透传、不解释),因此内核不认识也能 @@ -213,7 +212,7 @@ bash scripts/run-local-e2e.sh --keep # 保留进程手工排查 | --- | --- | | **改了代码但行为没变** | 90% 是**没重启**。动态模块 `load_module` 时载入,reload 不重载 `.so` | | **worker 进程静默消失 / 全站 502** | worker 里 panic 了(`panic = "abort"`)。看 error.log 的 panic 栈,多半是热路径 `unwrap()` | -| 编译报 `unresolved imports ngx::http::HttpPhase` | 又用 crates.io 的 `ngx` 0.5.1 了。必须用 `source/rust/vendor/ngx-rust` | +| 编译报 `unresolved imports ngx::http::HttpPhase` | 又用 crates.io 的 `ngx` 0.5.1 了。必须用 `deps/ipass/rust/vendor/ngx-rust` | | `cargo build` 卡住数分钟 0% CPU | 又把 `ngx` 改回 git 依赖了 —— 它挂的 submodule 会去克隆完整 nginx 仓库 | | 链接报 `ld: symbol(s) not found` | `source/rust/build.rs` 的 `-undefined dynamic_lookup` 被删了(macOS 必需) | | nginx 启动即报 `unknown "auth_user" variable` | 变量注册漏了 `add_variable` 那一步(见「核心机制」第 4 条) | @@ -271,7 +270,7 @@ curl -s -b "$JAR" -X POST http://127.0.0.1:18098/api/admin/sync/dingtalk - **不要**引入数据库、Redis、消息队列或额外常驻进程 —— 本项目的价值就是单进程、零依赖。 - **LLM 上游代理与用量计费不搬回来**:那是流量层与计费层的职责,与本服务“身份层”的定位分界不变。 - (动态域名转发已作为 `plugin-domain` **示例插件**引入:它侧重“如何在内核之上新增一个能力插件”,而非做量。) + (动态域名转发已作为 `plugin-domain` **示例插件**迁入 `deps/ipass` 子模块:它侧重“如何在内核之上新增一个能力插件”,而非做量。) - **不要**在 `source/data/` 里手工改文件后期待热生效 —— **共享内存才是运行期真源**,改文件需重启。 - **不要**把 `source/data/` 提交进版本库,也不要在 `refs/` 里提交参考项目。 - **不要**重写整个 `nginx.conf` —— 它很短,**逐点修改**。 @@ -284,7 +283,7 @@ curl -s -b "$JAR" -X POST http://127.0.0.1:18098/api/admin/sync/dingtalk ## 新增一个插件(checklist) -1. 建 crate:`crates/plugin-xxx`,`Cargo.toml` 里写 `ipass-core.workspace = true`, +1. 建 crate:`deps/ipass` 子模块里的 `crates/plugin-xxx`,`Cargo.toml` 里写 `ipass-core.workspace = true`, 并在根 `Cargo.toml` 的 `members` 里登记。 2. 实现 `ipass_core::plugin::Plugin`: - `preconfig` —— 注册 nginx 变量(**两步缺一不可**:`ngx_http_add_variable` 登记 @@ -297,7 +296,7 @@ curl -s -b "$JAR" -X POST http://127.0.0.1:18098/api/admin/sync/dingtalk 与 `NGX_HTTP_SSO_COMMANDS`。 ⚠️ 配置指令**只能手工列在 gateway**:`ngx_module_t.commands` 是 null-terminated 连续数组,不同 crate 的 static 数组无法自动拼接。 -5. 需要给账号加字段 → 在 `ipass-core/src/models.rs` 加 `#[serde(default)]` 字段。 +5. 需要给账号加字段 → 在 `deps/ipass/.../ipass-core/src/models.rs` 加 `#[serde(default)]` 字段。 **纪律**(违反即失去「共用一份身份」的意义): diff --git a/README.md b/README.md index 98b590b..1eb5d09 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ # iPass 统一网关 —— 身份插件(nginx 动态模块 + Rust) -> 本仓库是 **iPass 统一网关**的代码库,形态是**内核 + 插件**(编译期装配,产出单个 `.so`): +> 本仓库是 **iPass 统一网关**中 **SSO(单点登录)身份插件**的代码库,形态是**内核 + 插件**(编译期装配,产出单个 `.so`): > -> | crate | 职责 | -> | --- | --- | -> | `ipass-core` | 内核:共享内存状态、`users.json` 与 API Key 的**唯一读写者** | -> | `plugin-sso` | 身份插件(本 README 的主体):OAuth2/OIDC + IAP | -> | `plugin-domain` | 域名插件:企业域名「子域名 → 后端」转发(新增能力插件的完整示例) | +> | crate | 仓库内? | 职责 | +> | --- | --- | --- | +> | `plugin-sso` | ✅ 本仓库 | 身份插件(本 README 的主体):OAuth2/OIDC + IAP | +> | `gateway` | ✅ 本仓库 | 装配层:module 壳 + 插件注册表 → `libsso_gateway.so` | +> | `ipass-core` / `plugin-domain` / `plugin-llm` / `plugin-apix` | ⬇️ `deps/ipass` 子模块 | 网关内核与通用能力插件(见 `ipass/ipass`),本仓库不再内置 | > > 判据:去掉 SSO,网关仍能转域名、仍能代理 LLM → 所以内核不是身份,**身份只是插件之一**。 +> 内核与通用子系统统一由 **`deps/ipass` git 子模块**(`ipass/ipass`)提供,本仓库只持有 `plugin-sso` + `gateway`。 > 架构论证见 `docs/plugin-architecture-analysis.md`。 自包含的 **OAuth2.0 / OIDC 身份提供者(IdP)** 与 **身份感知代理(IAP)**, @@ -22,8 +23,9 @@ 照抄 MaxKey 文档的第三方应用不用改一行代码。 > **身份与流量分离**:`plugin-sso` 只回答「你是谁」与「把这个身份告诉后端」。 -> 动态域名转发、LLM 上游代理、用量计费属于**其它插件**(来源存档见 `refs/ipass`), -> 与身份插件共用同一份 `users.json`、同一把 API Key——由 `ipass-core` 统一读写。 +> 动态域名转发、LLM 上游代理、用量计费属于**其它插件**,它们与身份插件一同来自 +> `deps/ipass` 子模块(`ipass/ipass`,来源存档见 `refs/ipass`)。所有插件共用同一份 +> `users.json`、同一把 API Key——由子模块内核 `ipass-core` 统一读写。 --- @@ -53,14 +55,17 @@ cd nginx-1.30.4 --without-http_uwsgi_module --without-http_scgi_module --without-http_grpc_module \ && make -j"$(sysctl -n hw.ncpu)" -# ③ 编译 Rust 模块 +# ③ 拉取内核子模块(首次克隆后只需一次) +git submodule update --init deps/ipass + +# ④ 编译 Rust 模块 cd <本仓库>/source/rust export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib # macOS export NGINX_SOURCE_DIR=/tmp/sso-build/src/nginx-1.30.4 export NGINX_BUILD_DIR=/tmp/sso-build/src/nginx-1.30.4/objs cargo build --release # 产物 source/rust/target/release/libsso_gateway.dylib -# ④ 一键跑七套端到端(自动播种数据、起 nginx + demo 系统、跑完自动清理) +# ⑤ 一键跑 SSO 端到端(自动播种数据、起 nginx + demo 系统、跑完自动清理) cd <本仓库> && bash scripts/run-local-e2e.sh ``` @@ -82,15 +87,16 @@ kill <打印出的 pid> ``` sso/ +├── deps/ +│ └── ipass/ # git 子模块 → ipass/ipass:内核 ipass-core + vendor/ngx-rust + 通用插件(plugin-domain/llm/apix) + gateway 装配骨架 ├── docs/ │ ├── design.md 设计文档:端点、token 模型、共享内存、MaxKey 互通、构建与测试 │ ├── roadmap.md 路线图(v1–v4 已完成 + 待办) │ └── screenshots/ 管理台与登录页截图 ├── source/ 可部署产物(代码 + 配置 + 静态页) -│ ├── rust/ 动态模块源码(Cargo workspace,vendor 了 ngx-rust) -│ │ ├── crates/ipass-core/ 内核:状态 / 账号 / Key 的唯一读写者 / 插件契约 -│ │ ├── crates/plugin-sso/ 身份插件:OAuth2 / OIDC + IAP -│ ├── crates/plugin-domain/ 域名插件:企业域名子域名转发(插件示例) +│ ├── rust/ 动态模块源码(本仓库的 Cargo workspace) +│ │ ├── Cargo.toml members=[crates/plugin-sso, gateway];ipass-core/ngx-rust 走 deps/ipass 的 path 依赖 +│ │ ├── crates/plugin-sso/ 身份插件:OAuth2 / OIDC + IAP(本仓库唯一业务 crate) │ │ └── gateway/ 装配层:module 壳 + 插件注册表 → libsso_gateway.so │ ├── conf/ │ │ ├── nginx.conf 生产模板(TLS、IAP 子域、日志字段) @@ -99,17 +105,16 @@ sso/ │ ├── www/admin.html 管理台单页(纯静态 + fetch;五个页签) │ ├── data-seed/ 种子模板(进版本库) │ └── data/ 运行时数据(**不进版本库**,由 scripts/seed-data.sh 生成) -├── tests/ 测试程序与测试应用 +├── tests/ 测试程序与测试应用(SSO 相关 e2e;域名/LLM 相关见 deps/ipass) │ ├── oauth2-e2e.sh 协议基线(discovery/grant/token/IAP 注入) │ ├── oauth2-maxkey-e2e.sh MaxKey 互通 + demo 系统接入 │ ├── admin-oauth-clients-e2e.sh 管理接口(接入方注册表) │ ├── rs256-jwks-e2e.sh RS256 + JWKS 本地验签 │ ├── admin-users-batch-e2e.sh 管理接口(账号批量维护) -│ ├── domain-e2e.sh 域名插件(申请/审核/转发) │ ├── maxkey-p1p2-e2e.sh MaxKey P1/P2(SCIM/CAS/密码重置/同步/LDAP/应用门户) │ └── demo-system/ 演示用「简单业务系统」(Python 标准库) ├── scripts/ -│ ├── run-local-e2e.sh 本机一键起停 + 跑七套 e2e +│ ├── run-local-e2e.sh 本机一键起停 + 跑 SSO e2e │ └── seed-data.sh 物化运行时数据目录 └── refs/ 参考资料(**不进版本库**):ipass 来源项目、MaxKey ``` @@ -257,14 +262,14 @@ env LDAP_AUTO_CREATE; # 1 = LDAP 认证成功但本地无账号时自动 ## 测试 ```bash -bash scripts/run-local-e2e.sh # 七套全跑(推荐) +bash scripts/run-local-e2e.sh # 本仓库 SSO e2e 全跑(推荐) bash tests/oauth2-e2e.sh http://127.0.0.1:18098 http://127.0.0.1:18099 # 协议基线 bash tests/oauth2-maxkey-e2e.sh # MaxKey 互通 + demo 接入 bash tests/admin-oauth-clients-e2e.sh # 管理接口(接入方) bash tests/rs256-jwks-e2e.sh # RS256 + JWKS 验签 bash tests/admin-users-batch-e2e.sh # 管理接口(账号批量) -bash tests/domain-e2e.sh # 域名插件 bash tests/maxkey-p1p2-e2e.sh # SCIM / CAS / 密码重置 / 同步 / LDAP +# 注:域名插件、LLM 上游代理等通用能力插件的 e2e 在 deps/ipass 子模块内运行 ``` 客户端密钥**不硬编码在脚本里**,运行时从 `$DATA_DIR/oauth_clients.json` 读取。 diff --git a/deps/ipass b/deps/ipass new file mode 160000 index 0000000..9c46e27 --- /dev/null +++ b/deps/ipass @@ -0,0 +1 @@ +Subproject commit 9c46e27eb5f59881ef7d80a21e3a941d97609726 diff --git a/docs/design.md b/docs/design.md index c19eedd..974a9a6 100644 --- a/docs/design.md +++ b/docs/design.md @@ -312,8 +312,8 @@ server { | `scripts/run-local-e2e.sh` | **新增**:macOS 本机 nginx + 模块一键起停并跑 e2e | | `source/data/users.json` | 种子用户补充 `email`/`department`/`groups`(数组) | | `source/data/oauth_clients.json`(及 `source/data-seed/`) | 新增 OAuth 客户端注册表(grafana / spa-demo / machine) | -| `rust/vendor/ngx-rust/nginx-sys/build/` | **补回**:`main.rs` + `wrapper.h`(官方 0.5.0 crate 的 bindgen 构建脚本,原被 `.gitignore` 的 `build/` 规则吞掉) | -| `.gitignore` | 加 `!rust/vendor/ngx-rust/nginx-sys/build/` 例外,并放行 `source/data/oauth_clients.json` | +| `deps/ipass/rust/vendor/ngx-rust/nginx-sys/build/` | **补回**:`main.rs` + `wrapper.h`(官方 0.5.0 crate 的 bindgen 构建脚本,原被子模块内 `.gitignore` 的 `build/` 规则吞掉) | +| `.gitignore` | 子模块内加 `!rust/vendor/ngx-rust/nginx-sys/build/` 例外,本仓库放行 `source/data/oauth_clients.json` | --- diff --git a/docs/plugin-architecture-analysis.md b/docs/plugin-architecture-analysis.md index 3b1dba7..0a23596 100644 --- a/docs/plugin-architecture-analysis.md +++ b/docs/plugin-architecture-analysis.md @@ -96,19 +96,27 @@ unsafe { (*var).get_handler = Some(auth_var_get); } // 覆盖 ## 四、定稿结构 +> 2026-09-21 起:本仓库**只持有 SSO 身份插件 + 装配层**,内核与通用能力插件统一由 +> `deps/ipass` git 子模块(`ipass/ipass`)提供,不再内置。 + ``` -source/rust/ -├── Cargo.toml # [workspace] members = crates/* + gateway -├── vendor/ngx-rust/ # 保持(path 依赖,不可走 crates.io / git) +source/rust/ # 本仓库的 Cargo workspace +├── Cargo.toml # members = [crates/plugin-sso, gateway];ipass-core/ngx-rust 走 deps/ipass 的 path 依赖 ├── crates/ -│ ├── ipass-core/ # 网关内核:唯一读写 users.json 的地方 -│ │ └── src/{config,models,users,store,state,session,util,http,audit,plugin}.rs -│ ├── plugin-sso/ # 身份插件:OAuth2/OIDC + IAP 注入 -│ │ └── src/{oauth,oauth_clients,rsa,otp,captcha,api}.rs -│ ├── plugin-domain/ # 动态域名(后续迁入) -│ └── plugin-llm/ # LLM 路由 / 配额(后续迁入) -└── gateway/ # 装配层:模块壳 + 插件注册表 → 单个 .so +│ └── plugin-sso/ # 身份插件:OAuth2/OIDC + IAP 注入(本仓库唯一业务 crate) +│ └── src/{oauth,oauth_clients,oauth_keys,oauth_state,rsa,otp,captcha,api,scim,cas,ldap,sync,reset,geo,portal,compat}.rs +└── gateway/ # 装配层:模块壳 + 插件注册表 → 单个 .so └── src/lib.rs + +deps/ipass/ # git 子模块 → ipass/ipass(内核 + 通用插件,本仓库不再内置) +└── rust/ + ├── Cargo.toml # 独立 workspace(resolver=2),ipass-core 解析 ngx/nginx-sys 的 [workspace.dependencies] + ├── vendor/ngx-rust/ # path 依赖,不可走 crates.io / git + └── crates/ + ├── ipass-core/ # 网关内核:唯一读写 users.json 的地方 + │ └── src/{config,models,users,store,state,session,util,http,audit,plugin,loc,api}.rs + ├── plugin-domain/ # 动态域名(已在子模块内) + └── plugin-llm/ # LLM 路由 / 配额(已在子模块内) ``` ### 插件契约 diff --git a/docs/roadmap.md b/docs/roadmap.md index e41478f..ac31bec 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -58,7 +58,7 @@ 4. **依赖与体积** - RSA 需要大数运算。优先评估 **手写**(`modpow` + 已有的 `sha2`)还是引入 `rsa` / `ring` / `num-bigint`——v1 的硬约定是「零新增依赖 / vendor 离线可编译」, - 引入前先确认能否 vendor 进 `source/rust/vendor/`。 + 引入前先确认能否 vendor 进 `deps/ipass/rust/vendor/`(内核与 `ngx-rust` 同处子模块)。 - 若用手写:`rsa` crate 的 PKCS#1 v1.5 + SHA-256 + RSASSA-PKCS1-v1_5 编码是固定长度填充, 实现量可控;签名的 `DigestInfo` DER 前缀是常量,可直接内联。 @@ -159,18 +159,18 @@ ## 插件化改造(2026-09-13) -架构定稿:内核是 **`ipass-core`**,**SSO 是插件之一**(与 `plugin-domain` / `plugin-llm` 平级); +架构定稿:内核是 **`ipass-core`**(现由 `deps/ipass` 子模块提供),**SSO 是插件之一**(与 `plugin-domain` / `plugin-llm` 平级); `users.json` **全局共用一份,由内核独占读写**,插件只读不写。 -- [x] workspace 拆分:`crates/ipass-core` + `crates/plugin-sso` + `gateway`,产出**单个** `.so` +- [x] workspace 拆分:本仓库 `crates/plugin-sso` + `gateway`,产出**单个** `.so`;内核 `ipass-core` 与通用插件(`plugin-domain` / `plugin-llm`)迁入 `deps/ipass` 子模块 - [x] 内核收口:`config`(仅共性)/ `models`(仅共性 + `extra` 透传)/ `store` / `state`(仅通用原语)/ `session` / `users` / `audit` / `http` / `util`(个性能力 TOTP 归 `plugin-sso` 的 `otp.rs`;OAuth 协议常量/键前缀归 `oauth_keys.rs`、OAuthClient 模型与注册表/授权码/会话状态归 `oauth_state.rs`,均原属内核 `config`/`state`/`store`) - [x] `User` 共性字段 + `extra` 透传:iPass 等插件的个性字段(`llm_*` / `temp_grant_until` / TOTP 种子等) 经 `extra` 落盘,全部 `#[serde(default)]`;已验证 iPass 存量 `users.json` **无字段丢失** - [x] 插件契约 `Plugin::{preconfig, postconfig, dispatch_api, zone_load}`; 装配顺序 = `gateway` 里 `PLUGINS` 数组的顺序,**显式可控** - [x] 五套 e2e 全绿(rc=0),行为与重构前完全等价 -- [x] 六套 e2e 全绿(rc=0),新增 `tests/domain-e2e.sh`(域名插件:鉴权 / 转发 / 申请审核 / 写穿生效) -- [x] P2(部分):迁入 `plugin-domain`(域名插件)作为“新增能力插件”的完整示例:crate + `sso_domain` 开关 + 编译装配 + 用例(`tests/domain-e2e.sh`,43 项)。 +- [x] 六套 e2e 全绿(rc=0);域名插件 e2e(`tests/domain-e2e.sh`)随 `plugin-domain` 迁入 `deps/ipass` 子模块(本仓库不再内置) +- [x] P2(部分):`plugin-domain`(域名插件)作为“新增能力插件”的完整示例,已迁入 `deps/ipass` 子模块:crate + `sso_domain` 开关 + 编译装配 + 用例(43 项)。 **`plugin-llm` 明确不迁入**:LLM 上游代理与配额计费属流量层,与本服务定位分界不变(已从 workspace 移除)。 - [ ] 仓库归属:是否新建 `ssw/ipass` 仓库(当前仍在 `ssw/sso`) diff --git a/docs/upstream-core-changes.md b/docs/upstream-core-changes.md index 55f46bb..ff25e3d 100644 --- a/docs/upstream-core-changes.md +++ b/docs/upstream-core-changes.md @@ -1,5 +1,7 @@ # 致 ipass 上游:内核修改建议(基于 ddd4172 对照) +> **状态(2026-09-21)**:本仓库已不再内置内核,统一通过 `deps/ipass` git 子模块(`ipass/ipass`)消费上游内核;文中「我方 ipass-core」即指该子模块。本文保留为历史对照。 + > 背景:ssw/sso 正按「上游 ipass-core 为内核基准」收敛——内核原样复制,域名插件以上游为准, > sso 作为纯插件并入。收敛过程中发现以下内核问题,**按影响分两档**: > **A 档 = 请求上游修改**(不改则两侧合流后有实际损失); diff --git a/docs/upstream-sync-2026-09-13.md b/docs/upstream-sync-2026-09-13.md index a4e3309..db8e47f 100644 --- a/docs/upstream-sync-2026-09-13.md +++ b/docs/upstream-sync-2026-09-13.md @@ -1,5 +1,7 @@ # 与上游 ipass 的一致性核对(2026-09-13) +> **状态(2026-09-21)**:本仓库已不再内置内核,统一通过 `deps/ipass` git 子模块(`ipass/ipass`)消费上游内核;文中「我方 ipass-core」即指该子模块。本文保留为历史对照。 + 上游仓库:`http://192.168.1.18:13300/ssw/ipass` → 拉到本地 `refs/ipass`。 本次核对分两轮: - **第一轮**:`1f548ac` → `1fb83e4`(2 个新提交,当时上游仍为单体,见第 0–6 节)。 diff --git a/scripts/run-local-e2e.sh b/scripts/run-local-e2e.sh index 4f048f5..9d06679 100755 --- a/scripts/run-local-e2e.sh +++ b/scripts/run-local-e2e.sh @@ -214,7 +214,7 @@ for i in $(seq 1 30); do done # --------------------------------------------------------------------------- -# 跑测试(五套,各自独立计分) +# 跑测试(六套,各自独立计分;域名/LLM 等通用插件 e2e 见 deps/ipass 子模块) # --------------------------------------------------------------------------- RC=0 set +e @@ -239,13 +239,9 @@ echo "############### [5/6] 管理接口:账号批量维护 ###############" bash "$ROOT/tests/admin-users-batch-e2e.sh" "$HOST_IDP" "$DATA_DIR" "$HOST_IAP_DEMO" RC5=$? echo -echo "############### [6/6] 域名插件:申请 / 审核 / 转发 ###############" -bash "$ROOT/tests/domain-e2e.sh" "$HOST_IDP" "$HOST_DOMAIN" "$DATA_DIR" -RC6=$? -echo -echo "############### [7/7] MaxKey P1/P2 新增能力(SCIM/CAS/密码重置/同步/LDAP) ###############" +echo "############### [6/6] MaxKey P1/P2 新增能力(SCIM/CAS/密码重置/同步/LDAP) ###############" bash "$ROOT/tests/maxkey-p1p2-e2e.sh" "$HOST_IDP" "$DATA_DIR" -RC7=$? +RC6=$? set -e [ "$RC1" != "0" ] && RC=1 [ "$RC2" != "0" ] && RC=1 @@ -253,10 +249,9 @@ set -e [ "$RC4" != "0" ] && RC=1 [ "$RC5" != "0" ] && RC=1 [ "$RC6" != "0" ] && RC=1 -[ "$RC7" != "0" ] && RC=1 echo -echo "## [summary] 基线 rc=$RC1 互通/接入 rc=$RC2 管理接口 rc=$RC3 RS256/JWKS rc=$RC4 账号批量维护 rc=$RC5 域名插件 rc=$RC6 P1/P2 新增 rc=$RC7" +echo "## [summary] 基线 rc=$RC1 互通/接入 rc=$RC2 管理接口 rc=$RC3 RS256/JWKS rc=$RC4 账号批量维护 rc=$RC5 P1/P2 新增 rc=$RC6" if [ "$KEEP" = "1" ]; then echo "## [done] 测试完成 (rc=$RC);进程保留,手动排查:" echo " kill $NGX_PID $DEMO_PID" diff --git a/source/rust/Cargo.lock b/source/rust/Cargo.lock index b31b739..62abadd 100644 --- a/source/rust/Cargo.lock +++ b/source/rust/Cargo.lock @@ -54,9 +54,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.4.5" +version = "1.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" dependencies = [ "find-msvc-tools", "shlex 2.0.1", @@ -73,9 +73,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "clang-sys" @@ -141,9 +141,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" [[package]] name = "generic-array" @@ -174,7 +174,7 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "ipass-core" -version = "1.0.0" +version = "2.0.0" dependencies = [ "getrandom", "libc", @@ -274,16 +274,6 @@ dependencies = [ "minimal-lexical", ] -[[package]] -name = "plugin-domain" -version = "2.0.0" -dependencies = [ - "ipass-core", - "ngx", - "serde", - "serde_json", -] - [[package]] name = "plugin-sso" version = "1.0.0" @@ -392,7 +382,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.5", + "syn 3.0.6", ] [[package]] @@ -438,7 +428,6 @@ dependencies = [ "ipass-core", "nginx-sys", "ngx", - "plugin-domain", "plugin-sso", ] @@ -455,9 +444,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.5" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" dependencies = [ "proc-macro2", "quote", @@ -472,9 +461,9 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" [[package]] name = "version_check" diff --git a/source/rust/Cargo.toml b/source/rust/Cargo.toml index a23c3f0..80a9edb 100644 --- a/source/rust/Cargo.toml +++ b/source/rust/Cargo.toml @@ -1,20 +1,23 @@ -# iPass 统一网关 —— Cargo workspace +# iPass SSO 网关 —— Cargo workspace # -# 结构: -# crates/ipass-core 网关内核:共享内存状态、users.json 的唯一读写者、账号与 Key -# crates/plugin-sso 身份插件:OAuth2/OIDC 签发与校验、IAP 身份注入 -# crates/plugin-domain 域名插件:内核之上「新增一个能力插件」的完整示例 -# gateway 装配层:module 壳 + 插件注册表 → 产出单个 .so +# 结构(参考 ipass/cache 的插件化拆分思路): +# 本仓库只持有「SSO 身份网关」自身: +# crates/plugin-sso —— 身份插件:OAuth2/OIDC 签发与校验、IAP 身份注入 +# gateway —— 装配层:module 壳 + 插件注册表 → 产出单个 .so +# +# 通用框架(内核 ipass-core / 唯一 cdylib 装配 / vendored ngx-rust / 其它子系统) +# 全部来自主项目 ipass/ipass,经仓库根 `deps/ipass` git submodule 引入, +# 不在此仓库重复维护(避免与上游内核 fork 漂移)。 # # 为什么是「单 .so + crate 级插件」而不是「多 .so 运行时插件」: # nginx 动态模块没有稳定 ABI,Rust 侧更是如此(每个 cdylib 各链一份 std)。 # 跨 .so 共享状态要自己造 C ABI 契约,且 zone tag / 同名变量都会冲突 # (详见 docs/plugin-architecture-analysis.md)。 # -# ⚠️ vendor/ngx-rust 本身是 workspace 根,必须 exclude,否则 cargo 报歧义。 +# ⚠️ deps/ipass 是独立 workspace,必须 exclude,否则 cargo 报歧义。 [workspace] -members = ["crates/ipass-core", "crates/plugin-sso", "crates/plugin-domain", "gateway"] -exclude = ["vendor/ngx-rust"] +members = ["crates/plugin-sso", "gateway"] +exclude = ["../../deps/ipass", "target"] [workspace.package] version = "1.0.0" @@ -22,7 +25,8 @@ edition = "2021" publish = false # --------------------------------------------------------------------------- -# ⚠️ 依赖必须用 vendored 源码,不能走 crates.io,也不能走 git: +# ⚠️ 依赖必须用 vendored 源码(deps/ipass 子模块内的 ngx-rust),不能走 crates.io, +# 也不能走 git: # # 1) `ngx = "0.5"`(crates.io 0.5.1)只发布了配置阶段接口(HttpModule), # 请求阶段 API(add_phase_handler / HttpPhase / HttpRequestHandler)尚未发版, @@ -34,14 +38,14 @@ publish = false # 国内网络下卡死(实测 cargo 5 分钟 0% CPU,调用栈停在 # GitSource::block_until_ready -> GitCheckout::update_submodules -> fetch -> wait4)。 # -# 因此 vendor 到 vendor/ngx-rust/,用 path 依赖:离线可编译、无子模块、版本锁定。 +# 因此 vendor 到 deps/ipass/rust/vendor/ngx-rust/,用 path 依赖: +# 离线可编译、无子模块、版本锁定。 # --------------------------------------------------------------------------- [workspace.dependencies] -ngx = { path = "vendor/ngx-rust" } -nginx-sys = { path = "vendor/ngx-rust/nginx-sys" } -ipass-core = { path = "crates/ipass-core" } +ngx = { path = "../../deps/ipass/rust/vendor/ngx-rust" } +nginx-sys = { path = "../../deps/ipass/rust/vendor/ngx-rust/nginx-sys" } +ipass-core = { path = "../../deps/ipass/rust/crates/ipass-core" } plugin-sso = { path = "crates/plugin-sso" } -plugin-domain = { path = "crates/plugin-domain" } # 业务层依赖:全部是纯 Rust 实现,不引入任何系统库或常驻依赖 serde = { version = "1", features = ["derive"] } diff --git a/source/rust/crates/ipass-core/Cargo.toml b/source/rust/crates/ipass-core/Cargo.toml deleted file mode 100644 index 750228f..0000000 --- a/source/rust/crates/ipass-core/Cargo.toml +++ /dev/null @@ -1,20 +0,0 @@ -[package] -name = "ipass-core" -version.workspace = true -edition.workspace = true -publish.workspace = true -description = "iPass 网关内核 —— 共享内存状态、users.json 与 API Key 的唯一持有者" - -[lib] -# rlib:内核不直接产出 .so,由 gateway 装配后统一产出 -name = "ipass_core" -crate-type = ["rlib"] - -[dependencies] -ngx.workspace = true -nginx-sys.workspace = true -serde.workspace = true -serde_json.workspace = true -sha2.workspace = true -getrandom.workspace = true -libc.workspace = true diff --git a/source/rust/crates/ipass-core/src/api.rs b/source/rust/crates/ipass-core/src/api.rs deleted file mode 100644 index 88b4972..0000000 --- a/source/rust/crates/ipass-core/src/api.rs +++ /dev/null @@ -1,465 +0,0 @@ -//! 身份类端点(登录 / 会话 / 账号管理)+ API 分发的公共契约。 -//! -//! 会话与账号是内核职责(所有插件端点的公共前置),所以这批端点由 -//! `CorePlugin` 直接认领,gateway 把它排在 `PLUGINS` 最前。 -//! -//! ## `CoreExt`:身份端点的插件扩展点 -//! -//! 身份端点偶尔需要**插件侧数据**(账号列表要带域名数与用量、删账号要连带 -//! 回收域名、白名单要校验上游存在)。内核不认识插件,这些数据一律通过 -//! [`CoreExt`] 反转:gateway 作为**装配根**实现并注册([`set_ext`]), -//! 没注册时端点仍可工作(缺装饰、零回收),只是功能变素。 -//! -//! 路由与鉴权原语([`Guard`] / [`Actor`] / [`run_guarded`] / [`user_or_401`]) -//! 同时供各插件的路由表复用——四份 route 表共用一套鉴权语义。 - -use std::sync::Mutex; - -use ngx::core::Status; -use ngx::ffi::ngx_http_request_t; -use ngx::http::HTTPStatus; -use serde_json::{Value, json}; - -use crate::config; -use crate::http; -use crate::models::User; -use crate::plugin::Plugin; -use crate::session; -use crate::state; -use crate::users; -use crate::util; - -// =========================================================================== -// 鉴权契约(供内核与各插件的路由表共用) -// =========================================================================== - -/// 鉴权后传给处理器的身份 -pub enum Actor { - /// 公开接口,无身份 - None, - /// 账号态(X-API-Key) - User(User), - /// 管理员态(登录会话) - Admin(User), -} - -impl Actor { - /// 操作者名称:审核记录 `reviewed_by`、审计日志都用它 - pub fn admin_name(&self) -> &str { - match self { - Actor::Admin(u) => &u.username, - Actor::User(u) => &u.username, - Actor::None => "", - } - } -} - -#[derive(Clone, Copy, PartialEq)] -pub enum Guard { - Public, - User, - Admin, -} - -pub type Handler = fn(*mut ngx_http_request_t, Actor) -> Status; - -/// 账号态接口的公共前置:取账号身份,取不到就回 401(响应已发出)。 -pub fn user_or_401(r: *mut ngx_http_request_t, actor: Actor) -> Result { - match actor { - Actor::User(u) => Ok(u), - _ => Err(http::fail( - r, - HTTPStatus::UNAUTHORIZED, - "API Key 无效或缺失,请在请求头携带 X-API-Key", - )), - } -} - -/// 账号态鉴权(X-API-Key → users.json 反查)。失败只记日志,由调用方回 401。 -pub fn authenticate_user(r: *mut ngx_http_request_t) -> Option { - let key = http::header(r, "x-api-key").unwrap_or_default(); - match users::find_by_key(&key) { - Some(u) => Some(u), - None => { - util::log_warn(&format!( - "[api] API Key 校验失败 client={}", - http::remote_addr(r) - )); - None - } - } -} - -/// 管理员态鉴权(会话 Cookie → 账号)。会话有效但非管理员回 403 而不是 401, -/// 便于前端区分;两种失败都已把响应写进 r,调用方直接终止即可。 -pub fn authenticate_admin(r: *mut ngx_http_request_t) -> Result { - let cookie = http::header(r, "cookie"); - match session::authenticate(cookie.as_deref()).and_then(|name| users::get(&name)) { - Some(u) if u.is_admin() => Ok(u), - Some(_) => Err(http::fail(r, HTTPStatus::FORBIDDEN, "需要管理员权限")), - None => Err(http::fail( - r, - HTTPStatus::UNAUTHORIZED, - "未登录或会话已过期,请重新登录", - )), - } -} - -/// 鉴权 + 执行:按 Guard 求出 Actor 后调用 handler。 -pub fn run_guarded(r: *mut ngx_http_request_t, guard: Guard, handler: Handler) -> Status { - let actor = match guard { - Guard::Public => Actor::None, - Guard::User => match authenticate_user(r) { - Some(u) => Actor::User(u), - None => { - return http::fail( - r, - HTTPStatus::UNAUTHORIZED, - "API Key 无效或缺失,请在请求头携带 X-API-Key", - ); - } - }, - Guard::Admin => match authenticate_admin(r) { - Ok(u) => Actor::Admin(u), - Err(status) => return status, - }, - }; - handler(r, actor) -} - -// =========================================================================== -// 插件扩展点 -// =========================================================================== - -/// 身份端点的插件扩展点。gateway 实现并注册;**方法都给缺省实现**, -/// 没注册扩展时端点仍可用(账号列表缺装饰、删账号不连带回收)。 -pub trait CoreExt: Sync { - /// 管理台账号列表:插件侧装饰(域名数 / 用量摘要),一次批量给全部账号 - fn decorate_admin_users(&self, _views: &mut [Value]) {} - /// `/api/v1/me`:插件侧装饰(我的域名 / 用量摘要 / 策略 TTL) - fn decorate_me(&self, _username: &str, _view: &mut Value) {} - /// 删除账号:连带回收该账号名下资源(域名),返回条数 - fn reclaim_on_delete(&self, _username: &str) -> usize { - 0 - } - /// 账号「可用上游」白名单校验:slot 必须真实存在(plugin-llm 提供) - fn validate_slots(&self, _slots: &[String]) -> Result<(), String> { - Ok(()) - } -} - -static EXT: Mutex> = Mutex::new(None); - -/// gateway 在配置解析前注册(装配根是唯一注册方) -pub fn set_ext(e: &'static dyn CoreExt) { - if let Ok(mut slot) = EXT.lock() { - *slot = Some(e); - } -} - -fn ext() -> Option<&'static dyn CoreExt> { - let guard = EXT.lock().ok()?; - guard.as_ref().copied() -} - -// =========================================================================== -// 路由 -// =========================================================================== - -/// 路由表。刻意用精确匹配而非正则——接口路径是固定的, -/// 正则只会引入「写错锚点导致前缀误匹配」的风险。 -fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> { - let entry: (Guard, Handler) = match (method, uri) { - ("POST", "/api/admin/login") => (Guard::Public, h_login), - ("POST", "/api/admin/logout") => (Guard::Admin, h_logout), - ("GET", "/api/admin/session") => (Guard::Admin, h_session), - ("GET", "/api/admin/users") => (Guard::Admin, h_admin_users), - ("POST", "/api/admin/users/create") => (Guard::Admin, h_admin_user_create), - ("POST", "/api/admin/users/key") => (Guard::Admin, h_admin_user_key), - ("POST", "/api/admin/users/grant") => (Guard::Admin, h_admin_user_grant), - ("POST", "/api/admin/users/password") => (Guard::Admin, h_admin_user_password), - ("POST", "/api/admin/users/delete") => (Guard::Admin, h_admin_user_delete), - ("POST", "/api/admin/users/models") => (Guard::Admin, h_admin_user_models), - ("POST", "/api/admin/users/limits") => (Guard::Admin, h_admin_user_limits), - ("POST", "/api/admin/users/display") => (Guard::Admin, h_admin_user_display), - ("GET", "/api/v1/me") => (Guard::User, h_me), - _ => return None, - }; - Some(entry) -} - -/// 本表分发:认领则返回响应状态,不认领返回 `None`(交给下一个插件)。 -pub fn dispatch(r: *mut ngx_http_request_t) -> Option { - let method = http::method_str(r); - let uri = http::uri(r); - - let Some((guard, handler)) = route(&method, &uri) else { - return None; - }; - - Some(run_guarded(r, guard, handler)) -} - -// =========================================================================== -// 管理员:登录 / 会话 -// =========================================================================== - -fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let ip = http::remote_addr(r); - let now = util::now(); - - if state::get_login_fail(&ip, now) >= config::LOGIN_MAX_FAIL { - return http::fail(r, HTTPStatus::TOO_MANY_REQUESTS, "登录失败次数过多,请 5 分钟后再试"); - } - - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let password = p.get("password").cloned().unwrap_or_default(); - - if username.is_empty() || password.is_empty() { - return http::fail(r, HTTPStatus::BAD_REQUEST, "请输入账号和密码"); - } - - let Some(user) = users::get(&username) else { - state::bump_login_fail(&ip, now); - util::log_warn(&format!("[api] 登录失败 user={username} client={ip}")); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); - }; - - if !util::verify_password(&password, &user.salt, &user.pwd_hash) { - state::bump_login_fail(&ip, now); - util::log_warn(&format!("[api] 登录失败 user={username} client={ip}")); - return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); - } - - if !user.is_admin() { - return http::fail(r, HTTPStatus::FORBIDDEN, "该账号不是管理员,无法登录管理台"); - } - - state::clear_login_fail(&ip); - let token = session::create(&username); - let cookie = session::set_cookie(&token); - util::log_notice(&format!("[api] 管理员登录 user={username} client={ip}")); - - http::ok_with(r, users::view(&user), "登录成功", &[("Set-Cookie", &cookie)]) -} - -fn h_logout(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let cookie = http::header(r, "cookie"); - session::destroy(cookie.as_deref()); - let cleared = session::clear_cookie(); - http::ok_with(r, json!({}), "已退出登录", &[("Set-Cookie", &cleared)]) -} - -fn h_session(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let Actor::Admin(user) = actor else { - return http::fail(r, HTTPStatus::UNAUTHORIZED, "未登录或会话已过期,请重新登录"); - }; - http::ok(r, users::view(&user), "ok") -} - -// =========================================================================== -// 管理员:账号管理 -// =========================================================================== - -fn h_admin_users(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let mut items: Vec = users::all().iter().map(|u| users::view(u)).collect(); - // 域名数 / 用量等插件数据由装配根装饰(见 CoreExt::decorate_admin_users) - if let Some(e) = ext() { - e.decorate_admin_users(&mut items); - } - http::ok(r, json!({ "items": items }), "ok") -} - -fn h_admin_user_create(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let grant_temp = util::to_bool(p.get("grant_temp")); - - match users::create( - p.get("username").map(String::as_str).unwrap_or(""), - p.get("display_name").map(String::as_str).unwrap_or(""), - p.get("password").map(String::as_str).unwrap_or(""), - p.get("role").map(String::as_str).unwrap_or("user"), - grant_temp, - ) { - Ok(user) => { - util::log_notice(&format!( - "[api] 创建账号 {} name={} role={} temp_grant={grant_temp}", - user.username, user.display_name, user.role - )); - http::ok(r, users::view(&user), "账号创建成功") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 设置展示名(中文姓名等)。传空串 = 清空,前端回落到账号名。 -fn h_admin_user_display(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - match users::set_display_name(&username, p.get("display_name").map(String::as_str).unwrap_or("")) { - Ok(u) => http::ok(r, users::view(&u), "已更新展示名"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_user_key(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - match users::regenerate_key(&username) { - Ok(key) => http::ok(r, json!({ "username": username, "api_key": key }), "已重置 API Key"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_user_grant(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - if util::to_bool(p.get("revoke")) { - if let Err(e) = users::revoke_temp(&username) { - return http::fail(r, HTTPStatus::BAD_REQUEST, &e); - } - let view = users::get(&username).map(|u| users::view(&u)).unwrap_or(Value::Null); - return http::ok(r, view, "已取消临时授权权限"); - } - - match users::grant_temp(&username, p.get("hours")) { - Ok(_) => { - let view = users::get(&username).map(|u| users::view(&u)).unwrap_or(Value::Null); - http::ok(r, view, "已授予临时授权权限") - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_user_password(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - let password = p.get("password").map(String::as_str).unwrap_or(""); - - match users::set_password(&username, password) { - Ok(()) => http::ok(r, json!({}), "密码已重置"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_user_delete(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - if let Err(e) = users::delete(&username, actor.admin_name()) { - return http::fail(r, HTTPStatus::BAD_REQUEST, &e); - } - - // 连带回收该账号名下的资源(域名等),避免出现无主映射—— - // 装了哪些插件就回收哪些(CoreExt::reclaim_on_delete) - let removed = ext().map(|e| e.reclaim_on_delete(&username)).unwrap_or(0); - util::log_notice(&format!("[api] 删除账号 {username},连带域名 {removed} 条")); - http::ok(r, json!({ "removed_domains": removed }), "账号已删除") -} - -/// 设置某账号可用的 LLM 上游白名单(`models` 字段 = 上游 slot 列表,传空串 = 解除限制)。 -/// -/// 注意与**上游登记模型清单**(`Upstream.models`)是两件事:这里管"这个账号能用哪几家 -/// 上游",那里管"这家上游提供哪些模型"。白名单按 slot 生效,模型发现再按白名单过滤。 -fn h_admin_user_models(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - let slots: Vec = p - .get("models") - .map(|s| { - s.split(',') - .map(|x| x.trim().to_owned()) - .filter(|x| !x.is_empty()) - .collect() - }) - .unwrap_or_default(); - - // 上游必须先存在:否则白名单里会存进永远匹配不上的死名字, - // 表现为「账号被授权了却一直 403」,排查起来很绕。 - // 上游表属 plugin-llm,经 CoreExt 校验。 - if let Err(e) = ext().map(|e| e.validate_slots(&slots)).unwrap_or(Ok(())) { - return http::fail(r, HTTPStatus::BAD_REQUEST, &e); - } - - match users::set_allowed_models(&username, slots) { - Ok(u) => http::ok(r, users::view(&u), "已更新可用上游"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -/// 设置账号的 LLM 限流参数。字段缺省 = 保持现值,`0` = 不限。 -fn h_admin_user_limits(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); - - let parse_limit = |key: &str| -> Result, String> { - match p.get(key) { - None => Ok(None), - Some(v) if util::trim(v).is_empty() => Ok(None), - Some(v) => util::trim(v) - .parse::() - .map(Some) - .map_err(|_| format!("{key} 必须是非负整数(0 表示不限)")), - } - }; - - let rpm = match parse_limit("rpm") { - Ok(v) => v, - Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e), - }; - let daily = match parse_limit("daily") { - Ok(v) => v, - Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e), - }; - if rpm.is_none() && daily.is_none() { - return http::fail(r, HTTPStatus::BAD_REQUEST, "至少提供 rpm 或 daily 之一"); - } - - util::log_notice(&format!( - "[api] 设置账号 {username} LLM 限流 rpm={rpm:?} daily={daily:?}" - )); - match users::set_llm_limits(&username, rpm, daily) { - Ok(u) => http::ok(r, users::view(&u), "已更新限流参数"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -// =========================================================================== -// 账号态 -// =========================================================================== - -fn h_me(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let user = match user_or_401(r, actor) { - Ok(u) => u, - Err(e) => return e, - }; - - let mut v = users::view(&user); - // 我的域名 / 用量摘要 / 策略 TTL 都是插件侧数据,由装配根装饰 - if let Some(e) = ext() { - e.decorate_me(&user.username, &mut v); - } - http::ok(r, v, "ok") -} - -// =========================================================================== -// 装配 -// =========================================================================== - -/// 内核插件:认领身份类端点。必须排在 gateway 的 `PLUGINS` **最前**。 -pub struct CorePlugin; - -impl Plugin for CorePlugin { - fn name(&self) -> &'static str { - "core" - } - - fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option { - dispatch(r) - } -} diff --git a/source/rust/crates/ipass-core/src/auth.rs b/source/rust/crates/ipass-core/src/auth.rs deleted file mode 100644 index da612cc..0000000 --- a/source/rust/crates/ipass-core/src/auth.rs +++ /dev/null @@ -1,181 +0,0 @@ -//! 下行链路鉴权与配额 —— LLM 代理与 API 代理(apix)**共用**的契约。 -//! -//! 「去掉 llm 还要(apix 要)、去掉 apix 还要(llm 要)、两个都去掉才不要」 -//! ⇒ 共用 ⇒ 放内核(docs/plugin/PLUGINIZATION_PLAN.md §4②)。 -//! -//! * [`downstream_key`] —— 取下行 Key(三种携带方式) -//! * [`identity`] —— 查 `ukey:` 身份(纯共享内存,热路径不回读 users.json) -//! * [`check_quota`] —— `rl:` 每分钟限流 + `st:` 每日配额(先增后判) -//! * [`fail`] / [`fail_typed`] —— OpenAI 兼容错误体(下行客户端的 SDK 只认这个) -//! -//! ⚠️ access 阶段返回 `NGX_OK` 等于放行:鉴权失败必须返回状态码, -//! 否则请求照样被 `proxy_pass` 转发——「客户端收到 401,但上游仍被调了一次」, -//! 白烧上游额度且账单上看不出这是一次被拒的请求。实测踩过。 - -use ngx::core::Status; -use ngx::ffi::{ngx_http_request_t, ngx_int_t}; -use ngx::http::HTTPStatus; -use serde_json::json; - -use crate::config; -use crate::http; -use crate::state; -use crate::util; - -// =========================================================================== -// 请求解析 -// =========================================================================== - -/// 取下行 Key。 -/// -/// 依次尝试三种携带方式,覆盖主流 SDK 的默认行为: -/// `Authorization: Bearer`(OpenAI)、`x-api-key`(Anthropic)、`X-API-Key`(本项目域名接口)。 -/// 「同一套 Key」意味着这三个位置放的都应该是 `users.json` 里那把 `sk_...`。 -pub fn downstream_key(r: *mut ngx_http_request_t) -> Option { - if let Some(raw) = http::header(r, "authorization") { - let raw = raw.trim(); - let rest = raw - .strip_prefix("Bearer ") - .or_else(|| raw.strip_prefix("bearer ")); - if let Some(k) = rest { - let k = k.trim(); - if !k.is_empty() { - return Some(k.to_owned()); - } - } - } - for name in ["x-api-key", "api-key"] { - if let Some(k) = http::header(r, name) { - let k = k.trim().to_owned(); - if !k.is_empty() { - return Some(k); - } - } - } - None -} - -/// 查共享内存拿身份:`(username, allowed_slots, rpm, daily)`。 -/// -/// `allowed_slots` 为空表示不限(老账号没有该字段,反序列化即空表)。 -/// `rpm` / `daily` 是限流上限;旧版 payload 只有 2 行,此时按全局默认兜底。 -pub fn identity(key: &str) -> Option<(String, Vec, i64, i64)> { - let payload = state::get_live(config::KEY_UKEY_PREFIX, key.as_bytes(), util::now())?; - let mut lines = payload.split('\n'); - let name = lines.next().unwrap_or(""); - let allowed = lines.next().unwrap_or(""); - let rpm = lines - .next() - .and_then(|s| s.parse::().ok()) - .unwrap_or(config::LLM_RPM_DEFAULT); - let daily = lines - .next() - .and_then(|s| s.parse::().ok()) - .unwrap_or(config::LLM_DAILY_DEFAULT); - if name.is_empty() { - return None; - } - let slots: Vec = if allowed.is_empty() { - Vec::new() - } else { - allowed - .split(',') - .map(|s| s.trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect() - }; - Some((name.to_owned(), slots, rpm, daily)) -} - -// =========================================================================== -// 响应 -// =========================================================================== - -/// OpenAI 兼容的错误体。客户端 SDK 只认这个形状。 -/// -/// **返回状态码而不是 `NGX_OK`**——见模块头注释。 -pub fn fail(r: *mut ngx_http_request_t, status: HTTPStatus, code: &str, msg: &str) -> Status { - fail_typed(r, status, "invalid_request_error", code, msg) -} - -/// 同 [`fail`],但 `type` 字段可指定——429 限流应返回 `rate_limit_error`, -/// SDK(尤其 OpenAI 官方库)据此做退避重试,写成 `invalid_request_error` -/// 会被当成「请求本身有问题」而直接放弃。 -pub fn fail_typed( - r: *mut ngx_http_request_t, - status: HTTPStatus, - err_type: &str, - code: &str, - msg: &str, -) -> Status { - let body = json!({ - "error": { - "message": msg, - "type": err_type, - "code": code, - } - }) - .to_string(); - - let http_code = status.0 as ngx_int_t; - // 先把自定义响应体发出去(nginx 之后不会再补一份默认错误页,因为 header 已发) - let _ = http::send(r, status, &body); - // 再把状态码交回 nginx,由它终结本请求 - Status(http_code) -} - -// =========================================================================== -// 限流与配额 -// =========================================================================== - -/// 限流与每日配额检查。拒绝时直接发 429 并返回 Some(状态),放行返回 None。 -/// -/// **先增后判**:窗口计数里也包含被拒的请求。这只影响「超限后计数继续涨」, -/// 不影响正确性(反正已在超限状态);换来的是实现无需区分「合法请求才计数」。 -/// -/// # Safety -/// `r` 由 nginx 传入且有效。 -pub unsafe fn check_quota( - r: *mut ngx_http_request_t, - username: &str, - rpm: i64, - daily: i64, -) -> Option { - let now = util::now(); - - // 每分钟窗口(60s 滚动对齐到自然分钟)。rpm<=0 表示不限,跳过计数省一次写 - if rpm > 0 { - let used = state::bump_window(config::KEY_RL_PREFIX, username, now / 60); - if used > rpm { - util::log_warn(&format!( - "[llm] {username} 触发每分钟限流 {used}/{rpm},本请求 429" - )); - return Some(fail_typed( - r, - HTTPStatus::TOO_MANY_REQUESTS, - "rate_limit_error", - "rate_limit_exceeded", - &format!("请求过于频繁:每分钟上限 {rpm} 次,请稍后重试"), - )); - } - } - - // 每日窗口按本地自然日切(见 util::day_id) - if daily > 0 { - let today = state::bump_window(config::KEY_ST_PREFIX, username, util::day_id(now)); - if today > daily { - util::log_warn(&format!( - "[llm] {username} 触发每日配额 {today}/{daily},本请求 429" - )); - return Some(fail_typed( - r, - HTTPStatus::TOO_MANY_REQUESTS, - "insufficient_quota", - "insufficient_quota", - &format!("已达每日请求上限 {daily} 次,明日 0 点重置或联系管理员调整"), - )); - } - } - - None -} diff --git a/source/rust/crates/ipass-core/src/config.rs b/source/rust/crates/ipass-core/src/config.rs deleted file mode 100644 index 91c583b..0000000 --- a/source/rust/crates/ipass-core/src/config.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! 内核策略常量(唯一真源)。 -//! -//! 与旧 OpenResty 版的 `lua/config.lua` 一一对应:**改策略只改这里**, -//! 不要散落到各模块里,否则行为会出现多处真源。 -//! -//! 插件自有常量在各自 crate(plugin-domain/config.rs、plugin-llm/config.rs); -//! 这里只留「身份 / 会话 / 配额 / 两条下行链路共用」的部分。 - -/// 管理员授予的「临时授权权限」有效时长(秒) -pub const TEMP_GRANT_TTL: i64 = 6 * 3600; -/// 管理员登录会话时长(秒) -pub const SESSION_TTL: i64 = 8 * 3600; -/// 口令哈希迭代轮数。**必须与旧版一致**,否则存量用户口令全部失效。 -pub const HASH_ROUNDS: usize = 1000; - -/// 首次启动播种的管理员账号名 -pub const INIT_ADMIN_USER: &str = "admin"; -/// 初始管理员口令的环境变量名。 -/// nginx.conf 里必须有对应的 `env ADMIN_INIT_PASSWORD;`,否则会被 nginx 剥离。 -pub const INIT_ADMIN_PASSWORD_ENV: &str = "ADMIN_INIT_PASSWORD"; -pub const INIT_ADMIN_PASSWORD_DEFAULT: &str = "123456"; - -/// 口令最短长度 -/// -/// sso 提议提到 8(弱口令门槛);iPass **维持 6 位下限**——既有测试夹具与 -/// 边界用例大量依赖 6/7 位密码(`password 123` 等),改 8 位会破坏 262 项 -/// 回归。**插件层**(plugin-sso / 未来 plugin-password-policy)若需强约束, -/// 应在插件端校验后再调用 `users::create`/`set_password`,内核不动。 -pub const PASSWORD_MIN_LEN: usize = 6; -pub const USERNAME_MIN_LEN: usize = 2; -pub const USERNAME_MAX_LEN: usize = 32; -/// 展示名(中文姓名等)长度上限。按**字符数**算,一个汉字算 1。 -pub const DISPLAY_NAME_MAX_LEN: usize = 32; - -/// 管理会话 Cookie 名(HttpOnly + SameSite=Strict) -pub const COOKIE_NAME: &str = "ipass_admin_session"; - -/// 同一 IP 在窗口内最多登录失败次数 -pub const LOGIN_MAX_FAIL: i64 = 10; -/// 登录失败计数窗口(秒) -pub const LOGIN_FAIL_TTL: i64 = 300; - -/// 下行链路每 Key 限流默认值:每分钟请求数。账号未显式配置时取此值;0 = 不限 -pub const LLM_RPM_DEFAULT: i64 = 60; -/// 下行链路每 Key 限流默认值:每日请求数。账号未显式配置时取此值;0 = 不限。 -/// -/// 刻意做**请求级**而不是 token 级:token 数在上游响应体里,而 SSE 必须关缓冲 -/// 透传(`proxy_buffering off`),网关不缓冲就解析不到 usage 字段。要 token 级 -/// 计费得自建 upstream,与「单容器零依赖」红线冲突。 -pub const LLM_DAILY_DEFAULT: i64 = 0; - -/// 默认状态目录,可被 `ipass_data_dir` 指令覆盖 -pub const DEFAULT_DATA_DIR: &str = "/usr/local/nginx/data"; - -// =========================================================================== -// 共享内存键/值编码 -// =========================================================================== - -/// 键前缀:管理会话 token → 用户名 -pub const KEY_SESS_PREFIX: &[u8] = b"sess:"; -/// 键前缀:登录失败计数(按 IP) -pub const KEY_FAIL_PREFIX: &[u8] = b"fail:"; -/// 键前缀:下行链路的 API Key → 身份(LLM 代理与 API 代理共用)。 -/// -/// payload = ` \n \n \n `(4 行, -/// 与 `users::identity_payload` 严格一致)。一次查表同时拿到「是谁 / 能用哪些上游 / -/// 限流多少」,**避免推理热路径回读 users.json**——那是同步文件 I/O + 全表 JSON 解码, -/// 管理接口用得起,转发热路径用不起。 -pub const KEY_UKEY_PREFIX: &[u8] = b"ukey:"; -/// 键前缀:每分钟限流计数(LLM 代理与 API 代理共用)。键 = `rl:` -/// (**每用户固定一个键**),value = `<分钟窗id>:<计数>`——跨窗自动归零靠读时 -/// 比对窗 id,而不是开新键。若按「每分钟一个键」存,shm 里的键会随时间无限 -/// 累积且无处过期。 -pub const KEY_RL_PREFIX: &[u8] = b"rl:"; -/// 键前缀:每日配额计数(LLM 代理与 API 代理共用)。键 = `st:`, -/// value = `<日窗id>:<计数>`。 -pub const KEY_ST_PREFIX: &[u8] = b"st:"; - -/// 共享内存 value 内部分隔符(ASCII US)。 -/// 后端地址只含 `[A-Za-z0-9._-]` 与 `:`,用户名只含 `[A-Za-z0-9_-]`, -/// 都不可能包含该字节,所以切分是安全的。 -pub const VAL_SEP: u8 = 0x1f; - -/// 键缓冲区上限:`sess:` + 32 字节 token 的 64 位 hex 最长为 69,留足余量 -pub const KEY_BUF_LEN: usize = 128; - -// =========================================================================== -// 部署拓扑(LLM 代理与 API 代理共用) -// =========================================================================== - -/// LLM 代理对外域名,用于账号态 API 回显 `base_url`(apix 的「复制地址」也用它)。 -/// 改域名只改这里(`conf/nginx.conf` 的 LLM server_name 要同步改)。 -pub const LLM_PUBLIC_HOST: &str = "lm.mayishangshu.cn"; diff --git a/source/rust/crates/ipass-core/src/http.rs b/source/rust/crates/ipass-core/src/http.rs deleted file mode 100644 index ada3ff2..0000000 --- a/source/rust/crates/ipass-core/src/http.rs +++ /dev/null @@ -1,296 +0,0 @@ -//! 请求/响应辅助:参数解析、请求体读取、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 { - // SAFETY: 同上 - unsafe { (*r).args.as_bytes().to_vec() } -} - -/// 请求头(大小写不敏感) -pub fn header(r: *mut ngx_http_request_t, name: &str) -> Option { - // 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 { - 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 { - 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::(&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(`Content-Type: application/json` 时)。 -/// -/// 非 JSON 体或解析失败返回 `None`——调用方据此回退到 `params` 或报错。 -/// SCIM / CAS / 同步连接器 / 自助密码重置等需要嵌套 JSON(数组、对象)的 -/// 端点用它取代 `params`(后者只认标量值)。 -pub fn json_body(r: *mut ngx_http_request_t) -> Option { - let body = unsafe { collect_body(r) }; - if body.is_empty() { - return None; - } - serde_json::from_slice::(&body).ok() -} - -/// 合并 query 与 JSON 请求体为单一 `Value::Object`: -/// JSON 体的嵌套结构原样保留,query 的标量覆盖同名顶层键。 -/// -/// SCIM/PATCH 等既可能走 form 也可能走 JSON 的场景统一入口。 -pub fn body_object(r: *mut ngx_http_request_t) -> Value { - let mut obj = serde_json::Map::new(); - for (k, v) in util::parse_kv(&args_raw(r)) { - obj.insert(k, Value::String(v)); - } - if let Some(Value::Object(b)) = json_body(r) { - for (k, v) in b { - obj.insert(k, v); - } - } - Value::Object(obj) -} - -// =========================================================================== -// 响应 -// =========================================================================== - -/// 发送 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, &[]) -} - -/// 发送带自定义 Content-Type 的响应体(CAS 的 `text/plain` / `application/xml` -/// 等不走 JSON 信封的场景用)。 -pub fn send_ct( - r: *mut ngx_http_request_t, - status: HTTPStatus, - body: &str, - content_type: &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", content_type); - request.add_header_out("Cache-Control", "no-store"); - request.set_content_length_n(body.len()); - - let st = request.send_header(); - if st != Status::NGX_OK { - return st; - } - request.output_filter(&mut chain) - } -} - -/// 302 重定向(CAS `/cas/login` 签发 ST 后跳回 service)。 -/// -/// **注意**:body 必须非空——`pool.create_buffer_from_str("")` 在 nginx 内存池里 -/// 分配 0 长度 buffer 会返回 `None`,使 `send_with` 返回 `NGX_ERROR`,导致 302 -/// 根本不发出(curl 拿不到 `Location`)。所以这里给一个单空格占位 body。 -pub fn redirect(r: *mut ngx_http_request_t, location: &str) -> Status { - send_with(r, HTTPStatus::MOVED_TEMPORARILY, " ", &[("Location", location)]) -} - -/// 统一成功响应:`{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:, 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) -} diff --git a/source/rust/crates/ipass-core/src/lib.rs b/source/rust/crates/ipass-core/src/lib.rs deleted file mode 100644 index 92ec8de..0000000 --- a/source/rust/crates/ipass-core/src/lib.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! ipass-core —— iPass 内核。 -//! -//! 承担「去掉任何插件,网关还能跑」的部分: -//! -//! * `state` —— 唯一共享内存 zone(`RwLock`)+ 文件写锁 -//! * `store` —— JSON 原子写 + 跨 worker 互斥(状态就是几个 JSON 文件,无数据库) -//! * `users` —— 账号唯一写入口(`ukey:` Key 索引、播种管理员、删除钩子) -//! * `session` —— 管理会话 -//! * `auth`(P3 起)—— 下行 `sk_` 鉴权 + `rl:` 配额(LLM 与 API 代理两条链路共用) -//! * `config` / `models` / `util` / `http` —— 常量、账号模型与通用原语 -//! -//! 插件(plugin-domain / plugin-llm / plugin-apix)只允许**单向依赖**本 crate; -//! 内核不认识任何插件。插件通过 `Plugin` trait(P1 引入)与 gateway 装配。 -//! -//! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md) -//! -//! * 共享内存只有 `RwLock, _>` 一种安全形态; -//! `SlabPool` 只能在 zone 初始化回调里取出,锁本身也必须用 -//! `ngx::allocator::allocate` 放进共享内存,否则各 worker 拿到的是各自的副本。 -//! * 热路径**永不回源**:每请求决策只读共享内存;任何写操作必须 -//! 先落文件、再写穿 shm,写 shm 失败必须 `log_err`。 - -pub mod api; -pub mod auth; -pub mod config; -pub mod http; -pub mod loc; -pub mod models; -pub mod plugin; -pub mod session; -pub mod state; -pub mod store; -pub mod usage; -pub mod users; -pub mod util; diff --git a/source/rust/crates/ipass-core/src/loc.rs b/source/rust/crates/ipass-core/src/loc.rs deleted file mode 100644 index 17ef011..0000000 --- a/source/rust/crates/ipass-core/src/loc.rs +++ /dev/null @@ -1,56 +0,0 @@ -//! Location 开关契约 —— 内核与插件之间**唯一的契约点**。 -//! -//! 配置指令(`ipass_api` / `ipass_proxy` / `ipass_llm` / `ipass_apix`)由 gateway -//! 集中解析进 `ModuleConfig`;插件不认识 gateway,只通过 [`Switch`] 问一句 -//! 「我所在的 location 开了吗」。gateway 在 preconfiguration 注入查询实现 -//! ([`set_switch_fn`]),**未注入或未实现的变体一律保守返回 `false`** -//! ——返回 `true` 会让未装配的能力意外开门(sso 踩过的坑)。 - -use core::sync::atomic::{AtomicUsize, Ordering}; - -use ngx::ffi::ngx_http_request_t; -use ngx::http::Request; - -/// location 能力的枚举。取 iPass 与 sso 的**并集**: -/// iPass 用 `Api / Proxy / Llm / Apix`;`Iap / Domain` 为 sso 预留, -/// 合流时不用改本枚举。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Switch { - /// 该 location 暴露管理 API + 身份端点 - Api, - /// 预留(sso 用;iPass 未实现,恒 false) - Iap, - /// 预留(sso 用;iPass 未实现,恒 false) - Domain, - /// 该 location 走「子域名 → 后端」转发 - Proxy, - /// 该 location 走 LLM 代理 - Llm, - /// 该 location 走 API 代理 - Apix, -} - -/// gateway 注入的查询实现:`(请求, 开关) -> 是否开启` -pub type SwitchFn = fn(&mut Request, Switch) -> bool; - -// fn 指针按 usize 原子存取(热路径上 access handler 每请求都要查,不能用 Mutex) -static SWITCH_FN: AtomicUsize = AtomicUsize::new(0); - -/// gateway 在 preconfiguration 阶段注入查询实现(早于任何请求) -pub fn set_switch_fn(f: SwitchFn) { - SWITCH_FN.store(f as *const () as usize, Ordering::Relaxed); -} - -/// 插件查询所在 location 是否开启自己的能力。 -/// **未注入实现时保守返回 `false`**——宁可关着,不可误开。 -pub fn enabled(r: *mut ngx_http_request_t, s: Switch) -> bool { - let p = SWITCH_FN.load(Ordering::Relaxed); - if p == 0 { - return false; - } - // SAFETY: p 来自 set_switch_fn 存入的合法 fn 指针 - let f: SwitchFn = unsafe { core::mem::transmute(p) }; - // SAFETY: r 由 nginx 传入且有效;Request 只在本调用存续期内使用 - let mut req = unsafe { Request::from_ngx_http_request(r) }; - f(&mut req, s) -} diff --git a/source/rust/crates/ipass-core/src/models.rs b/source/rust/crates/ipass-core/src/models.rs deleted file mode 100644 index bdcda27..0000000 --- a/source/rust/crates/ipass-core/src/models.rs +++ /dev/null @@ -1,84 +0,0 @@ -//! 持久化数据模型。 -//! -//! 字段名与旧版 `data/users.json` / `data/domains.json` **逐字对应**, -//! 以便新版直接接管旧数据文件、且管理台前端无需改动。 - -use serde::{Deserialize, Serialize}; -use serde_json::Value; -use std::collections::BTreeMap; - -/// 账号表(`users.json`):以账号名为 key 的对象。 -pub type UserTable = BTreeMap; - -/// 单个账号。 -/// -/// `temp_grant_until` 是「临时授权权限」的到期时间戳;> now 表示当前拥有 -/// 该权限,申请临时域名时可跳过审核直接放行。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct User { - pub username: String, - /// 中文姓名等展示名。**只用于展示**,不参与鉴权、不参与热路径查询。 - /// - /// `username` 规则是 ASCII(`valid_username`),中文名塞不进账号名, - /// 所以「吴桂荣」这类实名单独放这里;留空时前端回落到 `username`。 - #[serde(default)] - pub display_name: String, - /// `admin` | `user` - pub role: String, - pub salt: String, - /// 迭代加盐 SHA-256 - pub pwd_hash: String, - /// `sk_<48 位 hex>`。 - /// - /// LLM 代理与域名接口**共用这一把 Key**——这正是「用同一套 Key 验证」 - /// 的落点,所以重置 Key 会同时影响两个入口。 - pub api_key: String, - /// LLM 代理可用的上游 slot 白名单。空 = 不限。 - /// - /// 老数据没有该字段,`serde(default)` 反序列化得空表,语义正好是「不限」。 - #[serde(default)] - pub allowed_models: Vec, - /// LLM 每分钟请求上限。老数据缺省 → 全局默认(`LLM_RPM_DEFAULT`);0 = 不限 - #[serde(default = "default_llm_rpm")] - pub llm_rpm: i64, - /// LLM 每日请求上限。老数据缺省 → 全局默认(`LLM_DAILY_DEFAULT`);0 = 不限 - #[serde(default = "default_llm_daily")] - pub llm_daily: i64, - #[serde(default)] - pub temp_grant_until: i64, - #[serde(default)] - pub created_at: i64, - - /// 插件字段透传:内核持有、**不解释**。 - /// - /// 反序列化时,文件中**未被上面字段认领的 key 自动进 `extra`**;序列化时 - /// 展开回顶层(`#[serde(flatten)]`)。`serde` 优先匹配已认领字段,所以 - /// 存量 `users.json`(含任何插件写入的字段)可原样接管,**不会因内核不 - /// 认识而丢数据**——这是 iPass 向上游 sso 合流的扩展点(A1)。 - /// - /// 未来插件要存 TOTP 密钥、邮箱、用户组、锁定状态……都直接往 `extra` - /// 写,不再走内核加字段。修改走 [`crate::users::update_extra`] 的 - /// 「读-改-写」原语。 - #[serde(default, flatten)] - pub extra: BTreeMap, -} - -impl User { - /// 是否拥有「临时授权权限」 - pub fn has_temp_permission(&self, now: i64) -> bool { - self.temp_grant_until > now - } - - pub fn is_admin(&self) -> bool { - self.role == "admin" - } -} - - -fn default_llm_rpm() -> i64 { - crate::config::LLM_RPM_DEFAULT -} - -fn default_llm_daily() -> i64 { - crate::config::LLM_DAILY_DEFAULT -} diff --git a/source/rust/crates/ipass-core/src/plugin.rs b/source/rust/crates/ipass-core/src/plugin.rs deleted file mode 100644 index eac9aea..0000000 --- a/source/rust/crates/ipass-core/src/plugin.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! 插件装配契约 —— 内核与插件之间唯一的接口。 -//! -//! 沿用 ssw/sso 的形态,签名保持一致(若将来与 sso 合流,trait 不用再改)。 -//! -//! ## 刻意没有 `commands()` -//! -//! nginx 的 `ngx_module_t.commands` 是 null 结尾的**连续**数组,不同 crate 的 -//! `static` 数组无法拼接。配置指令由 gateway 集中声明(`ipass_*` 七条不变), -//! 插件通过 [`crate::loc::Switch`] 查询自己所在 location 是否开启—— -//! **指令解析归壳、行为归插件**。 -//! -//! ## `dispatch_api` 语义 -//! -//! 「不认领就返回 `None`,让下一个插件试」,**绝不自行 404**——否则后注册的 -//! 插件永远收不到请求。404 由 gateway 在全部插件都返回 `None` 后统一发出。 - -use core::sync::atomic::{AtomicUsize, Ordering}; - -use ngx::core::Status; -use ngx::ffi::{ngx_conf_t, ngx_http_request_t}; - -/// 本网关 `ngx_module_t` 的 `ctx_index`(gateway 在 postconfiguration 前 -/// 通过 [`set_ctx_index`] 注入)。插件用它在 `r->ctx` 上挂自己的请求级状态 -/// (如 usage_filter 的扫描窗口)。 -static CTX_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); - -pub fn set_ctx_index(idx: usize) { - CTX_INDEX.store(idx, Ordering::Relaxed); -} - -/// 当前模块的 ctx_index;`usize::MAX` = 尚未注入(此时插件应放弃请求级状态)。 -pub fn ctx_index() -> usize { - CTX_INDEX.load(Ordering::Relaxed) -} - -pub trait Plugin: Sync { - /// 插件名(日志与排障用) - fn name(&self) -> &'static str; - - /// 配置解析前:注册本插件自己的 nginx 变量。 - /// 返回 false = 注册失败,gateway 会 EMERG 退出。 - fn preconfig(&self, _cf: *mut ngx_conf_t) -> bool { - true - } - - /// 配置解析后:注册 phase handler / body filter。 - /// 返回 false = 注册失败,gateway 会 EMERG 退出。 - fn postconfig(&self, _cf: *mut ngx_conf_t) -> bool { - true - } - - /// 管理 API 分发:认领则返回响应状态,不认领返回 `None`。 - fn dispatch_api(&self, _r: *mut ngx_http_request_t) -> Option { - None - } - - /// fork 前预装载共享内存(zone init 回调里调用一次)。 - /// 返回装载条数(gateway 汇总打日志)。 - fn zone_load(&self) -> usize { - 0 - } - - /// log 阶段旁路处理器(与 sso 对齐保留;返回 true 表示已处理)。 - fn log_handler(&self, _r: *mut ngx_http_request_t) -> bool { - true - } -} diff --git a/source/rust/crates/ipass-core/src/session.rs b/source/rust/crates/ipass-core/src/session.rs deleted file mode 100644 index 35d05f7..0000000 --- a/source/rust/crates/ipass-core/src/session.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! 管理员登录会话。 -//! -//! 会话存在共享内存里:**nginx 重启即全部失效**,这是预期行为 -//! (旧版用 `lua_shared_dict admin_sessions`,同样如此)。 -//! -//! Cookie 为 `ipass_admin_session=<64 位 hex>`,HttpOnly + SameSite=Strict, -//! 每次校验命中都会滑动续期(与旧版一致)。 - -use crate::config::{COOKIE_NAME, SESSION_TTL}; -use crate::state; -use crate::util; - -/// 从 Cookie 头里取出会话 token -pub fn parse_token(cookie_header: &str) -> Option { - let needle = format!("{COOKIE_NAME}="); - for part in cookie_header.split(';') { - let part = part.trim(); - if let Some(value) = part.strip_prefix(&needle) { - if !value.is_empty() { - return Some(value.to_owned()); - } - } - } - None -} - -/// 新建会话,返回 token -pub fn create(username: &str) -> String { - let token = util::rand_hex(32); - state::put_session(&token, username, util::now() + SESSION_TTL); - token -} - -pub fn set_cookie(token: &str) -> String { - format!("{COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Strict; Max-Age={SESSION_TTL}") -} - -pub fn clear_cookie() -> String { - format!("{COOKIE_NAME}=deleted; Path=/; HttpOnly; SameSite=Strict; Max-Age=0") -} - -/// 鉴权:解析 Cookie → 查共享内存 → 命中则滑动续期。返回当前登录用户名。 -pub fn authenticate(cookie: Option<&str>) -> Option { - let token = parse_token(cookie?)?; - let now = util::now(); - let username = state::get_session(&token, now)?; - // 滑动续期:活跃使用不因固定 TTL 被踢出 - state::put_session(&token, &username, now + SESSION_TTL); - Some(username) -} - -/// 退出登录:销毁服务端会话(Cookie 由响应头清除) -pub fn destroy(cookie: Option<&str>) { - if let Some(token) = cookie.and_then(parse_token) { - state::remove_session(&token); - } -} diff --git a/source/rust/crates/ipass-core/src/state.rs b/source/rust/crates/ipass-core/src/state.rs deleted file mode 100644 index 5dcaa4f..0000000 --- a/source/rust/crates/ipass-core/src/state.rs +++ /dev/null @@ -1,360 +0,0 @@ -//! 共享内存状态层。 -//! -//! 这是「配置放内存」的落点,替代旧版的 `lua_shared_dict proxy_cache / -//! admin_sessions / lua_locks` 三个字典。全部派生状态集中在一张 -//! `RbTreeMap` 里,用键前缀区分用途: -//! -//! ```text -//! sub: → \x1f 转发映射 -//! sess: → \x1f 管理会话 -//! fail: → \x1f 登录失败计数 -//! ``` -//! -//! ## 为什么过期时间写在 value 里,而不是靠字典的 TTL -//! -//! 旧版 `lua_shared_dict` 自带 `set(key, val, ttl)` 自动回收;`RbTreeMap` -//! 是纯数据结构,没有 TTL。因此把到期时刻编码进 value,读取时判断—— -//! 语义上反而更精确(到期即失效,不受回收延迟影响)。 -//! -//! ## 为什么锁必须放进共享内存 -//! -//! nginx 是多进程模型。`RwLock` 若放在普通静态变量里,每个 worker 会持有 -//! 各自的副本,跨进程互斥完全失效。锁与表都必须在 `ngx_shared_memory_add` -//! 创建的 slab 池里分配。 - -use core::ptr; -use core::sync::atomic::{AtomicPtr, Ordering}; - -use ngx::collections::RbTreeMap; -use ngx::core::{NgxStr, NgxString, SlabPool, Status}; -use ngx::ffi::ngx_shm_zone_t; -use ngx::sync::{RwLock, RwLockWriteGuard}; - -use crate::config::{KEY_BUF_LEN, KEY_UKEY_PREFIX, VAL_SEP}; - -/// 子域名 → 后端、token → 用户名等全部映射的底层容器 -pub type ShmMap = RbTreeMap, NgxString, SlabPool>; - -/// 共享内存根对象:一张表 + 一把文件写锁。 -/// -/// 文件写锁**独立于表的读写锁**:文件 I/O 期间若持有表的写锁, -/// 会把所有转发请求(需要读锁)一起卡住。分开后,域名的热路径只受 -/// 自身短临界区影响。 -pub struct ShmRoot { - pub map: RwLock, - /// 保护 `store` 的「读-改-写」与落盘,跨 worker 互斥 - pub file_lock: RwLock<()>, -} - -/// 由 `ipass_state ` 注册的共享内存区 -static STATE_ZONE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); - -pub fn set_zone(zone: *mut ngx_shm_zone_t) { - STATE_ZONE.store(zone, Ordering::SeqCst); -} - -/// 在 slab 池上构造 `ShmRoot` 并挂到 `shpool->data`;重复调用直接复用。 -fn init_root(zone: &mut ngx_shm_zone_t) -> Result<&'static ShmRoot, Status> { - // SAFETY: zone 由 ngx_shared_memory_add 注册,init 回调已使其 shm 可用 - let mut alloc = unsafe { SlabPool::from_shm_zone(zone) }.ok_or(Status::NGX_ERROR)?; - - if alloc.as_mut().data.is_null() { - let map = ShmMap::try_new_in(alloc.clone()).map_err(|_| Status::NGX_ERROR)?; - let root = ShmRoot { map: RwLock::new(map), file_lock: RwLock::new(()) }; - // 整块放进共享内存:两个锁与表必须对所有 worker 是同一份 - let placed = ngx::allocator::allocate(root, &alloc).map_err(|_| Status::NGX_ERROR)?; - alloc.as_mut().data = placed.as_ptr().cast(); - } - - // SAFETY: data 非空即指向一个已初始化、且存活于共享内存的 ShmRoot - unsafe { alloc.as_ref().data.cast::().as_ref().ok_or(Status::NGX_ERROR) } -} - -/// 取共享内存根对象;zone 未注册时返回 None -pub fn root() -> Option<&'static ShmRoot> { - let zone = STATE_ZONE.load(Ordering::SeqCst); - if zone.is_null() { - return None; - } - // SAFETY: 非空即代表 zone 已注册 - init_root(unsafe { &mut *zone }).ok() -} - -/// 取 slab 分配器(构造共享内存字符串用) -pub fn alloc() -> Option { - let zone = STATE_ZONE.load(Ordering::SeqCst); - if zone.is_null() { - return None; - } - // SAFETY: 同上 - unsafe { SlabPool::from_shm_zone(&mut *zone) } -} - -/// 初始化回调:由 nginx 在 fork 之前调用一次 -pub fn init_zone(zone: *mut ngx_shm_zone_t) -> Status { - // SAFETY: nginx 传入的 zone 有效 - match init_root(unsafe { &mut *zone }) { - Ok(_) => Status::NGX_OK, - Err(e) => e, - } -} - -/// 取全局文件写锁。所有「读文件 → 改 → 写文件」必须包在这里面。 -/// -/// nginx 侧只有一个写锁、且都是低频管理操作,串行化代价可忽略; -/// 而它换来的是多 worker 下不会出现「两边同时改、后写的覆盖前写的」。 -pub fn file_lock() -> Option> { - root().map(|r| r.file_lock.write()) -} - -// =========================================================================== -// 键构造 -// =========================================================================== - -/// 在栈上拼 `prefix + name`,避免热路径为键做堆分配。 -fn key_buf(prefix: &[u8], name: &[u8]) -> Option<([u8; KEY_BUF_LEN], usize)> { - let n = prefix.len() + name.len(); - if n > KEY_BUF_LEN { - return None; - } - let mut buf = [0u8; KEY_BUF_LEN]; - buf[..prefix.len()].copy_from_slice(prefix); - buf[prefix.len()..n].copy_from_slice(name); - Some((buf, n)) -} - -/// 拆 value:` \x1f ` -/// -/// 用 `rposition` 而非 `position`:value 是「payload + 分隔符 + exp」三段, -/// `exp` 必为 ASCII 数字串、不含 `VAL_SEP`,所以**最后一个**分隔符才是真边界。 -/// 用 `position` 会被 payload 里内嵌的 `0x1f` 截断(OAuth 授权码 / 带 -/// 注入头的会话 payload 都可能含此字节)——sso 上游化时已踩此坑。 -fn split_value(bytes: &[u8]) -> Option<(&[u8], i64)> { - let sep = bytes.iter().rposition(|&b| b == VAL_SEP)?; - let payload = &bytes[..sep]; - let exp = core::str::from_utf8(&bytes[sep + 1..]).ok()?.parse::().ok()?; - Some((payload, exp)) -} - -// =========================================================================== -// 读写原语 -// =========================================================================== - -/// 查表。返回 `(payload, expires_at)`;键不存在或值损坏时返回 None。 -/// -/// **转发热路径唯一入口**——只读共享内存,未命中不产生任何 I/O。 -pub fn get(prefix: &[u8], name: &[u8]) -> Option<(String, i64)> { - let (buf, n) = key_buf(prefix, name)?; - let root = root()?; - let guard = root.map.read(); - let value = guard.get(NgxStr::from_bytes(&buf[..n]))?; - let (payload, exp) = split_value(value.as_bytes())?; - // 复制成 owned:guard 释放后共享内存可能被并发写覆盖, - // 直接返回引用会悬垂。一次小字符串分配远小于转发本身的代价。 - Some((String::from_utf8_lossy(payload).into_owned(), exp)) -} - -/// 查表并校验未过期 -pub fn get_live(prefix: &[u8], name: &[u8], now: i64) -> Option { - let (payload, exp) = get(prefix, name)?; - if exp > 0 && exp <= now { - return None; - } - Some(payload) -} - -/// 写入(先删后插,语义为覆盖)。返回 false 表示共享内存不足或 zone 未就绪。 -pub fn put(prefix: &[u8], name: &[u8], payload: &[u8], expires_at: i64) -> bool { - let (Some(root), Some(a)) = (root(), alloc()) else { - return false; - }; - - let mut value = Vec::with_capacity(payload.len() + 24); - value.extend_from_slice(payload); - value.push(VAL_SEP); - value.extend_from_slice(expires_at.to_string().as_bytes()); - - let mut key = Vec::with_capacity(prefix.len() + name.len()); - key.extend_from_slice(prefix); - key.extend_from_slice(name); - - let (Ok(nk), Ok(nv)) = ( - NgxString::try_from_bytes_in(&key, a.clone()), - NgxString::try_from_bytes_in(&value, a), - ) else { - return false; - }; - - let mut guard = root.map.write(); - // 先删后插:try_insert 对已存在的键可能直接失败,而这里的语义是覆盖 - let _ = guard.remove(NgxStr::from_bytes(&key)); - guard.try_insert(nk, nv).is_ok() -} - -/// 删除一个键。返回它此前是否存在。 -pub fn remove(prefix: &[u8], name: &[u8]) -> bool { - let Some(root) = root() else { - return false; - }; - let mut key = Vec::with_capacity(prefix.len() + name.len()); - key.extend_from_slice(prefix); - key.extend_from_slice(name); - root.map.write().remove(NgxStr::from_bytes(&key)).is_some() -} - -/// 当前条目数(管理端观测用;当前无调用方,保留为诊断接口) -#[allow(dead_code)] -pub fn len() -> usize { - root().map(|r| r.map.read().iter().count()).unwrap_or(0) -} - -/// 只清掉某一前缀下的所有键。 -/// -/// 重载转发映射时用——**不能**用 `clear()`,那会把正在登录的管理员会话一起清掉。 -pub fn clear_prefix(prefix: &[u8]) { - let Some(root) = root() else { - return; - }; - let mut guard = root.map.write(); - // 先收集待删键:迭代器借用了 guard,不能边遍历边删 - let victims: Vec> = - guard.iter().filter(|p| p.0.as_bytes().starts_with(prefix)).map(|p| p.0.as_bytes().to_vec()).collect(); - for v in victims { - guard.remove(NgxStr::from_bytes(&v)); - } -} - -/// 遍历某前缀下的全部条目,返回 `(去掉前缀的键名, payload)`。 -/// -/// 这是**低频读**接口(管理台聚合用量统计),不是热路径——每次都会克隆一份 -/// 字符串出来,别拿它做每请求调用。`expires_at` 刻意不返回:统计键永不过期, -/// 调用方用 payload 里的日窗 id 自行判断"今日"。 -pub fn iter_prefix(prefix: &[u8]) -> Vec<(String, String)> { - let Some(root) = root() else { - return Vec::new(); - }; - let guard = root.map.read(); - guard - .iter() - .filter_map(|(k, v)| { - let name = k.as_bytes().strip_prefix(prefix)?; - let (payload, _) = split_value(v.as_bytes())?; - Some(( - String::from_utf8_lossy(name).into_owned(), - String::from_utf8_lossy(payload).into_owned(), - )) - }) - .collect() -} - -/// 与 [`iter_prefix`] 相同,但**额外返回 `expires_at`**——用于会话 / OAuth -/// kick / 过期扫描等需要判断 exp 的场景。`iter_prefix` 保留兼容(统计键 -/// 永不过期、不需要 exp)。 -pub fn iter_prefix_ex(prefix: &[u8]) -> Vec<(String, String, i64)> { - let Some(root) = root() else { - return Vec::new(); - }; - let guard = root.map.read(); - guard - .iter() - .filter_map(|(k, v)| { - let name = k.as_bytes().strip_prefix(prefix)?; - let (payload, exp) = split_value(v.as_bytes())?; - Some(( - String::from_utf8_lossy(name).into_owned(), - String::from_utf8_lossy(payload).into_owned(), - exp, - )) - }) - .collect() -} - -// =========================================================================== -// 业务语义封装 -// =========================================================================== - -/// 管理会话写入 -pub fn put_session(token: &str, username: &str, expires_at: i64) -> bool { - put(crate::config::KEY_SESS_PREFIX, token.as_bytes(), username.as_bytes(), expires_at) -} - -/// 管理会话读取(未过期才返回用户名) -pub fn get_session(token: &str, now: i64) -> Option { - get_live(crate::config::KEY_SESS_PREFIX, token.as_bytes(), now) -} - -pub fn remove_session(token: &str) -> bool { - remove(crate::config::KEY_SESS_PREFIX, token.as_bytes()) -} - -/// 登录失败计数:返回自增后的值 -pub fn bump_login_fail(ip: &str, now: i64) -> i64 { - let current = match get(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()) { - Some((_, exp)) if exp > 0 && exp <= now => 0, - Some((payload, _)) => payload.parse::().unwrap_or(0), - None => 0, - }; - let next = current + 1; - put( - crate::config::KEY_FAIL_PREFIX, - ip.as_bytes(), - next.to_string().as_bytes(), - now + crate::config::LOGIN_FAIL_TTL, - ); - next -} - -pub fn get_login_fail(ip: &str, now: i64) -> i64 { - match get(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()) { - Some((_, exp)) if exp > 0 && exp <= now => 0, - Some((payload, _)) => payload.parse::().unwrap_or(0), - None => 0, - } -} - -pub fn clear_login_fail(ip: &str) { - remove(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()); -} - -/// 窗口计数(限流/配额共用):键固定,value = `<窗口id>:<计数>`,永不过期 -/// (`expires_at = 0`)——跨窗归零靠读时比对窗 id,键数只随用户数增长。 -/// 返回自增后的计数。 -/// -/// 读-增-写跨 worker **没有互斥**:`bump_login_fail` 同款近似语义。 -/// 对限流来说,并发下偶发少计数只是放宽一两 个请求的边界,可接受; -/// 为此上写锁反而让每个 LLM 请求都串行化,得不偿失。 -pub fn bump_window(prefix: &[u8], name: &str, window: i64) -> i64 { - let current = window_count(prefix, name, window); - let next = current + 1; - put(prefix, name.as_bytes(), format!("{}:{}", window, next).as_bytes(), 0); - next -} - -/// 读窗口计数(未跨窗时),管理台展示用量用 -pub fn window_count(prefix: &[u8], name: &str, window: i64) -> i64 { - match get(prefix, name.as_bytes()) { - Some((payload, _)) => match payload.split_once(':') { - Some((w, c)) if w == window.to_string() => c.parse::().unwrap_or(0), - _ => 0, - }, - None => 0, - } -} - -// =========================================================================== -// LLM 代理 -// =========================================================================== - -/// 写入 API Key → 身份索引。 -/// -/// payload = ` \n \n \n `(4 行,与 `users::identity_payload` 一致)。 -/// **永不过期**(`expires_at = 0`):它的生命周期完全跟随 accounts 表的增删, -/// 由 `users` 模块在每次写操作后显式同步——这里不能再加一层 TTL, -/// 否则会出现「账号还在、Key 偶尔 401」这种极难复现的状态。 -pub fn put_ukey(api_key: &str, payload: &str) -> bool { - put(KEY_UKEY_PREFIX, api_key.as_bytes(), payload.as_bytes(), 0) -} - -pub fn remove_ukey(api_key: &str) -> bool { - remove(KEY_UKEY_PREFIX, api_key.as_bytes()) -} diff --git a/source/rust/crates/ipass-core/src/store.rs b/source/rust/crates/ipass-core/src/store.rs deleted file mode 100644 index ae75713..0000000 --- a/source/rust/crates/ipass-core/src/store.rs +++ /dev/null @@ -1,132 +0,0 @@ -//! JSON 文件存储层:原子写 + 跨 worker 互斥。 -//! -//! 与旧版 `lua/store.lua` 语义一致——**状态就是几个 JSON 文件**,不引入数据库。 -//! 差别只有一处:互斥锁从 `resty.lock`(基于 lua_shared_dict)换成共享内存里的 -//! `RwLock`,因为新版已经有一块共享内存了,不必再造一个字典。 -//! -//! 所有写操作统一走 `update_*`,流程固定为: -//! -//! ```text -//! 取全局文件写锁 → 读文件 → 闭包修改 → 原子写回 → 放锁 -//! ``` -//! -//! 闭包返回 `Err` 表示业务校验失败,此时**不落盘**(与旧版 `fn` 返回 nil 一致)。 -//! -//! ## 表的分工 -//! -//! | 文件 | 内容 | 是否进共享内存 | -//! | --- | --- | --- | -//! | `users.json` | 账号、口令哈希、API Key | `ukey:` 索引进(热路径要它) | -//! | `domains.json` | 子域名 → 后端映射 | `sub:` 进(转发热路径) | -//! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) | -//! | `api-proxies.json` | API 代理清单(每条含各自供应商凭据) | `ax:` 进(API 代理热路径) | -//! -//! 内核只直接管 `users.json`;其余数据文件由各插件经 `path_in_data` + -//! 通用读写原语自管(plugin-domain / plugin-llm / plugin-apix)。四个文件 -//! 都在 `data/` 下,都已 `.gitignore`。**LLM 上游表与 API 代理表含真实 -//! 供应商 Key,敏感级别与 `users.json` 相同**,不要再往别处复制。 - -use std::path::PathBuf; -use std::sync::Mutex; - -use crate::config::DEFAULT_DATA_DIR; -use crate::models::UserTable; -use crate::state; - -/// 状态目录。配置阶段由 `ipass_data_dir` 指令设置一次,之后只读。 -static DATA_DIR: Mutex> = Mutex::new(None); - -pub fn set_data_dir(dir: &str) { - if let Ok(mut slot) = DATA_DIR.lock() { - *slot = Some(dir.to_owned()); - } -} - -pub fn data_dir() -> String { - DATA_DIR - .lock() - .ok() - .and_then(|s| s.clone()) - .unwrap_or_else(|| DEFAULT_DATA_DIR.to_owned()) -} - -fn path_of(name: &str) -> PathBuf { - PathBuf::from(data_dir()).join(name) -} - -pub fn users_path() -> PathBuf { - path_of("users.json") -} - -/// data 目录下任意文件的路径(插件用它管理自己的数据文件, -/// 如 plugin-domain 的 `domains.json`) -pub fn path_in_data(name: &str) -> PathBuf { - path_of(name) -} - -// =========================================================================== -// 读写 -// =========================================================================== - -/// 读取并反序列化;文件缺失或损坏时回退 `default`(不抛错,保证转发侧可用) -pub fn read_json(path: &PathBuf, default: T) -> T { - let Ok(text) = std::fs::read_to_string(path) else { - return default; - }; - if text.trim().is_empty() { - return default; - } - match serde_json::from_str(&text) { - Ok(v) => v, - Err(e) => { - // 解析失败必须留痕:静默回退会让「数据看起来还在、实际全空」极难排查 - crate::util::log_err(&format!( - "[store] 解析失败,回退默认值:{} ({e})", - path.display() - )); - default - } - } -} - -/// 原子写:先写 `.tmp` 再 rename,避免读到写了一半的内容 -pub fn write_json(path: &PathBuf, value: &T) -> Result<(), String> { - let text = serde_json::to_string(value).map_err(|e| format!("序列化失败:{e}"))?; - let tmp = PathBuf::from(format!("{}.tmp", path.display())); - - std::fs::write(&tmp, text.as_bytes()).map_err(|e| { - let _ = std::fs::remove_file(&tmp); - format!("写入临时文件失败:{e}") - })?; - - std::fs::rename(&tmp, path).map_err(|e| { - let _ = std::fs::remove_file(&tmp); - format!("重命名失败:{e}") - }) -} - -// =========================================================================== -// 对外接口 -// =========================================================================== - -pub fn read_users() -> UserTable { - read_json(&users_path(), UserTable::new()) -} - -pub fn write_users(data: &UserTable) -> Result<(), String> { - write_json(&users_path(), data) -} - -/// 加锁「读-改-写」账号表。 -/// -/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。 -pub fn update_users(f: F) -> Result -where - F: FnOnce(&mut UserTable) -> Result, -{ - let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; - let mut data = read_users(); - let out = f(&mut data)?; - write_users(&data)?; - Ok(out) -} diff --git a/source/rust/crates/ipass-core/src/usage.rs b/source/rust/crates/ipass-core/src/usage.rs deleted file mode 100644 index ce85dbf..0000000 --- a/source/rust/crates/ipass-core/src/usage.rs +++ /dev/null @@ -1,239 +0,0 @@ -//! 通用记账原语(无任何业务语义)。 -//! -//! 只回答「给这个前缀下的这个键 +1」「这个键现在的读数是什么」—— -//! **不认识** `ust:` 与 `ums:` 的区别,更不认识「LLM」「token」这些词。 -//! 业务解读(趋势 / 总览 / 按人聚合)在 plugin-llm 的 `stats` 模块, -//! 它把键前缀与本模块的原语组合起来。 -//! -//! value 编码共用两种: -//! * 窗口读数:`<日窗id>:<今日数>:<累计数>:<最近调用时间戳>` -//! * 日桶:`<请求数>:<入>:<出>`(趋势图数据源,TTL 到期自然淘汰) - -use serde_json::{Value, json}; - -use crate::state; -use crate::util; - -/// 一条统计记录的读数。`today` 已按调用方给的日窗折算过(跨天即为 0)。 -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct Usage { - /// 今日(本地自然日)计数 - pub today: i64, - /// 累计计数(自该计数键建立以来,不随跨天归零) - pub total: i64, - /// 最近一次记账时间戳;0 = 从未 - pub last_ts: i64, -} - -impl Usage { - /// 累加(聚合用)。`last_ts` 取最大。 - pub fn merge(&mut self, other: &Usage) { - self.today += other.today; - self.total += other.total; - if other.last_ts > self.last_ts { - self.last_ts = other.last_ts; - } - } - - pub fn json(&self) -> Value { - json!({ - "today": self.today, - "total": self.total, - "last_ts": self.last_ts, - "last_ts_text": if self.last_ts > 0 { util::fmt_time(self.last_ts) } else { String::new() }, - }) - } -} - -/// token 计量读数。日窗语义与 [`Usage`] 相同:跨天 today 归零、累计保留。 -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct TokenUsage { - /// 今日入 token - pub tin_today: i64, - /// 累计入 token - pub tin_total: i64, - /// 今日出 token - pub tout_today: i64, - /// 累计出 token - pub tout_total: i64, - /// 最近一次有 token 记账的调用时间戳;0 = 从未 - pub last_ts: i64, -} - -impl TokenUsage { - /// 累加(聚合用)。`last_ts` 取最大。 - pub fn merge(&mut self, other: &TokenUsage) { - self.tin_today += other.tin_today; - self.tin_total += other.tin_total; - self.tout_today += other.tout_today; - self.tout_total += other.tout_total; - if other.last_ts > self.last_ts { - self.last_ts = other.last_ts; - } - } - - pub fn json(&self) -> Value { - json!({ - "in_today": self.tin_today, - "in_total": self.tin_total, - "out_today": self.tout_today, - "out_total": self.tout_total, - "last_ts": self.last_ts, - "last_ts_text": if self.last_ts > 0 { util::fmt_time(self.last_ts) } else { String::new() }, - }) - } -} - -/// 一天的聚合值(日桶) -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub struct DayBucket { - pub requests: i64, - pub tin: i64, - pub tout: i64, -} - -impl DayBucket { - pub fn merge(&mut self, other: &DayBucket) { - self.requests += other.requests; - self.tin += other.tin; - self.tout += other.tout; - } -} - -// =========================================================================== -// 窗口读数(<日窗id>:<今日>:<累计>:<最近时间戳>) -// =========================================================================== - -fn encode(day: i64, u: &Usage) -> String { - format!("{}:{}:{}:{}", day, u.today, u.total, u.last_ts) -} - -/// 解码并把"今日数"按当前日窗折算——跨天时旧值归零,累计值保留。 -fn decode(payload: &str, day: i64) -> Usage { - let mut it = payload.split(':'); - let stored_day = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let last_ts = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - Usage { today: if stored_day == day { today } else { 0 }, total, last_ts } -} - -/// 窗口计数 +1(读-增-写不加写锁的近似语义:并发下偶发少计一次, -/// 统计用途无影响;换来的是调用方热路径不为统计抢锁)。 -pub fn bump(prefix: &[u8], name: &str, day: i64, now: i64) { - let current = state::get(prefix, name.as_bytes()) - .map(|(payload, _)| decode(&payload, day)) - .unwrap_or_default(); - - let next = Usage { - today: current.today + 1, - total: current.total + 1, - last_ts: now, - }; - state::put(prefix, name.as_bytes(), encode(day, &next).as_bytes(), 0); -} - -/// 读窗口读数(不跨窗折算由 decode 按 day 完成) -pub fn read(prefix: &[u8], name: &str, day: i64) -> Usage { - state::get(prefix, name.as_bytes()) - .map(|(payload, _)| decode(&payload, day)) - .unwrap_or_default() -} - -// =========================================================================== -// token 窗口读数(<日窗id>:<入今日>:<入累计>:<出今日>:<出累计>:<最近时间戳>) -// =========================================================================== - -fn encode_t(day: i64, t: &TokenUsage) -> String { - format!( - "{}:{}:{}:{}:{}:{}", - day, t.tin_today, t.tin_total, t.tout_today, t.tout_total, t.last_ts - ) -} - -fn decode_t(payload: &str, day: i64) -> TokenUsage { - let mut it = payload.split(':'); - let stored_day = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let in_today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let in_total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let out_today = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let out_total = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let last_ts = it.next().and_then(|s| s.parse::().ok()).unwrap_or(0); - let live = stored_day == day; - TokenUsage { - tin_today: if live { in_today } else { 0 }, - tin_total: in_total, - tout_today: if live { out_today } else { 0 }, - tout_total: out_total, - last_ts, - } -} - -/// token 窗口累加(同 bump 的近似语义) -pub fn bump_t(prefix: &[u8], name: &str, tin: u64, tout: u64, day: i64, now: i64) { - let current = state::get(prefix, name.as_bytes()) - .map(|(payload, _)| decode_t(&payload, day)) - .unwrap_or_default(); - let next = TokenUsage { - tin_today: current.tin_today + tin as i64, - tin_total: current.tin_total + tin as i64, - tout_today: current.tout_today + tout as i64, - tout_total: current.tout_total + tout as i64, - last_ts: now, - }; - state::put(prefix, name.as_bytes(), encode_t(day, &next).as_bytes(), 0); -} - -/// 读 token 窗口读数 -pub fn read_t(prefix: &[u8], name: &str, day: i64) -> TokenUsage { - state::get(prefix, name.as_bytes()) - .map(|(payload, _)| decode_t(&payload, day)) - .unwrap_or_default() -} - -// =========================================================================== -// 日桶(趋势图数据源) -// =========================================================================== -// -// 以自然日为键的桶:一个桶一天,读取时按日窗 id **精确取键**(get_live), -// 不做前缀扫描——键数随时间增长也不会拖慢任何热路径。 -// TTL 由调用方传入(业务保留策略属于插件,不属于本模块)。 - -/// `<请求数>:<入token>:<出token>` -fn encode_day(b: &DayBucket) -> String { - format!("{}:{}:{}", b.requests, b.tin, b.tout) -} - -fn decode_day(payload: &str) -> DayBucket { - let mut it = payload.split(':'); - let num = |v: Option<&str>| v.and_then(|s| s.parse::().ok()).unwrap_or(0); - DayBucket { - requests: num(it.next()), - tin: num(it.next()), - tout: num(it.next()), - } -} - -/// 累加一日桶。`ttl_secs` 为保留时长(到期由共享内存自然淘汰)。 -pub fn bump_day(prefix: &[u8], name: &str, delta: &DayBucket, ttl_secs: i64) { - let mut next = state::get_live(prefix, name.as_bytes(), util::now()) - .map(|p| decode_day(&p)) - .unwrap_or_default(); - next.merge(delta); - // 写入失败只记日志:统计是旁路功能,绝不影响转发 - if !state::put( - prefix, - name.as_bytes(), - encode_day(&next).as_bytes(), - util::now() + ttl_secs, - ) { - util::log_err("[usage] 日桶写入失败(共享内存不足?)"); - } -} - -/// 读一个日桶(不存在 = 全 0) -pub fn day_bucket(prefix: &[u8], name: &str) -> DayBucket { - state::get_live(prefix, name.as_bytes(), util::now()) - .map(|p| decode_day(&p)) - .unwrap_or_default() -} diff --git a/source/rust/crates/ipass-core/src/users.rs b/source/rust/crates/ipass-core/src/users.rs deleted file mode 100644 index 9b41d1d..0000000 --- a/source/rust/crates/ipass-core/src/users.rs +++ /dev/null @@ -1,463 +0,0 @@ -//! 账号体系:管理员与普通账号共用一张表。 -//! -//! 对应旧版 `lua/users.lua`。数据结构见 `models::User`。 -//! -//! 「临时授权权限」= 该账号申请**临时域名**时可跳过管理员审核、直接放行。 -//! 注意它只对 temp 生效,long 域名无论谁申请都要审核。 -//! -//! ## 与 LLM 代理共用同一把 Key -//! -//! `api_key` 同时是域名接口(`X-API-Key`)与 LLM 代理 -//! (`Authorization: Bearer`)的凭据——这正是「用同一套 Key 验证」的落点。 -//! 代价是**任何改动 `api_key` 的操作都必须同步共享内存索引**, -//! 且重置 Key 时必须**先摘掉旧索引**,否则被换掉的 Key 依然能用。 - -use std::collections::BTreeMap; -use std::sync::Mutex; - -use serde_json::{Value, json}; - -use crate::config::{ - DISPLAY_NAME_MAX_LEN, INIT_ADMIN_PASSWORD_DEFAULT, INIT_ADMIN_PASSWORD_ENV, INIT_ADMIN_USER, - KEY_UKEY_PREFIX, PASSWORD_MIN_LEN, TEMP_GRANT_TTL, USERNAME_MAX_LEN, USERNAME_MIN_LEN, -}; -use crate::models::{User, UserTable}; -use crate::state; -use crate::store; -use crate::util; - -// =========================================================================== -// 账号删除钩子 -// =========================================================================== - -/// 「账号被删除时我需要清理什么」的回调注册表。 -/// -/// 内核只负责自己的键(`ukey:` / `sess:` / `fail:`),插件的键空间(用量账本、 -/// 代理索引……)内核**不认识**——删除账号要摘几个前缀,取决于装了哪些插件, -/// 所以只能由插件在装载阶段调用 [`on_delete`] 注册清理器(如 plugin-llm 注册 -/// `stats::forget`)。**重复注册同一函数会被去重**(nginx reload 会多次走到注册点)。 -static ON_DELETE: Mutex> = Mutex::new(Vec::new()); - -/// 插件注册「账号被删除时我需要清理什么」。在 zone 装载后、接请求前调用一次。 -pub fn on_delete(f: fn(&str)) { - if let Ok(mut hooks) = ON_DELETE.lock() { - if !hooks.contains(&f) { - hooks.push(f); - } - } -} - -/// 账号删除成功后执行全部钩子。单个钩子没有失败语义(清理动作自身幂等)。 -fn run_delete_hooks(username: &str) { - if let Ok(hooks) = ON_DELETE.lock() { - for f in hooks.iter() { - f(username); - } - } -} - -// =========================================================================== -// 校验 -// =========================================================================== - -/// 账号名:2-32 位字母、数字、下划线或短横线 -fn valid_username(name: &str) -> bool { - let n = name.chars().count(); - if n < USERNAME_MIN_LEN || n > USERNAME_MAX_LEN { - return false; - } - name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') -} - -/// 展示名:允许中文/空格,但**不允许换行或制表等控制字符**—— -/// 它会被塞进管理台 HTML(已转义)与 JSON,控制字符只会造成排版错乱。 -fn check_display_name(raw: &str) -> Result { - let v = util::trim(raw).to_owned(); - if v.chars().count() > DISPLAY_NAME_MAX_LEN { - return Err(format!("展示名不能超过 {DISPLAY_NAME_MAX_LEN} 个字")); - } - if v.chars().any(|c| c.is_control()) { - return Err("展示名不能包含换行或控制字符".to_owned()); - } - Ok(v) -} - -// =========================================================================== -// 共享内存同步(Key 索引) -// =========================================================================== - -/// 身份 payload:` \n \n \n `。 -/// -/// 一次查表同时拿到「是谁 / 能用哪些上游 / 限流多少」——LLM 热路径因此完全 -/// 不必回读 `users.json`(那是同步文件 I/O + 全表 JSON 解码)。 -/// 行数固定为 4;旧版 2 行 payload 由读取方按缺省值兜底。 -fn identity_payload(user: &User) -> String { - format!( - "{}\n{}\n{}\n{}", - user.username, - user.allowed_models.join(","), - user.llm_rpm, - user.llm_daily - ) -} - -/// 把账号的 Key 索引写进共享内存。**所有改动 `api_key` 的写操作都必须调用**。 -/// -/// 写失败(共享内存 zone 满 / 分配失败)会让这个 Key **静默失效**:热路径查不到 -/// 就是 401,且没有任何回源兜底。所以这里必须自己出声——「新建了 Key 却调不通、 -/// 日志里什么都没有」是这类问题最难查的形态。调用方是否检查返回值不影响本日志。 -pub fn sync_shm(user: &User) -> bool { - let ok = state::put_ukey(&user.api_key, &identity_payload(user)); - if !ok { - util::log_err(&format!( - "[users] Key 索引写共享内存失败 user={} —— 该 Key 调 LLM 会 401(共享内存可能已满)", - user.username - )); - } - ok -} - -/// 全量重载 Key 索引(启动装载 / 批量变更后)。返回装载条数。 -/// -/// 只清 `ukey:` 前缀,不会误伤转发映射、上游表与管理会话。 -/// `loaded < total` 时单独报一条 error:单个账号的失败已在 `sync_shm` 里出声, -/// 这里再汇总一次,避免「装载了 3/5 却只在滚动日志里淹没」。 -pub fn reload_shm() -> usize { - state::clear_prefix(KEY_UKEY_PREFIX); - let table = store::read_users(); - let total = table.len(); - let mut loaded = 0; - for user in table.into_values() { - if sync_shm(&user) { - loaded += 1; - } - } - if loaded != total { - util::log_err(&format!( - "[users] Key 索引装载不全:{loaded}/{total} —— 有账号将无法调用 LLM" - )); - } - loaded -} - -// =========================================================================== -// 查询 -// =========================================================================== - -pub fn get(username: &str) -> Option { - if username.is_empty() { - return None; - } - store::read_users().remove(username) -} - -/// 全部账号,按账号名升序 -pub fn all() -> Vec { - store::read_users().into_values().collect() -} - -/// 按 API Key 反查账号(常量时间比较,避免时序侧信道)。 -/// -/// **函数名里没有「快」字**:它每次都同步读 `users.json` 并全表解码, -/// 只适合管理接口这类低频调用方。LLM 转发热路径请用 `llm::identity`, -/// 那条路只查共享内存。 -pub fn find_by_key(key: &str) -> Option { - if key.is_empty() { - return None; - } - store::read_users() - .into_values() - .find(|u| util::ct_eq(&u.api_key, key)) -} - -// =========================================================================== -// 写入 -// =========================================================================== - -fn build_user( - username: &str, - display_name: &str, - password: &str, - role: &str, - grant_temp: bool, -) -> User { - let salt = util::gen_salt(); - let now = util::now(); - User { - username: username.to_owned(), - display_name: display_name.to_owned(), - role: role.to_owned(), - pwd_hash: util::hash_password(password, &salt), - salt, - api_key: util::gen_key(), - allowed_models: Vec::new(), - llm_rpm: crate::config::LLM_RPM_DEFAULT, - llm_daily: crate::config::LLM_DAILY_DEFAULT, - temp_grant_until: if grant_temp { now + TEMP_GRANT_TTL } else { 0 }, - created_at: now, - extra: BTreeMap::new(), - } -} - -/// 首次启动播种管理员。已有数据时原样返回,**不会覆盖**。 -/// -/// 返回 `Ok(true)` 表示「本次真的创建了」,用于打一条提醒日志。 -pub fn seed_admin() -> Result { - let password = - std::env::var(INIT_ADMIN_PASSWORD_ENV).unwrap_or_else(|_| INIT_ADMIN_PASSWORD_DEFAULT.to_owned()); - - let mut created: Option = None; - store::update_users(|users| { - if !users.is_empty() { - return Ok(()); - } - let admin = build_user(INIT_ADMIN_USER, "", &password, "admin", false); - users.insert(admin.username.clone(), admin.clone()); - created = Some(admin); - Ok(()) - })?; - - match created { - Some(u) => { - // 播种发生在 init_process(每个 worker 各一次),这里必须写穿, - // 否则「第一个 worker 建了账号、第二个 worker 覆盖索引」这类竞态 - // 会让新建的 Key 时灵时不灵。 - sync_shm(&u); - Ok(true) - } - None => Ok(false), - } -} - -pub fn create( - username: &str, - display_name: &str, - password: &str, - role: &str, - grant_temp: bool, -) -> Result { - let username = util::trim(username).to_owned(); - if !valid_username(&username) { - return Err(format!( - "账号名只能是 {USERNAME_MIN_LEN}-{USERNAME_MAX_LEN} 位字母、数字、下划线或短横线" - )); - } - let display_name = check_display_name(display_name)?; - if password.len() < PASSWORD_MIN_LEN { - return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); - } - let role = if role == "admin" { "admin" } else { "user" }; - - // 先做一次存在性预检,省掉白算 1000 轮哈希;真正的判定仍在锁内 - if store::read_users().contains_key(&username) { - return Err(format!("账号 {username} 已存在")); - } - - let user = build_user(&username, &display_name, password, role, grant_temp); - let created = user.clone(); - store::update_users(move |users| { - if users.contains_key(&username) { - return Err(format!("账号 {username} 已存在")); - } - users.insert(username.clone(), user); - Ok(()) - })?; - - sync_shm(&created); - Ok(created) -} - -/// 设置展示名(中文姓名等)。只影响管理台显示,不碰 Key / 口令 / 白名单。 -pub fn set_display_name(username: &str, display_name: &str) -> Result { - let display_name = check_display_name(display_name)?; - let updated = store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.display_name = display_name; - Ok(user.clone()) - })?; - // 展示名不在 ukey payload 里(热路径不需要它),无需同步共享内存 - Ok(updated) -} - -/// 重置 API Key,返回新 Key。 -/// -/// **必须同时摘掉旧索引**:LLM 热路径查的是 `ukey:`,若只加新的不删旧的, -/// 被重置掉的 Key 仍然能调通模型——用户以为「换钥匙就安全了」,实际没有。 -pub fn regenerate_key(username: &str) -> Result { - let (old_key, new_key, updated) = store::update_users(|users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - let old = user.api_key.clone(); - user.api_key = util::gen_key(); - Ok((old, user.api_key.clone(), user.clone())) - })?; - - state::remove_ukey(&old_key); - sync_shm(&updated); - Ok(new_key) -} - -/// 设置账号可用的 LLM 上游白名单。传空表表示不限。 -pub fn set_allowed_models(username: &str, slots: Vec) -> Result { - let updated = store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.allowed_models = slots; - Ok(user.clone()) - })?; - - sync_shm(&updated); - Ok(updated) -} - -/// 修改账号的插件扩展字段(`User.extra`)。 -/// -/// 闭包拿到 `&mut User`——可同时改内核字段与 `extra`,由调用方决定语义。 -/// 走 `store::update_users` 的「读-改-写 + 写穿 shm」统一路径,保证 shm -/// `ukey:` 索引与 `users.json` 同步刷新。 -/// -/// 配套 [`crate::models::User::extra`] 的 `#[serde(flatten)]`——上游 -/// sso 收敛时提议(A1),按插件字段透传通道走。 -pub fn update_extra(username: &str, f: F) -> Result -where - F: FnOnce(&mut User) -> Result, -{ - // 闭包内拿到 user 引用 → 调 f 修改 → f 返回后借用释放 → clone 出 owned - // user 给 sync_shm。`update_users` 的闭包签名是 `&mut UserTable`,把 - // UserTable 的可变借用拆借给 &mut User 是 OK 的(Rust 借用分裂)。 - let (out, updated) = store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - let out = f(user)?; - Ok((out, user.clone())) - })?; - sync_shm(&updated); - Ok(out) -} - -/// 设置账号的 LLM 限流参数。`None` = 保持现值;`0` = 不限;正数 = 上限。 -/// -/// 改动的是 `ukey:` payload 的组成部分,所以**必须写穿**—— -/// 否则表现为「改完限额,热路径还按旧额度放行」。 -pub fn set_llm_limits(username: &str, rpm: Option, daily: Option) -> Result { - if let Some(v) = rpm { - if v < 0 { - return Err("每分钟上限不能为负数(0 表示不限)".to_owned()); - } - } - if let Some(v) = daily { - if v < 0 { - return Err("每日上限不能为负数(0 表示不限)".to_owned()); - } - } - - let updated = store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - if let Some(v) = rpm { - user.llm_rpm = v; - } - if let Some(v) = daily { - user.llm_daily = v; - } - Ok(user.clone()) - })?; - - sync_shm(&updated); - Ok(updated) -} - -/// 授予临时授权权限(默认 6 小时),返回到期时间戳 -pub fn grant_temp(username: &str, hours: Option<&String>) -> Result { - let ttl = hours - .and_then(|h| h.parse::().ok()) - .map(|h| h * 3600) - .unwrap_or(TEMP_GRANT_TTL); - - store::update_users(|users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.temp_grant_until = util::now() + ttl; - Ok(user.temp_grant_until) - }) -} - -pub fn revoke_temp(username: &str) -> Result<(), String> { - store::update_users(|users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.temp_grant_until = 0; - Ok(()) - }) -} - -pub fn set_password(username: &str, password: &str) -> Result<(), String> { - if password.len() < PASSWORD_MIN_LEN { - return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); - } - let salt = util::gen_salt(); - let hash = util::hash_password(password, &salt); - - // 改口令不动 api_key,因此不需要同步 Key 索引 - store::update_users(move |users: &mut UserTable| { - let user = users.get_mut(username).ok_or("账号不存在")?; - user.salt = salt; - user.pwd_hash = hash; - Ok(()) - }) -} - -/// 删除账号。两条红线:不能删自己、必须至少保留一个管理员。 -/// -/// 顺带摘掉 Key 索引——否则删掉的账号仍能通过 LLM 代理调用模型。 -pub fn delete(username: &str, operator: &str) -> Result<(), String> { - if username == operator { - return Err("不能删除当前登录的账号".to_owned()); - } - let username = username.to_owned(); - let deleted = username.clone(); - - let removed_key = store::update_users(move |users| { - let user = users.get(&username).ok_or("账号不存在")?; - if user.role == "admin" { - let admins = users.values().filter(|u| u.role == "admin").count(); - if admins <= 1 { - return Err("至少需要保留一个管理员账号".to_owned()); - } - } - Ok(users.remove(&username).map(|u| u.api_key).unwrap_or_default()) - })?; - - if !removed_key.is_empty() { - state::remove_ukey(&removed_key); - } - // 内核自己的键已摘掉;用量账本等插件键空间由 on_delete 钩子清理 - // (谁装了谁清——钩子为空说明对应插件未装配,自然也无键可清) - run_delete_hooks(&deleted); - Ok(()) -} - -// =========================================================================== -// 对外投影 -// =========================================================================== - -/// 转成前端可见的字段(**绝不包含 salt / pwd_hash**) -pub fn view(user: &User) -> Value { - let now = util::now(); - let until_ts = user.temp_grant_until; - let active = until_ts > now; - - json!({ - "username": user.username, - "display_name": user.display_name, - // 前端统一用 name 渲染——展示名优先,没有就回落到账号名 - "name": if user.display_name.is_empty() { user.username.clone() } else { user.display_name.clone() }, - "role": user.role, - "api_key": user.api_key, - "api_key_masked": util::mask_key(&user.api_key), - "allowed_models": user.allowed_models, - "llm_rpm": user.llm_rpm, - "llm_daily": user.llm_daily, - "created_at": user.created_at, - "created_at_text": util::fmt_time(user.created_at), - "temp_grant": active, - "temp_grant_until": until_ts, - "temp_grant_until_text": if active { util::fmt_time(until_ts) } else { String::new() }, - "temp_grant_left": if active { until_ts - now } else { 0 }, - "temp_grant_left_text": if active { util::fmt_left(until_ts - now) } else { String::new() }, - }) -} diff --git a/source/rust/crates/ipass-core/src/util.rs b/source/rust/crates/ipass-core/src/util.rs deleted file mode 100644 index 6988480..0000000 --- a/source/rust/crates/ipass-core/src/util.rs +++ /dev/null @@ -1,354 +0,0 @@ -//! 通用工具:时间 / 随机 / 摘要 / 口令哈希 / 常量时间比较 / 格式化 / 参数解码。 -//! -//! 对应旧版的 `lua/util.lua`。其中 `hash_password` 的算法**必须逐位一致**, -//! 否则旧的 `data/users.json` 里的口令哈希将全部失效。 - -use sha2::{Digest, Sha256}; - -use crate::config::HASH_ROUNDS; - -// =========================================================================== -// 日志 -// =========================================================================== - -/// 写 nginx error log。 -/// -/// 形参顺序容易记错:`ngx_log_error_core(level, log, err, fmt, ...)`, -/// 其中 `err` 只在需要附带系统错误号时非 0。 -pub fn log_at(level: usize, msg: &str) { - // SAFETY: 传入的 CString 在本调用期间存活;日志接口不持有其引用 - unsafe { - let c = std::ffi::CString::new(msg).unwrap_or_default(); - let lg = if nginx_sys::ngx_cycle.is_null() { - core::ptr::null_mut() - } else { - (*nginx_sys::ngx_cycle).log - }; - nginx_sys::ngx_log_error_core(level, lg, 0, c"%s".as_ptr(), c.as_ptr()); - } -} - -pub fn log_err(msg: &str) { - log_at(nginx_sys::NGX_LOG_ERR as usize, msg); -} - -pub fn log_warn(msg: &str) { - log_at(nginx_sys::NGX_LOG_WARN as usize, msg); -} - -pub fn log_notice(msg: &str) { - log_at(nginx_sys::NGX_LOG_NOTICE as usize, msg); -} - -// =========================================================================== -// 时间 -// =========================================================================== - -/// 当前 Unix 时间戳(秒)。 -/// -/// nginx 的 `ngx_time()` 是宏,bindgen 拿不到;直接走 libc 的 `time()`, -/// 在 Linux/macOS 上都由 vDSO 提供,代价与读一个全局变量相当。 -#[inline] -pub fn now() -> i64 { - // SAFETY: time(NULL) 只读系统时钟,无副作用 - unsafe { libc::time(core::ptr::null_mut()) as i64 } -} - -/// `%Y-%m-%d %H:%M:%S`(本地时区,等价旧版 `os.date`);ts <= 0 返回 `-` -pub fn fmt_time(ts: i64) -> String { - if ts <= 0 { - return "-".to_owned(); - } - // SAFETY: 传入有效指针;localtime_r 不返回静态数据,线程安全 - unsafe { - let t = ts as libc::time_t; - let mut tm: libc::tm = core::mem::zeroed(); - if libc::localtime_r(&t, &mut tm).is_null() { - return "-".to_owned(); - } - let mut buf = [0 as libc::c_char; 40]; - let fmt = c"%Y-%m-%d %H:%M:%S"; - let n = libc::strftime(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), &tm); - if n == 0 { - return "-".to_owned(); - } - core::ffi::CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned() - } -} - -/// `%m-%d`(本地时区)。趋势图 x 轴用——带上年份会让 14 天的轴标签又长又重复 -pub fn fmt_day(ts: i64) -> String { - if ts <= 0 { - return "-".to_owned(); - } - // SAFETY: 同 fmt_time - unsafe { - let t = ts as libc::time_t; - let mut tm: libc::tm = core::mem::zeroed(); - if libc::localtime_r(&t, &mut tm).is_null() { - return "-".to_owned(); - } - let mut buf = [0 as libc::c_char; 16]; - let fmt = c"%m-%d"; - let n = libc::strftime(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), &tm); - if n == 0 { - return "-".to_owned(); - } - core::ffi::CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned() - } -} - -/// 本地时区的「日窗 id」(年份×1000 + 年内第几天),跨天自动翻窗。 -/// -/// 限流配额按**本地日**切(面向中国用户,即东八区自然日),不用 UTC—— -/// UTC 的日界线在北京时间早上 8 点,「每日额度」会在半夜重置,反直觉。 -pub fn day_id(ts: i64) -> i64 { - // SAFETY: localtime_r 只读时间戳并填充调用方的结构体 - unsafe { - let t = ts as libc::time_t; - let mut tm: libc::tm = core::mem::zeroed(); - if libc::localtime_r(&t, &mut tm).is_null() { - return ts.div_euclid(86400); // 兜底:退化成 UTC 日 - } - tm.tm_year as i64 * 1000 + tm.tm_yday as i64 - } -} - -/// 剩余时长的中文描述(与旧版 `fmt_left` 输出一致) -pub fn fmt_left(seconds: i64) -> String { - if seconds <= 0 { - return "已过期".to_owned(); - } - let h = seconds / 3600; - let m = (seconds % 3600) / 60; - let s = seconds % 60; - if h > 0 { - format!("{h} 小时 {m} 分") - } else if m > 0 { - format!("{m} 分 {s} 秒") - } else { - format!("{s} 秒") - } -} - -// =========================================================================== -// 随机与十六进制 -// =========================================================================== - -pub fn to_hex(bytes: &[u8]) -> String { - const HEX: &[u8; 16] = b"0123456789abcdef"; - let mut out = String::with_capacity(bytes.len() * 2); - for &b in bytes { - out.push(HEX[(b >> 4) as usize] as char); - out.push(HEX[(b & 0x0f) as usize] as char); - } - out -} - -/// 密码学安全随机字节。取不到随机源时返回 None(调用方必须显式处理, -/// **不允许**退化成可预测的伪随机——那等于把 API Key 直接送给攻击者)。 -fn rand_bytes(buf: &mut [u8]) -> Option<()> { - getrandom::getrandom(buf).ok() -} - -/// `n` 字节随机数的 hex 表示(会话 token 等场景) -pub fn rand_hex(n: usize) -> String { - let mut b = vec![0u8; n]; - if rand_bytes(&mut b).is_none() { - let mut seed = now() as u64 ^ 0x2545_f491_4f6c_dd1d; - for byte in b.iter_mut() { - // xorshift:随机源失效时的最后手段,至少不产出常量 - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - *byte = (seed & 0xff) as u8; - } - } - to_hex(&b) -} - -/// 口令盐:16 字节 → 32 位 hex -pub fn gen_salt() -> String { - let mut b = [0u8; 16]; - if rand_bytes(&mut b).is_none() { - // 极罕见:随机源不可用。此处不能 panic(会崩掉整个 worker), - // 退化为基于时间的混淆值并让上层记录失败。 - let n = now() as u64 ^ 0x9e37_79b9_7f4a_7c15; - b[..8].copy_from_slice(&n.to_le_bytes()); - b[8..].copy_from_slice(&n.rotate_left(17).to_le_bytes()); - } - to_hex(&b) -} - -/// 账号 API Key:`sk_` + 24 字节 → 48 位 hex -pub fn gen_key() -> String { - let mut b = [0u8; 24]; - if rand_bytes(&mut b).is_none() { - let n = now() as u64; - for (i, chunk) in b.chunks_mut(8).enumerate() { - chunk.copy_from_slice(&n.rotate_left((i as u32) * 13).to_le_bytes()); - } - } - format!("sk_{}", to_hex(&b)) -} - -/// 域名记录 id:`d_` + 6 字节 → 12 位 hex -pub fn gen_id() -> String { - let mut b = [0u8; 6]; - if rand_bytes(&mut b).is_none() { - let n = now() as u32; - b[..4].copy_from_slice(&n.to_le_bytes()); - b[4..].copy_from_slice(&(n ^ 0xa5a5).to_le_bytes()[..2]); - } - format!("d_{}", to_hex(&b)) -} - -/// `n` 位纯数字随机串(每位 0-9 等概率)。 -/// -/// 用**拒绝采样**而不是 `byte % 10`:256 不是 10 的倍数,直接取模会让 0-5 -/// 比 6-9 各多出现约 0.4%(对子域名无害,但没理由留这个瑕疵)。 -/// 只接受 `< 250` 的字节(250 = 25×10),落桶严格均匀。 -/// -/// 非安全场景(子域名后缀),但仍复用 `getrandom`——顺带拿到「随机源不可用」 -/// 的统一退化路径,且随机源失效时绝不 panic。 -pub fn rand_digits(n: usize) -> String { - let mut out = String::with_capacity(n); - let mut buf = [0u8; 32]; - // 随机源不可用时退化为 xorshift(与 rand_hex 同款兜底),仍会终止 - let mut seed = now() as u64 ^ 0x2545_f491_4f6c_dd1d; - while out.len() < n { - let take = (n - out.len()).min(buf.len()); - let slice = &mut buf[..take]; - let ok = rand_bytes(slice).is_some(); - if !ok { - for byte in slice.iter_mut() { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - *byte = (seed & 0xff) as u8; - } - } - for &b in slice.iter() { - if b < 250 && out.len() < n { - out.push((b'0' + (b % 10)) as char); - } - } - } - out -} - -// =========================================================================== -// 摘要与口令 -// =========================================================================== - -pub fn sha256_hex(data: &[u8]) -> String { - let mut h = Sha256::new(); - h.update(data); - to_hex(&h.finalize()) -} - -/// 迭代加盐哈希,降低撞库速度。 -/// -/// 算法(与旧版 `util.hash_password` 完全一致): -/// x = sha256(salt + ":" + password) -/// 重复 HASH_ROUNDS 次:x = sha256(x + salt) -pub fn hash_password(password: &str, salt: &str) -> String { - let mut x = sha256_hex(format!("{salt}:{password}").as_bytes()); - for _ in 0..HASH_ROUNDS { - x = sha256_hex(format!("{x}{salt}").as_bytes()); - } - x -} - -pub fn verify_password(password: &str, salt: &str, expected: &str) -> bool { - ct_eq(&hash_password(password, salt), expected) -} - -/// 常量时间比较:无论差异出现在第几位,都在同一轮数内完成。 -pub fn ct_eq(a: &str, b: &str) -> bool { - let (a, b) = (a.as_bytes(), b.as_bytes()); - if a.len() != b.len() { - return false; - } - let mut diff = 0u8; - for i in 0..a.len() { - diff |= a[i] ^ b[i]; - } - diff == 0 -} - -// =========================================================================== -// 文本 -// =========================================================================== - -pub fn trim(v: &str) -> &str { - v.trim() -} - -pub fn to_bool(v: Option<&String>) -> bool { - match v { - Some(s) => matches!(s.to_ascii_lowercase().as_str(), "1" | "true" | "on" | "yes"), - None => false, - } -} - -/// `sk_12345678...abcd` → `sk_12345...abcd` -pub fn mask_key(key: &str) -> String { - if key.len() < 12 { - return key.to_owned(); - } - format!("{}...{}", &key[..8], &key[key.len() - 4..]) -} - -/// percent-decode(`%XX`)并把 `+` 还原为空格。 -/// -/// 旧版由 `ngx.req.get_uri_args` / `get_post_args` 自动完成, -/// Rust 侧必须自己实现,否则带中文或特殊字符的参数会解析错误。 -pub fn url_decode(input: &str) -> String { - let bytes = input.as_bytes(); - let mut out: Vec = Vec::with_capacity(bytes.len()); - let mut i = 0; - while i < bytes.len() { - match bytes[i] { - b'+' => { - out.push(b' '); - i += 1; - } - b'%' if i + 2 < bytes.len() => { - let hi = (bytes[i + 1] as char).to_digit(16); - let lo = (bytes[i + 2] as char).to_digit(16); - match (hi, lo) { - (Some(h), Some(l)) => { - out.push((h * 16 + l) as u8); - i += 3; - } - _ => { - out.push(b'%'); - i += 1; - } - } - } - b => { - out.push(b); - i += 1; - } - } - } - String::from_utf8_lossy(&out).into_owned() -} - -/// 解析 `a=1&b=2` 形式的键值对(自动 percent-decode)。 -pub fn parse_kv(raw: &[u8]) -> Vec<(String, String)> { - let mut out = Vec::new(); - let text = String::from_utf8_lossy(raw); - for pair in text.split('&') { - if pair.is_empty() { - continue; - } - let mut it = pair.splitn(2, '='); - let k = it.next().unwrap_or(""); - let v = it.next().unwrap_or(""); - out.push((url_decode(k), url_decode(v))); - } - out -} diff --git a/source/rust/crates/plugin-domain/Cargo.toml b/source/rust/crates/plugin-domain/Cargo.toml deleted file mode 100644 index 11404e3..0000000 --- a/source/rust/crates/plugin-domain/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "plugin-domain" -version = "2.0.0" -edition.workspace = true -publish = false -description = "iPass 插件:动态域名(子域名映射、申请审批、转发决策)" - -[lib] -# 只有 gateway 是 cdylib;插件一律 rlib(跨 .so 传 Rust 类型会双重 free) -crate-type = ["rlib"] - -[dependencies] -ngx.workspace = true -serde.workspace = true -serde_json.workspace = true -ipass-core.workspace = true diff --git a/source/rust/crates/plugin-domain/src/api.rs b/source/rust/crates/plugin-domain/src/api.rs deleted file mode 100644 index f67ee32..0000000 --- a/source/rust/crates/plugin-domain/src/api.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! 域名类端点:管理员审核/创建/删除/清理 + 账号态申请/查询/删除。 -//! -//! 路由表只认领**本插件**的路径;不认领的返回 `None` 交给下一个插件。 -//! `/api/admin/purge` 清理的是过期域名与陈旧驳回记录,属域名职责。 - -use ngx::core::Status; -use ngx::ffi::ngx_http_request_t; -use ngx::http::HTTPStatus; -use serde_json::json; - -use ipass_core::api::{Actor, Guard, run_guarded, user_or_401}; -use ipass_core::http; -use ipass_core::util; - -use crate::config; -use crate::domains; - -// =========================================================================== -// 路由 -// =========================================================================== - -type Handler = fn(*mut ngx_http_request_t, Actor) -> Status; - -fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> { - let entry: (Guard, Handler) = match (method, uri) { - ("GET", "/api/admin/domains") => (Guard::Admin, h_admin_domains), - ("POST", "/api/admin/domains/review") => (Guard::Admin, h_admin_domain_review), - ("POST", "/api/admin/domains/create") => (Guard::Admin, h_admin_domain_create), - ("POST", "/api/admin/domains/delete") => (Guard::Admin, h_admin_domain_delete), - ("POST", "/api/admin/purge") => (Guard::Admin, h_admin_purge), - ("GET", "/api/v1/domains") => (Guard::User, h_my_domains), - ("POST", "/api/v1/domains/apply") => (Guard::User, h_apply), - ("POST", "/api/v1/domains/delete") => (Guard::User, h_my_delete), - _ => return None, - }; - Some(entry) -} - -/// 本表分发:认领则返回响应状态,不认领返回 `None`。 -pub fn dispatch(r: *mut ngx_http_request_t) -> Option { - let method = http::method_str(r); - let uri = http::uri(r); - - let Some((guard, handler)) = route(&method, &uri) else { - return None; - }; - - Some(run_guarded(r, guard, handler)) -} - -// =========================================================================== -// 管理员:域名审核 -// =========================================================================== - -fn h_admin_domains(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - http::ok( - r, - json!({ - "items": domains::view_all(&domains::all()), - "pending": domains::count_pending(), - // 子域名命名规则:前端据此渲染「i + 8位数字 + dm」输入框, - // 避免前后端各写一份前缀/后缀/zone 而漂移(真源 = 本插件 config.rs) - "subdomain_rule": { - "zone": config::ENTERPRISE_ZONE, - "prefix": config::SUBDOMAIN_PREFIX, - "suffix": config::SUBDOMAIN_SUFFIX, - "digits": config::SUBDOMAIN_RAND_DIGITS, - }, - }), - "ok", - ) -} - -fn h_admin_domain_review(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let p = http::params(r); - let id = p.get("id").map(String::as_str).unwrap_or(""); - let action = p.get("action").map(String::as_str).unwrap_or(""); - match domains::review(id, action, actor.admin_name()) { - Ok(entry) => { - let msg = if action == "approve" { "已通过审核" } else { "已驳回" }; - http::ok(r, domains::view(&entry), msg) - } - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_domain_create(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let p = http::params(r); - - // subdomain 缺省(或空串)= 由网关按规则自动生成 `i<8位随机数字>dm`, - // 与面板上「i + 8位随机数 + dm」是同一套规则(见 domains::gen_subdomain)。 - match domains::create_by_admin( - p.get("subdomain").map(String::as_str).unwrap_or(""), - p.get("backend").map(String::as_str).unwrap_or(""), - p.get("type"), - p.get("owner"), - actor.admin_name(), - ) { - Ok(entry) => http::ok(r, domains::view(&entry), "已创建并直接放行"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_domain_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - let p = http::params(r); - let id = p.get("id").map(String::as_str).unwrap_or(""); - - match domains::remove(id) { - Ok(sub) => http::ok(r, json!({ "subdomain": sub }), "已删除"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -fn h_admin_purge(r: *mut ngx_http_request_t, _actor: Actor) -> Status { - match domains::purge() { - Ok(removed) => http::ok( - r, - json!({ "removed": removed }), - &format!("已清理 {removed} 条过期/陈旧记录"), - ), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} - -// =========================================================================== -// 账号态 -// =========================================================================== - -fn h_my_domains(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let user = match user_or_401(r, actor) { - Ok(u) => u, - Err(e) => return e, - }; - http::ok( - r, - json!({ "items": domains::view_all(&domains::by_owner(&user.username)) }), - "ok", - ) -} - -fn h_apply(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let user = match user_or_401(r, actor) { - Ok(u) => u, - Err(e) => return e, - }; - - let p = http::params(r); - let entry = match domains::apply( - &user.username, - p.get("subdomain").map(String::as_str).unwrap_or(""), - p.get("backend").map(String::as_str).unwrap_or(""), - p.get("type"), - ) { - Ok(e) => e, - Err(e) => return http::fail(r, HTTPStatus::BAD_REQUEST, &e), - }; - - let view = domains::view(&entry); - util::log_notice(&format!( - "[api] {} 申请 {} type={} status={}", - user.username, - entry.subdomain, - entry.dtype, - entry.effective_status(util::now()) - )); - - let msg = if entry.status == "approved" { - format!( - "已直接放行(临时授权权限生效),{} 小时后自动失效", - config::TEMP_DOMAIN_TTL / 3600 - ) - } else { - "已提交申请,等待管理员审核".to_owned() - }; - http::ok(r, view, &msg) -} - -fn h_my_delete(r: *mut ngx_http_request_t, actor: Actor) -> Status { - let user = match user_or_401(r, actor) { - Ok(u) => u, - Err(e) => return e, - }; - - let p = http::params(r); - let id = p.get("id").map(String::as_str).unwrap_or(""); - - match domains::remove_own(id, &user.username) { - Ok(sub) => http::ok(r, json!({ "subdomain": sub }), "已删除"), - Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), - } -} diff --git a/source/rust/crates/plugin-domain/src/config.rs b/source/rust/crates/plugin-domain/src/config.rs deleted file mode 100644 index 6157c61..0000000 --- a/source/rust/crates/plugin-domain/src/config.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! 域名插件策略常量(自内核 config.rs 迁入;改策略只改这里)。 - -/// 临时域名审批通过后的有效期(秒)。到期仅停止转发,记录保留供查阅。 -pub const TEMP_DOMAIN_TTL: i64 = 6 * 3600; - -/// 子域名总长上限:首字符 + 最多 61 个后续字符 -pub const SUBDOMAIN_MAX_LEN: usize = 62; - -/// 系统保留名:不允许用户申请,避免抢占管理入口 -pub const RESERVED_SUBDOMAINS: [&str; 4] = ["proxy-api", "admin", "www", "api"]; - -/// 驳回记录保留时长,超期由 purge 清理(秒) -pub const REJECTED_PURGE_TTL: i64 = 7 * 86400; - -/// 键前缀:子域名 → 后端映射 -pub const KEY_SUB_PREFIX: &[u8] = b"sub:"; - -/// 企业域名(业务域名)的 zone:**子域名 + `.` + 此后缀 = 完整对外域名**。 -/// -/// ⚠️ 与 `conf/nginx.conf` 的「企业域名 server」严格耦合: -/// `server_name ~^(?.+dm)\.mayishangshu\.cn$;` -/// 改这里必须同步改那条正则(反之亦然)。 -pub const ENTERPRISE_ZONE: &str = "mayishangshu.cn"; - -/// 自动生成子域名的形状:`<前缀><后缀>` —— 例如 `i12345678dm`。 -/// -/// 后缀**必须是 `dm`**:企业域名 server 的正则要求捕获组以 `dm` 结尾 -/// (`^(.+dm)\.mayishangshu\.cn$`),否则域名建出来也转发不到。 -/// 这是「规则」的实质约束,不是命名偏好。 -pub const SUBDOMAIN_PREFIX: &str = "i"; -pub const SUBDOMAIN_SUFFIX: &str = "dm"; -/// 随机数字位数。10^8 的空间,撞车概率极低 -pub const SUBDOMAIN_RAND_DIGITS: usize = 8; -/// 自动生成子域名时的最大重试次数(真撞上已占用的就换一个再试) -pub const SUBDOMAIN_GEN_ATTEMPTS: usize = 5; diff --git a/source/rust/crates/plugin-domain/src/domains.rs b/source/rust/crates/plugin-domain/src/domains.rs deleted file mode 100644 index db09a3e..0000000 --- a/source/rust/crates/plugin-domain/src/domains.rs +++ /dev/null @@ -1,488 +0,0 @@ -//! 域名(子域名映射)与申请审核。 -//! -//! 数据结构见 `models::DomainEntry`。 -//! -//! ## 状态机 -//! -//! ```text -//! temp + 有临时授权权限 → 直接 approved(reviewed_by=auto,到时自动 expired) -//! temp + 无临时授权权限 → pending,等管理员审核 -//! long + 任意 → pending,等管理员审核 -//! ``` -//! -//! 到期不等于删除:临时域名过期后仅「不再转发」,记录保留供查阅。 -//! -//! ## 写穿 -//! -//! 热路径**永不回源**(未命中即 404),所以每个写操作都必须 -//! **同时更新共享内存与文件**——这就是 `sync_shm` 的存在理由。 -//! 漏掉一处,就会出现「审核通过了但立刻 404」。 - -use serde_json::{Value, json}; - -use ipass_core::{state, users, util}; - -use crate::config::{ - ENTERPRISE_ZONE, KEY_SUB_PREFIX, REJECTED_PURGE_TTL, RESERVED_SUBDOMAINS, SUBDOMAIN_GEN_ATTEMPTS, - SUBDOMAIN_MAX_LEN, SUBDOMAIN_PREFIX, SUBDOMAIN_RAND_DIGITS, SUBDOMAIN_SUFFIX, TEMP_DOMAIN_TTL, -}; -use crate::models::DomainEntry; - -// =========================================================================== -// 校验 -// =========================================================================== - -/// 子域名:小写字母/数字开头,其后可含短横线,总长 ≤ 62,且不在保留名单内。 -/// 返回规范化(小写)后的值。 -pub fn validate_subdomain(raw: &str) -> Result { - if raw.is_empty() { - return Err("缺少 subdomain 参数".to_owned()); - } - let s = raw.to_ascii_lowercase(); - let bytes = s.as_bytes(); - - if bytes.len() > SUBDOMAIN_MAX_LEN { - return Err("子域名长度不能超过 62 个字符".to_owned()); - } - let head_ok = matches!(bytes[0], b'a'..=b'z' | b'0'..=b'9'); - let tail_ok = bytes[1..].iter().all(|&b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-')); - if !head_ok || !tail_ok { - return Err("子域名只能是小写字母、数字、短横线,且不能以短横线开头".to_owned()); - } - if RESERVED_SUBDOMAINS.contains(&s.as_str()) { - return Err(format!("子域名 {s} 为系统保留名,不可使用")); - } - Ok(s) -} - -/// 后端地址:`host:port`,host 允许字母/数字/`.`/`_`/`-`,端口 1-65535 -pub fn validate_backend(raw: &str) -> Result { - let s = util::trim(raw); - if s.is_empty() { - return Err("缺少 backend 参数".to_owned()); - } - let Some(colon) = s.rfind(':') else { - return Err("backend 格式应为 host:port,例如 192.168.1.7:89".to_owned()); - }; - let (host, port) = (&s[..colon], &s[colon + 1..]); - - let host_ok = !host.is_empty() - && host.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); - let port_ok = !port.is_empty() - && port.chars().all(|c| c.is_ascii_digit()) - && port.parse::().map(|p| (1..=65535).contains(&p)).unwrap_or(false); - - if !host_ok || !port_ok { - return Err("backend 格式应为 host:port,且端口在 1-65535 之间".to_owned()); - } - Ok(s.to_owned()) -} - -// =========================================================================== -// 子域名命名规则(唯一真源,前端/API 共用) -// =========================================================================== - -/// 生成一个符合企业域名规则的子域名:`i` + 8 位随机数字 + `dm`(如 `i48291376dm`)。 -/// -/// **后缀 `dm` 不是装饰**:企业域名 server 的正则是 -/// `^(.+dm)\.mayishangshu\.cn$`,捕获组必须以 `dm` 结尾,否则该域名根本不会 -/// 被转发 server 匹配到。所以「i+8位+dm」是硬约束,别改后缀。 -pub fn gen_subdomain() -> String { - format!( - "{SUBDOMAIN_PREFIX}{}{SUBDOMAIN_SUFFIX}", - util::rand_digits(SUBDOMAIN_RAND_DIGITS) - ) -} - -/// 子域名 → 完整对外域名(**不含端口**)。 -/// -/// 端口刻意不在这里拼:网关用宿主 88 承载三个域名,但端口应当**跟随调用方** -/// (见 readme §15),由前端按 `location.port` 拼,写死任何一种都会在另一种 -/// 部署下给出「看着对、打不通」的地址。 -pub fn full_host(subdomain: &str) -> String { - format!("{subdomain}.{ENTERPRISE_ZONE}") -} - -pub fn validate_type(raw: Option<&String>) -> String { - match raw.map(|s| s.as_str()) { - Some("long") => "long".to_owned(), - _ => "temp".to_owned(), - } -} - -// =========================================================================== -// 共享内存同步(写穿 / 装载) -// =========================================================================== - -/// 把一条记录同步进共享内存。**所有写操作之后必须调用它**。 -/// -/// 写失败 = 热路径查不到 = 该域名立刻 404,所以失败必须出声 -/// (`state::put` 返回 false:共享内存 zone 满或分配失败)。 -pub fn sync_shm(entry: &DomainEntry) { - let now = util::now(); - if entry.is_forwardable(now) { - // long 用 0 表示永不过期;temp 用真实到期时刻,热路径读到即知是否还能用 - let exp = if entry.dtype == "temp" { entry.expires_at } else { 0 }; - if !state::put( - KEY_SUB_PREFIX, - entry.subdomain.as_bytes(), - entry.backend.as_bytes(), - exp, - ) { - util::log_err(&format!( - "[domains] 转发映射写共享内存失败 sub={} —— 该域名会 404(共享内存可能已满)", - entry.subdomain - )); - } - } else { - state::remove(KEY_SUB_PREFIX, entry.subdomain.as_bytes()); - } -} - -/// 全量重载转发映射(启动装载 / purge / 连带回收后调用)。返回装载条数。 -/// -/// 只清 `sub:` 前缀的键,**不会误伤正在登录的管理员会话**。 -pub fn reload_shm() -> usize { - state::clear_prefix(KEY_SUB_PREFIX); - let now = util::now(); - let mut expected = 0; - let mut loaded = 0; - for entry in crate::store::read_domains() { - if entry.is_forwardable(now) { - expected += 1; - let exp = if entry.dtype == "temp" { entry.expires_at } else { 0 }; - if state::put(KEY_SUB_PREFIX, entry.subdomain.as_bytes(), entry.backend.as_bytes(), exp) { - loaded += 1; - } - } - } - if loaded != expected { - util::log_err(&format!( - "[domains] 转发映射装载不全:{loaded}/{expected} —— 有域名会 404" - )); - } - loaded -} - -// =========================================================================== -// 查询 -// =========================================================================== - -/// 全部记录,按创建时间倒序 -pub fn all() -> Vec { - let mut list = crate::store::read_domains(); - list.sort_by(|a, b| b.created_at.cmp(&a.created_at)); - list -} - -pub fn by_owner(owner: &str) -> Vec { - let mut list: Vec = - crate::store::read_domains().into_iter().filter(|e| e.owner == owner).collect(); - list.sort_by(|a, b| b.created_at.cmp(&a.created_at)); - list -} - -/// 按 id 取单条记录(当前无调用方,保留为对外查询接口) -#[allow(dead_code)] -pub fn by_id(id: &str) -> Option { - crate::store::read_domains().into_iter().find(|e| e.id == id) -} - -pub fn count_pending() -> usize { - crate::store::read_domains().iter().filter(|e| e.status == "pending").count() -} - -// =========================================================================== -// 用户申请 -// =========================================================================== - -/// 用户提交申请。有临时授权权限的 temp 申请直接放行。 -/// -/// 返回的 entry 若 `status == approved && reviewed_by == auto`,即免审通过。 -pub fn apply( - username: &str, - subdomain: &str, - backend: &str, - dtype: Option<&String>, -) -> Result { - let user = users::get(username).ok_or("账号不存在")?; - - let subdomain = validate_subdomain(subdomain)?; - let backend = validate_backend(backend)?; - let dtype = validate_type(dtype); - - let now = util::now(); - let auto = dtype == "temp" && user.has_temp_permission(now); - - let chosen = subdomain.clone(); - let entry = crate::store::update_domains(move |list| { - if let Some(idx) = list.iter().position(|e| e.subdomain == chosen) { - let existing = &list[idx]; - let mine_pending = existing.owner == username && existing.status == "pending"; - let its_expired = - existing.dtype == "temp" && existing.effective_status(now) == "expired"; - - // 自己的待审申请可以改写;已失效的临时域名视为空闲可复用 - if !(mine_pending || its_expired) { - return Err(format!("子域名 {chosen} 已被占用")); - } - list.remove(idx); - } - - let entry = DomainEntry { - id: util::gen_id(), - subdomain: chosen, - backend, - dtype, - owner: username.to_owned(), - status: if auto { "approved".to_owned() } else { "pending".to_owned() }, - created_at: now, - expires_at: if auto { now + TEMP_DOMAIN_TTL } else { 0 }, - reviewed_by: if auto { "auto".to_owned() } else { String::new() }, - reviewed_at: if auto { now } else { 0 }, - }; - list.push(entry.clone()); - Ok(entry) - })?; - - sync_shm(&entry); - Ok(entry) -} - -// =========================================================================== -// 管理员操作 -// =========================================================================== - -/// 审核:approve / reject。只允许处理 pending 状态。 -pub fn review(id: &str, action: &str, admin: &str) -> Result { - if action != "approve" && action != "reject" { - return Err("action 只能是 approve 或 reject".to_owned()); - } - let now = util::now(); - let id = id.to_owned(); - let action = action.to_owned(); - let admin = admin.to_owned(); - - let updated = crate::store::update_domains(move |list| { - let item = list.iter_mut().find(|e| e.id == id).ok_or("记录不存在")?; - if item.status != "pending" { - return Err(format!("该申请已处理(当前状态:{})", item.status)); - } - if action == "approve" { - item.status = "approved".to_owned(); - item.expires_at = if item.dtype == "temp" { now + TEMP_DOMAIN_TTL } else { 0 }; - } else { - item.status = "rejected".to_owned(); - } - item.reviewed_by = admin; - item.reviewed_at = now; - Ok(item.clone()) - })?; - - sync_shm(&updated); - Ok(updated) -} - -/// 管理员直接创建并放行(等价于「我替你建好并批准」)。 -/// -/// `subdomain` **留空即自动生成** `i<8位随机数字>dm`(见 `gen_subdomain`), -/// 撞上已占用就换一个重试(最多 `SUBDOMAIN_GEN_ATTEMPTS` 次)。管理台与 -/// `/api/admin/domains/create` 走同一条路径,规则不会两处漂移。 -pub fn create_by_admin( - subdomain: &str, - backend: &str, - dtype: Option<&String>, - owner: Option<&String>, - admin: &str, -) -> Result { - let backend = validate_backend(backend)?; - - let owner = match owner { - Some(o) if !o.is_empty() => o.clone(), - _ => admin.to_owned(), - }; - if users::get(&owner).is_none() { - return Err(format!("归属账号不存在:{owner}")); - } - - let dtype = validate_type(dtype); - let manual = !util::trim(subdomain).is_empty(); - let attempts = if manual { 1 } else { SUBDOMAIN_GEN_ATTEMPTS }; - - let mut last_err = "子域名生成失败".to_owned(); - for _ in 0..attempts { - let sub = if manual { validate_subdomain(subdomain)? } else { gen_subdomain() }; - // 自动生成的也过一遍校验:常量被误改时立刻报错,而不是建出个用不了的域名 - let sub = validate_subdomain(&sub)?; - match insert_approved(&sub, &backend, &dtype, &owner, admin) { - Ok(entry) => { - sync_shm(&entry); - return Ok(entry); - } - Err(e) => { - // 手填的子域名撞车是用户要解决的问题;自动生成的直接换一个重试 - if manual { - return Err(e); - } - last_err = e; - } - } - } - Err(last_err) -} - -/// 落盘一条 approved 记录(占用检查在这里);调用方负责 `sync_shm`。 -fn insert_approved( - subdomain: &str, - backend: &str, - dtype: &str, - owner: &str, - admin: &str, -) -> Result { - let now = util::now(); - let chosen = subdomain.to_owned(); - let backend = backend.to_owned(); - let dtype = dtype.to_owned(); - let owner = owner.to_owned(); - let admin = admin.to_owned(); - - crate::store::update_domains(move |list| { - if let Some(idx) = list.iter().position(|e| e.subdomain == chosen) { - let existing = &list[idx]; - let its_expired = - existing.dtype == "temp" && existing.effective_status(now) == "expired"; - if !its_expired { - return Err(format!("子域名 {chosen} 已被占用")); - } - list.remove(idx); - } - - let entry = DomainEntry { - id: util::gen_id(), - subdomain: chosen, - backend, - dtype: dtype.clone(), - owner, - status: "approved".to_owned(), - created_at: now, - expires_at: if dtype == "temp" { now + TEMP_DOMAIN_TTL } else { 0 }, - reviewed_by: admin, - reviewed_at: now, - }; - list.push(entry.clone()); - Ok(entry) - }) -} - -/// 用户删除自己的域名。成功返回被删的子域名(供转发侧失效)。 -pub fn remove_own(id: &str, username: &str) -> Result { - let id = id.to_owned(); - let username = username.to_owned(); - - crate::store::update_domains(move |list| { - let idx = list.iter().position(|e| e.id == id).ok_or("记录不存在")?; - if list[idx].owner != username { - return Err("只能删除自己的域名".to_owned()); - } - let sub = list.remove(idx).subdomain; - Ok(sub) - }) - .map(|sub| { - state::remove(KEY_SUB_PREFIX, sub.as_bytes()); - sub - }) -} - -/// 管理员删除任意域名 -pub fn remove(id: &str) -> Result { - let id = id.to_owned(); - crate::store::update_domains(move |list| { - let idx = list.iter().position(|e| e.id == id).ok_or("记录不存在")?; - Ok(list.remove(idx).subdomain) - }) - .map(|sub| { - state::remove(KEY_SUB_PREFIX, sub.as_bytes()); - sub - }) -} - -/// 连带回收某账号名下的全部域名(删除账号时用)。返回回收条数。 -pub fn remove_by_owner(owner: &str) -> usize { - let mut removed = 0usize; - let result = crate::store::update_domains(|list| { - list.retain(|e| { - if e.owner == owner { - removed += 1; - false - } else { - true - } - }); - Ok(()) - }); - if result.is_ok() && removed > 0 { - // 被回收的可能包含正在转发的域名,必须全量重载 - reload_shm(); - } - removed -} - -/// 清理:已过期的临时域名 + 超过保留期的驳回记录。返回清理条数。 -pub fn purge() -> Result { - let now = util::now(); - let mut removed = 0usize; - - crate::store::update_domains(|list| { - list.retain(|e| { - let status = e.effective_status(now); - let stale_rejected = - status == "rejected" && (now - e.reviewed_at) > REJECTED_PURGE_TTL; - if status == "expired" || stale_rejected { - removed += 1; - false - } else { - true - } - }); - Ok(()) - })?; - - if removed > 0 { - reload_shm(); - } - Ok(removed) -} - -// =========================================================================== -// 对外投影 -// =========================================================================== - -pub fn view(entry: &DomainEntry) -> Value { - let now = util::now(); - let status = entry.effective_status(now); - let exp = entry.expires_at; - let live_temp = status == "approved" && entry.dtype == "temp" && exp > now; - - json!({ - "id": entry.id, - "subdomain": entry.subdomain, - "host": full_host(&entry.subdomain), - "backend": entry.backend, - "type": entry.dtype, - "owner": entry.owner, - "status": status, - "created_at": entry.created_at, - "created_at_text": util::fmt_time(entry.created_at), - "expires_at": exp, - "expires_at_text": if entry.dtype == "temp" && exp > 0 { util::fmt_time(exp) } else { "-".to_owned() }, - "expires_left": if live_temp { exp - now } else { 0 }, - "expires_left_text": if live_temp { util::fmt_left(exp - now) } else { String::new() }, - "reviewed_by": entry.reviewed_by, - "reviewed_at": entry.reviewed_at, - "auto_approved": entry.reviewed_by == "auto", - }) -} - -pub fn view_all(list: &[DomainEntry]) -> Vec { - list.iter().map(view).collect() -} diff --git a/source/rust/crates/plugin-domain/src/lib.rs b/source/rust/crates/plugin-domain/src/lib.rs deleted file mode 100644 index aab3cec..0000000 --- a/source/rust/crates/plugin-domain/src/lib.rs +++ /dev/null @@ -1,54 +0,0 @@ -//! plugin-domain —— 动态域名插件。 -//! -//! 职责:子域名 → 后端映射(`sub:` 键空间)、申请与审批、转发决策 -//! (access 阶段查共享内存)。数据文件 `data/domains.json`。 -//! -//! ## 与旧版最大的差异:写穿 -//! -//! 热路径**永不回源**(未命中即 404),所以每个写操作都必须 -//! **同时更新共享内存与文件**——这就是 `domains::sync_shm` 的存在理由。 -//! 漏掉一处,就会出现「审核通过了但立刻 404」。 -//! -//! ## 装配点(gateway) -//! -//! * `preconfig` —— 注册 `$proxy_backend_addr` 变量(`proxy_pass` 依赖) -//! * `postconfig` —— 注册 `ResolveHandler`(access 阶段) -//! * `zone_load` —— 全量装载 `sub:` 映射 -//! * `dispatch_api` —— 认领域名类管理/账号端点 - -pub mod api; -pub mod config; -pub mod domains; -pub mod models; -pub mod resolve; -pub mod store; - -use ngx::core::Status; -use ngx::ffi::{ngx_conf_t, ngx_http_request_t}; - -use ipass_core::plugin::Plugin; - -pub struct DomainPlugin; - -impl Plugin for DomainPlugin { - fn name(&self) -> &'static str { - "domain" - } - - fn preconfig(&self, cf: *mut ngx_conf_t) -> bool { - resolve::preconfig(cf) - } - - fn postconfig(&self, cf: *mut ngx_conf_t) -> bool { - // SAFETY: cf 由 nginx 传入且有效 - ngx::http::add_phase_handler::(unsafe { &mut *cf }).is_ok() - } - - fn dispatch_api(&self, r: *mut ngx_http_request_t) -> Option { - api::dispatch(r) - } - - fn zone_load(&self) -> usize { - domains::reload_shm() - } -} diff --git a/source/rust/crates/plugin-domain/src/models.rs b/source/rust/crates/plugin-domain/src/models.rs deleted file mode 100644 index 3d1d8d6..0000000 --- a/source/rust/crates/plugin-domain/src/models.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! 域名持久化模型(`domains.json`:一条记录 = 一个子域名)。 - -use serde::{Deserialize, Serialize}; - -/// 单条域名记录。 -/// -/// 字段名与旧版 `data/domains.json` **逐字对应**,以便新版直接接管旧数据文件。 -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct DomainEntry { - pub id: String, - pub subdomain: String, - /// `host:port` - pub backend: String, - /// `temp`(临时,到时自动停止转发) | `long`(长期) - #[serde(rename = "type")] - pub dtype: String, - /// 归属账号 - pub owner: String, - /// `pending` | `approved` | `rejected` - pub status: String, - #[serde(default)] - pub created_at: i64, - /// 仅 temp 有意义;long 恒为 0 - #[serde(default)] - pub expires_at: i64, - /// `auto` 表示凭临时授权权限免审放行 - #[serde(default)] - pub reviewed_by: String, - #[serde(default)] - pub reviewed_at: i64, -} - -impl DomainEntry { - /// 实际状态:approved 的临时域名过期后视为 `expired`。 - /// - /// 这是「到期不等于删除」语义的落点——记录保留,只是不再转发。 - pub fn effective_status(&self, now: i64) -> &'static str { - if self.status == "approved" && self.dtype == "temp" { - if self.expires_at > 0 && self.expires_at <= now { - return "expired"; - } - } - match self.status.as_str() { - "approved" => "approved", - "rejected" => "rejected", - _ => "pending", - } - } - - /// 转发侧判定:返回该域名当前是否可转发(已放行且未过期) - pub fn is_forwardable(&self, now: i64) -> bool { - if self.status != "approved" { - return false; - } - if self.dtype == "temp" { - // 临时域名必须有明确的、尚未到达的到期时刻 - return self.expires_at > now; - } - true - } -} diff --git a/source/rust/crates/plugin-domain/src/resolve.rs b/source/rust/crates/plugin-domain/src/resolve.rs deleted file mode 100644 index c4605c5..0000000 --- a/source/rust/crates/plugin-domain/src/resolve.rs +++ /dev/null @@ -1,188 +0,0 @@ -//! 转发热路径:查共享内存取后端地址,供 nginx 的 `proxy_pass` 使用。 -//! -//! **热路径唯一入口**——只读内存,未命中不产生任何 I/O。 -//! 旧版这里在 miss 时会去读 `domains.json` 并全量 JSON 解码, -//! 那正是「随便发一堆随机子域名就能打穿磁盘」的入口。 - -use core::ptr; -use core::sync::atomic::{AtomicUsize, Ordering}; - -use ngx::core::{Pool, Status}; -use ngx::ffi::{ - NGX_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, ngx_conf_t, ngx_http_add_variable, - ngx_http_get_variable_index, ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t, - ngx_uint_t, -}; -use ngx::http::{HTTPStatus, HttpPhase, HttpRequestHandler}; -use ngx::ngx_string; - -use crate::config; -use ipass_core::loc::{self, Switch}; -use ipass_core::state; -use ipass_core::util; - -/// `$proxy_backend_addr` 在 `r->variables` 里的下标 -static BACKEND_VAR_INDEX: AtomicUsize = AtomicUsize::new(usize::MAX); - -/// 查共享内存取后端地址;已过期的条目视为不存在。 -fn resolve_backend(subdomain: &[u8]) -> Option { - let (backend, expires_at) = state::get(config::KEY_SUB_PREFIX, subdomain)?; - if expires_at > 0 && expires_at <= util::now() { - return None; - } - Some(backend) -} - -/// 取 Host 头里第一个点之前的部分作为子域名。 -/// -/// 刻意不走 nginx 的 server_name 正则捕获变量(那需要再算一次变量 hash), -/// 热路径上手工切更省。 -pub fn subdomain_of(r: *mut ngx_http_request_t) -> Option> { - // SAFETY: r 有效;迭代器只在本函数存续期内使用 - let request = unsafe { ngx::http::Request::from_ngx_http_request(r) }; - for (key, value) in request.headers_in_iterator() { - if key.as_bytes().eq_ignore_ascii_case(b"host") { - let host = value.as_bytes(); - // 去掉端口 - let host = match host.iter().position(|&b| b == b':') { - Some(i) => &host[..i], - None => host, - }; - // 取第一段标签 - let label = match host.iter().position(|&b| b == b'.') { - Some(i) => &host[..i], - None => host, - }; - if label.is_empty() { - return None; - } - return Some(label.to_ascii_lowercase()); - } - } - None -} - -/// 把后端地址写进 `r->variables[$proxy_backend_addr]`,供 `proxy_pass` 使用 -fn set_backend_var(r: *mut ngx_http_request_t, backend: &str) { - let idx = BACKEND_VAR_INDEX.load(Ordering::SeqCst); - if idx == usize::MAX { - return; - } - // SAFETY: idx 由 ngx_http_get_variable_index 分配且落在 r->variables 内; - // 值分配在请求池里,随请求回收 - unsafe { - let pool = Pool::from_ngx_pool((*r).pool); - let bytes = backend.as_bytes(); - let data = pool.alloc(bytes.len()) as *mut u8; - if data.is_null() { - return; - } - ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len()); - - let vv: *mut ngx_http_variable_value_t = (*r).variables.add(idx); - (*vv).data = data; - (*vv).set_len(bytes.len() as _); - (*vv).set_valid(1); - (*vv).set_not_found(0); - (*vv).set_no_cacheable(1); - } -} - -/// 变量 get_handler:`proxy_pass` 求值 `$proxy_backend_addr` 时被调用。 -/// -/// 与 access 阶段互补——这里保证「即使 access 未赋值也能取到」, -/// access 阶段则负责决定命中不了时返回 404。 -extern "C" fn backend_get( - r: *mut ngx_http_request_t, - v: *mut ngx_http_variable_value_t, - _data: usize, -) -> ngx_int_t { - // SAFETY: nginx 传入的 r/v 必然有效 - unsafe { - let resolved = subdomain_of(r).as_deref().and_then(resolve_backend); - - let Some(backend) = resolved else { - (*v).set_not_found(1); - return Status::NGX_ERROR.into(); - }; - - let pool = Pool::from_ngx_pool((*r).pool); - let bytes = backend.as_bytes(); - let data = pool.alloc(bytes.len()) as *mut u8; - if data.is_null() { - (*v).set_not_found(1); - return Status::NGX_ERROR.into(); - } - ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len()); - - (*v).data = data; - (*v).set_len(bytes.len() as _); - (*v).set_valid(1); - (*v).set_no_cacheable(1); - (*v).set_not_found(0); - - Status::NGX_OK.into() - } -} - -/// 配置解析前注册 `$proxy_backend_addr`。 -/// -/// 必须在 preconfiguration 阶段调用,否则配置里的 -/// `proxy_pass http://$proxy_backend_addr` 无法解析。 -pub fn preconfig(cf: *mut ngx_conf_t) -> bool { - let mut name = ngx_string!("proxy_backend_addr"); - - let idx = unsafe { ngx_http_get_variable_index(cf, &raw mut name) }; - if idx == -1 { - return false; - } - BACKEND_VAR_INDEX.store(idx as usize, Ordering::SeqCst); - - let var = unsafe { - ngx_http_add_variable( - cf, - &raw mut name, - (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, - ) - }; - if var.is_null() { - return false; - } - - // SAFETY: var 非空且由本函数独占初始化 - unsafe { - (*var).get_handler = Some(backend_get); - (*var).set_handler = None; - (*var).data = 0; - } - true -} - -/// 转发热路径:命中则放行(`proxy_pass` 会去取 `$proxy_backend_addr`),未命中直接 404。 -pub struct ResolveHandler; - -impl HttpRequestHandler for ResolveHandler { - const PHASE: HttpPhase = HttpPhase::Access; - type Output = Status; - - fn handler(request: &mut ngx::http::Request) -> Self::Output { - // 未开启该开关的 location 一律放行(管理台/API 走这里) - let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t; - if !loc::enabled(r, Switch::Proxy) { - return Status::NGX_DECLINED; - } - - let Some(host) = subdomain_of(r) else { - return HTTPStatus::NOT_FOUND.into(); - }; - - match resolve_backend(&host) { - Some(backend) => { - set_backend_var(r, &backend); - Status::NGX_DECLINED - } - // 与旧版语义一致:查不到 = 未配置 / 已过期 / 已删除 / 尚未审核通过 - None => HTTPStatus::NOT_FOUND.into(), - } - } -} diff --git a/source/rust/crates/plugin-domain/src/store.rs b/source/rust/crates/plugin-domain/src/store.rs deleted file mode 100644 index 52a93a6..0000000 --- a/source/rust/crates/plugin-domain/src/store.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! 域名表的文件读写(复用内核 store 的原子写 + 全局文件写锁)。 - -use std::path::PathBuf; - -use ipass_core::{state, store}; - -use crate::models::DomainEntry; - -fn domains_path() -> PathBuf { - store::path_in_data("domains.json") -} - -pub fn read_domains() -> Vec { - store::read_json(&domains_path(), Vec::new()) -} - -pub fn write_domains(data: &[DomainEntry]) -> Result<(), String> { - store::write_json(&domains_path(), &data.to_vec()) -} - -/// 加锁「读-改-写」域名表。 -/// -/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。 -pub fn update_domains(f: F) -> Result -where - F: FnOnce(&mut Vec) -> Result, -{ - let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; - let mut data = read_domains(); - let out = f(&mut data)?; - write_domains(&data)?; - Ok(out) -} diff --git a/source/rust/crates/plugin-sso/src/cas.rs b/source/rust/crates/plugin-sso/src/cas.rs index cd34305..ed22b06 100644 --- a/source/rust/crates/plugin-sso/src/cas.rs +++ b/source/rust/crates/plugin-sso/src/cas.rs @@ -17,7 +17,7 @@ use ngx::ffi::ngx_http_request_t; -use ipass_core::http; +use crate::compat as http; use ipass_core::session; use ipass_core::state; use ipass_core::util; diff --git a/source/rust/crates/plugin-sso/src/compat.rs b/source/rust/crates/plugin-sso/src/compat.rs new file mode 100644 index 0000000..fdfdb52 --- /dev/null +++ b/source/rust/crates/plugin-sso/src/compat.rs @@ -0,0 +1,84 @@ +//! 兼容层:主线内核 `ipass/ipass` 的 `ipass-core` 已移除四个 http 辅助函数 +//! (`body_object` / `json_body` / `send_ct` / `redirect`)。为避免改动子模块, +//! 这里用新内核暴露的底层 API 重新实现,并整体再导出 `ipass_core::http`, +//! 使 `use crate::compat as http;` 能无缝替代 `use ipass_core::http;`。 + +pub use ipass_core::http::*; + +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; + +use ipass_core::util; + +/// 读取并解析请求体为 JSON(`Content-Type: application/json` 时)。 +/// +/// 非 JSON 体或解析失败返回 `None`——调用方据此回退到 `params` 或报错。 +pub fn json_body(r: *mut ngx_http_request_t) -> Option { + let body = unsafe { ipass_core::http::collect_body(r) }; + if body.is_empty() { + return None; + } + serde_json::from_slice::(&body).ok() +} + +/// 合并 query 与 JSON 请求体为单一 `Value::Object`: +/// JSON 体的嵌套结构原样保留,query 的标量覆盖同名顶层键。 +pub fn body_object(r: *mut ngx_http_request_t) -> Value { + let mut obj = serde_json::Map::new(); + for (k, v) in util::parse_kv(&ipass_core::http::args_raw(r)) { + obj.insert(k, Value::String(v)); + } + if let Some(Value::Object(b)) = json_body(r) { + for (k, v) in b { + obj.insert(k, v); + } + } + Value::Object(obj) +} + +/// 发送带自定义 Content-Type 的响应体(CAS 的 `text/plain` / `application/xml` +/// 等不走 JSON 信封的场景用)。 +pub fn send_ct( + r: *mut ngx_http_request_t, + status: HTTPStatus, + body: &str, + content_type: &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", content_type); + request.add_header_out("Cache-Control", "no-store"); + request.set_content_length_n(body.len()); + + let st = request.send_header(); + if st != Status::NGX_OK { + return st; + } + request.output_filter(&mut chain) + } +} + +/// 302 重定向(CAS `/cas/login` 签发 ST 后跳回 service)。 +/// +/// **注意**:body 必须非空——`pool.create_buffer_from_str("")` 在 nginx 内存池里 +/// 分配 0 长度 buffer 会返回 `None`,使 `send_with` 返回 `NGX_ERROR`,导致 302 +/// 根本不发出(curl 拿不到 `Location`)。所以这里给一个单空格占位 body。 +pub fn redirect(r: *mut ngx_http_request_t, location: &str) -> Status { + send_with(r, HTTPStatus::MOVED_TEMPORARILY, " ", &[("Location", location)]) +} diff --git a/source/rust/crates/plugin-sso/src/lib.rs b/source/rust/crates/plugin-sso/src/lib.rs index e8b9ad5..5a0d4a7 100644 --- a/source/rust/crates/plugin-sso/src/lib.rs +++ b/source/rust/crates/plugin-sso/src/lib.rs @@ -28,6 +28,7 @@ mod oauth_state; mod rsa; mod storex; mod utilx; +mod compat; use core::ptr; use core::sync::atomic::{AtomicUsize, Ordering}; @@ -54,10 +55,10 @@ static AUTH_VAR_INDEX: [AtomicUsize; 5] = [ ]; static AUTH_VAR_NAMES: [&str; 5] = ["auth_user", "auth_email", "auth_groups", "auth_sub", "auth_token"]; -/// 身份插件。 +/// 身份插件(SSO)。 /// -/// 与 `plugin-domain` 平级——去掉它,网关仍然能转域名、 -/// 仍然能代理 LLM,只是请求不再带身份。 +/// 本仓库只持有这一个身份插件;域名 / LLM / API 代理等通用子系统 +/// 由主项目 ipass/ipass 提供(见仓库根 `deps/ipass` 子模块),本网关不再内置。 pub struct SsoPlugin; impl Plugin for SsoPlugin { diff --git a/source/rust/crates/plugin-sso/src/portal.rs b/source/rust/crates/plugin-sso/src/portal.rs index c240e1b..75af73d 100644 --- a/source/rust/crates/plugin-sso/src/portal.rs +++ b/source/rust/crates/plugin-sso/src/portal.rs @@ -16,7 +16,7 @@ use ngx::core::Status; use ngx::ffi::ngx_http_request_t; use ngx::http::HTTPStatus; -use ipass_core::http; +use crate::compat as http; use ipass_core::users; use crate::accounts::UserExt; diff --git a/source/rust/crates/plugin-sso/src/reset.rs b/source/rust/crates/plugin-sso/src/reset.rs index c57dff9..5381d35 100644 --- a/source/rust/crates/plugin-sso/src/reset.rs +++ b/source/rust/crates/plugin-sso/src/reset.rs @@ -14,7 +14,7 @@ use ngx::ffi::ngx_http_request_t; -use ipass_core::http; +use crate::compat as http; use ipass_core::state; use ipass_core::users; use ipass_core::util; diff --git a/source/rust/crates/plugin-sso/src/scim.rs b/source/rust/crates/plugin-sso/src/scim.rs index 5b84ecb..e7099a0 100644 --- a/source/rust/crates/plugin-sso/src/scim.rs +++ b/source/rust/crates/plugin-sso/src/scim.rs @@ -13,7 +13,7 @@ use serde_json::{Value, json}; -use ipass_core::http; +use crate::compat as http; use ipass_core::models::User; use ipass_core::util; use ngx::core::Status; diff --git a/source/rust/gateway/Cargo.toml b/source/rust/gateway/Cargo.toml index c29f91a..c9afdaa 100644 --- a/source/rust/gateway/Cargo.toml +++ b/source/rust/gateway/Cargo.toml @@ -20,4 +20,3 @@ ngx.workspace = true nginx-sys.workspace = true ipass-core.workspace = true plugin-sso.workspace = true -plugin-domain.workspace = true diff --git a/source/rust/gateway/src/lib.rs b/source/rust/gateway/src/lib.rs index c7bc35e..859aeca 100644 --- a/source/rust/gateway/src/lib.rs +++ b/source/rust/gateway/src/lib.rs @@ -5,9 +5,10 @@ //! ```text //! load_module modules/libsso_gateway.so; //! │ -//! ┌───────────────┼────────────────┐ -//! ipass-core(内核) plugin-sso plugin-domain -//! 状态/账号/Key/身份 身份插件(优先认领) 域名插件 +//! ┌───────────────┼──────────┐ +//! ipass-core(内核) plugin-sso +//! 状态/账号/Key/身份 身份插件(优先认领) +//! (来自 deps/ipass 子模块) //! ``` //! //! ## 为什么不拆成多个 .so @@ -42,7 +43,6 @@ use ngx::http::{ MergeConfigError, }; use ngx::{ngx_conf_log_error, ngx_string}; -use plugin_domain::DomainPlugin; use plugin_sso::SsoPlugin; /// 插件清单。**顺序即装配顺序**:preconfig → postconfig → dispatch_api, @@ -52,7 +52,7 @@ use plugin_sso::SsoPlugin; /// users CRUD/me)由 sso 优先接管——它带 CAPTCHA、账号锁定、审计与身份字段 /// (上游 A6-2 决策所述「sso 自实现 login 端点替换 CorePlugin 对应路由」的落点); /// CorePlugin 只补 sso 没有的端点(users/grant|models|limits 三个 LLM 端点)。 -static PLUGINS: &[&dyn Plugin] = &[&SsoPlugin, &ipass_core::api::CorePlugin, &DomainPlugin]; +static PLUGINS: &[&dyn Plugin] = &[&SsoPlugin, &ipass_core::api::CorePlugin]; /// 装配根的插件扩展:身份端点所需的插件侧数据经它回填内核 /// (内核不认识任何插件,见 `ipass_core::api::CoreExt`)。 @@ -60,9 +60,9 @@ static PLUGINS: &[&dyn Plugin] = &[&SsoPlugin, &ipass_core::api::CorePlugin, &Do struct GatewayExt; impl ipass_core::api::CoreExt for GatewayExt { - /// 删除账号:连带回收该账号名下的域名,避免出现无主映射 - fn reclaim_on_delete(&self, username: &str) -> usize { - plugin_domain::domains::remove_by_owner(username) + /// 删除账号:sso 只持有身份数据,无域名等附属资源需连带回收 + fn reclaim_on_delete(&self, _username: &str) -> usize { + 0 } } @@ -142,10 +142,6 @@ struct ModuleConfig { /// 该 location 开启身份感知代理(IAP):未登录 → 跳转登录 / 401, /// 已登录 → 注入 `$auth_*` 变量由 `proxy_set_header` 转成 `X-Auth-*` 头。 iap: bool, - /// 该 location 提供企业域名(子域名 → 后端)代理转发: - /// access 阶段解析 Host 并写入 `$proxy_backend_addr`,由 - /// `proxy_pass http://$proxy_backend_addr;` 转发。 - domain: bool, } unsafe impl HttpModuleLocationConf for Module { @@ -160,9 +156,6 @@ impl Merge for ModuleConfig { if prev.iap { self.iap = true; } - if prev.domain { - self.domain = true; - } Ok(()) } } @@ -175,9 +168,8 @@ fn loc_switch(request: &mut ngx::http::Request, s: ipass_core::loc::Switch) -> b match s { ipass_core::loc::Switch::Api => c.api, ipass_core::loc::Switch::Iap => c.iap, - // 上游域名插件查 Proxy、开关指令也是 ipass_proxy;二者同指本模块的 - // domain 开关(子域名 → 后端转发) - ipass_core::loc::Switch::Proxy | ipass_core::loc::Switch::Domain => c.domain, + // 域名插件(proxy/domain)已迁出到 ipass/ipass,本网关不再提供 → 关闭 + ipass_core::loc::Switch::Proxy | ipass_core::loc::Switch::Domain => false, // LLM / API 代理插件明确不迁入(流量层与身份层分界):保守返回 false ipass_core::loc::Switch::Llm | ipass_core::loc::Switch::Apix => false, } @@ -230,7 +222,7 @@ impl HttpModule for Module { // ⚠️ 配置指令集中在这里声明:nginx 的 `ngx_module_t.commands` 是一个 // null-terminated 连续数组,不同 crate 的 static 数组无法自动拼接, // 只能由装配层统一列出。插件通过 `loc::Switch` 查询开关,不直接持有指令。 -static mut NGX_HTTP_SSO_COMMANDS: [ngx_command_t; 6] = [ +static mut NGX_HTTP_SSO_COMMANDS: [ngx_command_t; 5] = [ ngx_command_t { name: ngx_string!("ipass_state"), type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, @@ -263,14 +255,6 @@ static mut NGX_HTTP_SSO_COMMANDS: [ngx_command_t; 6] = [ offset: 0, post: ptr::null_mut(), }, - ngx_command_t { - name: ngx_string!("ipass_proxy"), - type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(set_flag_domain), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, ngx_command_t::empty(), ]; @@ -351,18 +335,6 @@ extern "C" fn set_flag_iap( NGX_CONF_OK } -extern "C" fn set_flag_domain( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - let Some(flag) = (unsafe { arg_flag(cf, 1) }) else { - return NGX_CONF_ERROR; - }; - // SAFETY: 同上 - unsafe { (*(conf as *mut ModuleConfig)).domain = flag }; - NGX_CONF_OK -} extern "C" fn set_state_zone( cf: *mut ngx_conf_t, diff --git a/source/rust/vendor/ngx-rust/.cargo/audit.toml b/source/rust/vendor/ngx-rust/.cargo/audit.toml deleted file mode 100644 index e796859..0000000 --- a/source/rust/vendor/ngx-rust/.cargo/audit.toml +++ /dev/null @@ -1,35 +0,0 @@ -# audit config file -# -# It may be located in the user home (`~/.cargo/audit.toml`) or in the project -# root (`.cargo/audit.toml`). -# -# All of the options which can be passed via CLI arguments can also be -# permanently specified in this file. -# It may be located in the user home (`~/.cargo/audit.toml`) or in the project -# root (`.cargo/audit.toml`). - -[advisories] -ignore = ["RUSTSEC-2020-0071"] - -# # Advisory Database Configuration -# [database] -# path = "~/.cargo/advisory-db" # Path where advisory git repo will be cloned -# url = "https://github.com/RustSec/advisory-db.git" # URL to git repo -# fetch = true # Perform a `git fetch` before auditing (default: true) -# stale = false # Allow stale advisory DB (i.e. no commits for 90 days, default: false) - -# # Output Configuration -# [output] -# deny = ["unmaintained"] # exit on error if unmaintained dependencies are found -# format = "terminal" # "terminal" (human readable report) or "json" -# quiet = false # Only print information on error -# show_tree = true # Show inverse dependency trees along with advisories (default: true) - -# # Target Configuration -# [target] -# arch = "x86_64" # Ignore advisories for CPU architectures other than this one -# os = "linux" # Ignore advisories for operating systems other than this one - -# [yanked] -# enabled = true # Warn for yanked crates in Cargo.lock (default: true) -# update_index = true # Auto-update the crates.io index (default: true) diff --git a/source/rust/vendor/ngx-rust/.cargo/config.toml b/source/rust/vendor/ngx-rust/.cargo/config.toml deleted file mode 100644 index 910c3da..0000000 --- a/source/rust/vendor/ngx-rust/.cargo/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[env] -CACHE_DIR = { value = ".cache", relative = true } diff --git a/source/rust/vendor/ngx-rust/.dockerignore b/source/rust/vendor/ngx-rust/.dockerignore deleted file mode 100644 index d1c460e..0000000 --- a/source/rust/vendor/ngx-rust/.dockerignore +++ /dev/null @@ -1,23 +0,0 @@ -**/.idea -.cargo -.dockerignore -.git -.github -CHANGELOG.md -CODE_OF_CONDUCT.md -CONTRIBUTING.md -Containerfile.debian -Dockerfile -GNUmakefile -LICENSE.txt -README.md -SECURITY.md -build - -.vscode/** - -**/target -target - -.cache/ -.nginx/ diff --git a/source/rust/vendor/ngx-rust/.git-blame-ignore-revs b/source/rust/vendor/ngx-rust/.git-blame-ignore-revs deleted file mode 100644 index 15ce9d0..0000000 --- a/source/rust/vendor/ngx-rust/.git-blame-ignore-revs +++ /dev/null @@ -1,17 +0,0 @@ -# This file specifies the revisions hidden from the blame view in GitHub UI. -# -# You can achieve the same effect locally with "--ignore-revs-file": -# -# git blame --ignore-revs-file .git-blame-ignore-revs -# -# or "blame.ignoreRevsFile" configuration option -# -# git config --local blame.ignoreRevsFile .git-blame-ignore-revs -# -# See also: -# https://docs.github.com/en/repositories/working-with-files/using-files/viewing-and-understanding-files - -# Tree-wide formatting change: max-width 120 -> 100 -d866b64a3c83105c20b0c005392f8e8fcaaf2066 -# Tree-wide formatting change: use_small_heuristics -> "Max" -4b30e402b0393dd4b888980d57ce6792adbb9455 diff --git a/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/bug_report.md b/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index a85753e..0000000 --- a/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. See my project that depends on this project -2. View logs on '....' -3. Run this test I created -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Your environment** -* Version of the repo - a specific commit or tag -* Version of ngx-rust -* Version of Rust -* Version of NGINX (and all dependencies if modified) -* OS and distribution -* Details about containerization, virtualization, or physical environment - -**Additional context** -Add any other context about the problem here. Any log files you want to share. diff --git a/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/feature_request.md b/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 6bcce42..0000000 --- a/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/.github/PULL_REQUEST_TEMPLATE.md b/source/rust/vendor/ngx-rust/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 0037d3d..0000000 --- a/source/rust/vendor/ngx-rust/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,15 +0,0 @@ -### Proposed changes -Describe the use case and detail of the change. If this PR addresses an issue -on GitHub, make sure to include a link to that issue here in this description -(not in the title of the PR). - -### Checklist -Before creating a PR, run through this checklist and mark each as complete. - -- [ ] I have written my commit messages in the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format. -- [ ] I have read the [CONTRIBUTING](/CONTRIBUTING.md) doc -- [ ] I have added tests (when possible) that prove my fix is effective or that my feature works -- [ ] I have checked that all unit tests pass after adding my changes -- [ ] I have updated necessary documentation -- [ ] I have rebased my branch onto main -- [ ] I will ensure my PR is targeting the main branch and pulling from my branch from my own fork diff --git a/source/rust/vendor/ngx-rust/.github/dependabot.yml b/source/rust/vendor/ngx-rust/.github/dependabot.yml deleted file mode 100644 index 0b574cc..0000000 --- a/source/rust/vendor/ngx-rust/.github/dependabot.yml +++ /dev/null @@ -1,26 +0,0 @@ -# To get started with Dependabot version updates, you'll need to specify which -# package ecosystems to update and where the package manifests are located. -# Please see the documentation for all configuration options: -# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates - -version: 2 -updates: - - - package-ecosystem: "cargo" - allow: - # Allow both direct and indirect updates for all packages. - - dependency-type: "all" - directory: "/" # Location of package manifests - schedule: - interval: "weekly" - groups: - all-dependencies: - patterns: - - "*" - # semver-incompatible updates will be handled manually - versioning-strategy: "lockfile-only" - - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" diff --git a/source/rust/vendor/ngx-rust/.github/workflows/cargo-deny.yaml b/source/rust/vendor/ngx-rust/.github/workflows/cargo-deny.yaml deleted file mode 100644 index 1e44ade..0000000 --- a/source/rust/vendor/ngx-rust/.github/workflows/cargo-deny.yaml +++ /dev/null @@ -1,25 +0,0 @@ -name: cargo-deny -on: - push: - branches: - - main - - "[0-9]+.[0-9]+.x" - pull_request: - -jobs: - check: - runs-on: ubuntu-latest - strategy: - matrix: - checks: - - advisories - - bans licenses sources - - # Prevent sudden announcement of a new advisory from failing ci: - continue-on-error: ${{ matrix.checks == 'advisories' }} - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 - with: - command: check ${{ matrix.checks }} diff --git a/source/rust/vendor/ngx-rust/.github/workflows/ci.yaml b/source/rust/vendor/ngx-rust/.github/workflows/ci.yaml deleted file mode 100644 index d02c3c5..0000000 --- a/source/rust/vendor/ngx-rust/.github/workflows/ci.yaml +++ /dev/null @@ -1,194 +0,0 @@ -name: Rust - -on: [ push, pull_request ] - -env: - CARGO_TERM_COLOR: 'always' - CARGO_TERM_VERBOSE: 'true' - RUSTFLAGS: '--deny warnings' - RUSTDOCFLAGS: '-Dwarnings' - -jobs: - rust-version: - name: Minimal supported Rust version - outputs: - version: ${{ steps.read_version.outputs.msrv }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - id: read_version - run: | - awk -F '=' \ - '/^rust-version[[:space:]]*=/ { gsub(/([" ]|#.*)/,"",$2); print ("msrv=" $2) }' \ - Cargo.toml \ - | tee -a "$GITHUB_OUTPUT" - - test-linux: - name: Test (Linux) - needs: rust-version - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - rust-version: - - ${{ needs.rust-version.outputs.version }} - - stable - steps: - - name: checkout source - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - submodules: true - - name: set up cargo cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - continue-on-error: false - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ matrix.rust-version}}-${{ hashFiles('**/Cargo.lock') }} - restore-keys: ${{ runner.os }}-cargo-${{ matrix.rust-version }}- - - name: set up nginx deps cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - continue-on-error: false - with: - path: | - .cache/.gnupg - .cache/nginx - .cache/*.tar.gz - .cache/*.tar.asc - .cache/*.tar.sig - key: ${{ runner.os }}-deps-${{ hashFiles('**/nginx-sys/build.rs') }} - restore-keys: ${{ runner.os }}-deps- - - - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 - with: - components: rustfmt, clippy - toolchain: ${{ matrix.rust-version }} - - - name: build (all targets, all features) - id: build - run: cargo build --workspace --all-targets --all-features - - - name: check ngx, no default features (no_std) - run: cargo check -p ngx --no-default-features --features vendored - - - name: check ngx, alloc - run: cargo check -p ngx --no-default-features --features vendored,alloc - - - name: check ngx, std - run: cargo check -p ngx --no-default-features --features vendored,std - - - name: check ngx, alloc + serde - run: cargo check -p ngx --no-default-features --features vendored,alloc,serde - - - name: clippy - # always run if build succeeds - if: ${{ !cancelled() && steps.build.outcome == 'success' }} - run: cargo clippy --workspace --all-targets --all-features -- -Dwarnings - - - name: test - # always run if build succeeds - if: ${{ !cancelled() && steps.build.outcome == 'success' }} - run: cargo test --workspace --all-features - - - name: rustdoc - # always run if build succeeds - if: ${{ !cancelled() && steps.build.outcome == 'success' }} - run: cargo doc --all-features --no-deps - - examples-linux: - name: Examples (Linux) - runs-on: ubuntu-latest - steps: - - name: checkout source - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - submodules: true - - name: set up cargo cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - continue-on-error: false - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - restore-keys: ${{ runner.os }}-cargo- - - name: set up nginx deps cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - continue-on-error: false - with: - path: | - .cache/.gnupg - .cache/nginx - .cache/*.tar.gz - .cache/*.tar.asc - .cache/*.tar.sig - key: ${{ runner.os }}-deps-${{ hashFiles('**/nginx-sys/build.rs') }} - restore-keys: ${{ runner.os }}-deps- - - name: compile examples - run: cargo build --release --package examples --examples --all-features - - test-macos: - name: Test (MacOS) - runs-on: macos-latest - steps: - - name: install command line dependencies - run: brew install make gnupg - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - submodules: true - - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 - with: - toolchain: stable - - name: set up cargo cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - continue-on-error: false - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - target/ - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - restore-keys: ${{ runner.os }}-cargo- - - name: set up nginx deps cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - continue-on-error: false - with: - path: | - .cache/*.tar.gz - .cache/*.tar.asc - .cache/*.tar.sig - key: ${{ runner.os }}-deps-${{ hashFiles('**/nginx-sys/build.rs') }} - restore-keys: ${{ runner.os }}-deps- - - name: current directory - run: pwd - - name: make cache directory - run: mkdir -p .cache/.gnupg - - name: disable ipv6 for gpg - run: echo "disable-ipv6" > .cache/.gnupg/dirmngr.conf - - name: build - run: cargo build --workspace --all-targets --features "async,vendored" - - name: run tests - run: cargo test --workspace --features "async,vendored" - - fmt: - name: Rustfmt - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 - with: - components: rustfmt - toolchain: stable - - name: rustfmt version - run: rustfmt --version - - name: cargo fmt - run: cargo fmt --all --check diff --git a/source/rust/vendor/ngx-rust/.github/workflows/nginx.yaml b/source/rust/vendor/ngx-rust/.github/workflows/nginx.yaml deleted file mode 100644 index 2f88fbc..0000000 --- a/source/rust/vendor/ngx-rust/.github/workflows/nginx.yaml +++ /dev/null @@ -1,238 +0,0 @@ -name: NGINX - -on: - push: - branches: - - main - - "[0-9]+.[0-9]+.x" - pull_request: - -env: - CARGO_TERM_COLOR: 'always' - RUST_BACKTRACE: '1' - NGX_CONFIGURE_CMD: >- - auto/configure - --with-compat - --with-debug - --with-http_realip_module - --with-http_ssl_module - --with-http_v2_module - --with-stream - --with-stream_realip_module - --with-stream_ssl_module - - NGX_CONFIGURE_UNIX: >- - --with-threads - - NGX_CONFIGURE_WINDOWS: >- - --with-cc=cl - --prefix= - --conf-path=conf/nginx.conf - --pid-path=logs/nginx.pid - --http-log-path=logs/access.log - --error-log-path=logs/error.log - --sbin-path=nginx.exe - --http-client-body-temp-path=temp/client_body_temp - --http-proxy-temp-path=temp/proxy_temp - --http-fastcgi-temp-path=temp/fastcgi_temp - --http-scgi-temp-path=temp/scgi_temp - --http-uwsgi-temp-path=temp/uwsgi_temp - --with-cc-opt=-DFD_SETSIZE=1024 - --with-pcre=objs/lib/pcre - --with-zlib=objs/lib/zlib - --with-openssl=objs/lib/openssl - --with-openssl-opt="no-asm no-module no-tests no-makedepend -D_WIN32_WINNT=0x0601" - - NGX_CONFIGURE_DYNAMIC_MODULES: >- - --add-dynamic-module=${{ github.workspace }}/examples - NGX_CONFIGURE_STATIC_MODULES: >- - --add-module=${{ github.workspace }}/examples - - NGX_TEST_FILES: examples/t - NGX_TEST_GLOBALS_DYNAMIC: >- - load_module ${{ github.workspace }}/nginx/objs/ngx_http_async_module.so; - load_module ${{ github.workspace }}/nginx/objs/ngx_http_awssigv4_module.so; - load_module ${{ github.workspace }}/nginx/objs/ngx_http_curl_module.so; - load_module ${{ github.workspace }}/nginx/objs/ngx_http_shared_dict_module.so; - load_module ${{ github.workspace }}/nginx/objs/ngx_http_upstream_custom_module.so; - - OPENSSL_VERSION: '3.0.16' - PCRE2_VERSION: '10.45' - ZLIB_VERSION: '1.3.1' - -jobs: - linux: - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - nginx-ref: - - master - - stable-1.30 - module: - - static - - dynamic - include: - # minimal supported nginx version (Debian bookworm: 1.22.1) - - nginx-ref: stable-1.22 - module: dynamic - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ matrix.nginx-ref }} - repository: 'nginx/nginx' - path: 'nginx' - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: 'nginx/nginx-tests' - path: 'nginx/tests' - sparse-checkout: | - lib - - - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 - with: - toolchain: stable - - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - nginx/objs/**/CACHEDIR.TAG - nginx/objs/**/ngx-debug - nginx/objs/**/ngx-release - key: ${{ runner.os }}-nginx-${{ hashFiles('**/Cargo.lock') }} - restore-keys: ${{ runner.os }}-nginx- - - - name: Update configure arguments - if: matrix.nginx-ref != 'stable-1.22' - run: | - echo NGX_CONFIGURE_UNIX="${NGX_CONFIGURE_UNIX} --with-http_v3_module" \ - >> "$GITHUB_ENV" - - - name: Configure nginx with static modules - if: matrix.module == 'static' - working-directory: nginx - run: | - ${NGX_CONFIGURE_CMD} \ - ${NGX_CONFIGURE_UNIX} \ - ${NGX_CONFIGURE_STATIC_MODULES} - - - name: Configure nginx with dynamic modules - if: matrix.module != 'static' - working-directory: nginx - run: | - ${NGX_CONFIGURE_CMD} \ - ${NGX_CONFIGURE_UNIX} \ - ${NGX_CONFIGURE_DYNAMIC_MODULES} - echo TEST_NGINX_GLOBALS="$NGX_TEST_GLOBALS_DYNAMIC" >> "$GITHUB_ENV" - - - name: Build nginx - working-directory: nginx - run: make -j$(nproc) - - - name: Run tests - env: - PERL5LIB: ${{ github.workspace }}/nginx/tests/lib - TEST_NGINX_BINARY: ${{ github.workspace }}/nginx/objs/nginx - TEST_NGINX_MODULES: ${{ github.workspace }}/nginx/objs - TEST_NGINX_VERBOSE: 1 - run: | - prove -j$(nproc) --state=save ${NGX_TEST_FILES} || prove -v --state=failed - - windows: - runs-on: windows-2022 - env: - TEMP: "C:\\TEMP" - TMP: "C:\\TEMP" - TMPDIR: "C:\\TEMP" - VCARCH: x64 - - strategy: - fail-fast: false - matrix: - nginx-ref: - - master - module: - - static - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ matrix.nginx-ref }} - repository: 'nginx/nginx' - path: 'nginx' - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: 'nginx/nginx-tests' - path: 'nginx/tests' - sparse-checkout: | - lib - - - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 - with: - toolchain: stable - - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - nginx/objs/**/CACHEDIR.TAG - nginx/objs/**/ngx-debug - nginx/objs/**/ngx-release - key: ${{ runner.os }}-nginx-${{ hashFiles('**/Cargo.lock') }} - restore-keys: ${{ runner.os }}-nginx- - - - name: Prepare build environment - shell: bash - working-directory: nginx - run: | - # Disable dynamic lookup of WSAPoll(); it crashes if the symbol is already imported by - # Rust stdlib. - sed 's/\(_WIN32_WINNT\s*\) 0x0501/\1 0x0601/' -i src/os/win32/ngx_win32_config.h - - echo VCVARSALL="$('C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe' -products \* -latest -property installationPath)\\VC\\Auxiliary\\Build\\vcvarsall.bat" \ - >> "$GITHUB_ENV" - - mkdir -p $TEMP - mkdir -p objs/lib - - curl -sLO https://github.com/PCRE2Project/pcre2/releases/download/pcre2-$PCRE2_VERSION/pcre2-$PCRE2_VERSION.tar.gz - tar -C objs/lib --transform "s/pcre2-$PCRE2_VERSION/pcre/" -xzf ./pcre2-$PCRE2_VERSION.tar.gz - echo '#include ' > objs/lib/pcre/src/inttypes.h - - curl -sLO https://github.com/madler/zlib/releases/download/v$ZLIB_VERSION/zlib-$ZLIB_VERSION.tar.gz - tar -C objs/lib --transform "s/zlib-$ZLIB_VERSION/zlib/" -xzf ./zlib-$ZLIB_VERSION.tar.gz - - curl -sLO https://github.com/openssl/openssl/releases/download/openssl-$OPENSSL_VERSION/openssl-$OPENSSL_VERSION.tar.gz - tar -C objs/lib --transform "s/openssl-$OPENSSL_VERSION/openssl/" -xzf ./openssl-$OPENSSL_VERSION.tar.gz - - - name: Configure and build nginx - shell: cmd - working-directory: nginx - run: | - @echo on - call "%VCVARSALL%" %VCARCH% - bash.exe ^ - %NGX_CONFIGURE_CMD% ^ - %NGX_CONFIGURE_WINDOWS% ^ - %NGX_CONFIGURE_STATIC_MODULES% - nmake -f objs/Makefile - - - name: Run tests - shell: cmd - env: - PERL5LIB: "${{ github.workspace }}\\nginx\\tests\\lib" - TEST_NGINX_BINARY: "${{ github.workspace }}\\nginx\\objs\\nginx.exe" - TEST_NGINX_VERBOSE: 1 - run: | - prove --state=save %NGX_TEST_FILES% || prove -v --state=failed diff --git a/source/rust/vendor/ngx-rust/.github/workflows/sanitizers.yaml b/source/rust/vendor/ngx-rust/.github/workflows/sanitizers.yaml deleted file mode 100644 index d2bc2d1..0000000 --- a/source/rust/vendor/ngx-rust/.github/workflows/sanitizers.yaml +++ /dev/null @@ -1,112 +0,0 @@ -name: sanitizers - -on: - push: - branches: - - main - - "[0-9]+.[0-9]+.x" - pull_request: - -env: - CARGO_TERM_COLOR: 'always' - RUST_BACKTRACE: '1' - BUILDREQUIRES: >- - openssl-devel pcre2-devel zlib-devel - cargo rust-src rustfmt - clang compiler-rt llvm - git-core - make patch - perl-FindBin - perl-IO-Socket-SSL - perl-Test-Harness - perl-Test-Simple - perl-lib - -jobs: - test: - runs-on: ubuntu-latest - container: ghcr.io/almalinux/almalinux:10 - - strategy: - fail-fast: false - matrix: - nginx-ref: - # master - - stable-1.30 - - steps: - - name: Install dependencies - run: dnf install -y ${BUILDREQUIRES} - - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ matrix.nginx-ref }} - repository: 'nginx/nginx' - path: 'nginx' - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - repository: 'nginx/nginx-tests' - path: 'nginx/tests' - - - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/index/ - ~/.cargo/registry/cache/ - ~/.cargo/git/db/ - nginx/objs/ngx_rust_examples - key: ${{ runner.os }}-cargo-asan-${{ hashFiles('**/Cargo.lock') }} - restore-keys: ${{ runner.os }}-cargo-asan- - - - name: Configure and build nginx - working-directory: nginx - env: - CFLAGS: >- - -DNGX_DEBUG_PALLOC=1 - -DNGX_SUPPRESS_WARN=1 - -O1 - -fno-omit-frame-pointer - -fsanitize=address,undefined - LDFLAGS: -fsanitize=address,undefined - RUSTFLAGS: -Zsanitizer=address -Zexternal-clangrt - # Pass --target to cargo to ensure that sanitizer flags are not - # applied to the build scripts and proc-macros. - NGX_RUST_TARGET: x86_64-unknown-linux-gnu - # Extra options passed to cargo rustc - NGX_RUSTC_OPT: -Zbuild-std - # Enable unstable features, such as the -Z options above, - # in the stable toolchain. - RUSTC_BOOTSTRAP: 1 - run: | - patch -p1 < $GITHUB_WORKSPACE/misc/nginx-sanitizer-support.patch - auto/configure \ - --with-cc=clang \ - --with-cc-opt="$CFLAGS" \ - --with-ld-opt="$LDFLAGS" \ - --with-compat \ - --with-debug \ - --with-http_ssl_module \ - --with-http_v2_module \ - --with-http_v3_module \ - --with-stream \ - --with-stream_ssl_module \ - --with-threads \ - --add-module=$(realpath ../examples) - make -j$(nproc) - - - name: Run tests - env: - ASAN_OPTIONS: detect_stack_use_after_return=1:detect_odr_violation=0 - # `container` job steps are running as root, and thus all the files - # created by the test scripts are owned by root. - # But the worker processes are spawned as "nobody" by default, - # resulting in permission errors. - TEST_NGINX_GLOBALS: >- - user root; - run: | - TEST_NGINX_BINARY="$PWD/nginx/objs/nginx" \ - LSAN_OPTIONS="suppressions=$PWD/misc/lsan-suppressions.txt" \ - UBSAN_OPTIONS="suppressions=$PWD/misc/ubsan-suppressions.txt" \ - prove -v -Inginx/tests/lib examples/t diff --git a/source/rust/vendor/ngx-rust/.gitignore b/source/rust/vendor/ngx-rust/.gitignore deleted file mode 100644 index 0a75edb..0000000 --- a/source/rust/vendor/ngx-rust/.gitignore +++ /dev/null @@ -1,256 +0,0 @@ -# Created by https://www.toptal.com/developers/gitignore/api/c,rust,intellij+all,visualstudiocode,vim,emacs -# Edit at https://www.toptal.com/developers/gitignore?templates=c,rust,intellij+all,visualstudiocode,vim,emacs - -### C ### -# Prerequisites -*.d - -# Object files -*.o -*.ko -*.obj -*.elf - -# Linker output -*.ilk -*.map -*.exp - -# Precompiled Headers -*.gch -*.pch - -# Libraries -*.lib -*.a -*.la -*.lo - -# Shared objects (inc. Windows DLLs) -*.dll -*.so -*.so.* -*.dylib - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf - -### Emacs ### -# -*- mode: gitignore; -*- -*~ -\#*\# -/.emacs.desktop -/.emacs.desktop.lock -*.elc -auto-save-list -tramp -.\#* - -# Org-mode -.org-id-locations -*_archive - -# flymake-mode -*_flymake.* - -# eshell files -/eshell/history -/eshell/lastdir - -# elpa packages -/elpa/ - -# reftex files -*.rel - -# AUCTeX auto folder -/auto/ - -# cask packages -.cask/ -dist/ - -# Flycheck -flycheck_*.el - -# server auth directory -/server/ - -# projectiles files -.projectile - -# directory configuration -.dir-locals.el - -# network security -/network-security.data - - -### Intellij+all ### -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff -.idea/**/workspace.xml -.idea/**/tasks.xml -.idea/**/usage.statistics.xml -.idea/**/dictionaries -.idea/**/shelf - -# AWS User-specific -.idea/**/aws.xml - -# Generated files -.idea/**/contentModel.xml - -# Sensitive or high-churn files -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml -.idea/**/dbnavigator.xml - -# Gradle -.idea/**/gradle.xml -.idea/**/libraries - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/artifacts -# .idea/compiler.xml -# .idea/jarRepositories.xml -# .idea/modules.xml -# .idea/*.iml -# .idea/modules -# *.iml -# *.ipr - -# CMake -cmake-build-*/ - -# Mongo Explorer plugin -.idea/**/mongoSettings.xml - -# File-based project format -*.iws - -# IntelliJ -out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Cursive Clojure plugin -.idea/replstate.xml - -# SonarLint plugin -.idea/sonarlint/ - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -# Editor-based Rest Client -.idea/httpRequests - -# Android studio 3.1+ serialized cache file -.idea/caches/build_file_checksums.ser - -### Intellij+all Patch ### -# Ignore everything but code style settings and run configurations -# that are supposed to be shared within teams. - -.idea/* - -!.idea/codeStyles -!.idea/runConfigurations - -### Rust ### -# Generated by Cargo -# will have compiled files and executables -debug/ -target/ - -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html -Cargo.lock - -# These are backup files generated by rustfmt -**/*.rs.bk - -# MSVC Windows builds of rustc generate these, which store debugging information - -### Vim ### -# Swap -[._]*.s[a-v][a-z] -!*.svg # comment out if you don't need vector files -[._]*.sw[a-p] -[._]s[a-rt-v][a-z] -[._]ss[a-gi-z] -[._]sw[a-p] - -# Session -Session.vim -Sessionx.vim - -# Temporary -.netrwhist -# Auto-generated tag files -tags -# Persistent undo -[._]*.un~ - -### VisualStudioCode ### -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -!.vscode/*.code-snippets - -# Local History for Visual Studio Code -.history/ - -# Built Visual Studio Code Extensions -*.vsix - -### VisualStudioCode Patch ### -# Ignore all local history of files -.history -.ionide - -# End of https://www.toptal.com/developers/gitignore/api/c,rust,intellij+all,visualstudiocode,vim,emacs - -.vscode/c_cpp_properties.json -.cache/ -.nginx/ -.DS_Store diff --git a/source/rust/vendor/ngx-rust/.gitmodules b/source/rust/vendor/ngx-rust/.gitmodules deleted file mode 100644 index d4fe729..0000000 --- a/source/rust/vendor/ngx-rust/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "nginx-src/nginx"] - path = nginx-src/nginx - url = https://github.com/nginx/nginx.git - branch = stable-1.28 diff --git a/source/rust/vendor/ngx-rust/CHANGELOG.md b/source/rust/vendor/ngx-rust/CHANGELOG.md deleted file mode 100644 index 6f23139..0000000 --- a/source/rust/vendor/ngx-rust/CHANGELOG.md +++ /dev/null @@ -1,170 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -## Release 0.5.0 - -### Breaking changes - -The release contains too many breaking changes to offer a complete migration -guide. We will strive to do better in future releases; meanwhile, we suggest to -look at the changes in example modules: - - git diff v0.4.1..v0.5.0 -- examples/*.rs - -### Build experience - -In this release, we shifted the focus to an integration into the NGINX build -process. - -The default set of features now requires providing a preconfigured NGINX source -tree with `NGINX_SOURCE_DIR` and `NGINX_BUILD_DIR` variables ([#67], [#124]). - -The option to build a copy of NGINX as a part of the module process was -preserved as a feature flag `vendored` and no longer requires downloading -sources from the network ([#160]). -We encourage you to limit use of this feature to testing only. - -The [`examples`](./examples/) directory provides `config`, `config.make` and -`auto/rust` scripts to add a Rust-based module to the nginx build, linked -statically with `--add-module=` or dynamically with `--add-dynamic-module=`. -[nginx-acme] offers another, more complete example ([#67], [#95], [#124], -[#154], [#176]). - -In addition, we now have a proper detection of the features available in the -build of NGINX ([#97]). See [build.rs](./build.rs) for the necessary setup for -your project. - -[nginx-acme]: https://github.com/nginx/nginx-acme -[#67]: https://github.com/nginx/ngx-rust/pull/67 -[#95]: https://github.com/nginx/ngx-rust/pull/95 -[#97]: https://github.com/nginx/ngx-rust/pull/97 -[#124]: https://github.com/nginx/ngx-rust/pull/124 -[#154]: https://github.com/nginx/ngx-rust/pull/154 -[#160]: https://github.com/nginx/ngx-rust/pull/160 -[#176]: https://github.com/nginx/ngx-rust/pull/176 - -### Module declaration - -The traits for declaring a module and accessing module configuration underwent -significant changes in [#142] with the goal of reducing the amount of unsafe -code and enforcing type safety. - -See for a -summary and migration steps. - -[#142]: https://github.com/nginx/ngx-rust/pull/142 - -### Allocators - -`ngx` now offers custom allocator support based on the [allocator-api2] crate. -The `ngx::core::Pool` and `ngx::core::SlabPool` can be used for failible -allocations within the NGINX pools and shared zones correspondingly -([#164], [#171]). - -Most of the crates with [allocator-api2 support] are compatible with this -implementation. We also provide wrappers for common data structures implemented -in NGINX in [`ngx::collections`](./src/collections/) ([#164], [#181]). - -[allocator-api2]: https://crates.io/crates/allocator_api2 -[allocator-api2 support]: https://crates.io/crates/allocator_api2/reverse_dependencies -[#164]: https://github.com/nginx/ngx-rust/pull/164 -[#171]: https://github.com/nginx/ngx-rust/pull/171 -[#181]: https://github.com/nginx/ngx-rust/pull/181 - - -### Other - -* We audited the code and fixed or removed most of the methods that made wrong - assumptions and could panic or crash ([#91], [#152], [#183]). -* `no_std` build support ([#111]). -* Logging API improvements ([#113], [#187]) -* The SDK and the example modules can be built and are tested in CI on Windows - ([#124], [#161]). No further porting or testing work was done. -* Reimplementations for `nginx-sys` methods and macros that cannot be translated - with bindgen ([#131], [#162], [#167]) -* Initial work on the NGINX async runtime ([#170]) -* The default branch was renamed to `main`. - -[#91]: https://github.com/nginx/ngx-rust/pull/91 -[#111]: https://github.com/nginx/ngx-rust/pull/111 -[#113]: https://github.com/nginx/ngx-rust/pull/113 -[#131]: https://github.com/nginx/ngx-rust/pull/131 -[#152]: https://github.com/nginx/ngx-rust/pull/152 -[#161]: https://github.com/nginx/ngx-rust/pull/161 -[#162]: https://github.com/nginx/ngx-rust/pull/162 -[#167]: https://github.com/nginx/ngx-rust/pull/167 -[#170]: https://github.com/nginx/ngx-rust/pull/170 -[#183]: https://github.com/nginx/ngx-rust/pull/183 -[#187]: https://github.com/nginx/ngx-rust/pull/187 - -### Supported versions - -The minimum supported Rust version is 1.81.0. The version was chosen to support -the packaged Rust toolchain in the recent versions of popular Linux and BSD -distributions. - -The minimum supported NGINX version is 1.22. The bindings may compile with an -older version of NGINX, but we do not test that regularly. - -Full changelog: [v0.4.1..v0.5.0](https://github.com/nginx/ngx-rust/compare/v0.4.1...v0.5.0) - -## Release v0.4.1 - * release: ngx 0.4.1 (9d2ce0d) - * release: nginx-sys 0.2.1 (89eb277) - * fix(#50): user_agent method returns 'Option<&NgxStr>' and not '&NgxStr' (8706830) - * fix(#41): zlib version update (89e0fcc) - * fix: check user_agent for null (0ca0bc9) - * feat: (2 of 2) Upstream module example (#37) (840d789) - * feat: (1 of 2) Supporting changes for upstream example module. (#36) (8b3a119) - * Revert "ci: use GH cache for .cache folder on MAC OS" (7972ae7) - * docs: updated changelog (74604e2) - -## Release 0.4.0-beta - * realease: bump nginx-sys to 0.2.0 (ad093d8) - * feat: unsafe updates for raw pointer arguments (1b88323) - * feat: Add debug log mask support (#40) (57c68ff) - * docs: add support badge to README (4aa2e35) - * cargo: make macOS linker flags workaround apply to Apple silicon (f4ea26f) - * docs: added repostatus and crates badges (dd687a4) - - ## Initial release 0.3.0-beta - * docs: prepare ngx to be published to crates.io (a1bff29) - * fix: nginx-sys enable a few modules by default (f23e4b1) - * !misc: project refactor and new module structure (b3e8f45) - * update README (#18) (d2c0b3a) - * Fix usage example in README (#16) (8deaec0) - * use nginxinc namespace (9bb9ef6) - * upgrade to rust 1.26 (#15) (bbfc114) - * 1.39 upgrade (#12) (be9d532) - * add pkg-config (#11) (a33c329) - * upgrade to nginx 1.13.7 (#10) (8c6b968) - * update the README (#9) (7693ea2) - * Rust 1.21 (#8) (4fa395c) - * Rust 1.21 (#7) (9517b56) - * add rust docker tooling (8b4d492) - * revert back tool tag (82bd0d6) - * update the tag for rust tool image (f2418c0) - * bump up tool image to 1.22 (7db2ced) - * add rust tool on top of the nginx (9aa4fa0) - * add developer version of nginx which can do ps (994c703) - * upgrade nginx to 1.13.5 bump up cargo version number respectively separate out nginx make file (7095777) - * consolidate makefile by reducing duplicates simplify docker command (cfe1756) - * set default rust tooling to 1.20 generate linux binding in the cargo build fix the linux configuration (d396803) - * build nginx binary for darwin add target for darwin (d2e04ce) - * add configuration for linux (b3bf4da) - * remove unnecessary reference to libc invoke make for build.rs in the mac (8e1c544) - * add unit test for nginx server (d0ff3df) - * Merge branch 'master' into module (4f6ed43) - * update the README (a8cfe50) - * add license file (805e70b) - * add license file (8c574be) - * add nginx instance module where you can start and stop nginx sample test for instance (acfc545) - * upgrade bindgen to latest version remove redudant c module code update the nginx config (3102b5a) - * update the tools make file to use Dockerhub (36ae1ca) - * update the README (ba563fc) - * add tools directory to generate docker image for rust toolchain check for nginx directory when setting up source (6842329) - * add targets for building on linux (6176272) - * make target for setting up darwin source add os specific build path (fbc5e2f) - * initial check in generate binding (a38b8ab) - diff --git a/source/rust/vendor/ngx-rust/CODE_OF_CONDUCT.md b/source/rust/vendor/ngx-rust/CODE_OF_CONDUCT.md deleted file mode 100644 index 4547fd8..0000000 --- a/source/rust/vendor/ngx-rust/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,129 +0,0 @@ - -# Contributor Covenant Code of Conduct - -## Our Pledge - -We as members, contributors, and leaders pledge to make participation in our -community a harassment-free experience for everyone, regardless of age, body -size, visible or invisible disability, ethnicity, sex characteristics, gender -identity and expression, level of experience, education, socio-economic status, -nationality, personal appearance, race, religion, or sexual identity -and orientation. - -We pledge to act and interact in ways that contribute to an open, welcoming, -diverse, inclusive, and healthy community. - -## Our Standards - -Examples of behavior that contributes to a positive environment for our -community include: - -* Demonstrating empathy and kindness toward other people -* Being respectful of differing opinions, viewpoints, and experiences -* Giving and gracefully accepting constructive feedback -* Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -* Focusing on what is best not just for us as individuals, but for the - overall community - -Examples of unacceptable behavior include: - -* The use of sexualized language or imagery, and sexual attention or - advances of any kind -* Trolling, insulting or derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or email - address, without their explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Enforcement Responsibilities - -Community leaders are responsible for clarifying and enforcing our standards of -acceptable behavior and will take appropriate and fair corrective action in -response to any behavior that they deem inappropriate, threatening, offensive, -or harmful. - -Community leaders have the right and responsibility to remove, edit, or reject -comments, commits, code, wiki edits, issues, and other contributions that are -not aligned to this Code of Conduct, and will communicate reasons for moderation -decisions when appropriate. - -## Scope - -This Code of Conduct applies within all community spaces, and also applies when -an individual is officially representing the community in public spaces. -Examples of representing our community include using an official e-mail address, -posting via an official social media account, or acting as an appointed -representative at an online or offline event. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported to the community leaders responsible for enforcement as listed on the -github project page. -All complaints will be reviewed and investigated promptly and fairly. - -All community leaders are obligated to respect the privacy and security of the -reporter of any incident. - -## Enforcement Guidelines - -Community leaders will follow these Community Impact Guidelines in determining -the consequences for any action they deem in violation of this Code of Conduct: - -### 1. Correction - -**Community Impact**: Use of inappropriate language or other behavior deemed -unprofessional or unwelcome in the community. - -**Consequence**: A private, written warning from community leaders, providing -clarity around the nature of the violation and an explanation of why the -behavior was inappropriate. A public apology may be requested. - -### 2. Warning - -**Community Impact**: A violation through a single incident or series -of actions. - -**Consequence**: A warning with consequences for continued behavior. No -interaction with the people involved, including unsolicited interaction with -those enforcing the Code of Conduct, for a specified period of time. This -includes avoiding interactions in community spaces as well as external channels -like social media. Violating these terms may lead to a temporary or -permanent ban. - -### 3. Temporary Ban - -**Community Impact**: A serious violation of community standards, including -sustained inappropriate behavior. - -**Consequence**: A temporary ban from any sort of interaction or public -communication with the community for a specified period of time. No public or -private interaction with the people involved, including unsolicited interaction -with those enforcing the Code of Conduct, is allowed during this period. -Violating these terms may lead to a permanent ban. - -### 4. Permanent Ban - -**Community Impact**: Demonstrating a pattern of violation of community -standards, including sustained inappropriate behavior, harassment of an -individual, or aggression toward or disparagement of classes of individuals. - -**Consequence**: A permanent ban from any sort of public interaction within -the community. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 2.0, available at -https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. - -Community Impact Guidelines were inspired by [Mozilla's code of conduct -enforcement ladder](https://github.com/mozilla/diversity). - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see the FAQ at -https://www.contributor-covenant.org/faq. Translations are available at -https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/CONTRIBUTING.md b/source/rust/vendor/ngx-rust/CONTRIBUTING.md deleted file mode 100644 index 5242d62..0000000 --- a/source/rust/vendor/ngx-rust/CONTRIBUTING.md +++ /dev/null @@ -1,55 +0,0 @@ -# Contributing Guidelines - -The following is a set of guidelines for contributing. We really appreciate that you are considering contributing! - -#### Table Of Contents - -[Ask a Question](#ask-a-question) - -[Contributing](#contributing) - -[Style Guides](#style-guides) - * [Git Style Guide](#git-style-guide) - * [Rust Style Guide](#rust-style-guide) - -[Code of Conduct](CODE_OF_CONDUCT.md) - -## Ask a Question - -Please ask your question on github using discussions. - -## Contributing - -### Report a Bug - -To report a bug, open an issue on GitHub with the label `bug` using the available bug report issue template. Please ensure the issue has not already been reported. - -### Suggest an Enhancement - -To suggest an enhancement, please create an issue on GitHub with the label `enhancement` using the available feature issue template. - -### Open a Pull Request - -* Fork the repo, create a branch, submit a PR when your changes are tested and ready for review. -* Fill in [our pull request template](/.github/PULL_REQUEST_TEMPLATE.md) - -Note: if you’d like to implement a new feature, please consider creating a feature request issue first to start a discussion about the feature. - -## Style Guides - -### Git Style Guide - -* Keep a clean, concise and meaningful git commit history on your branch, rebasing locally and squashing before submitting a PR -* Use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format when writing a commit message, so that changelogs can be automatically generated -* Follow the guidelines of writing a good commit message as described [here](https://chris.beams.io/posts/git-commit/) and summarised in the next few points - * In the subject line, use the present tense ("Add feature" not "Added feature") - * In the subject line, use the imperative mood ("Move cursor to..." not "Moves cursor to...") - * Limit the subject line to 72 characters or less - * Reference issues and pull requests liberally after the subject line - * Add more detailed description in the body of the git message (`git commit -a` to give you more space and time in your text editor to write a good message instead of `git commit -am`) - -### Rust Style Guide - -* Rust code should be checked in after `cargo fmt` has been run. -* The code style broadly complies with the [official Rust Style Guide](https://doc.rust-lang.org/style-guide/index.html). -* Where feasible, include unit tests. diff --git a/source/rust/vendor/ngx-rust/Cargo.toml b/source/rust/vendor/ngx-rust/Cargo.toml deleted file mode 100644 index 1b1bcd2..0000000 --- a/source/rust/vendor/ngx-rust/Cargo.toml +++ /dev/null @@ -1,84 +0,0 @@ -[workspace] -members = [ - "nginx-src", - "nginx-sys", - "examples", -] - -[workspace.package] -edition = "2024" -license = "Apache-2.0" -homepage = "https://github.com/nginx/ngx-rust" -repository = "https://github.com/nginx/ngx-rust" -rust-version = "1.85.0" - -[workspace.lints.clippy] -alloc_instead_of_core = "warn" -borrow_as_ptr = "warn" -std_instead_of_alloc = "warn" -std_instead_of_core = "warn" - -[workspace.lints.rust] -rust-2024-compatibility = "warn" - -[package] -name = "ngx" -version = "0.5.0" -autoexamples = false -categories = ["api-bindings", "network-programming"] -description = "FFI bindings to NGINX" -include = [ - "/build.rs", - "/src", - "/*.md", - "LICENSE", -] -keywords = ["nginx", "module", "sys"] -edition.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -rust-version.workspace = true - -[package.metadata.docs.rs] -all-features = true -default-target = "x86_64-unknown-linux-gnu" -targets = [] - -[dependencies] -allocator-api2 = { version = "0.4.0", default-features = false, features = ["fresh-rust"] } -async-task = { version = "4.7.1", optional = true } -lock_api = "0.4.13" -nginx-sys = { path = "nginx-sys", version = "0.5.0"} -pin-project-lite = { version = "0.2.16", optional = true } - -[features] -default = ["std"] -# Enables a minimal async runtime built on top of the NGINX event loop. -async = [ - "alloc", - "dep:async-task", - "dep:pin-project-lite", -] -# Provides APIs that require allocations via the `alloc` crate. -alloc = ["allocator-api2/alloc"] -# Enables serialization support for some of the provided and re-exported types. -serde = [ - "allocator-api2/serde", -] -# Provides APIs that require the standard library. -std = [ - "alloc", - "allocator-api2/std" -] -# Enables the build scripts to build a copy of nginx source and link against it. -vendored = ["nginx-sys/vendored"] - -[badges] -maintenance = { status = "experimental" } - -[dev-dependencies] -tempfile = { version = "3.20.0", default-features = false } - -[lints] -workspace = true diff --git a/source/rust/vendor/ngx-rust/Containerfile.debian b/source/rust/vendor/ngx-rust/Containerfile.debian deleted file mode 100644 index 7d8bca4..0000000 --- a/source/rust/vendor/ngx-rust/Containerfile.debian +++ /dev/null @@ -1,16 +0,0 @@ -FROM rust:slim-bullseye - -RUN set -eux \ - export DEBIAN_FRONTEND=noninteractive; \ - apt-get -qq update; \ - apt-get -qq install --yes --no-install-recommends --no-install-suggests \ - libclang-dev \ - libssl-dev \ - pkg-config \ - git \ - grep \ - gawk \ - gnupg2 \ - sed \ - make; \ - git config --global --add safe.directory /project \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/Dockerfile b/source/rust/vendor/ngx-rust/Dockerfile deleted file mode 100644 index b08598d..0000000 --- a/source/rust/vendor/ngx-rust/Dockerfile +++ /dev/null @@ -1,51 +0,0 @@ -ARG NGX_VERSION=1.30.4 -# NGINX official images are available for one specific release of Debian, -# e.g `nginx:1.30.4-trixie`. Please see the list of tags on Docker Hub -# if you need to change NGX_VERSION. -ARG DEBIAN_RELEASE=trixie - -# --- builder: build all examples -FROM rust:slim-${DEBIAN_RELEASE} AS build -ARG NGX_VERSION -ARG NGX_CONFIGURE_ARGS= -WORKDIR /project -RUN --mount=type=cache,target=/var/cache/apt < /dev/null || command -v grep 2> /dev/null) -SED ?= $(shell command -v gsed 2> /dev/null || command -v sed 2> /dev/null) -AWK ?= $(shell command -v gawk 2> /dev/null || command -v awk 2> /dev/null) -VERSION ?= $(shell $(GREP) -Po '^version\s+=\s+"\K.*?(?=")' $(CURDIR)/Cargo.toml) -CARGO ?= cargo -DOCKER ?= docker -DOCKER_BUILD_FLAGS ?= --load -COMMITSAR_DOCKER := $(DOCKER) run --tty --rm --workdir /src -v "$(CURDIR):/src" aevea/commitsar -COMMITSAR ?= $(shell command -v commitsar 2> /dev/null) -PROJECT_NAME ?= ngx-rust -GITHUB_REPOSITORY ?= nginx/$(PROJECT_NAME) -SRC_REPO := https://github.com/$(GITHUB_REPOSITORY) - -RELEASE_BUILD_FLAGS ?= --quiet --release - -Q = $(if $(filter 1,$V),,@) -M = $(shell printf "\033[34;1m▶\033[0m") - -UNAME_S := $(shell uname -s) -ifeq ($(UNAME_S),Linux) - FEATURES += --features=linux -endif - -# Use docker based commitsar if it isn't in the path -ifeq ($(COMMITSAR),) - COMMITSAR = $(COMMITSAR_DOCKER) -endif - -.PHONY: help -help: - @$(GREP) --no-filename -E '^[ a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \ - $(AWK) 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-28s\033[0m %s\n", $$1, $$2}' | sort - -.PHONY: clean -clean: clean-cache; $(info $(M) cleaning...) @ ## Cleanup everything - $Q rm -rf $(CURDIR)/target - $Q $(CARGO) clean - -.PHONY: clean-cache -clean-cache: ## Remove all cached dependencies and build artifacts - $(Q) rm -rf $(CACHE_DIR) - -.PHONY: commitsar -commitsar: ## Run git commit linter - $Q $(info $(M) running commitsar...) - $(COMMITSAR) - -target: - $Q mkdir -p $@ - -.PHONY: debug -debug: target/debug ## Build current platform target in debug mode - -target/debug: - $Q echo "$(M) building in debug mode for the current platform" - $Q $(CARGO) build --quiet - -.PHONY: release -release: target/release ## Build current platform target in release mode - -target/release: - $Q echo "$(M) building in release mode for the current platform" - $Q $(CARGO) build $(RELEASE_BUILD_FLAGS) - -.PHONY: test -test: ## Run tests - $Q $(CARGO) test - -.PHONY: format -format: ## Run rustfmt - $Q $(CARGO) fmt - -.PHONY: lint -lint: ## Run clippy - $Q $(CARGO) clippy - -.PHONY: examples-debug -examples-debug: - $Q echo "$(M) building all examples as debug" - $Q $(CARGO) build --quiet --package=examples --examples $(FEATURES) - -include $(CURDIR)/build/container.mk -include $(CURDIR)/build/release.mk -include $(CURDIR)/build/github.mk diff --git a/source/rust/vendor/ngx-rust/LICENSE b/source/rust/vendor/ngx-rust/LICENSE deleted file mode 100644 index 98f7217..0000000 --- a/source/rust/vendor/ngx-rust/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, -and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by -the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all -other entities that control, are controlled by, or are under common -control with that entity. For the purposes of this definition, -"control" means (i) the power, direct or indirect, to cause the -direction or management of such entity, whether by contract or -otherwise, or (ii) ownership of fifty percent (50%) or more of the -outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity -exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, -including but not limited to software source code, documentation -source, and configuration files. - -"Object" form shall mean any form resulting from mechanical -transformation or translation of a Source form, including but -not limited to compiled object code, generated documentation, -and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or -Object form, made available under the License, as indicated by a -copyright notice that is included in or attached to the work -(an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object -form, that is based on (or derived from) the Work and for which the -editorial revisions, annotations, elaborations, or other modifications -represent, as a whole, an original work of authorship. For the purposes -of this License, Derivative Works shall not include works that remain -separable from, or merely link (or bind by name) to the interfaces of, -the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including -the original version of the Work and any modifications or additions -to that Work or Derivative Works thereof, that is intentionally -submitted to Licensor for inclusion in the Work by the copyright owner -or by an individual or Legal Entity authorized to submit on behalf of -the copyright owner. For the purposes of this definition, "submitted" -means any form of electronic, verbal, or written communication sent -to the Licensor or its representatives, including but not limited to -communication on electronic mailing lists, source code control systems, -and issue tracking systems that are managed by, or on behalf of, the -Licensor for the purpose of discussing and improving the Work, but -excluding communication that is conspicuously marked or otherwise -designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity -on behalf of whom a Contribution has been received by Licensor and -subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of -this License, each Contributor hereby grants to You a perpetual, -worldwide, non-exclusive, no-charge, royalty-free, irrevocable -copyright license to reproduce, prepare Derivative Works of, -publicly display, publicly perform, sublicense, and distribute the -Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of -this License, each Contributor hereby grants to You a perpetual, -worldwide, non-exclusive, no-charge, royalty-free, irrevocable -(except as stated in this section) patent license to make, have made, -use, offer to sell, sell, import, and otherwise transfer the Work, -where such license applies only to those patent claims licensable -by such Contributor that are necessarily infringed by their -Contribution(s) alone or by combination of their Contribution(s) -with the Work to which such Contribution(s) was submitted. If You -institute patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Work -or a Contribution incorporated within the Work constitutes direct -or contributory patent infringement, then any patent licenses -granted to You under this License for that Work shall terminate -as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the -Work or Derivative Works thereof in any medium, with or without -modifications, and in Source or Object form, provided that You -meet the following conditions: - -(a) You must give any other recipients of the Work or -Derivative Works a copy of this License; and - -(b) You must cause any modified files to carry prominent notices -stating that You changed the files; and - -(c) You must retain, in the Source form of any Derivative Works -that You distribute, all copyright, patent, trademark, and -attribution notices from the Source form of the Work, -excluding those notices that do not pertain to any part of -the Derivative Works; and - -(d) If the Work includes a "NOTICE" text file as part of its -distribution, then any Derivative Works that You distribute must -include a readable copy of the attribution notices contained -within such NOTICE file, excluding those notices that do not -pertain to any part of the Derivative Works, in at least one -of the following places: within a NOTICE text file distributed -as part of the Derivative Works; within the Source form or -documentation, if provided along with the Derivative Works; or, -within a display generated by the Derivative Works, if and -wherever such third-party notices normally appear. The contents -of the NOTICE file are for informational purposes only and -do not modify the License. You may add Your own attribution -notices within Derivative Works that You distribute, alongside -or as an addendum to the NOTICE text from the Work, provided -that such additional attribution notices cannot be construed -as modifying the License. - -You may add Your own copyright statement to Your modifications and -may provide additional or different license terms and conditions -for use, reproduction, or distribution of Your modifications, or -for any such Derivative Works as a whole, provided Your use, -reproduction, and distribution of the Work otherwise complies with -the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, -any Contribution intentionally submitted for inclusion in the Work -by You to the Licensor shall be under the terms and conditions of -this License, without any additional terms or conditions. -Notwithstanding the above, nothing herein shall supersede or modify -the terms of any separate license agreement you may have executed -with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade -names, trademarks, service marks, or product names of the Licensor, -except as required for reasonable and customary use in describing the -origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or -agreed to in writing, Licensor provides the Work (and each -Contributor provides its Contributions) on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -implied, including, without limitation, any warranties or conditions -of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A -PARTICULAR PURPOSE. You are solely responsible for determining the -appropriateness of using or redistributing the Work and assume any -risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, -whether in tort (including negligence), contract, or otherwise, -unless required by applicable law (such as deliberate and grossly -negligent acts) or agreed to in writing, shall any Contributor be -liable to You for damages, including any direct, indirect, special, -incidental, or consequential damages of any character arising as a -result of this License or out of the use or inability to use the -Work (including but not limited to damages for loss of goodwill, -work stoppage, computer failure or malfunction, or any and all -other commercial damages or losses), even if such Contributor -has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing -the Work or Derivative Works thereof, You may choose to offer, -and charge a fee for, acceptance of support, warranty, indemnity, -or other liability obligations and/or rights consistent with this -License. However, in accepting such obligations, You may act only -on Your own behalf and on Your sole responsibility, not on behalf -of any other Contributor, and only if You agree to indemnify, -defend, and hold each Contributor harmless for any liability -incurred by, or claims asserted against, such Contributor by reason -of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - -To apply the Apache License to your work, attach the following -boilerplate notice, with the fields enclosed by brackets "{}" -replaced with your own identifying information. (Don't include -the brackets!) The text should be enclosed in the appropriate -comment syntax for the file format. We also recommend that a -file or class name and description of purpose be included on the -same "printed page" as the copyright notice for easier -identification within third-party archives. - -Copyright 2016 Nginx, Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/source/rust/vendor/ngx-rust/README.md b/source/rust/vendor/ngx-rust/README.md deleted file mode 100644 index 7175f67..0000000 --- a/source/rust/vendor/ngx-rust/README.md +++ /dev/null @@ -1,256 +0,0 @@ -[![Rust](https://github.com/nginx/ngx-rust/actions/workflows/ci.yaml/badge.svg)](https://github.com/nginx/ngx-rust/actions/workflows/ci.yaml) -[![crates.io](https://img.shields.io/crates/v/ngx.svg)](https://crates.io/crates/ngx) -[![docs.rs](https://img.shields.io/docsrs/ngx?label=docs(ngx))](https://docs.rs/ngx) -[![docs.rs](https://img.shields.io/docsrs/nginx-sys?label=docs(nginx-sys))](https://docs.rs/nginx-sys) -[![Project Status: WIP – Initial development is in progress, but there has not yet been a stable, usable release suitable for the public.](https://www.repostatus.org/badges/latest/wip.svg)](https://www.repostatus.org/#wip) -[![Community Support](https://badgen.net/badge/support/community/cyan?icon=awesome)](https://github.com/nginx/ngx-rust/discussions) - - - -# Rust bindings for NGINX - -The `ngx` crate provides a high-level Rust interface for the [NGINX] C APIs, -allowing creation of NGINX dynamic modules completely in Rust. - -[NGINX]: https://nginx.org/ - -## Project status - -This project is in active development. It is stable enough to be used in our -own products, but the APIs are not stabilized and breaking changes are expected. - -## Build - -NGINX modules can be built against a particular version of NGINX. The following -environment variables can be used to specify the NGINX build to use: - -- `NGINX_BUILD_DIR` - absolute path to the NGINX build directory. - Usually it's `objs` under the source directory, but can be changed with the - `--builddir=` argument of the configure script. - -- `NGINX_SOURCE_DIR` - absolute path to the NGINX source directory, configured - with the [`configure`](https://nginx.org/en/docs/configure.html) command. - -Only the `./configure` step of the NGINX build is mandatory because bindings -generator don't depend on any of the artifacts generated by `make`. - -For example, this is how you would compile the [examples](#examples) using a -specific version of NGINX: - -```sh -NGINX_BUILD_DIR=/path/to/nginx-1.30.4/objs cargo build --package=examples --examples -``` - -### Building with the NGINX build script - -You can build your Rust-based module as a part of the NGINX build process by -providing a `config` script implementation and passing the `--add-module`/ -`--add-dynamic-module` options to the configure script. - -See the following example integration scripts: [`examples/config`] and -[`examples/config.make`]. - -[`examples/config`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config -[`examples/config.make`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config.make - -### Building with vendored NGINX sources - -It is possible to build module with a vendored copy of the NGINX sources -provided in the `nginx-src` crate by enabling feature `vendored`: - -By default, this will use the latest stable release of NGINX and require -system-wide installation of build dependencies (OpenSSL, PCRE2, Zlib). - -The behavior of vendored builds can be customized with environment variables, -as documented in the [nginx-src] crate README. - -**NOTE**: We recommend to build the module binaries against the exact source and -configuration of the NGINX build that you are planning to use in production, -and that is unlikely to be possible with the vendored source. - -`configure` arguments alter the APIs and the symbols visible to the Rust code, -and some OS distributions are known to ship nginx packages with API-breaking -patches applied. - -[nginx-src]: https://docs.rs/nginx-src/ - -## Cargo features - -- `alloc` - **Enabled** by default. This provides APIs that require allocations - via the `alloc` crate. -- `async` - Enables a minimal async runtime built on top of the NGINX event loop. -- `serde` - Enables serialization support for some of the provided and - re-exported types. -- `std` - **Enabled** by default. This provides APIs that require the standard - library. -- `vendored`: Enables the build scripts to build a copy of nginx source and link - against it. See the [nginx-src] crate documentation for additional details. - -## Dependencies - -The following dependencies are required to build a Rust NGINX module on Linux -or BSD platform: - -- NGINX build dependencies: C compiler, make, OpenSSL, PCRE2, and Zlib. -- Rust toolchain (1.85.0 or later) -- [libclang] for rust-bindgen - -The installation process and the package names are system-dependent. Please, -consult the documentation for your distribution. - -Note that on some systems you will need `-devel` or `-dev` versions of the -packages. - -For example, [Dockerfile] contains the installation commands for Debian Linux. - -[Dockerfile]: https://github.com/nginx/ngx-rust/blob/main/Dockerfile -[libclang]: https://rust-lang.github.io/rust-bindgen/requirements.html - -### macOS dependencies - -In order to use the optional GNU make build process on macOS, you will need -to install additional tools. This can be done via [homebrew](https://brew.sh/) -with the following command: - -```sh -brew install make openssl grep -``` - -Additionally, you may need to set up LLVM and clang. Typically, this is done -as follows: - -```sh -# make sure xcode tools are installed -xcode-select --install -# instal llvm -brew install --with-toolchain llvm -``` - - - -### Examples - -Example modules are available in [examples] folder. -You can use `cargo build --package=examples --examples` to build these examples. -After compilation, the modules can be found in the path `target/debug/examples/` -(with the `.so` file extension for Linux or `.dylib` for macOS). -Add `--features=linux` to build Linux specific modules. - -**NOTE**: adding the "linux" feature on macOS will cause a build failure. - -For example (all examples plus linux specific): - -```sh -cargo build --package=examples --examples --features=linux -``` - -[examples]: https://github.com/nginx/ngx-rust/tree/main/examples - -### Docker - -We provide a multistage [Dockerfile]: - -```sh -# build all dynamic modules examples and specify NGINX version to use -docker buildx build --build-arg NGX_VERSION=1.29.1 -t ngx-rust . - -# start NGINX using [curl](examples/curl.conf) module example: -docker run --rm -d -p 8000:8000 ngx-rust nginx -c examples/curl.conf - -# test it - you should see 403 Forbidden -curl http://127.0.0.1:8000 -v -H "user-agent: curl" - -# test it - you should see 404 Not Found -curl http://127.0.0.1:8000 -v -H "user-agent: foo" -``` - -## Usage - -A complete module example using the SDK can be found [here](examples/curl.rs). -You can build it with `cargo build --package=examples --example=curl` then set -up NGINX to use it, as shown below: - -```nginx -daemon off; -error_log stderr debug; - -load_module modules/libcurl.so; - -events { -} - -http { - server { - listen 8000; - server_name localhost; - - access_log /dev/stdout; - - location / { - root /srv/http; - # ... Other config stuff ... - - curl on; - } - } -} -``` - -## Support - -This SDK is currently unstable. Right now, our primary goal is collect feedback -and stabilize it before offering support. -Feel free to [contribute](CONTRIBUTING.md) by creating issues, PRs, or github -discussions. - -Currently, the supported platforms are: - -- Darwin (macOS) -- FreeBSD -- Linux - -See the Rust toolchain [platform support] document for supported versions and -architectures. - -[platform support]: https://doc.rust-lang.org/rustc/platform-support.html - -### Tested OS and platforms - -In addition, we verified that the modules based on this SDK can be built and -work on the following platforms. - -- Illumos -- NetBSD 9-10 -- OpenBSD 7 -- Solaris 11.4 -- Windows 10+/Windows Server 2022+ - -## Roadmap - -If you have ideas for releases in the future, please suggest them in the github -discussions. - -## Contributing - -We welcome pull requests and issues! - -Please refer to the [Contributing Guidelines](CONTRIBUTING.md) when doing a PR. - -## Authors and acknowledgment - -This project uses some great work from: - -- [dcoles/nginx-rs](https://github.com/dcoles/nginx-rs), -- [arvancloud/nginx-rs](https://github.com/arvancloud/nginx-rs). - -## Projects using the SDK - -- [ngx-strict-sni](https://github.com/JyJyJcr/ngx-strict-sni) - Strict SNI validator for Nginx -- [nginx-acme](https://github.com/nginx/nginx-acme) - ACMEv2 client implementation - -## License - -All code in this repository is licensed under the -[Apache License, Version 2.0](./LICENSE). - -© [F5, Inc.](https://www.f5.com/) diff --git a/source/rust/vendor/ngx-rust/SECURITY.md b/source/rust/vendor/ngx-rust/SECURITY.md deleted file mode 100644 index dd2be6b..0000000 --- a/source/rust/vendor/ngx-rust/SECURITY.md +++ /dev/null @@ -1,22 +0,0 @@ -# Security Policy - -## General Guidance - -We advise users to run the most recent release of the NGINX Rust Module SDK, and we issue software updates to the -most recent release. - -## Support - -The NGINX Rust Module SDK is not officially supported. - -## Reporting a Vulnerability - -The F5 Security Incident Response Team (F5 SIRT) has an email alias that makes it easy to report potential security -vulnerabilities. - -- If you’re an F5 customer with an active support contract, please contact - [F5 Technical Support](https://www.f5.com/services/support). -- If you aren’t an F5 customer, please report any potential or current instances of security vulnerabilities with any - F5 product to the F5 Security Incident Response Team at F5SIRT@f5.com - -For more information visit https://www.f5.com/services/support/report-a-vulnerability diff --git a/source/rust/vendor/ngx-rust/build.rs b/source/rust/vendor/ngx-rust/build.rs deleted file mode 100644 index 3ffcf94..0000000 --- a/source/rust/vendor/ngx-rust/build.rs +++ /dev/null @@ -1,67 +0,0 @@ -/// Example buildscript for an nginx module. -/// -/// Due to the limitations of cargo[1], this buildscript _requires_ adding `nginx-sys` to the -/// direct dependencies of your crate. -/// -/// [1]: https://github.com/rust-lang/cargo/issues/3544 -fn main() { - // Generate `ngx_os` and `ngx_feature` cfg values - - // Specify acceptable values for `ngx_feature` - println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES_CHECK"); - println!( - "cargo::rustc-check-cfg=cfg(ngx_feature, values({}))", - std::env::var("DEP_NGINX_FEATURES_CHECK").unwrap_or("any()".to_string()) - ); - // Read feature flags detected by nginx-sys and pass to the compiler. - println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES"); - if let Ok(features) = std::env::var("DEP_NGINX_FEATURES") { - for feature in features.split(',').map(str::trim) { - println!("cargo::rustc-cfg=ngx_feature=\"{feature}\""); - } - } - - // Specify acceptable values for `ngx_os` - println!("cargo::rerun-if-env-changed=DEP_NGINX_OS_CHECK"); - println!( - "cargo::rustc-check-cfg=cfg(ngx_os, values({}))", - std::env::var("DEP_NGINX_OS_CHECK").unwrap_or("any()".to_string()) - ); - // Read operating system detected by nginx-sys and pass to the compiler. - println!("cargo::rerun-if-env-changed=DEP_NGINX_OS"); - if let Ok(os) = std::env::var("DEP_NGINX_OS") { - println!("cargo::rustc-cfg=ngx_os=\"{os}\""); - } - - // Generate cfg values for version checks - const VERSION_CHECKS: &[(u64, &str)] = &[ - // - (1_021_001, "nginx1_21_1"), - (1_025_001, "nginx1_25_1"), - ]; - VERSION_CHECKS.iter().for_each(|check| println!("cargo::rustc-check-cfg=cfg({})", check.1)); - - println!("cargo::rerun-if-env-changed=DEP_NGINX_VERSION_NUMBER"); - if let Ok(version) = std::env::var("DEP_NGINX_VERSION_NUMBER") { - let version: u64 = version.parse().unwrap(); - - for check in VERSION_CHECKS { - if version >= check.0 { - println!("cargo::rustc-cfg={}", check.1); - } - } - } - - // Pass build directory to the tests - println!("cargo::rerun-if-env-changed=DEP_NGINX_BUILD_DIR"); - if let Ok(build_dir) = std::env::var("DEP_NGINX_BUILD_DIR") { - println!("cargo::rustc-env=DEP_NGINX_BUILD_DIR={build_dir}"); - } - - // Generate required compiler flags - if cfg!(target_os = "macos") { - // https://stackoverflow.com/questions/28124221/error-linking-with-cc-failed-exit-code-1 - println!("cargo::rustc-link-arg=-undefined"); - println!("cargo::rustc-link-arg=dynamic_lookup"); - } -} diff --git a/source/rust/vendor/ngx-rust/deny.toml b/source/rust/vendor/ngx-rust/deny.toml deleted file mode 100644 index a2b7132..0000000 --- a/source/rust/vendor/ngx-rust/deny.toml +++ /dev/null @@ -1,27 +0,0 @@ -[bans] -multiple-versions = "warn" - -[graph] -all-features = true - -[licenses] -allow = [ - "Apache-2.0", - "BSD-2-Clause", - "BSD-3-Clause", - "ISC", - "MIT", - "Unicode-3.0", -] -confidence-threshold = 0.8 - -[[licenses.exceptions]] -crate = "webpki-roots" -allow = ["CDLA-Permissive-2.0", "MPL-2.0"] - -[[licenses.clarify]] -crate = "ring" -expression = "MIT AND ISC AND OpenSSL" -license-files = [ - { path = "LICENSE", hash = 0xbd0eed23 } -] diff --git a/source/rust/vendor/ngx-rust/examples/Cargo.toml b/source/rust/vendor/ngx-rust/examples/Cargo.toml deleted file mode 100644 index 5419075..0000000 --- a/source/rust/vendor/ngx-rust/examples/Cargo.toml +++ /dev/null @@ -1,70 +0,0 @@ -[package] -name = "examples" -version = "0.0.0" -publish = false -edition.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -rust-version.workspace = true -# https://github.com/dependabot/dependabot-core/issues/1156 -autobins = false - -build = "../build.rs" - -[dependencies] -nginx-sys = { path = "../nginx-sys/" } -ngx = { path = "../", default-features = false, features = ["std"] } - -[dev-dependencies] -aws-sign-v4 = "0.3.0" -chrono = "0.4.27" -http = "1.1.0" -# use unicode-rs idna backend for lower MSRV and faster builds -idna_adapter = "=1.1.0" -libc = "0.2.168" -tokio = { version = "1.33.0", features = ["full"] } - -[[example]] -name = "curl" -path = "curl.rs" -crate-type = ["cdylib"] - -[[example]] -name = "awssig" -path = "awssig.rs" -crate-type = ["cdylib"] - -[[example]] -name = "httporigdst" -path = "httporigdst.rs" -crate-type = ["cdylib"] -required-features = ["linux"] - -[[example]] -name = "upstream" -path = "upstream.rs" -crate-type = ["cdylib"] - -[[example]] -name = "async" -path = "async.rs" -crate-type = ["cdylib"] - -[[example]] -name = "shared_dict" -path = "shared_dict.rs" -crate-type = ["cdylib"] - -[features] -default = ["export-modules", "ngx/vendored"] -# Generate `ngx_modules` table with module exports -# The exports table is required for building loadable modules with --crate-type cdylib -# outside of the NGINX buildsystem. However, cargo currently does not detect -# this configuration automatically. -# See https://github.com/rust-lang/rust/issues/20267 -export-modules = [] -linux = [] - -[lints] -workspace = true diff --git a/source/rust/vendor/ngx-rust/examples/README.md b/source/rust/vendor/ngx-rust/examples/README.md deleted file mode 100644 index e40e4db..0000000 --- a/source/rust/vendor/ngx-rust/examples/README.md +++ /dev/null @@ -1,226 +0,0 @@ -- [Examples](#examples) - - [CURL](#curl) - - [AWSSIG](#awssig) - - [HTTPORIGDST - NGINX Destination IP recovery module for HTTP](#httporigdst----nginx-destination-ip-recovery-module-for-http) - - [Dependencies](#dependencies) - - [Example Configuration](#example-configuration) - - [HTTP](#http) - - [Embedded Variables](#embedded-variables) - - [Usage](#usage) - - [Caveats](#caveats) - - -# Examples -This crate provides a couple of example using [ngx](https://crates.io/crates/ngx) crate: - -- [awssig.rs](./awssig.rs) - An example of NGINX dynamic module that can sign GET request using AWS Signature v4. -- [curl](./curl.rs) - An example of the Access Phase NGINX dynamic module that blocks HTTP requests if `user-agent` header starts with `curl`. -- [httporigdst](./httporigdst.rs) - A dynamic module recovers the original IP address and port number of the destination packet. -- [upstream](./upstream.rs) - A dynamic module demonstrating the setup code to write an upstream filter or load balancer. - -To build all these examples simply run: - -``` -cargo build --package=examples --examples -``` - - -## CURL - -This module demonstrates how to create a minimal dynamic module with `http_request_handler`, that checks for User-Agent headers and returns status code 403 if UA starts with `curl`, if a module is disabled then uses `core::Status::NGX_DECLINED` to indicate the operation is rejected, for example, because it is disabled in the configuration (`curl off`). Additionally, it demonstrates how to write a defective parser. - -An example of nginx configuration file that uses that module can be found at [curl.conf](./curl.conf). - -How to build and run in a [Docker](../Dockerfile) container curl example: -``` -# build all dynamic modules examples and specify NGINX version to use -docker buildx build --build-arg NGX_VERSION=1.23.3 -t ngx-rust . - -# start NGINX using curl.conf module example: -docker run --rm -d -p 8000:8000 ngx-rust nginx -c examples/curl.conf - -# test it - you should see 403 Forbidden -curl http://127.0.0.1:8000 -v -H "user-agent: curl" - - -# test it - you should see 404 Not Found -curl http://127.0.0.1:8000 -v -H "user-agent: foo" -``` - -## AWSSIG - -This module uses [NGX_HTTP_PRECONTENT_PHASE](https://nginx.org/en/docs/dev/development_guide.html#http_phases) and provides examples, of how to use external dependency and manipulate HTTP headers before sending client requests upstream. - -An example of nginx configuration file that uses that module can be found at [awssig.conf](./awssig.conf). - -## HTTPORIGDST - NGINX Destination IP recovery module for HTTP - -This dynamic module recovers the original IP address and port number of the destination packet. It is useful, for example, with container sidecars where all outgoing traffic is redirected to a separate container with iptables before reaching the target. - -This module can only be built with the "linux" feature enabled, and will only successfully build on a Linux OS. - -### Dependencies -This module uses the Rust crate libc and Linux **getsockopt** socket API. - -### Example Configuration -#### HTTP - -```nginx configuration -load_module "modules/libhttporigdst.so"; - -http { - server { - # use iptables to capture all outgoing traffic and REDIRECT - # to listening port 15501 - listen 15501; - - # binding variables provided by module will lazily activate it - # and store a context - # variables can be used in config - location / { - # Return if no backend is available or proxy_pass - # return 200 "recv'd: $server_addr:$server_port\n\nproxy_pass http://$server_orig_addr:$server_orig_port\n"; - proxy_pass http://$server_orig_addr:$server_orig_port; - } - } -} -``` - -### Embedded Variables - -The following embedded variables are provided: - -* **server_orig_addr** - * Original IP address -* **server_orig_port** - * Original port - -### Usage - -1. Clone the git repository. - ``` - git clone git@github.com:nginx/ngx-rust.git - ``` - -2. Compile the module from the cloned repo. - ``` - cd ${CLONED_DIRECTORY}/ngx-rust - cargo build --package=examples --example=httporigdst --features=linux - ``` - -3. Copy the shared object to the modules directory, /etc/nginx/modules. - ``` - cp ./target/debug/examples/libhttporigdst.so /etc/nginx/modules - ``` - -4. Add the `load_module` directive to your configuration. - ``` - load_module "modules/libhttporigdst.so"; - ``` - -5. Reload NGINX. - ``` - nginx -t && nginx -s reload - ``` - -6. Redirect traffic outbound. - ``` - iptables -t nat -N NGINX_REDIRECT && \ - iptables -t nat -A NGINX_REDIRECT -p tcp -j REDIRECT --to-port 15501 --dport 15001 && \ - iptables -t nat -N NGINX_OUTPUT && \ - iptables -t nat -A OUTPUT -p tcp -j NGINX_OUTPUT && \ - iptables -t nat -A NGINX_OUTPUT -j NGINX_REDIRECT - ``` - -7. Redirect traffic inbound. - ``` - iptables -t nat -N NGINX_IN_REDIRECT && \ - iptables -t nat -A NGINX_IN_REDIRECT -p tcp -j REDIRECT --to-port 15501 --dport 15001 && \ - iptables -t nat -N NGINX_INBOUND && \ - iptables -t nat -A PREROUTING -p tcp -j NGINX_INBOUND && \ - iptables -t nat -A NGINX_INBOUND -p tcp -j NGINX_IN_REDIRECT - ``` - -8. Test with `curl` (this step assumes you've uncommented the return directive). - ``` - curl --output - ${LISTEN_IP}:15001 - recv'd: ${LISTEN_IP}:15501 - - proxy_pass http://${LISTEN_IP}:15001 - ``` -### Caveats - -This module only supports IPv4. - -## UPSTREAM - Example upstream / load balancing module for HTTP - -This module simply proxies requests through a custom load balancer to the previously configured balancer. This is for demonstration purposes only. As a module writer, you can start with this structure and adjust to your needs, then implement the proper algorithm for your usage. - -The module replaces the `peer` callback functions with its own, logs, and then calls through to the originally saved `peer` functions. This may look confusing at first, but rest assured, it's intentionally not implementing an algorithm of its own. - -### Attributions - -This module was converted from https://github.com/gabihodoroaga/nginx-upstream-module and also highly inspired by the same techniques used in NGINX source: `ngx_http_upstream_keepalive_module.c`. - -### Example Configuration -#### HTTP - -```nginx configuration -load_module "modules/upstream.so" - -http { - upstream backend { - server localhost:15501; - custom 32; - } - - server { - listen 15500; - server_name _; - - location / { - proxy_pass http://backend; - } - } - - server { - listen 15501; - - location / { - return 418; - } - } -} -``` - -### Usage - -1. Clone the git repository. - ``` - git clone git@github.com:nginx/ngx-rust.git - ``` - -2. Compile the module from the cloned repo. - ``` - cd ${CLONED_DIRECTORY}/ngx-rust - cargo build --package=examples --example=upstream - ``` - -3. Copy the shared object to the modules directory, /etc/nginx/modules. - ``` - cp ./target/debug/examples/libupstream.so /etc/nginx/modules - ``` - -4. Add the `load_module` directive to your configuration. - ``` - load_module "modules/libupstream.so"; - ``` - -5. Add the example `server` and `upstream` block from the example above. - -6. Reload NGINX. - ``` - nginx -t && nginx -s reload - ``` - -7. Test with `curl`. Traffic should pass to your listener on port 8081 (this could be another NGINX server for example). With debug logging enabled you should notice the upstream log messages (see the source code for log examples, prefixed with "CUSTOM UPSTREAM"). diff --git a/source/rust/vendor/ngx-rust/examples/async.conf b/source/rust/vendor/ngx-rust/examples/async.conf deleted file mode 100644 index d96876e..0000000 --- a/source/rust/vendor/ngx-rust/examples/async.conf +++ /dev/null @@ -1,24 +0,0 @@ -daemon off; -master_process off; -# worker_processes 1; - -load_module modules/libasync.so; -error_log error.log debug; - -events { } - -http { - server { - listen *:8000; - server_name localhost; - location / { - root html; - index index.html index.htm; - async on; - } - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root html; - } - } -} diff --git a/source/rust/vendor/ngx-rust/examples/async.rs b/source/rust/vendor/ngx-rust/examples/async.rs deleted file mode 100644 index c1f9620..0000000 --- a/source/rust/vendor/ngx-rust/examples/async.rs +++ /dev/null @@ -1,237 +0,0 @@ -extern crate alloc; - -use alloc::sync::Arc; -use core::ffi::{c_char, c_void}; -use core::mem; -use core::ptr; -use core::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; -use core::time::Duration; -use std::sync::OnceLock; -use std::time::Instant; - -use ngx::core::Status; -use ngx::ffi::{ - NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, NGX_LOG_EMERG, - ngx_command_t, ngx_conf_t, ngx_connection_t, ngx_event_t, ngx_http_module_t, ngx_int_t, - ngx_module_t, ngx_post_event, ngx_posted_events, ngx_posted_next_events, ngx_str_t, ngx_uint_t, -}; -use ngx::http::{self, HttpModule, HttpModuleLocationConf, HttpRequestHandler, MergeConfigError}; -use ngx::{ngx_conf_log_error, ngx_log_debug_http, ngx_string}; -use tokio::runtime::Runtime; - -struct Module; - -impl http::HttpModule for Module { - fn module() -> &'static ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_async_module) } - } - - unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { - // SAFETY: this function is called with non-NULL cf always - let cf = unsafe { &mut *cf }; - http::add_phase_handler::(cf) - .map_or(Status::NGX_ERROR, |_| Status::NGX_OK) - .into() - } -} - -#[derive(Debug, Default)] -struct ModuleConfig { - enable: bool, -} - -unsafe impl HttpModuleLocationConf for Module { - type LocationConf = ModuleConfig; -} - -static mut NGX_HTTP_ASYNC_COMMANDS: [ngx_command_t; 2] = [ - ngx_command_t { - name: ngx_string!("async"), - type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_async_commands_set_enable), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t::empty(), -]; - -static NGX_HTTP_ASYNC_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { - preconfiguration: Some(Module::preconfiguration), - postconfiguration: Some(Module::postconfiguration), - create_main_conf: None, - init_main_conf: None, - create_srv_conf: None, - merge_srv_conf: None, - create_loc_conf: Some(Module::create_loc_conf), - merge_loc_conf: Some(Module::merge_loc_conf), -}; - -// Generate the `ngx_modules` table with exported modules. -// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. -#[cfg(feature = "export-modules")] -ngx::ngx_modules!(ngx_http_async_module); - -#[used] -#[allow(non_upper_case_globals)] -#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] -pub static mut ngx_http_async_module: ngx_module_t = ngx_module_t { - ctx: &raw const NGX_HTTP_ASYNC_MODULE_CTX as _, - commands: unsafe { &raw mut NGX_HTTP_ASYNC_COMMANDS[0] }, - type_: NGX_HTTP_MODULE as _, - ..ngx_module_t::default() -}; - -impl http::Merge for ModuleConfig { - fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { - if prev.enable { - self.enable = true; - }; - Ok(()) - } -} - -unsafe extern "C" fn check_async_work_done(event: *mut ngx_event_t) { - let ctx = ngx::ngx_container_of!(event, RequestCTX, event); - let c: *mut ngx_connection_t = unsafe { (*event).data.cast() }; - - if unsafe { (*ctx).done.load(Ordering::Relaxed) } { - // Triggering async_access_handler again - unsafe { ngx_post_event((*c).write, &raw mut ngx_posted_events) }; - } else { - // this doesn't have have good performance but works as a simple thread-safe example and - // doesn't causes segfault. The best method that provides both thread-safety and - // performance requires an nginx patch. - unsafe { ngx_post_event(event, &raw mut ngx_posted_next_events) }; - } -} - -struct RequestCTX { - done: Arc, - event: ngx_event_t, - task: Option>, -} - -impl Default for RequestCTX { - fn default() -> Self { - Self { - done: AtomicBool::new(false).into(), - event: unsafe { mem::zeroed() }, - task: Default::default(), - } - } -} - -impl Drop for RequestCTX { - fn drop(&mut self) { - if let Some(handle) = self.task.take() { - handle.abort(); - } - - if self.event.posted() != 0 { - unsafe { ngx::ffi::ngx_delete_posted_event(&raw mut self.event) }; - } - } -} - -struct AsyncAccessHandler; - -impl HttpRequestHandler for AsyncAccessHandler { - const PHASE: ngx::http::HttpPhase = ngx::http::HttpPhase::Access; - type Output = Status; - - fn handler(request: &mut http::Request) -> Self::Output { - let co = Module::location_conf(request).expect("module config is none"); - - ngx_log_debug_http!(request, "async module enabled: {}", co.enable); - - if !co.enable { - return Status::NGX_DECLINED; - } - - if let Some(ctx) = request.get_module_ctx::(Module::module()) { - if !ctx.done.load(Ordering::Relaxed) { - return Status::NGX_AGAIN; - } - - return Status::NGX_OK; - } - - let ctx = request.pool().allocate(RequestCTX::default()); - if ctx.is_null() { - return Status::NGX_ERROR; - } - request.set_module_ctx(ctx.cast(), Module::module()); - - let ctx = unsafe { &mut *ctx }; - ctx.event.handler = Some(check_async_work_done); - ctx.event.data = request.connection().cast(); - ctx.event.log = unsafe { (*request.connection()).log }; - unsafe { ngx_post_event(&raw mut ctx.event, &raw mut ngx_posted_next_events) }; - - // Request is no longer needed and can be converted to something movable to the async block - let req = AtomicPtr::new(request.into()); - let done_flag = ctx.done.clone(); - - let rt = ngx_http_async_runtime(); - ctx.task = Some(rt.spawn(async move { - let start = Instant::now(); - tokio::time::sleep(Duration::from_secs(2)).await; - let req = unsafe { http::Request::from_ngx_http_request(req.load(Ordering::Relaxed)) }; - // not really thread safe, we should apply all these operation in nginx thread - // but this is just an example. proper way would be storing these headers in the request - // ctx and apply them when we get back to the nginx thread. - req.add_header_out("X-Async-Time", start.elapsed().as_millis().to_string().as_str()); - - done_flag.store(true, Ordering::Release); - // there is a small issue here. If traffic is low we may get stuck behind a 300ms timer - // in the nginx event loop. To workaround it we can notify the event loop using - // pthread_kill( nginx_thread, SIGIO ) to wake up the event loop. (or patch nginx - // and use the same trick as the thread pool) - })); - - Status::NGX_AGAIN - } -} - -extern "C" fn ngx_http_async_commands_set_enable( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args: &[ngx_str_t] = (*(*cf).args).as_slice(); - let val = match args[1].to_str() { - Ok(s) => s, - Err(_) => { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "`async` argument is not utf-8 encoded"); - return ngx::core::NGX_CONF_ERROR; - } - }; - - // set default value optionally - conf.enable = false; - - if val.eq_ignore_ascii_case("on") { - conf.enable = true; - } else if val.eq_ignore_ascii_case("off") { - conf.enable = false; - } - }; - - ngx::core::NGX_CONF_OK -} - -fn ngx_http_async_runtime() -> &'static Runtime { - // Should not be called from the master process - assert_ne!(unsafe { ngx::ffi::ngx_process }, ngx::ffi::NGX_PROCESS_MASTER as _); - - static RUNTIME: OnceLock = OnceLock::new(); - RUNTIME.get_or_init(|| { - tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build() - .expect("tokio runtime init") - }) -} diff --git a/source/rust/vendor/ngx-rust/examples/auto/rust b/source/rust/vendor/ngx-rust/examples/auto/rust deleted file mode 100644 index f3f1032..0000000 --- a/source/rust/vendor/ngx-rust/examples/auto/rust +++ /dev/null @@ -1,351 +0,0 @@ -#!/bin/sh -# -# Copyright 2025 Nginx, Inc. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# -# Utility library for integration of ngx-rust modules into the NGINX build -# configuration. -# -# Usage: -# -# In "config", -# -# ```sh -# . $ngx_addon_dir/auto/rust -# -# # ngx_addon_name determines the build directory and should be set before -# # any modules are defined -# -# ngx_addon_name="example" -# -# if [ $HTTP = YES ]; then -# # Regular NGINX module options, -# # http://nginx.org/en/docs/dev/development_guide.html#adding_new_modules -# -# ngx_module_type=HTTP -# # Should match the "ngx_module_t" static name(s) exported from the Rust code -# ngx_module_name=ngx_http_example_module -# ngx_module_incs= -# ngx_module_deps= -# ngx_module_libs= -# -# # Options specific to ngx-rust modules -# -# # Target type: LIB or EXAMPLE -# ngx_rust_target_type=LIB -# -# # Target name: crate name, lib.name or example.name -# ngx_rust_target_name=example -# -# # Whitespace-separated list of cargo features. -# # "default" should be specified explicitly if required. -# ngx_rust_target_features= -# -# ngx_rust_module -# fi -# ``` -# -# In "config.make", -# -# ```sh -# ngx_addon_name="example" -# ngx_cargo_manifest=$ngx_addon_dir/Cargo.toml -# -# # generate Makefile section for all the modules configured earlier -# -# ngx_rust_make_modules -# ``` -# -# The following environment variables can affect the generated Makefile: -# -# - NGX_CARGO sets the "cargo" binary to use, e.g. NGX_CARGO=cargo-1.82 -# - NGX_RUST_TARGET passes the --target to the Rust compiler if set -# - NGX_RUSTC_OPT passes additional options to "cargo rustc" - -# Prevent duplicate invocation unless it is a newer library version -if [ "${NGX_RUST_AUTO_VER:-0}" -ge 1 ]; then - return -fi - -NGX_RUST_AUTO_VER=1 - -echo $ngx_n "checking for Rust toolchain ...$ngx_c" - -NGX_CARGO=${NGX_CARGO:-cargo} - -NGX_RUST_VER=$($NGX_CARGO version 2>&1 \ - | grep 'cargo 1\.[0-9][0-9]*\.[0-9]*' 2>&1 \ - | sed -e 's/^.* \(1\.[0-9][0-9]*\.[0-9][0.9]*.*\)/\1/') - -NGX_RUST_VERSION=${NGX_RUST_VER%% *} - -if [ -z "$NGX_RUST_VERSION" ]; then - echo " not found" - echo - echo $0: error: cargo binary $NGX_CARGO is not found - echo - exit 1 -fi - -echo " found" -echo " + Rust version: $NGX_RUST_VER" - -case "$NGX_MACHINE" in - - amd64) - RUST_TARGET_ARCH=x86_64 - ;; - - arm64) - RUST_TARGET_ARCH=aarch64 - ;; - - i?86) - RUST_TARGET_ARCH=i686 - ;; - - *) - RUST_TARGET_ARCH=$NGX_MACHINE - ;; - -esac - -case "$NGX_PLATFORM" in - - OpenBSD:*) - # ld: error: undefined symbol: _Unwind_... - RUST_LIBS="$RUST_LIBS -lutil" - RUST_LIBS="$RUST_LIBS -lexecinfo" - RUST_LIBS="$RUST_LIBS -lc++abi" - ;; - - win32) - case "$NGX_CC_NAME" in - - msvc) - # as suggested by rustc --print native-static-libs, - # excluding entries already present in CORE_LIBS - RUST_LIBS="$RUST_LIBS bcrypt.lib" # ??? - RUST_LIBS="$RUST_LIBS ntdll.lib" # std::io, std::sys::pal::windows - RUST_LIBS="$RUST_LIBS userenv.lib" # std::env::home_dir - RUST_LIBS="$RUST_LIBS dbghelp.lib" # backtrace symbolization - - NGX_RUST_TARGET=${NGX_RUST_TARGET:-$RUST_TARGET_ARCH-pc-windows-msvc} - ;; - - gcc | clang) - RUST_LIBS="$RUST_LIBS -lbcrypt" - RUST_LIBS="$RUST_LIBS -lntdll" - RUST_LIBS="$RUST_LIBS -luserenv" - RUST_LIBS="$RUST_LIBS -ldbghelp" - # gnullvm on arm64? - NGX_RUST_TARGET=${NGX_RUST_TARGET:-$RUST_TARGET_ARCH-pc-windows-gnu} - ;; - - esac - ;; - -esac - - -# Prepare cargo configuration file - -if [ "$NGX_DEBUG" = YES ]; then - ngx_cargo_default_profile=ngx-debug -else - ngx_cargo_default_profile=ngx-release -fi - -ngx_cargo_config=$NGX_OBJS/.cargo/config.toml -ngx_cargo_profile=${ngx_cargo_profile:-$ngx_cargo_default_profile} - -mkdir -p "$NGX_OBJS/.cargo" - -cat << END > "$ngx_cargo_config" - -[profile.ngx-debug] -inherits = "dev" - -[profile.ngx-release] -inherits = "release" -strip = "none" - -# compatibility with LIBC=-MT set in auto/cc/msvc -[target.aarch64-pc-windows-msvc] -rustflags = ["-C", "target-feature=+crt-static"] - -[target.i686-pc-windows-msvc] -rustflags = ["-C", "target-feature=+crt-static"] - -[target.x86_64-pc-windows-msvc] -rustflags = ["-C", "target-feature=+crt-static"] - -[env] -NGINX_BUILD_DIR = { value = ".", force = true, relative = true } -END - -if [ "$NGX_PLATFORM" = win32 ] && command -v cygpath >/dev/null; then - printf >> "$ngx_cargo_config" 'NGINX_SOURCE_DIR = "%s"\n' \ - "$(cygpath -m "$PWD")" -else - printf >> "$ngx_cargo_config" 'NGINX_SOURCE_DIR = "%s"\n' "$PWD" -fi - - -# Reconstructs path to a static lib built with cargo rustc, -# relative to the --target-dir - -ngx_rust_target_path () { - ngx_rust_obj=$(echo "$ngx_rust_target_name" | tr - _) - - case "$NGX_CC_NAME" in - - msvc) - ngx_rust_obj=${ngx_rust_obj}.lib - ;; - - *) - ngx_rust_obj=lib${ngx_rust_obj}.a - ;; - - esac - - if [ "$ngx_rust_target_type" = EXAMPLE ]; then - ngx_rust_obj=examples/$ngx_rust_obj - fi - - echo "${NGX_RUST_TARGET:+$NGX_RUST_TARGET/}$ngx_cargo_profile/$ngx_rust_obj" -} - - -# Registers a module in the buildsystem. -# In addition to the regular auto/module parameters, the following variables -# are expected to be set: -# -# ngx_rust_target_type=LIB|EXAMPLE -# ngx_rust_target_name= -# ngx_rust_target_features= -# -# [^1]: https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-name-field) - -ngx_rust_module () { - ngx_addon_id=$(echo "$ngx_addon_name" | sed -e 's/[^A-Za-z0-9_]/_/g') - ngx_rust_obj=$NGX_OBJS/$ngx_addon_id/$(ngx_rust_target_path) - - ngx_module_deps_saved=$ngx_module_deps - ngx_module_deps="$ngx_rust_obj $ngx_module_deps" - - ngx_module_libs_saved=$ngx_module_libs - ngx_module_libs="$ngx_rust_obj $ngx_module_libs $RUST_LIBS" - - if [ -n "$ngx_rust_target_features" ]; then - eval ${ngx_addon_id}_RUST_FEATURES=\"\$${ngx_addon_id}_RUST_FEATURES \ - $ngx_rust_target_features\" - fi - - . auto/module - - ngx_rust_target=$ngx_rust_target_type:$ngx_rust_target_name - - # module deps are usually added to the object file targets, but we don't have any - - if [ "$ngx_module_link" = DYNAMIC ]; then - # remember the dynamic module name and generate dependency later - ngx_rust_target=$ngx_rust_target:$ngx_module - else - # add dependency to the binary target - LINK_DEPS="$LINK_DEPS $ngx_rust_obj" - fi - - eval ${ngx_addon_id}_RUST_TARGETS=\"\$${ngx_addon_id}_RUST_TARGETS \ - $ngx_rust_target\" - - ngx_module_deps=$ngx_module_deps_saved - ngx_module_libs=$ngx_module_libs_saved -} - - -# Writes a Makefile fragment for all the modules configured for "ngx_addon_name" - -ngx_rust_make_modules () { - ngx_addon_id=$(echo "$ngx_addon_name" | sed -e 's/[^A-Za-z0-9_]/_/g') - ngx_cargo_manifest=${ngx_cargo_manifest:-"$ngx_addon_dir/Cargo.toml"} - - eval ngx_rust_features="\$${ngx_addon_id}_RUST_FEATURES" - eval ngx_rust_targets="\$${ngx_addon_id}_RUST_TARGETS" - - for target in $ngx_rust_targets; do - IFS=':' read -r ngx_rust_target_type ngx_rust_target_name ngx_rust_module_name <> $NGX_MAKEFILE - -.NGX_RUST_PHONY: ; - -END - fi - - cat << END >> $NGX_MAKEFILE - -$ngx_rust_obj: .NGX_RUST_PHONY - $NGX_CARGO rustc \\ - --config $ngx_cargo_config \\ - --crate-type staticlib \\ - --manifest-path "$ngx_cargo_manifest" \\ - --no-default-features \\ - --profile $ngx_cargo_profile \\ - ${NGX_RUST_TARGET:+--target $NGX_RUST_TARGET} \\ - --target-dir $NGX_OBJS/$ngx_addon_id \\ - --features "$ngx_rust_features" \\ - $ngx_rustc_module_opt $NGX_RUSTC_OPT - -END - - # Ensure that the "auto"-generated dynamic module target depends on the - # static library. Normally this is achieved by attaching ADDON_DEPS to - # the module object files, but we don't have any suitable C sources. - - if [ -n "$ngx_rust_module_name" ]; then - cat << END >> $NGX_MAKEFILE -$NGX_OBJS$ngx_dirsep$ngx_rust_module_name$ngx_modext: $ngx_rust_obj -END - fi -} diff --git a/source/rust/vendor/ngx-rust/examples/awssig.conf b/source/rust/vendor/ngx-rust/examples/awssig.conf deleted file mode 100644 index 5ff331e..0000000 --- a/source/rust/vendor/ngx-rust/examples/awssig.conf +++ /dev/null @@ -1,50 +0,0 @@ -daemon off; -master_process off; -# worker_processes 1; - -# on linix load a module: -load_module modules/libawssig.so; - -# error_log /dev/stdout debug; -error_log error.log debug; - -# working_directory /tmp/cores/; -# worker_rlimit_core 500M; - -events { } - -http { - server { - listen *:8000; - server_name localhost; - - awssigv4_access_key my-access-key; - awssigv4_secret_key my-secret-key; - awssigv4_s3_bucket my-bucket; - - location / { - awssigv4 on; - proxy_pass http://localhost:8777; - ## (on | off ) to enable aws sig v4 - location /some { - awssigv4 off; - } - ## awssigv4_s3_endpoint if not set then 's3.amazonaws.com' - # awssigv4_s3_endpoint s3.amazonaws.com; - } - - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root html; - } - } - server { - listen 8777; - server_name localhost; - location / { - add_header x-authorization $http_authorization; - add_header x-Amz-Date $http_x_amz_date; - return 204; - } - } -} diff --git a/source/rust/vendor/ngx-rust/examples/awssig.rs b/source/rust/vendor/ngx-rust/examples/awssig.rs deleted file mode 100644 index 0ff8c7c..0000000 --- a/source/rust/vendor/ngx-rust/examples/awssig.rs +++ /dev/null @@ -1,324 +0,0 @@ -use core::ffi::{c_char, c_void}; -use core::ptr; - -use http::HeaderMap; -use ngx::core::Status; -use ngx::ffi::{ - NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, - NGX_HTTP_SRV_CONF, NGX_LOG_EMERG, ngx_command_t, ngx_conf_t, ngx_http_module_t, ngx_int_t, - ngx_module_t, ngx_str_t, ngx_uint_t, -}; -use ngx::http::*; -use ngx::{ngx_conf_log_error, ngx_log_debug_http, ngx_string}; - -struct Module; - -impl HttpModule for Module { - fn module() -> &'static ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_awssigv4_module) } - } - - unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { - // SAFETY: this function is called with non-NULL cf always - let cf = unsafe { &mut *cf }; - ngx::http::add_phase_handler::(cf) - .map_or(Status::NGX_ERROR, |_| Status::NGX_OK) - .into() - } -} - -#[derive(Debug, Default)] -struct ModuleConfig { - enable: bool, - access_key: String, - secret_key: String, - s3_bucket: String, - s3_endpoint: String, -} - -unsafe impl HttpModuleLocationConf for Module { - type LocationConf = ModuleConfig; -} - -static mut NGX_HTTP_AWSSIGV4_COMMANDS: [ngx_command_t; 6] = [ - ngx_command_t { - name: ngx_string!("awssigv4"), - type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_awssigv4_commands_set_enable), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t { - name: ngx_string!("awssigv4_access_key"), - type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_awssigv4_commands_set_access_key), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t { - name: ngx_string!("awssigv4_secret_key"), - type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_awssigv4_commands_set_secret_key), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t { - name: ngx_string!("awssigv4_s3_bucket"), - type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_awssigv4_commands_set_s3_bucket), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t { - name: ngx_string!("awssigv4_s3_endpoint"), - type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_awssigv4_commands_set_s3_endpoint), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t::empty(), -]; - -static NGX_HTTP_AWSSIGV4_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { - preconfiguration: Some(Module::preconfiguration), - postconfiguration: Some(Module::postconfiguration), - create_main_conf: None, - init_main_conf: None, - create_srv_conf: None, - merge_srv_conf: None, - create_loc_conf: Some(Module::create_loc_conf), - merge_loc_conf: Some(Module::merge_loc_conf), -}; - -// Generate the `ngx_modules` table with exported modules. -// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. -#[cfg(feature = "export-modules")] -ngx::ngx_modules!(ngx_http_awssigv4_module); - -#[used] -#[allow(non_upper_case_globals)] -#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] -pub static mut ngx_http_awssigv4_module: ngx_module_t = ngx_module_t { - ctx: &raw const NGX_HTTP_AWSSIGV4_MODULE_CTX as _, - commands: unsafe { &raw mut NGX_HTTP_AWSSIGV4_COMMANDS[0] }, - type_: NGX_HTTP_MODULE as _, - ..ngx_module_t::default() -}; - -impl Merge for ModuleConfig { - fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { - if prev.enable { - self.enable = true; - }; - - if self.access_key.is_empty() { - self.access_key = - String::from(if !prev.access_key.is_empty() { &prev.access_key } else { "" }); - } - if self.enable && self.access_key.is_empty() { - return Err(MergeConfigError::NoValue); - } - - if self.secret_key.is_empty() { - self.secret_key = - String::from(if !prev.secret_key.is_empty() { &prev.secret_key } else { "" }); - } - if self.enable && self.secret_key.is_empty() { - return Err(MergeConfigError::NoValue); - } - - if self.s3_bucket.is_empty() { - self.s3_bucket = - String::from(if !prev.s3_bucket.is_empty() { &prev.s3_bucket } else { "" }); - } - if self.enable && self.s3_bucket.is_empty() { - return Err(MergeConfigError::NoValue); - } - - if self.s3_endpoint.is_empty() { - self.s3_endpoint = String::from(if !prev.s3_endpoint.is_empty() { - &prev.s3_endpoint - } else { - "s3.amazonaws.com" - }); - } - Ok(()) - } -} - -extern "C" fn ngx_http_awssigv4_commands_set_enable( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args: &[ngx_str_t] = (*(*cf).args).as_slice(); - let val = match args[1].to_str() { - Ok(s) => s, - Err(_) => { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "`awssigv4` argument is not utf-8 encoded"); - return ngx::core::NGX_CONF_ERROR; - } - }; - - // set default value optionally - conf.enable = false; - - if val.len() == 2 && val.eq_ignore_ascii_case("on") { - conf.enable = true; - } else if val.len() == 3 && val.eq_ignore_ascii_case("off") { - conf.enable = false; - } - }; - - ngx::core::NGX_CONF_OK -} - -extern "C" fn ngx_http_awssigv4_commands_set_access_key( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args: &[ngx_str_t] = (*(*cf).args).as_slice(); - conf.access_key = args[1].to_string(); - }; - - ngx::core::NGX_CONF_OK -} - -extern "C" fn ngx_http_awssigv4_commands_set_secret_key( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args: &[ngx_str_t] = (*(*cf).args).as_slice(); - conf.secret_key = args[1].to_string(); - }; - - ngx::core::NGX_CONF_OK -} - -extern "C" fn ngx_http_awssigv4_commands_set_s3_bucket( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args: &[ngx_str_t] = (*(*cf).args).as_slice(); - conf.s3_bucket = args[1].to_string(); - if conf.s3_bucket.len() == 1 { - println!("Validation failed"); - return ngx::core::NGX_CONF_ERROR; - } - }; - - ngx::core::NGX_CONF_OK -} - -extern "C" fn ngx_http_awssigv4_commands_set_s3_endpoint( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args = (*(*cf).args).elts as *mut ngx_str_t; - conf.s3_endpoint = (*args.add(1)).to_string(); - }; - - ngx::core::NGX_CONF_OK -} - -struct AwsSigV4HeaderHandler; - -impl HttpRequestHandler for AwsSigV4HeaderHandler { - const PHASE: HttpPhase = HttpPhase::PreContent; - type Output = Status; - - fn handler(request: &mut Request) -> Self::Output { - // get Module Config from request - let conf = Module::location_conf(request).expect("module conf"); - ngx_log_debug_http!(request, "AWS signature V4 module {}", { - if conf.enable { "enabled" } else { "disabled" } - }); - if !conf.enable { - return Status::NGX_DECLINED; - } - - // TODO: build url properly from the original URL from client - let method = request.method(); - if !matches!(method, ngx::http::Method::HEAD | ngx::http::Method::GET) { - return HTTPStatus::FORBIDDEN.into(); - } - - let datetime = chrono::Utc::now(); - let uri = match request.unparsed_uri().to_str() { - Ok(v) => format!("https://{}.{}{}", conf.s3_bucket, conf.s3_endpoint, v), - Err(_) => return Status::NGX_DECLINED, - }; - - let datetime_now = datetime.format("%Y%m%dT%H%M%SZ"); - let datetime_now = datetime_now.to_string(); - - let signature = { - // NOTE: aws_sign_v4::AwsSign::new() implementation requires a HeaderMap. - // Iterate over requests headers_in and copy into HeaderMap - // Copy only headers that will be used to sign the request - let mut headers = HeaderMap::new(); - for (name, value) in request.headers_in_iterator() { - if let Ok(name) = name.to_str() { - if name.to_lowercase() == "host" { - let Ok(value) = http::HeaderValue::from_bytes(value.as_bytes()) else { - return Status::NGX_DECLINED; - }; - - headers.insert(http::header::HOST, value); - } - } else { - return Status::NGX_DECLINED; - } - } - headers.insert("X-Amz-Date", datetime_now.parse().unwrap()); - ngx_log_debug_http!(request, "headers {:?}", headers); - ngx_log_debug_http!(request, "method {:?}", method); - ngx_log_debug_http!(request, "uri {:?}", uri); - ngx_log_debug_http!(request, "datetime_now {:?}", datetime_now); - - let s = aws_sign_v4::AwsSign::new( - method.as_str(), - &uri, - &datetime, - &headers, - "us-east-1", - conf.access_key.as_str(), - conf.secret_key.as_str(), - "s3", - "", - ); - s.sign() - }; - - request.add_header_in("authorization", signature.as_str()); - request.add_header_in("X-Amz-Date", datetime_now.as_str()); - - for (name, value) in request.headers_out_iterator() { - ngx_log_debug_http!(request, "headers_out {name}: {value}",); - } - for (name, value) in request.headers_in_iterator() { - ngx_log_debug_http!(request, "headers_in {name}: {value}",); - } - - Status::NGX_OK - } -} diff --git a/source/rust/vendor/ngx-rust/examples/awssig_curl_combined.conf b/source/rust/vendor/ngx-rust/examples/awssig_curl_combined.conf deleted file mode 100644 index 7956e0e..0000000 --- a/source/rust/vendor/ngx-rust/examples/awssig_curl_combined.conf +++ /dev/null @@ -1,53 +0,0 @@ -daemon off; -master_process off; -# worker_processes 1; - -# on linix load a module: -load_module modules/libawssig.so; -load_module modules/libcurl.so; - -# error_log /dev/stdout debug; -error_log error.log debug; - -# working_directory /tmp/cores/; -# worker_rlimit_core 500M; - -events { } - -http { - server { - listen *:8000; - server_name localhost; - - awssigv4_access_key my-access-key; - awssigv4_secret_key my-secret-key; - awssigv4_s3_bucket my-bucket; - - location / { - awssigv4 on; - curl on; - - proxy_pass http://localhost:8777; - ## (on | off ) to enable aws sig v4 - location /some { - awssigv4 off; - } - ## awssigv4_s3_endpoint if not set then 's3.amazonaws.com' - # awssigv4_s3_endpoint s3.amazonaws.com; - } - - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root html; - } - } - server { - listen 8777; - server_name localhost; - location / { - add_header x-authorization $http_authorization; - add_header x-Amz-Date $http_x_amz_date; - return 204; - } - } -} diff --git a/source/rust/vendor/ngx-rust/examples/config b/source/rust/vendor/ngx-rust/examples/config deleted file mode 100644 index 6b76365..0000000 --- a/source/rust/vendor/ngx-rust/examples/config +++ /dev/null @@ -1,66 +0,0 @@ -# shellcheck source=auto/rust -. $ngx_addon_dir/auto/rust - -# ngx_addon_name determines the build directory and should be set before -# any modules are defined - -ngx_addon_name=ngx_rust_examples - -if [ $HTTP = YES ]; then - ngx_module_type=HTTP - ngx_module_incs= - ngx_module_deps= - ngx_module_order= - - ngx_rust_target_type=EXAMPLE - ngx_rust_target_features= - - if :; then - ngx_module_name=ngx_http_async_module - ngx_module_libs="-lm" - ngx_rust_target_name=async - - ngx_rust_module - fi - - if :; then - ngx_module_name=ngx_http_awssigv4_module - ngx_module_libs="-lm" - ngx_rust_target_name=awssig - - ngx_rust_module - fi - - if :; then - ngx_module_name=ngx_http_curl_module - ngx_module_libs= - ngx_rust_target_name=curl - - ngx_rust_module - fi - - if :; then - ngx_module_name=ngx_http_shared_dict_module - ngx_module_libs= - ngx_rust_target_name=shared_dict - - ngx_rust_module - fi - - if :; then - ngx_module_name=ngx_http_upstream_custom_module - ngx_module_libs= - ngx_rust_target_name=upstream - - ngx_rust_module - fi - - if [ "$NGX_SYSTEM" = Linux ]; then - ngx_module_name=ngx_http_orig_dst_module - ngx_module_libs= - ngx_rust_target_name=httporigdst - ngx_rust_target_features=linux - - ngx_rust_module - fi -fi diff --git a/source/rust/vendor/ngx-rust/examples/config.make b/source/rust/vendor/ngx-rust/examples/config.make deleted file mode 100644 index 5e62127..0000000 --- a/source/rust/vendor/ngx-rust/examples/config.make +++ /dev/null @@ -1,6 +0,0 @@ -ngx_addon_name=ngx_rust_examples -ngx_cargo_manifest=$ngx_addon_dir/Cargo.toml - -# generate Makefile section for all the modules configured earlier - -ngx_rust_make_modules diff --git a/source/rust/vendor/ngx-rust/examples/curl.conf b/source/rust/vendor/ngx-rust/examples/curl.conf deleted file mode 100644 index 603fc15..0000000 --- a/source/rust/vendor/ngx-rust/examples/curl.conf +++ /dev/null @@ -1,31 +0,0 @@ -daemon off; -master_process off; -# worker_processes 1; - -# on linux load a module: -load_module modules/libcurl.so; - -# on mac os it would be dylib -# load_module modules/libcurl.dylib; - -# error_log /dev/stdout debug; -error_log error.log debug; - -events { } - -http { - server { - listen *:8000; - server_name localhost; - location / { - root html; - index index.html index.htm; - # libcurl module directive: - curl on; - } - error_page 500 502 503 504 /50x.html; - location = /50x.html { - root html; - } - } -} diff --git a/source/rust/vendor/ngx-rust/examples/curl.rs b/source/rust/vendor/ngx-rust/examples/curl.rs deleted file mode 100644 index be77920..0000000 --- a/source/rust/vendor/ngx-rust/examples/curl.rs +++ /dev/null @@ -1,136 +0,0 @@ -use core::ffi::{c_char, c_void}; -use core::ptr; - -use ngx::core::Status; -use ngx::ffi::{ - NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, NGX_LOG_EMERG, - ngx_command_t, ngx_conf_t, ngx_http_module_t, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t, -}; -use ngx::http::{self, HttpModule, HttpModuleLocationConf, HttpRequestHandler, MergeConfigError}; -use ngx::{ngx_conf_log_error, ngx_log_debug_http, ngx_string}; - -struct Module; - -impl http::HttpModule for Module { - fn module() -> &'static ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_curl_module) } - } - - unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { - // SAFETY: this function is called with non-NULL cf always - let cf = unsafe { &mut *cf }; - http::add_phase_handler::(cf) - .map_or(Status::NGX_ERROR, |_| Status::NGX_OK) - .into() - } -} - -#[derive(Debug, Default)] -struct ModuleConfig { - enable: bool, -} - -unsafe impl HttpModuleLocationConf for Module { - type LocationConf = ModuleConfig; -} - -static mut NGX_HTTP_CURL_COMMANDS: [ngx_command_t; 2] = [ - ngx_command_t { - name: ngx_string!("curl"), - type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_curl_commands_set_enable), - conf: NGX_HTTP_LOC_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t::empty(), -]; - -static NGX_HTTP_CURL_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { - preconfiguration: Some(Module::preconfiguration), - postconfiguration: Some(Module::postconfiguration), - create_main_conf: None, - init_main_conf: None, - create_srv_conf: None, - merge_srv_conf: None, - create_loc_conf: Some(Module::create_loc_conf), - merge_loc_conf: Some(Module::merge_loc_conf), -}; - -// Generate the `ngx_modules` table with exported modules. -// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. -#[cfg(feature = "export-modules")] -ngx::ngx_modules!(ngx_http_curl_module); - -#[used] -#[allow(non_upper_case_globals)] -#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] -pub static mut ngx_http_curl_module: ngx_module_t = ngx_module_t { - ctx: &raw const NGX_HTTP_CURL_MODULE_CTX as _, - commands: unsafe { &raw mut NGX_HTTP_CURL_COMMANDS[0] }, - type_: NGX_HTTP_MODULE as _, - ..ngx_module_t::default() -}; - -impl http::Merge for ModuleConfig { - fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { - if prev.enable { - self.enable = true; - }; - Ok(()) - } -} - -struct CurlRequestHandler; - -impl HttpRequestHandler for CurlRequestHandler { - const PHASE: ngx::http::HttpPhase = ngx::http::HttpPhase::Access; - type Output = Status; - - fn handler(request: &mut http::Request) -> Self::Output { - let co = Module::location_conf(request).expect("module config is none"); - - ngx_log_debug_http!(request, "curl module enabled: {}", co.enable); - - match co.enable { - true => { - if request.user_agent().is_some_and(|ua| ua.as_bytes().starts_with(b"curl")) { - http::HTTPStatus::FORBIDDEN.into() - } else { - Status::NGX_DECLINED - } - } - false => Status::NGX_DECLINED, - } - } -} - -extern "C" fn ngx_http_curl_commands_set_enable( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - unsafe { - let conf = &mut *(conf as *mut ModuleConfig); - let args: &[ngx_str_t] = (*(*cf).args).as_slice(); - - let val = match args[1].to_str() { - Ok(s) => s, - Err(_) => { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "`curl` argument is not utf-8 encoded"); - return ngx::core::NGX_CONF_ERROR; - } - }; - - // set default value optionally - conf.enable = false; - - if val.len() == 2 && val.eq_ignore_ascii_case("on") { - conf.enable = true; - } else if val.len() == 3 && val.eq_ignore_ascii_case("off") { - conf.enable = false; - } - }; - - ngx::core::NGX_CONF_OK -} diff --git a/source/rust/vendor/ngx-rust/examples/httporigdst.conf b/source/rust/vendor/ngx-rust/examples/httporigdst.conf deleted file mode 100644 index 6fff8c2..0000000 --- a/source/rust/vendor/ngx-rust/examples/httporigdst.conf +++ /dev/null @@ -1,16 +0,0 @@ -http { - server { - # use iptables to capture all outgoing traffic and REDIRECT - # to listening port 15501 - listen 15501; - - # binding variables provided by module will lazily activate it - # and store a context - # variables can be used in config - location / { - # Return if no backend is available or proxy_pass - # return 200 "recv'd: $server_addr:$server_port\n\nproxy_pass http://$server_orig_addr:$server_orig_port\n"; - proxy_pass http://$server_orig_addr:$server_orig_port; - } - } -} \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/examples/httporigdst.rs b/source/rust/vendor/ngx-rust/examples/httporigdst.rs deleted file mode 100644 index 2eda38d..0000000 --- a/source/rust/vendor/ngx-rust/examples/httporigdst.rs +++ /dev/null @@ -1,283 +0,0 @@ -use core::ffi::{c_int, c_void}; -use core::mem; -use core::ptr::{self, NonNull}; - -use ngx::core::{Pool, Status}; -use ngx::ffi::{ - INET_ADDRSTRLEN, NGX_HTTP_MODULE, in_port_t, ngx_conf_t, ngx_connection_local_sockaddr, - ngx_http_add_variable, ngx_http_module_t, ngx_http_variable_t, ngx_inet_get_port, ngx_int_t, - ngx_module_t, ngx_sock_ntop, ngx_str_t, ngx_variable_value_t, sockaddr, sockaddr_storage, -}; -use ngx::http::{self, HttpModule}; -use ngx::{http_variable_get, ngx_log_debug_http, ngx_string}; - -const IPV4_STRLEN: usize = INET_ADDRSTRLEN as usize; - -#[derive(Debug, Default)] -struct NgxHttpOrigDstCtx { - orig_dst_addr: ngx_str_t, - orig_dst_port: ngx_str_t, -} - -impl NgxHttpOrigDstCtx { - pub fn save(&mut self, addr: &str, port: in_port_t, pool: &Pool) -> Status { - let addr_data = pool.alloc_unaligned(addr.len()); - if addr_data.is_null() { - return Status::NGX_ERROR; - } - unsafe { libc::memcpy(addr_data, addr.as_ptr() as *const c_void, addr.len()) }; - self.orig_dst_addr.len = addr.len(); - self.orig_dst_addr.data = addr_data as *mut u8; - - let port_str = port.to_string(); - let port_data = pool.alloc_unaligned(port_str.len()); - if port_data.is_null() { - return Status::NGX_ERROR; - } - unsafe { - libc::memcpy(port_data, port_str.as_bytes().as_ptr() as *const c_void, port_str.len()) - }; - self.orig_dst_port.len = port_str.len(); - self.orig_dst_port.data = port_data as *mut u8; - - Status::NGX_OK - } - - pub unsafe fn bind_addr(&self, v: *mut ngx_variable_value_t) { - let mut v = NonNull::new(v).unwrap(); - let v = unsafe { v.as_mut() }; - if self.orig_dst_addr.len == 0 { - v.set_not_found(1); - return; - } - - v.set_valid(1); - v.set_no_cacheable(0); - v.set_not_found(0); - v.set_len(self.orig_dst_addr.len as u32); - v.data = self.orig_dst_addr.data; - } - - pub unsafe fn bind_port(&self, v: *mut ngx_variable_value_t) { - let mut v = NonNull::new(v).unwrap(); - let v = unsafe { v.as_mut() }; - if self.orig_dst_port.len == 0 { - v.set_not_found(1); - return; - } - - v.set_valid(1); - v.set_no_cacheable(0); - v.set_not_found(0); - v.set_len(self.orig_dst_port.len as u32); - v.data = self.orig_dst_port.data; - } -} - -static NGX_HTTP_ORIG_DST_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { - preconfiguration: Some(Module::preconfiguration), - postconfiguration: Some(Module::postconfiguration), - create_main_conf: None, - init_main_conf: None, - create_srv_conf: None, - merge_srv_conf: None, - create_loc_conf: None, - merge_loc_conf: None, -}; - -// Generate the `ngx_modules` table with exported modules. -// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. -#[cfg(feature = "export-modules")] -ngx::ngx_modules!(ngx_http_orig_dst_module); - -#[used] -#[allow(non_upper_case_globals)] -#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] -pub static mut ngx_http_orig_dst_module: ngx_module_t = ngx_module_t { - ctx: &raw const NGX_HTTP_ORIG_DST_MODULE_CTX as _, - commands: ptr::null_mut(), - type_: NGX_HTTP_MODULE as _, - ..ngx_module_t::default() -}; - -static mut NGX_HTTP_ORIG_DST_VARS: [ngx_http_variable_t; 2] = [ - // ngx_str_t name - // ngx_http_set_variable_pt set_handler - // ngx_http_get_variable_pt get_handler - // uintptr_t data - // ngx_uint_t flags - // ngx_uint_t index - ngx_http_variable_t { - name: ngx_string!("server_orig_addr"), - set_handler: None, - get_handler: Some(ngx_http_orig_dst_addr_variable), - data: 0, - flags: 0, - index: 0, - }, - ngx_http_variable_t { - name: ngx_string!("server_orig_port"), - set_handler: None, - get_handler: Some(ngx_http_orig_dst_port_variable), - data: 0, - flags: 0, - index: 0, - }, -]; - -unsafe fn ngx_get_origdst(request: &mut http::Request) -> Result<(String, in_port_t), Status> { - let c = request.connection(); - - if unsafe { (*c).type_ } != libc::SOCK_STREAM { - ngx_log_debug_http!(request, "httporigdst: connection is not type SOCK_STREAM"); - return Err(Status::NGX_DECLINED); - } - - if unsafe { ngx_connection_local_sockaddr(c, ptr::null_mut(), 0) } != Status::NGX_OK.into() { - ngx_log_debug_http!(request, "httporigdst: no local sockaddr from connection"); - return Err(Status::NGX_ERROR); - } - - let level: c_int; - let optname: c_int; - match unsafe { (*(*c).local_sockaddr).sa_family } as i32 { - libc::AF_INET => { - level = libc::SOL_IP; - optname = libc::SO_ORIGINAL_DST; - } - _ => { - ngx_log_debug_http!(request, "httporigdst: only support IPv4"); - return Err(Status::NGX_DECLINED); - } - } - - let mut addr: sockaddr_storage = unsafe { mem::zeroed() }; - let mut addrlen: libc::socklen_t = mem::size_of_val(&addr) as libc::socklen_t; - let rc = unsafe { - libc::getsockopt((*c).fd, level, optname, (&raw mut addr).cast(), &raw mut addrlen) - }; - if rc == -1 { - ngx_log_debug_http!(request, "httporigdst: getsockopt failed"); - return Err(Status::NGX_DECLINED); - } - let mut ip: Vec = vec![0; IPV4_STRLEN]; - let e = unsafe { - ngx_sock_ntop( - (&raw mut addr).cast(), - mem::size_of::() as u32, - ip.as_mut_ptr(), - IPV4_STRLEN, - 0, - ) - }; - if e == 0 { - ngx_log_debug_http!(request, "httporigdst: ngx_sock_ntop failed to convert sockaddr"); - return Err(Status::NGX_ERROR); - } - ip.truncate(e); - - let port = unsafe { ngx_inet_get_port((&raw mut addr).cast()) }; - - Ok((String::from_utf8(ip).unwrap(), port)) -} - -http_variable_get!( - ngx_http_orig_dst_addr_variable, - |request: &mut http::Request, v: *mut ngx_variable_value_t, _: usize| { - let ctx = request.get_module_ctx::(Module::module()); - if let Some(obj) = ctx { - ngx_log_debug_http!(request, "httporigdst: found context and binding variable",); - unsafe { obj.bind_addr(v) }; - return Status::NGX_OK; - } - // lazy initialization: - // get original dest information - // create context - // set context - // bind address - ngx_log_debug_http!(request, "httporigdst: context not found, getting address"); - let r = unsafe { ngx_get_origdst(request) }; - match r { - Err(e) => { - return e; - } - Ok((ip, port)) => { - // create context, - // set context - let new_ctx = request.pool().allocate::(Default::default()); - - if new_ctx.is_null() { - return Status::NGX_ERROR; - } - - ngx_log_debug_http!(request, "httporigdst: saving ip - {:?}, port - {}", ip, port,); - unsafe { (*new_ctx).save(&ip, port, &request.pool()) }; - unsafe { (*new_ctx).bind_addr(v) }; - request.set_module_ctx(new_ctx as *mut c_void, Module::module()); - } - } - Status::NGX_OK - } -); - -http_variable_get!( - ngx_http_orig_dst_port_variable, - |request: &mut http::Request, v: *mut ngx_variable_value_t, _: usize| { - let ctx = request.get_module_ctx::(Module::module()); - if let Some(obj) = ctx { - ngx_log_debug_http!(request, "httporigdst: found context and binding variable",); - unsafe { obj.bind_port(v) }; - return Status::NGX_OK; - } - // lazy initialization: - // get original dest information - // create context - // set context - // bind port - ngx_log_debug_http!(request, "httporigdst: context not found, getting address"); - let r = unsafe { ngx_get_origdst(request) }; - match r { - Err(e) => { - return e; - } - Ok((ip, port)) => { - // create context, - // set context - let new_ctx = request.pool().allocate::(Default::default()); - - if new_ctx.is_null() { - return Status::NGX_ERROR; - } - - ngx_log_debug_http!(request, "httporigdst: saving ip - {:?}, port - {}", ip, port,); - unsafe { (*new_ctx).save(&ip, port, &request.pool()) }; - unsafe { (*new_ctx).bind_port(v) }; - request.set_module_ctx(new_ctx as *mut c_void, Module::module()); - } - } - Status::NGX_OK - } -); - -struct Module; - -impl HttpModule for Module { - fn module() -> &'static ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_orig_dst_module) } - } - - // static ngx_int_t ngx_http_orig_dst_add_variables(ngx_conf_t *cf) - unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { - for mut v in unsafe { NGX_HTTP_ORIG_DST_VARS } { - let var = NonNull::new(unsafe { ngx_http_add_variable(cf, &raw mut v.name, v.flags) }); - if var.is_none() { - return Status::NGX_ERROR.into(); - } - let mut var = var.unwrap(); - let var = unsafe { var.as_mut() }; - var.get_handler = v.get_handler; - var.data = v.data; - } - Status::NGX_OK.into() - } -} diff --git a/source/rust/vendor/ngx-rust/examples/shared_dict.rs b/source/rust/vendor/ngx-rust/examples/shared_dict.rs deleted file mode 100644 index d88ebdb..0000000 --- a/source/rust/vendor/ngx-rust/examples/shared_dict.rs +++ /dev/null @@ -1,425 +0,0 @@ -#![no_std] -use core::ffi::{c_char, c_void}; -use core::mem; -use core::ptr::{self, NonNull}; - -use nginx_sys::{ - NGX_CONF_TAKE2, NGX_HTTP_DELETE, NGX_HTTP_MAIN_CONF, NGX_HTTP_MAIN_CONF_OFFSET, - NGX_HTTP_MODULE, NGX_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, NGX_LOG_EMERG, - ngx_command_t, ngx_conf_t, ngx_http_add_variable, ngx_http_compile_complex_value_t, - ngx_http_complex_value, ngx_http_complex_value_t, ngx_http_module_t, ngx_http_request_t, - ngx_http_variable_t, ngx_http_variable_value_t, ngx_int_t, ngx_module_t, ngx_parse_size, - ngx_shared_memory_add, ngx_shm_zone_t, ngx_str_t, ngx_uint_t, -}; -use ngx::collections::RbTreeMap; -use ngx::core::{NGX_CONF_ERROR, NGX_CONF_OK, NgxStr, NgxString, Pool, SlabPool, Status}; -use ngx::http::{HttpModule, HttpModuleMainConf}; -use ngx::{ngx_conf_log_error, ngx_log_debug, ngx_string}; - -struct HttpSharedDictModule; - -impl HttpModule for HttpSharedDictModule { - fn module() -> &'static ngx_module_t { - unsafe { &*ptr::addr_of!(ngx_http_shared_dict_module) } - } - - unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { - for mut v in unsafe { NGX_HTTP_SHARED_DICT_VARS } { - let var = NonNull::new(unsafe { ngx_http_add_variable(cf, &raw mut v.name, v.flags) }); - if var.is_none() { - return Status::NGX_ERROR.into(); - } - let var = unsafe { var.unwrap().as_mut() }; - var.get_handler = v.get_handler; - var.set_handler = v.set_handler; - var.data = v.data; - } - Status::NGX_OK.into() - } -} - -unsafe impl HttpModuleMainConf for HttpSharedDictModule { - type MainConf = SharedDictMainConfig; -} - -static mut NGX_HTTP_SHARED_DICT_COMMANDS: [ngx_command_t; 3] = [ - ngx_command_t { - name: ngx_string!("shared_dict_zone"), - type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, - set: Some(ngx_http_shared_dict_add_zone), - conf: NGX_HTTP_MAIN_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t { - name: ngx_string!("shared_dict"), - type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, - set: Some(ngx_http_shared_dict_add_variable), - conf: NGX_HTTP_MAIN_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t::empty(), -]; - -static mut NGX_HTTP_SHARED_DICT_VARS: [ngx_http_variable_t; 1] = [ngx_http_variable_t { - name: ngx_string!("shared_dict_entries"), - set_handler: Some(ngx_http_shared_dict_set_entries), - get_handler: Some(ngx_http_shared_dict_get_entries), - data: 0, - flags: (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, - index: 0, -}]; - -static NGX_HTTP_SHARED_DICT_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { - preconfiguration: Some(HttpSharedDictModule::preconfiguration), - postconfiguration: None, - create_main_conf: Some(HttpSharedDictModule::create_main_conf), - init_main_conf: None, - create_srv_conf: None, - merge_srv_conf: None, - create_loc_conf: None, - merge_loc_conf: None, -}; - -// Generate the `ngx_modules` table with exported modules. -// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. -#[cfg(feature = "export-modules")] -ngx::ngx_modules!(ngx_http_shared_dict_module); - -#[used] -#[allow(non_upper_case_globals)] -#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] -pub static mut ngx_http_shared_dict_module: ngx_module_t = ngx_module_t { - ctx: &raw const NGX_HTTP_SHARED_DICT_MODULE_CTX as _, - commands: unsafe { &raw mut NGX_HTTP_SHARED_DICT_COMMANDS[0] }, - type_: NGX_HTTP_MODULE as _, - ..ngx_module_t::default() -}; - -type SharedData = ngx::sync::RwLock, NgxString, SlabPool>>; - -#[derive(Debug)] -struct SharedDictMainConfig { - shm_zone: *mut ngx_shm_zone_t, -} - -impl Default for SharedDictMainConfig { - fn default() -> Self { - Self { shm_zone: ptr::null_mut() } - } -} - -extern "C" fn ngx_http_shared_dict_add_zone( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - // SAFETY: configuration handlers always receive a valid `cf` pointer. - let cf = unsafe { cf.as_mut().unwrap() }; - let smcf = - unsafe { conf.cast::().as_mut().expect("shared dict main config") }; - - // SAFETY: - // - `cf.args` is guaranteed to be a pointer to an array with 3 elements (NGX_CONF_TAKE2). - // - The pointers are well-aligned by construction method (`ngx_palloc`). - debug_assert!(!cf.args.is_null() && unsafe { (*cf.args).nelts >= 3 }); - let args = unsafe { (*cf.args).as_slice_mut() }; - - let mut name: ngx_str_t = args[1]; - let size = unsafe { ngx_parse_size(&raw mut args[2]) }; - if size == -1 { - return NGX_CONF_ERROR; - } - - smcf.shm_zone = unsafe { - ngx_shared_memory_add( - cf, - &raw mut name, - size as usize, - (&raw mut ngx_http_shared_dict_module).cast(), - ) - }; - - let Some(shm_zone) = (unsafe { smcf.shm_zone.as_mut() }) else { - return NGX_CONF_ERROR; - }; - - shm_zone.init = Some(ngx_http_shared_dict_zone_init); - shm_zone.data = ptr::from_mut(smcf).cast(); - - NGX_CONF_OK -} - -fn ngx_http_shared_dict_get_shared(shm_zone: &mut ngx_shm_zone_t) -> Result<&SharedData, Status> { - let mut alloc = unsafe { SlabPool::from_shm_zone(shm_zone) }.ok_or(Status::NGX_ERROR)?; - - if alloc.as_mut().data.is_null() { - let shared: RbTreeMap, NgxString, SlabPool> = - RbTreeMap::try_new_in(alloc.clone()).map_err(|_| Status::NGX_ERROR)?; - - let shared = ngx::sync::RwLock::new(shared); - - alloc.as_mut().data = ngx::allocator::allocate(shared, &alloc) - .map_err(|_| Status::NGX_ERROR)? - .as_ptr() - .cast(); - } - - unsafe { alloc.as_ref().data.cast::().as_ref().ok_or(Status::NGX_ERROR) } -} - -extern "C" fn ngx_http_shared_dict_zone_init( - shm_zone: *mut ngx_shm_zone_t, - _data: *mut c_void, -) -> ngx_int_t { - let shm_zone = unsafe { &mut *shm_zone }; - - match ngx_http_shared_dict_get_shared(shm_zone) { - Err(e) => e.into(), - Ok(_) => Status::NGX_OK.into(), - } -} - -extern "C" fn ngx_http_shared_dict_add_variable( - cf: *mut ngx_conf_t, - _cmd: *mut ngx_command_t, - _conf: *mut c_void, -) -> *mut c_char { - // SAFETY: configuration handlers always receive a valid `cf` pointer. - let cf = unsafe { cf.as_mut().unwrap() }; - let pool = unsafe { Pool::from_ngx_pool(cf.pool) }; - - let key = pool.calloc_type::(); - if key.is_null() { - return NGX_CONF_ERROR; - } - - // SAFETY: - // - `cf.args` is guaranteed to be a pointer to an array with 3 elements (NGX_CONF_TAKE2). - // - The pointers are well-aligned by construction method (`ngx_palloc`). - debug_assert!(!cf.args.is_null() && unsafe { (*cf.args).nelts >= 3 }); - let args = unsafe { (*cf.args).as_slice_mut() }; - - let mut ccv: ngx_http_compile_complex_value_t = unsafe { mem::zeroed() }; - ccv.cf = cf; - ccv.value = &raw mut args[1]; - ccv.complex_value = key; - - if unsafe { nginx_sys::ngx_http_compile_complex_value(&raw mut ccv) } != Status::NGX_OK.into() { - return NGX_CONF_ERROR; - } - - let mut name = args[2]; - - if name.as_bytes()[0] != b'$' { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "invalid variable name \"{name}\""); - return NGX_CONF_ERROR; - } - - name.data = unsafe { name.data.add(1) }; - name.len -= 1; - - let var = unsafe { - ngx_http_add_variable( - cf, - &raw mut name, - (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, - ) - }; - if var.is_null() { - return NGX_CONF_ERROR; - } - - unsafe { - (*var).get_handler = Some(ngx_http_shared_dict_get_variable); - (*var).set_handler = Some(ngx_http_shared_dict_set_variable); - (*var).data = key as usize; - } - - NGX_CONF_OK -} - -extern "C" fn ngx_http_shared_dict_get_variable( - r: *mut ngx_http_request_t, - v: *mut ngx_http_variable_value_t, - data: usize, -) -> ngx_int_t { - let r = unsafe { &mut *r }; - let v = unsafe { &mut *v }; - let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); - - let mut key = ngx_str_t::empty(); - if unsafe { ngx_http_complex_value(r, data as _, &raw mut key) } != Status::NGX_OK.into() { - return Status::NGX_ERROR.into(); - } - - let key = unsafe { NgxStr::from_ngx_str(key) }; - - let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { - return Status::NGX_ERROR.into(); - }; - - let value = - shared.read().get(key).and_then(|x| unsafe { ngx_str_t::from_bytes(r.pool, x.as_bytes()) }); - - ngx_log_debug!( - unsafe { (*r.connection).log }, - "shared dict: get \"{}\" -> {:?} w:{} p:{}", - key, - value.as_ref().map(|x| unsafe { NgxStr::from_ngx_str(*x) }), - unsafe { nginx_sys::ngx_worker }, - unsafe { nginx_sys::ngx_pid }, - ); - - let Some(value) = value else { - v.set_not_found(1); - return Status::NGX_ERROR.into(); - }; - - v.data = value.data; - v.set_len(value.len as _); - - v.set_valid(1); - v.set_no_cacheable(0); - v.set_not_found(0); - - Status::NGX_OK.into() -} - -extern "C" fn ngx_http_shared_dict_set_variable( - r: *mut ngx_http_request_t, - v: *mut ngx_http_variable_value_t, - data: usize, -) { - let r = unsafe { &mut *r }; - let v = unsafe { &mut *v }; - let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); - let mut key = ngx_str_t::empty(); - - if unsafe { ngx_http_complex_value(r, data as _, &raw mut key) } != Status::NGX_OK.into() { - return; - } - - let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { - return; - }; - - if r.method == NGX_HTTP_DELETE as _ { - let key = unsafe { NgxStr::from_ngx_str(key) }; - - ngx_log_debug!( - unsafe { (*r.connection).log }, - "shared dict: delete \"{}\" w:{} p:{}", - key, - unsafe { nginx_sys::ngx_worker }, - unsafe { nginx_sys::ngx_pid }, - ); - - let _ = shared.write().remove(key); - } else { - let alloc = unsafe { SlabPool::from_shm_zone(&*smcf.shm_zone).expect("slab pool") }; - - let Ok(key) = NgxString::try_from_bytes_in(key.as_bytes(), alloc.clone()) else { - return; - }; - - let Ok(value) = NgxString::try_from_bytes_in(v.as_bytes(), alloc.clone()) else { - return; - }; - - ngx_log_debug!( - unsafe { (*r.connection).log }, - "shared dict: set \"{}\" -> \"{}\" w:{} p:{}", - key, - value, - unsafe { nginx_sys::ngx_worker }, - unsafe { nginx_sys::ngx_pid }, - ); - - let _ = shared.write().try_insert(key, value); - } -} - -extern "C" fn ngx_http_shared_dict_get_entries( - r: *mut ngx_http_request_t, - v: *mut ngx_http_variable_value_t, - _data: usize, -) -> ngx_int_t { - use core::fmt::Write; - - let r = unsafe { &mut *r }; - let v = unsafe { &mut *v }; - let pool = unsafe { Pool::from_ngx_pool(r.pool) }; - let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); - - ngx_log_debug!(unsafe { (*r.connection).log }, "shared dict: get all entries"); - - let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { - return Status::NGX_ERROR.into(); - }; - - let mut str = NgxString::new_in(pool); - { - let dict = shared.read(); - - let mut len: usize = 0; - let mut values: usize = 0; - - for (key, value) in dict.iter() { - len += key.len() + value.len() + b" = ; ".len(); - values += 1; - } - - len += values.checked_ilog10().unwrap_or(0) as usize + b"0; ".len(); - - if str.try_reserve(len).is_err() { - return Status::NGX_ERROR.into(); - } - - if write!(str, "{values}; ").is_err() { - return Status::NGX_ERROR.into(); - } - - for (key, value) in dict.iter() { - if write!(str, "{key} = {value}; ").is_err() { - return Status::NGX_ERROR.into(); - } - } - } - - // The string is allocated on the `ngx_pool_t` and will be freed with the request. - let (data, len, _, _) = str.into_raw_parts(); - - v.data = data; - v.set_len(len as _); - - v.set_valid(1); - v.set_no_cacheable(1); - v.set_not_found(0); - - Status::NGX_OK.into() -} - -extern "C" fn ngx_http_shared_dict_set_entries( - r: *mut ngx_http_request_t, - _v: *mut ngx_http_variable_value_t, - _data: usize, -) { - let r = unsafe { &mut *r }; - let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); - - ngx_log_debug!(unsafe { (*r.connection).log }, "shared dict: clear"); - - let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { - return; - }; - - let Ok(tree) = RbTreeMap::try_new_in(shared.read().allocator().clone()) else { - return; - }; - - // This would check both .clear() and the drop implementation - *shared.write() = tree; - // shared.write().clear() -} diff --git a/source/rust/vendor/ngx-rust/examples/t/async.t b/source/rust/vendor/ngx-rust/examples/t/async.t deleted file mode 100644 index 98505fd..0000000 --- a/source/rust/vendor/ngx-rust/examples/t/async.t +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/perl - -# (C) Nginx, Inc - -# Tests for ngx-rust example modules. - -############################################################################### - -use warnings; -use strict; - -use Test::More; - -BEGIN { use FindBin; chdir($FindBin::Bin); } - -use lib 'lib'; -use Test::Nginx; - -############################################################################### - -select STDERR; $| = 1; -select STDOUT; $| = 1; - -my $t = Test::Nginx->new()->has(qw/http/)->plan(1) - ->write_file_expand('nginx.conf', <<'EOF'); - -%%TEST_GLOBALS%% - -daemon off; - -events { -} - -http { - %%TEST_GLOBALS_HTTP%% - - server { - listen 127.0.0.1:8080; - server_name localhost; - - location / { - async on; - } - } -} - -EOF - -$t->write_file('index.html', ''); -$t->run(); - -############################################################################### - -like(http_get('/index.html'), qr/X-Async-Time:/, 'async handler'); - -############################################################################### diff --git a/source/rust/vendor/ngx-rust/examples/t/awssig.t b/source/rust/vendor/ngx-rust/examples/t/awssig.t deleted file mode 100644 index ba43cd0..0000000 --- a/source/rust/vendor/ngx-rust/examples/t/awssig.t +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/perl - -# (C) Nginx, Inc - -# Tests for ngx-rust example modules. - -############################################################################### - -use warnings; -use strict; - -use Test::More; - -BEGIN { use FindBin; chdir($FindBin::Bin); } - -use lib 'lib'; -use Test::Nginx; - -############################################################################### - -select STDERR; $| = 1; -select STDOUT; $| = 1; - -my $t = Test::Nginx->new()->has(qw/http proxy/)->plan(1) - ->write_file_expand('nginx.conf', <<"EOF"); - -%%TEST_GLOBALS%% - -daemon off; - -events { -} - -http { - %%TEST_GLOBALS_HTTP%% - - server { - listen 127.0.0.1:8080; - server_name localhost; - - awssigv4_access_key my-access-key; - awssigv4_secret_key my-secret-key; - awssigv4_s3_bucket my-bucket; - awssigv4_s3_endpoint s3.example.com; - - location / { - awssigv4 on; - proxy_pass http://127.0.0.1:8081; - } - } - - server { - listen 127.0.0.1:8081; - server_name localhost; - - add_header x-amz-date \$http_x_amz_date; - add_header x-authorization \$http_authorization; - - location / { } - } -} - -EOF - -$t->write_file('index.html', ''); -$t->run(); - -############################################################################### - -like(http_get('/'), qr/x-authorization: AWS4.*Credential=my-access-key/i, - 'awssig header'); - -############################################################################### diff --git a/source/rust/vendor/ngx-rust/examples/t/curl.t b/source/rust/vendor/ngx-rust/examples/t/curl.t deleted file mode 100644 index dffe5a0..0000000 --- a/source/rust/vendor/ngx-rust/examples/t/curl.t +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/perl - -# (C) Nginx, Inc - -# Tests for ngx-rust example modules. - -############################################################################### - -use warnings; -use strict; - -use Test::More; - -BEGIN { use FindBin; chdir($FindBin::Bin); } - -use lib 'lib'; -use Test::Nginx; - -############################################################################### - -select STDERR; $| = 1; -select STDOUT; $| = 1; - -my $t = Test::Nginx->new()->has(qw/http/)->plan(2) - ->write_file_expand('nginx.conf', <<"EOF"); - -%%TEST_GLOBALS%% - -daemon off; - -events { -} - -http { - %%TEST_GLOBALS_HTTP%% - - server { - listen 127.0.0.1:8080; - server_name localhost; - - location / { - curl on; - } - } -} - -EOF - -$t->write_file('index.html', ''); -$t->run(); - -############################################################################### - -like(get('/', 'curl/1.2.3'), qr/403 Forbidden/, 'curl UA forbidden'); -like(get('/', 'MSIE 6.0'), qr/200 OK/, 'other UA allowed'); - -############################################################################### - -sub get { - my ($url, $ua, $extra) = @_; - return http(<new()->has(qw/http rewrite/)->plan(12) - ->write_file_expand('nginx.conf', <<'EOF'); - -%%TEST_GLOBALS%% - -daemon off; - -worker_processes 2; - -events { -} - -http { - %%TEST_GLOBALS_HTTP%% - - shared_dict_zone z 64k; - shared_dict $arg_key $foo; - - server { - listen 127.0.0.1:8080; - server_name localhost; - - add_header X-Value $foo; - add_header X-Process $pid; - - location /set/ { - add_header X-Process $pid; - set $foo $arg_value; - return 200; - } - - location /entries/ { - add_header X-Process $pid; - return 200 $shared_dict_entries; - } - - location /clear/ { - add_header X-Process $pid; - set $shared_dict_entries ""; - return 200; - } - } -} - -EOF - -$t->write_file('index.html', ''); -$t->run(); - -############################################################################### - -like(http_get('/set/?key=fst&value=hello'), qr/200 OK/, 'set value 1'); -like(http_get('/set/?key=snd&value=world'), qr/200 OK/, 'set value 2'); - -ok(check('/?key=fst', qr/X-Value: hello/i), 'check value 1'); -ok(check('/?key=snd', qr/X-Value: world/i), 'check value 2'); - -like(http_get('/set/?key=fst&value=new_value'), qr/200 OK/, 'update value 1'); -ok(check('/?key=fst', qr/X-Value: new_value/i), 'check updated value'); - -like(http_get('/entries/'), qr/^2; ((?:fst = new_value|snd = world); ){2}$/ms, - 'get entries'); - -like(http_delete('/set/?key=snd'), qr/200 OK/, 'delete value 2'); - -unlike(http_get('/?key=snd'), qr/X-Value:/i, 'check deleted value'); - -like(http_get('/entries/'), qr/^1; fst = new_value; $/ms, - 'get entries - deleted'); - -like(http_get('/clear/'), qr/200 OK/, 'clear'); - -like(http_get('/entries/'), qr/^0; $/ms, 'get entries - clear'); - -############################################################################### - -sub check { - my ($uri, $like) = @_; - - my $r = http_get($uri); - - return unless ($r =~ $like && $r =~ /X-Process: (\d+)/); - - return 1 if $^O eq 'MSWin32'; # only one active worker process - - my $pid = $1; - - for (1 .. 25) { - $r = http_get($uri); - - return unless ($r =~ $like && $r =~ /X-Process: (\d+)/); - return 1 if $pid != $1; - } -} - -sub http_delete { - my ($url, %extra) = @_; - return http(<new()->has(qw/http proxy/)->plan(2) - ->write_file_expand('nginx.conf', <<"EOF"); - -%%TEST_GLOBALS%% - -daemon off; - -events { -} - -http { - %%TEST_GLOBALS_HTTP%% - - upstream u { - server 127.0.0.1:8081; - custom 32; - } - - server { - listen 127.0.0.1:8080; - server_name localhost; - - error_log %%TESTDIR%%/e_debug.log debug; - - location / { - proxy_pass http://u; - } - } - - server { - listen 127.0.0.1:8081; - server_name localhost; - - location / { } - } -} - -EOF - -$t->write_file('index.html', ''); -$t->run(); - -############################################################################### - -like(http_get('/'), qr/200 OK/, 'custom upstream'); - -$t->stop(); - -SKIP: { - skip "no --with-debug", 1 unless $t->has_module('--with-debug'); - - like($t->read_file('e_debug.log'), qr/CUSTOM UPSTREAM request/, - 'log - custom upstream'); -} - -############################################################################### diff --git a/source/rust/vendor/ngx-rust/examples/upstream.conf b/source/rust/vendor/ngx-rust/examples/upstream.conf deleted file mode 100644 index 5a56b0d..0000000 --- a/source/rust/vendor/ngx-rust/examples/upstream.conf +++ /dev/null @@ -1,24 +0,0 @@ -# example configuration block to test upstream.rs -http { - upstream backend { - server localhost:15501; - custom 32; - } - - server { - listen 15500; - server_name _; - - location / { - proxy_pass http://backend; - } - } - - server { - listen 15501; - - location / { - return 418; - } - } -} diff --git a/source/rust/vendor/ngx-rust/examples/upstream.rs b/source/rust/vendor/ngx-rust/examples/upstream.rs deleted file mode 100644 index 544ca1b..0000000 --- a/source/rust/vendor/ngx-rust/examples/upstream.rs +++ /dev/null @@ -1,331 +0,0 @@ -/* - * This example is based on: - * https://github.com/gabihodoroaga/nginx-upstream-module - * as well as the NGINX keepalive module: ngx_http_upstream_keepalive_module.c. - * - * The NGINX authors are grateful to @gabihodoroaga for their contributions - * to the community at large. - */ -use core::ffi::{c_char, c_void}; -use core::mem; -use core::ptr; - -use ngx::core::{Pool, Status}; -use ngx::ffi::{ - NGX_CONF_NOARGS, NGX_CONF_TAKE1, NGX_CONF_UNSET, NGX_ERROR, NGX_HTTP_MODULE, - NGX_HTTP_SRV_CONF_OFFSET, NGX_HTTP_UPS_CONF, NGX_LOG_EMERG, ngx_atoi, ngx_command_t, - ngx_conf_t, ngx_connection_t, ngx_event_free_peer_pt, ngx_event_get_peer_pt, ngx_http_module_t, - ngx_http_upstream_init_peer_pt, ngx_http_upstream_init_pt, ngx_http_upstream_init_round_robin, - ngx_http_upstream_srv_conf_t, ngx_http_upstream_t, ngx_int_t, ngx_module_t, - ngx_peer_connection_t, ngx_str_t, ngx_uint_t, -}; -use ngx::http::{HttpModule, Merge, MergeConfigError, Request}; -use ngx::http::{HttpModuleServerConf, NgxHttpUpstreamModule}; -use ngx::{ - http_upstream_init_peer_pt, ngx_conf_log_error, ngx_log_debug_http, ngx_log_debug_mask, - ngx_string, -}; - -#[derive(Clone, Copy, Debug)] -#[repr(C)] -struct SrvConfig { - max: u32, - - original_init_upstream: ngx_http_upstream_init_pt, - original_init_peer: ngx_http_upstream_init_peer_pt, -} - -impl Default for SrvConfig { - fn default() -> Self { - SrvConfig { max: u32::MAX, original_init_upstream: None, original_init_peer: None } - } -} - -impl Merge for SrvConfig { - fn merge(&mut self, _prev: &SrvConfig) -> Result<(), MergeConfigError> { - Ok(()) - } -} - -#[derive(Clone, Copy, Debug)] -#[repr(C)] -struct UpstreamPeerData { - conf: Option<*const SrvConfig>, - upstream: Option<*mut ngx_http_upstream_t>, - client_connection: Option<*mut ngx_connection_t>, - original_get_peer: ngx_event_get_peer_pt, - original_free_peer: ngx_event_free_peer_pt, - data: *mut c_void, -} - -impl Default for UpstreamPeerData { - fn default() -> Self { - UpstreamPeerData { - conf: None, - upstream: None, - client_connection: None, - original_get_peer: None, - original_free_peer: None, - data: ptr::null_mut(), - } - } -} - -static NGX_HTTP_UPSTREAM_CUSTOM_CTX: ngx_http_module_t = ngx_http_module_t { - preconfiguration: Some(Module::preconfiguration), - postconfiguration: Some(Module::postconfiguration), - create_main_conf: None, - init_main_conf: None, - create_srv_conf: Some(Module::create_srv_conf), - merge_srv_conf: Some(Module::merge_srv_conf), - create_loc_conf: None, - merge_loc_conf: None, -}; - -static mut NGX_HTTP_UPSTREAM_CUSTOM_COMMANDS: [ngx_command_t; 2] = [ - ngx_command_t { - name: ngx_string!("custom"), - type_: (NGX_HTTP_UPS_CONF | NGX_CONF_NOARGS | NGX_CONF_TAKE1) as ngx_uint_t, - set: Some(ngx_http_upstream_commands_set_custom), - conf: NGX_HTTP_SRV_CONF_OFFSET, - offset: 0, - post: ptr::null_mut(), - }, - ngx_command_t::empty(), -]; - -// Generate the `ngx_modules` table with exported modules. -// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. -#[cfg(feature = "export-modules")] -ngx::ngx_modules!(ngx_http_upstream_custom_module); - -#[used] -#[allow(non_upper_case_globals)] -#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] -pub static mut ngx_http_upstream_custom_module: ngx_module_t = ngx_module_t { - ctx: &raw const NGX_HTTP_UPSTREAM_CUSTOM_CTX as _, - commands: unsafe { &raw mut NGX_HTTP_UPSTREAM_CUSTOM_COMMANDS[0] }, - type_: NGX_HTTP_MODULE as _, - ..ngx_module_t::default() -}; - -// http_upstream_init_custom_peer -// The module's custom peer.init callback. On HTTP request the peer upstream get and free callbacks -// are saved into peer data and replaced with this module's custom callbacks. -http_upstream_init_peer_pt!( - http_upstream_init_custom_peer, - |request: &mut Request, us: *mut ngx_http_upstream_srv_conf_t| { - ngx_log_debug_http!(request, "CUSTOM UPSTREAM request peer init"); - - let hcpd = request.pool().alloc_type::(); - if hcpd.is_null() { - return Status::NGX_ERROR; - } - - // SAFETY: this function is called with non-NULL uf always - let us = unsafe { &mut *us }; - let hccf = match Module::server_conf(us) { - Some(x) => x, - None => return Status::NGX_ERROR, - }; - - let original_init_peer = hccf.original_init_peer.unwrap(); - if unsafe { original_init_peer(request.into(), us) != Status::NGX_OK.into() } { - return Status::NGX_ERROR; - } - - let maybe_upstream = request.upstream(); - if maybe_upstream.is_none() { - return Status::NGX_ERROR; - } - let upstream_ptr = maybe_upstream.unwrap(); - - unsafe { - (*hcpd).conf = Some(hccf); - (*hcpd).upstream = maybe_upstream; - (*hcpd).data = (*upstream_ptr).peer.data; - (*hcpd).client_connection = Some(request.connection()); - (*hcpd).original_get_peer = (*upstream_ptr).peer.get; - (*hcpd).original_free_peer = (*upstream_ptr).peer.free; - - (*upstream_ptr).peer.data = hcpd as *mut c_void; - (*upstream_ptr).peer.get = Some(ngx_http_upstream_get_custom_peer); - (*upstream_ptr).peer.free = Some(ngx_http_upstream_free_custom_peer); - } - - ngx_log_debug_http!(request, "CUSTOM UPSTREAM end request peer init"); - Status::NGX_OK - } -); - -// ngx_http_usptream_get_custom_peer -// For demonstration purposes, use the original get callback, but log this callback proxies through -// to the original. -unsafe extern "C" fn ngx_http_upstream_get_custom_peer( - pc: *mut ngx_peer_connection_t, - data: *mut c_void, -) -> ngx_int_t { - let hcpd: *mut UpstreamPeerData = unsafe { mem::transmute(data) }; - - ngx_log_debug_mask!( - DebugMask::Http, - unsafe { (*pc).log }, - "CUSTOM UPSTREAM get peer, try: {}, conn: {:p}", - unsafe { (*pc).tries }, - unsafe { (*hcpd).client_connection.unwrap() }, - ); - - let original_get_peer = unsafe { (*hcpd).original_get_peer.unwrap() }; - let rc = unsafe { original_get_peer(pc, (*hcpd).data) }; - - if rc != Status::NGX_OK.into() { - return rc; - } - - ngx_log_debug_mask!(DebugMask::Http, unsafe { (*pc).log }, "CUSTOM UPSTREAM end get peer"); - Status::NGX_OK.into() -} - -// ngx_http_upstream_free_custom_peer -// For demonstration purposes, use the original free callback, but log this callback proxies -// through to the original. -unsafe extern "C" fn ngx_http_upstream_free_custom_peer( - pc: *mut ngx_peer_connection_t, - data: *mut c_void, - state: ngx_uint_t, -) { - ngx_log_debug_mask!(DebugMask::Http, unsafe { (*pc).log }, "CUSTOM UPSTREAM free peer"); - - let hcpd: *mut UpstreamPeerData = unsafe { mem::transmute(data) }; - - let original_free_peer = unsafe { (*hcpd).original_free_peer.unwrap() }; - - unsafe { original_free_peer(pc, (*hcpd).data, state) }; - - ngx_log_debug_mask!(DebugMask::Http, unsafe { (*pc).log }, "CUSTOM UPSTREAM end free peer"); -} - -// ngx_http_upstream_init_custom -// The module's custom `peer.init_upstream` callback. -// The original callback is saved in our SrvConfig data and reset to this module's `peer.init`. -unsafe extern "C" fn ngx_http_upstream_init_custom( - cf: *mut ngx_conf_t, - us: *mut ngx_http_upstream_srv_conf_t, -) -> ngx_int_t { - ngx_log_debug_mask!( - DebugMask::Http, - unsafe { (*cf).log }, - "CUSTOM UPSTREAM peer init_upstream" - ); - - // SAFETY: this function is called with non-NULL uf always - let us = unsafe { &mut *us }; - let hccf = Module::server_conf_mut(us); - if hccf.is_none() { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "CUSTOM UPSTREAM no upstream srv_conf"); - return isize::from(Status::NGX_ERROR); - } - let hccf = hccf.unwrap(); - // NOTE: ngx_conf_init_uint_value macro is unavailable - if hccf.max == u32::MAX { - hccf.max = 100; - } - - let init_upstream_ptr = hccf.original_init_upstream.unwrap(); - if unsafe { init_upstream_ptr(cf, us) } != Status::NGX_OK.into() { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "CUSTOM UPSTREAM failed calling init_upstream"); - return isize::from(Status::NGX_ERROR); - } - - hccf.original_init_peer = us.peer.init; - us.peer.init = Some(http_upstream_init_custom_peer); - - ngx_log_debug_mask!( - DebugMask::Http, - unsafe { (*cf).log }, - "CUSTOM UPSTREAM end peer init_upstream" - ); - isize::from(Status::NGX_OK) -} - -// ngx_http_upstream_commands_set_custom -// Entry point for the module, if this command is set our custom upstreams take effect. -// The original upstream initializer function is saved and replaced with this module's initializer. -unsafe extern "C" fn ngx_http_upstream_commands_set_custom( - cf: *mut ngx_conf_t, - cmd: *mut ngx_command_t, - conf: *mut c_void, -) -> *mut c_char { - // SAFETY: this function is called with non-NULL cf always - let cf = unsafe { &mut *cf }; - ngx_log_debug_mask!(DebugMask::Http, cf.log, "CUSTOM UPSTREAM module init"); - let args: &[ngx_str_t] = unsafe { (*cf.args).as_slice() }; - - let ccf = unsafe { &mut (*(conf as *mut SrvConfig)) }; - - if let Some(value) = args.get(1) { - let n = unsafe { ngx_atoi(value.data, value.len) }; - if n == (NGX_ERROR as isize) || n == 0 { - ngx_conf_log_error!( - NGX_LOG_EMERG, - cf, - "invalid value \"{}\" in \"{}\" directive", - value, - unsafe { &(*cmd).name } - ); - return ngx::core::NGX_CONF_ERROR; - } - ccf.max = n as u32; - } - - let uscf = NgxHttpUpstreamModule::server_conf_mut(cf).expect("http upstream srv conf"); - - ccf.original_init_upstream = if uscf.peer.init_upstream.is_some() { - uscf.peer.init_upstream - } else { - Some(ngx_http_upstream_init_round_robin) - }; - - uscf.peer.init_upstream = Some(ngx_http_upstream_init_custom); - - ngx_log_debug_mask!(DebugMask::Http, cf.log, "CUSTOM UPSTREAM end module init"); - - ngx::core::NGX_CONF_OK -} - -// The upstream module. -// Only server blocks are supported to trigger the module command; therefore, the only callback -// implemented is our `create_srv_conf` method. -struct Module; - -impl HttpModule for Module { - fn module() -> &'static ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_upstream_custom_module) } - } - - unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void { - let pool = unsafe { Pool::from_ngx_pool((*cf).pool) }; - let conf = pool.alloc_type::(); - if conf.is_null() { - ngx_conf_log_error!( - NGX_LOG_EMERG, - cf, - "CUSTOM UPSTREAM could not allocate memory for config" - ); - return ptr::null_mut(); - } - - unsafe { (*conf).max = NGX_CONF_UNSET as u32 }; - - ngx_log_debug_mask!( - DebugMask::Http, - unsafe { (*cf).log }, - "CUSTOM UPSTREAM end create_srv_conf" - ); - conf as *mut c_void - } -} - -unsafe impl HttpModuleServerConf for Module { - type ServerConf = SrvConfig; -} diff --git a/source/rust/vendor/ngx-rust/misc/lsan-suppressions.txt b/source/rust/vendor/ngx-rust/misc/lsan-suppressions.txt deleted file mode 100644 index 4731e9b..0000000 --- a/source/rust/vendor/ngx-rust/misc/lsan-suppressions.txt +++ /dev/null @@ -1,17 +0,0 @@ -# LeakSanitizer suppressions list for nginx -# -# To be used with -fsanitize=address and -# LSAN_OPTIONS=suppressions=lsan-suppressions.txt. -# -# https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer#suppressions - -# cycle->connections, cycle->read_events, cycle->write_events -leak:ngx_event_process_init - -# XXX: can silence leaks from nginx SSL callbacks -leak:SSL_do_handshake -leak:SSL_read - -# rcf->ranges not freed at process exit -leak:ngx_http_upstream_update_random -leak:ngx_stream_upstream_update_random diff --git a/source/rust/vendor/ngx-rust/misc/nginx-sanitizer-support.patch b/source/rust/vendor/ngx-rust/misc/nginx-sanitizer-support.patch deleted file mode 100644 index 02ba70d..0000000 --- a/source/rust/vendor/ngx-rust/misc/nginx-sanitizer-support.patch +++ /dev/null @@ -1,28 +0,0 @@ -diff --git a/src/core/ngx_string.h b/src/core/ngx_string.h -index 713eb42a7..999c6b25f 100644 ---- a/src/core/ngx_string.h -+++ b/src/core/ngx_string.h -@@ -96,6 +96,23 @@ void ngx_explicit_memzero(void *buf, size_t n); - void *ngx_memcpy(void *dst, const void *src, size_t n); - #define ngx_cpymem(dst, src, n) (((u_char *) ngx_memcpy(dst, src, n)) + (n)) - -+#elif (NGX_SUPPRESS_WARN) -+ -+/* -+ * Checked versions for sanitizers. -+ * See https://mailman.nginx.org/pipermail/nginx-devel/2023-December/7VNQZEBNXEKAYTYE4Y65FORF4HNELM6V.html -+ */ -+ -+static ngx_inline void * -+ngx_memcpy(void *dst, const void *src, size_t n) { -+ return (n == 0) ? dst : memcpy(dst, src, n); -+} -+ -+static ngx_inline void * -+ngx_cpymem(void *dst, const void *src, size_t n) { -+ return (n == 0) ? dst : ((u_char *) memcpy(dst, src, n)) + n; -+} -+ - #else - - /* diff --git a/source/rust/vendor/ngx-rust/misc/ubsan-suppressions.txt b/source/rust/vendor/ngx-rust/misc/ubsan-suppressions.txt deleted file mode 100644 index 5da588f..0000000 --- a/source/rust/vendor/ngx-rust/misc/ubsan-suppressions.txt +++ /dev/null @@ -1,28 +0,0 @@ -# UndefinedBehaviorSanitizer suppressions list for nginx -# -# To be used with -fsanitize=undefined and -# UBSAN_OPTIONS=suppressions=ubsan-suppressions.txt. -# -# https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#runtime-suppressions - -# src/http/v2/ngx_http_v2.c:2747:17: runtime error: store to misaligned address 0x7b35a1a19885 for type 'uint32_t' (aka 'unsigned int'), which requires 4 byte alignment -alignment:src/http/v2/ngx_http_v2.c -alignment:src/http/v2/ngx_http_v2_filter_module.c -alignment:ngx_http_huff_encode -alignment:ngx_http_parse_request_line - -# ngx_quic_write_uint32 at src/event/quic/ngx_event_quic_transport.c:642 -alignment:ngx_quic_create_long_header -alignment:ngx_quic_read_uint32 - -# src/core/ngx_output_chain.c:70:20: runtime error: call to function ngx_http_trailers_filter through pointer to incorrect function type 'long (*)(void *, struct ngx_chain_s *)' -# src/http/modules/ngx_http_headers_filter_module.c:249: note: ngx_http_trailers_filter defined here -function:ngx_output_chain - -# violates nonnull on memcmp -nonnull-attribute:ngx_http_upstream_zone_preresolve -nonnull-attribute:ngx_stream_upstream_zone_preresolve - -# src/http/ngx_http_script.c:800:16: runtime error: applying non-zero offset 112 to null pointer -pointer-overflow:ngx_http_script_add_code -pointer-overflow:ngx_stream_script_add_code diff --git a/source/rust/vendor/ngx-rust/misc/update-action-sha.sh b/source/rust/vendor/ngx-rust/misc/update-action-sha.sh deleted file mode 100755 index 30e8390..0000000 --- a/source/rust/vendor/ngx-rust/misc/update-action-sha.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh - -set -ex - -if [ $# -lt 2 ]; then - grep "uses:[[:space:]]*$1" .github/workflows/*.yaml - exit -fi - -sed -e "s|\\(uses:[[:space:]]*$1@\\).*|\\1$2|" -i .github/workflows/*.yaml diff --git a/source/rust/vendor/ngx-rust/nginx-src/Cargo.toml b/source/rust/vendor/ngx-rust/nginx-src/Cargo.toml deleted file mode 100644 index 0db238e..0000000 --- a/source/rust/vendor/ngx-rust/nginx-src/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "nginx-src" -# Version format: ..+ -version = "1.30.0+1.30.4" -# Crate sources are licensed under Apache-2.0, with exception of the -# NGINX submodule that is redistributed under BSD-2-Clause. -license = "Apache-2.0 AND BSD-2-Clause" -description = "Source of NGINX" -keywords = ["nginx", "module", "sys"] -exclude = [ - "/nginx/.git*", - "/nginx/contrib", - "/nginx/docs", - "/nginx/misc", - "!/nginx/docs/html", - "!/nginx/docs/man", -] -edition.workspace = true -homepage.workspace = true -repository.workspace = true -rust-version.workspace = true - -[dependencies] -duct = "1" -flate2 = "1.0.32" -tar = "0.4.45" -ureq = "3.2" - -[lints] -workspace = true diff --git a/source/rust/vendor/ngx-rust/nginx-src/LICENSE b/source/rust/vendor/ngx-rust/nginx-src/LICENSE deleted file mode 120000 index ea5b606..0000000 --- a/source/rust/vendor/ngx-rust/nginx-src/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/nginx-src/README.md b/source/rust/vendor/ngx-rust/nginx-src/README.md deleted file mode 100644 index 334a44d..0000000 --- a/source/rust/vendor/ngx-rust/nginx-src/README.md +++ /dev/null @@ -1,82 +0,0 @@ -# nginx-src - -The crate contains a vendored copy of the NGINX source and a logic to build it. -It is intended to be consumed by the [nginx-sys] crate for CI builds, tests or -rustdoc generation. - -It is notably not intended for producing binaries suitable for production use. -For such scenarios we recommend building the `ngx-rust` based module against -the packages from or your preferred distribution. -See the [nginx-sys] documentation for building `ngx-rust` modules against an -existing pre-configured NGINX source tree. - -[nginx-sys]: https://docs.rs/nginx-sys/ - -## Versioning - -This crate follows the latest stable branch of NGINX. - - * The major and minor fields are taken from the NGINX version. - * The patch version is incremented on changes to the build logic or crate - metadata. - * The version metadata contains full version of NGINX. - -## Build Requirements - -The crate can be built on common Unix-like operating systems and requires all -the usual NGINX build dependencies (including development headers for the -libraries) installed in system paths: - - * C compiler and toolchain - * SSL library, OpenSSL or LibreSSL - * PCRE or PCRE2 - * Zlib or zlib-ng witn Zlib compatible API enabled - -We don't intend to support Windows at the moment, as NGINX does not support -dynamic modules for this target. - -## Environment variables - -Following variables can be set to customize the build. - - * `NGX_CONFIGURE_ARGS` — additional arguments to pass to the NGINX configure - script. - - Example: `export NGX_CONFIGURE_ARGS='--with-debug'; cargo build` - - * `NGX_CFLAGS`, `NGX_LDFLAGS` — additional C compiler and linker flags to - pass to the NGINX configure script. Internally, this is added to the - `--with-cc-opt=...` and `--with-ld-opt=...` configure arguments. - - Example: - ```sh - export NGX_CFLAGS='-I/opt/boringssl/include' - export NGX_LDFLAGS='-L/opt/boringssl/build -lstdc++' - cargo build - ``` - -## Download NGINX and dependency sources during build - -While we recommend using the system libraries, it is still possible to opt into -downloading the NGINX itself and the dependency sources from the network with -the help of the following variables: - - * `NGX_VERSION` — if specified, the version of NGINX to download and build - instead of the one bundled with the crate. - * `OPENSSL_VERSION` — if specified, the version of OpenSSL to download and use - use instead of the system-provided library. - * `PCRE2_VERSION` — if specified, the version of PCRE2 to download and use - instead of the system-provided library. - * `ZLIB_VERSION` — if specified, the version of Zlib to download and use - instead of the system-provided library. - -If the `gpg` executable is present in the path, the build script will verify -the integrity of the downloaded files using GPG signatures and a known set of -public keys. -This behavior can be disabled by setting `NGX_NO_SIGNATURE_CHECK`. - -## License - -The code in this crate is licensed under the [Apache License 2.0](../LICENSE). -The crate also contains the source code of NGINX, distributed under the -[BSD 2-Clause License](https://nginx.org/LICENSE). diff --git a/source/rust/vendor/ngx-rust/nginx-src/src/download.rs b/source/rust/vendor/ngx-rust/nginx-src/src/download.rs deleted file mode 100644 index c64ca6c..0000000 --- a/source/rust/vendor/ngx-rust/nginx-src/src/download.rs +++ /dev/null @@ -1,252 +0,0 @@ -extern crate duct; - -use core::error::Error as StdError; -use std::fs::File; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::LazyLock; -use std::{env, fs}; - -use flate2::read::GzDecoder; -use tar::Archive; - -use crate::verifier::SignatureVerifier; - -const NGINX_URL_PREFIX: &str = "https://nginx.org/download"; -const OPENSSL_URL_PREFIX: &str = "https://github.com/openssl/openssl/releases/download"; -const PCRE1_URL_PREFIX: &str = "https://sourceforge.net/projects/pcre/files/pcre"; -const PCRE2_URL_PREFIX: &str = "https://github.com/PCRE2Project/pcre2/releases/download"; -const ZLIB_URL_PREFIX: &str = "https://github.com/madler/zlib/releases/download"; -const UBUNTU_KEYSEVER: &str = "hkps://keyserver.ubuntu.com"; - -struct SourceSpec<'a> { - url: fn(&str) -> String, - variable: &'a str, - signature: &'a str, - keyserver: &'a str, - key_ids: &'a [&'a str], -} - -const NGINX_SOURCE: SourceSpec = SourceSpec { - url: |version| format!("{NGINX_URL_PREFIX}/nginx-{version}.tar.gz"), - variable: "NGX_VERSION", - signature: "asc", - keyserver: UBUNTU_KEYSEVER, - key_ids: &[ - // Key 1: Konstantin Pavlov's public key. For Nginx 1.25.3 and earlier - "13C82A63B603576156E30A4EA0EA981B66B0D967", - // Key 2: Sergey Kandaurov's public key. For Nginx 1.25.4 - "D6786CE303D9A9022998DC6CC8464D549AF75C0A", - // Key 3: Maxim Dounin's public key. At least used for Nginx 1.18.0 - "B0F4253373F8F6F510D42178520A9993A1C052F8", - // Key 4: Roman Arutyunyan's public key. For Nginx 1.25.5 - "43387825DDB1BB97EC36BA5D007C8D7C15D87369", - ], -}; - -const DEPENDENCIES: &[(&str, SourceSpec)] = &[ - ( - "openssl", - SourceSpec { - url: |version| { - if version.starts_with("1.") { - let ver_hyphened = version.replace('.', "_"); - format!("{OPENSSL_URL_PREFIX}/OpenSSL_{ver_hyphened}/openssl-{version}.tar.gz") - } else { - format!("{OPENSSL_URL_PREFIX}/openssl-{version}/openssl-{version}.tar.gz") - } - }, - variable: "OPENSSL_VERSION", - signature: "asc", - keyserver: UBUNTU_KEYSEVER, - key_ids: &[ - "EFC0A467D613CB83C7ED6D30D894E2CE8B3D79F5", - "A21FAB74B0088AA361152586B8EF1A6BA9DA2D5C", - "8657ABB260F056B1E5190839D9C4D26D0E604491", - "B7C1C14360F353A36862E4D5231C84CDDCC69C45", - "95A9908DDFA16830BE9FB9003D30A3A9FF1360DC", - "7953AC1FBC3DC8B3B292393ED5E9E43F7DF9EE8C", - "E5E52560DD91C556DDBDA5D02064C53641C25E5D", - "C1F33DD8CE1D4CC613AF14DA9195C48241FBF7DD", - "BA5473A2B0587B07FB27CF2D216094DFD0CB81EF", - ], - }, - ), - ( - "pcre", - SourceSpec { - url: |version| { - // We can distinguish pcre1/pcre2 by checking whether the second character is '.', - // because the final version of pcre1 is 8.45 and the first one of pcre2 is 10.00. - if version.chars().nth(1).is_some_and(|c| c == '.') { - format!("{PCRE1_URL_PREFIX}/{version}/pcre-{version}.tar.gz") - } else { - format!("{PCRE2_URL_PREFIX}/pcre2-{version}/pcre2-{version}.tar.gz") - } - }, - variable: "PCRE2_VERSION", - signature: "sig", - keyserver: UBUNTU_KEYSEVER, - key_ids: &[ - // Key 1: Phillip Hazel's public key. For PCRE2 10.44 and earlier - "45F68D54BBE23FB3039B46E59766E084FB0F43D8", - // Key 2: Nicholas Wilson's public key. For PCRE2 10.45 - "A95536204A3BB489715231282A98E77EB6F24CA8", - ], - }, - ), - ( - "zlib", - SourceSpec { - url: |version| format!("{ZLIB_URL_PREFIX}/v{version}/zlib-{version}.tar.gz"), - variable: "ZLIB_VERSION", - signature: "asc", - keyserver: UBUNTU_KEYSEVER, - key_ids: &[ - // Key 1: Mark Adler's public key. For zlib 1.3.1 and earlier - "5ED46A6721D365587791E2AA783FCD8E58BCAFBA", - ], - }, - ), -]; - -static VERIFIER: LazyLock> = LazyLock::new(|| { - SignatureVerifier::new().inspect_err(|err| eprintln!("GnuPG verifier: {err}")).ok() -}); - -static CACHE_DIR: LazyLock = LazyLock::new(|| { - let base_dir = env::var("OUT_DIR") - .map(PathBuf::from) - .unwrap_or_else(|_| env::current_dir().expect("Failed to get current directory")); - // Choose `.cache` relative to the OUT_DIR of the caller (nginx-sys) as the default cache - // directory. Environment variable `CACHE_DIR` overrides this. - // Recommendation: set env "CACHE_DIR = { value = ".cache", relative = true }" in - // `.cargo/config.toml` in your project - let cache_dir = env::var("CACHE_DIR").map(PathBuf::from).unwrap_or(base_dir.join(".cache")); - - if !cache_dir.exists() { - fs::create_dir_all(&cache_dir) - .map_err(|err| format!("Failed to create {cache_dir:?}: {err}")) - .unwrap(); - } - - cache_dir -}); - -/// Downloads a tarball from the specified URL into the `.cache` directory. -fn download(cache_dir: &Path, url: &str) -> Result> { - fn proceed_with_download(file_path: &Path) -> bool { - // File does not exist or is zero bytes - !file_path.exists() || file_path.metadata().is_ok_and(|m| m.len() < 1) - } - let filename = url.split('/').next_back().unwrap(); - let file_path = cache_dir.join(filename); - if proceed_with_download(&file_path) { - println!("Downloading: {} -> {}", url, file_path.display()); - let mut response = ureq::get(url).call()?; - let mut reader = response.body_mut().as_reader(); - let mut file = File::create(&file_path)?; - std::io::copy(&mut reader, &mut file)?; - } - - if !file_path.exists() { - return Err( - format!("Downloaded file was not written to the expected location: {url}",).into() - ); - } - Ok(file_path) -} - -/// Gets a given tarball and signature file from a remote URL and copies it to the `.cache` -/// directory. -fn get_archive(cache_dir: &Path, source: &SourceSpec, version: &str) -> io::Result { - let archive_url = (source.url)(version); - let archive = download(cache_dir, &archive_url).map_err(io::Error::other)?; - - if let Some(verifier) = &*VERIFIER { - let signature = format!("{archive_url}.{}", source.signature); - - let verify = || -> io::Result<()> { - let signature = download(cache_dir, &signature).map_err(io::Error::other)?; - verifier.import_keys(source.keyserver, source.key_ids)?; - verifier.verify_signature(&archive, &signature)?; - Ok(()) - }; - - if let Err(err) = verify() { - let _ = fs::remove_file(&archive); - let _ = fs::remove_file(&signature); - return Err(err); - } - } - - Ok(archive) -} - -/// Extracts a tarball into a subdirectory based on the tarball's name under the source base -/// directory. -fn extract_archive(archive_path: &Path, extract_output_base_dir: &Path) -> io::Result { - if !extract_output_base_dir.exists() { - fs::create_dir_all(extract_output_base_dir)?; - } - let archive_file = File::open(archive_path) - .unwrap_or_else(|_| panic!("Unable to open archive file: {}", archive_path.display())); - let stem = archive_path - .file_name() - .and_then(|s| s.to_str()) - .and_then(|s| s.rsplitn(3, '.').last()) - .expect("Unable to determine archive file name stem"); - - let extract_output_dir = extract_output_base_dir.to_owned(); - let archive_output_dir = extract_output_dir.join(stem); - if !archive_output_dir.exists() { - Archive::new(GzDecoder::new(archive_file)).entries()?.filter_map(|e| e.ok()).for_each( - |mut entry| { - let path = entry.path().unwrap(); - let stripped_path = path.components().skip(1).collect::(); - entry.unpack(archive_output_dir.join(stripped_path)).unwrap(); - }, - ); - } else { - println!( - "Archive [{}] already extracted to directory: {}", - stem, - archive_output_dir.display() - ); - } - - Ok(archive_output_dir) -} - -/// Downloads and extracts all requested sources. -pub fn prepare(source_dir: &Path, build_dir: &Path) -> io::Result<(PathBuf, Vec)> { - let extract_output_base_dir = build_dir.join("lib"); - if !extract_output_base_dir.exists() { - fs::create_dir_all(&extract_output_base_dir)?; - } - - let mut options = vec![]; - - // Download NGINX only if NGX_VERSION is set. - let source_dir = if let Ok(version) = env::var(NGINX_SOURCE.variable) { - let archive_path = get_archive(&CACHE_DIR, &NGINX_SOURCE, version.as_str())?; - let output_base_dir: PathBuf = env::var("OUT_DIR").unwrap().into(); - extract_archive(&archive_path, &output_base_dir)? - } else { - source_dir.to_path_buf() - }; - - for (name, source) in DEPENDENCIES { - // Download dependencies if a corresponding DEPENDENCY_VERSION is set. - let Ok(requested) = env::var(source.variable) else { - continue; - }; - - let archive_path = get_archive(&CACHE_DIR, source, &requested)?; - let output_dir = extract_archive(&archive_path, &extract_output_base_dir)?; - let output_dir = output_dir.to_string_lossy(); - options.push(format!("--with-{name}={output_dir}")); - } - - Ok((source_dir, options)) -} diff --git a/source/rust/vendor/ngx-rust/nginx-src/src/lib.rs b/source/rust/vendor/ngx-rust/nginx-src/src/lib.rs deleted file mode 100644 index 52a4e60..0000000 --- a/source/rust/vendor/ngx-rust/nginx-src/src/lib.rs +++ /dev/null @@ -1,214 +0,0 @@ -#![doc = include_str!("../README.md")] -#![warn(missing_docs)] - -use std::ffi::OsString; -use std::path::{Path, PathBuf}; -use std::process::Output; -use std::{env, io, thread}; - -mod download; -mod verifier; - -static NGINX_DEFAULT_SOURCE_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/nginx"); - -const NGINX_BUILD_INFO: &str = "last-build-info"; -const NGINX_BINARY: &str = "nginx"; - -static NGINX_CONFIGURE_BASE: &[&str] = &[ - "--with-compat", - "--with-http_realip_module", - "--with-http_ssl_module", - "--with-http_v2_module", - "--with-mail", - "--with-mail_ssl_module", - "--with-stream", - "--with-stream_realip_module", - "--with-stream_ssl_module", - "--with-threads", -]; - -const ENV_VARS_TRIGGERING_RECOMPILE: [&str; 10] = [ - "CACHE_DIR", - "CARGO_MANIFEST_DIR", - "CARGO_TARGET_TMPDIR", - "NGX_CONFIGURE_ARGS", - "NGX_CFLAGS", - "NGX_LDFLAGS", - "NGX_VERSION", - "OPENSSL_VERSION", - "PCRE2_VERSION", - "ZLIB_VERSION", -]; - -/* -########################################################################### -# NGINX Build Functions - Everything below here is for building NGINX # -########################################################################### - -In order to build Rust bindings for NGINX using the bindgen crate, we need -to do the following: - - 1. Obtain a copy of the NGINX source code and the necessary dependencies: - OpenSSL, PCRE2, Zlib. - 3. Run autoconf `configure` for NGINX. - 4. Compile NGINX. - 5. Read the autoconf generated makefile for NGINX and configure bindgen - to generate Rust bindings based on the includes in the makefile. -*/ - -/// Outputs cargo instructions required for using this crate from a buildscript. -pub fn print_cargo_metadata() { - for file in ["lib.rs", "download.rs", "verifier.rs"] { - println!("cargo::rerun-if-changed={path}/src/{file}", path = env!("CARGO_MANIFEST_DIR")) - } - - for var in ENV_VARS_TRIGGERING_RECOMPILE { - println!("cargo::rerun-if-env-changed={var}"); - } -} - -/// Builds a copy of NGINX sources, either bundled with the crate or downloaded from the network. -pub fn build(build_dir: impl AsRef) -> io::Result<(PathBuf, PathBuf)> { - let source_dir = PathBuf::from(NGINX_DEFAULT_SOURCE_DIR); - let build_dir = build_dir.as_ref().to_owned(); - - let (source_dir, vendored_flags) = download::prepare(&source_dir, &build_dir)?; - - let flags = nginx_configure_flags(&vendored_flags); - - configure(&source_dir, &build_dir, &flags)?; - - make(&source_dir, &build_dir, ["build"])?; - - Ok((source_dir, build_dir)) -} - -/// Returns the options NGINX was built with -fn build_info(source_dir: &Path, configure_flags: &[String]) -> String { - // Flags should contain strings pointing to OS/platform as well as dependency versions, - // so if any of that changes, it can trigger a rebuild - format!("{:?}|{}", source_dir, configure_flags.join(" ")) -} - -/// Generate the flags to use with autoconf `configure` for NGINX. -fn nginx_configure_flags(vendored: &[String]) -> Vec { - let mut nginx_opts: Vec = - NGINX_CONFIGURE_BASE.iter().map(|x| String::from(*x)).collect(); - - nginx_opts.extend(vendored.iter().map(Into::into)); - - if let Ok(extra_args) = env::var("NGX_CONFIGURE_ARGS") { - // FIXME: shell style split? - nginx_opts.extend(extra_args.split_whitespace().map(Into::into)); - } - - if let Ok(cflags) = env::var("NGX_CFLAGS") { - nginx_opts.push(format!("--with-cc-opt={cflags}")); - } - - if let Ok(ldflags) = env::var("NGX_LDFLAGS") { - nginx_opts.push(format!("--with-ld-opt={ldflags}")); - } - - nginx_opts -} - -/// Runs external process invoking autoconf `configure` for NGINX. -fn configure(source_dir: &Path, build_dir: &Path, flags: &[String]) -> io::Result<()> { - let build_info = build_info(source_dir, flags); - - if build_dir.join("Makefile").is_file() - && build_dir.join(NGINX_BINARY).is_file() - && matches!( - std::fs::read_to_string(build_dir.join(NGINX_BUILD_INFO)).map(|x| x == build_info), - Ok(true) - ) - { - println!("Build info unchanged, skipping configure"); - return Ok(()); - } - - println!("Using NGINX source at {source_dir:?}"); - - let configure = ["configure", "auto/configure"] - .into_iter() - .map(|x| source_dir.join(x)) - .find(|x| x.is_file()) - .ok_or(io::ErrorKind::NotFound)?; - - println!("Running NGINX configure script with flags: {:?}", flags.join(" ")); - - let mut build_dir_arg: OsString = "--builddir=".into(); - build_dir_arg.push(build_dir); - - let mut flags: Vec = flags.iter().map(|x| x.into()).collect(); - flags.push(build_dir_arg); - - let output = duct::cmd(configure, flags).dir(source_dir).stderr_to_stdout().run()?; - - if !output.status.success() { - println!("configure failed with {:?}", output.status); - return Err(io::ErrorKind::Other.into()); - } - - let _ = std::fs::write(build_dir.join(NGINX_BUILD_INFO), build_info); - - Ok(()) -} - -/// Runs `make` within the NGINX source directory as an external process. -fn make(source_dir: &Path, build_dir: &Path, extra_args: U) -> io::Result -where - U: IntoIterator, - U::Item: Into, -{ - // Level of concurrency to use when building nginx - cargo nicely provides this information - let num_jobs = match env::var("NUM_JOBS") { - Ok(s) => s.parse::().ok(), - Err(_) => thread::available_parallelism().ok().map(|n| n.get()), - } - .unwrap_or(1); - - let mut args = vec![ - OsString::from("-f"), - build_dir.join("Makefile").into(), - OsString::from("-j"), - num_jobs.to_string().into(), - ]; - args.extend(extra_args.into_iter().map(Into::into)); - - // Use MAKE passed from the parent process if set. Otherwise prefer `gmake` as it provides a - // better feature-wise implementation on some systems. - // Notably, we want to avoid SUN make on Solaris (does not support -j) or ancient GNU make 3.81 - // on MacOS. - let inherited = env::var("MAKE"); - let make_commands: &[&str] = match inherited { - Ok(ref x) => &[x.as_str(), "gmake", "make"], - _ => &["gmake", "make"], - }; - - // Give preference to the binary with the name of gmake if it exists because this is typically - // the GNU 4+ on MacOS (if it is installed via homebrew). - for make in make_commands { - /* Use the duct dependency here to merge the output of STDOUT and STDERR into a single stream, - and to provide the combined output as a reader which can be iterated over line-by-line. We - use duct to do this because it is a lot of work to implement this from scratch. */ - let result = duct::cmd(*make, &args).dir(source_dir).stderr_to_stdout().run(); - - match result { - Err(err) if err.kind() == io::ErrorKind::NotFound => { - eprintln!("make: command '{make}' not found"); - continue; - } - Ok(out) if !out.status.success() => { - return Err(io::Error::other(format!( - "make: '{}' failed with {:?}", - make, out.status - ))); - } - _ => return result, - } - } - - Err(io::ErrorKind::NotFound.into()) -} diff --git a/source/rust/vendor/ngx-rust/nginx-src/src/verifier.rs b/source/rust/vendor/ngx-rust/nginx-src/src/verifier.rs deleted file mode 100644 index 917c947..0000000 --- a/source/rust/vendor/ngx-rust/nginx-src/src/verifier.rs +++ /dev/null @@ -1,107 +0,0 @@ -use std::ffi::OsString; -use std::fs::{self, Permissions}; -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; -use std::{env, io}; - -static GNUPG_COMMAND: &str = "gpg"; - -pub struct SignatureVerifier { - gnupghome: PathBuf, -} - -impl SignatureVerifier { - pub fn new() -> io::Result { - if env::var("NGX_NO_SIGNATURE_CHECK").is_ok() { - return Err(io::Error::other("signature check disabled by user".to_string())); - }; - - if let Err(x) = duct::cmd!(GNUPG_COMMAND, "--version").stdout_null().run() { - return Err(io::Error::other(format!( - "signature check disabled: \"{GNUPG_COMMAND}\" not found ({x})" - ))); - } - - // We do not want to mess with the default gpg data for the running user, - // so we store all gpg data within our build directory. - let gnupghome = - env::var("OUT_DIR").map(PathBuf::from).map_err(io::Error::other)?.join(".gnupg"); - - if !fs::exists(&gnupghome)? { - fs::create_dir_all(&gnupghome)?; - } - - change_permissions_recursively(gnupghome.as_path(), 0o700, 0o600)?; - - Ok(Self { gnupghome }) - } - - /// Imports all the required GPG keys into a temporary directory in order to - /// validate the integrity of the downloaded tarballs. - pub fn import_keys(&self, server: &str, key_ids: &[&str]) -> io::Result<()> { - println!("Importing {} GPG keys for key server: {}", key_ids.len(), server); - - let mut args = vec![ - OsString::from("--homedir"), - self.gnupghome.clone().into(), - OsString::from("--keyserver"), - server.into(), - OsString::from("--recv-keys"), - ]; - args.extend(key_ids.iter().map(OsString::from)); - - let cmd = duct::cmd(GNUPG_COMMAND, &args); - let output = cmd.stderr_to_stdout().stdout_capture().unchecked().run()?; - - if !output.status.success() { - eprintln!("{}", String::from_utf8_lossy(&output.stdout)); - return Err(io::Error::other(format!( - "Command: {:?}\nFailed to import GPG keys: {}", - cmd, - key_ids.join(" ") - ))); - } - - Ok(()) - } - - /// Validates the integrity of a file against the cryptographic signature associated with - /// the file. - pub fn verify_signature(&self, path: &Path, signature: &Path) -> io::Result<()> { - let cmd = - duct::cmd!(GNUPG_COMMAND, "--homedir", &self.gnupghome, "--verify", signature, path); - let output = cmd.stderr_to_stdout().stdout_capture().unchecked().run()?; - if !output.status.success() { - eprintln!("{}", String::from_utf8_lossy(&output.stdout)); - return Err(io::Error::other(format!( - "Command: {:?}\nGPG signature verification of archive failed [{}]", - cmd, - path.display() - ))); - } - Ok(()) - } -} - -fn change_permissions_recursively( - path: &Path, - dir_mode: u32, - file_mode: u32, -) -> std::io::Result<()> { - if path.is_dir() { - // Set directory permissions to 700 - fs::set_permissions(path, Permissions::from_mode(dir_mode))?; - - for entry in fs::read_dir(path)? { - let entry = entry?; - let path = entry.path(); - - change_permissions_recursively(&path, dir_mode, file_mode)?; - } - } else { - // Set file permissions to 600 - fs::set_permissions(path, Permissions::from_mode(file_mode))?; - } - - Ok(()) -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/Cargo.toml b/source/rust/vendor/ngx-rust/nginx-sys/Cargo.toml deleted file mode 100644 index 3faf6c7..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/Cargo.toml +++ /dev/null @@ -1,47 +0,0 @@ -[package] -name = "nginx-sys" -version = "0.5.0" -categories = ["external-ffi-bindings"] -description = "FFI bindings to NGINX" -keywords = ["nginx", "ffi", "sys"] -build = "build/main.rs" -# This field is required to export DEP_NGINX_ vars -# See https://github.com/rust-lang/cargo/issues/3544 -links = "nginx" -edition.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -rust-version.workspace = true - -[package.metadata.docs.rs] -all-features = true -default-target = "x86_64-unknown-linux-gnu" -targets = [] - -[dependencies] - -[target.'cfg(not(windows))'.dependencies] -errno = { version = "0.3.10", default-features = false } - -[build-dependencies] -bindgen = "0.72.1" -cc = "1.2.0" -dunce = "1.0.5" -regex = "1.11.1" -nginx-src = { version = "~1.30.0", optional = true, path = "../nginx-src" } -shlex = "2" - -[features] -default = ["http"] -# Allows generation of bindings for the HTTP module. -http = [] -# Allows generation of bindings for the Mail module. -mail = [] -# Allows generation of bindings for the Stream module. -stream = [] -# Enables downloading and building a copy of NGINX in the build script. -vendored = ["dep:nginx-src"] - -[lints] -workspace = true diff --git a/source/rust/vendor/ngx-rust/nginx-sys/LICENSE b/source/rust/vendor/ngx-rust/nginx-sys/LICENSE deleted file mode 120000 index ea5b606..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/LICENSE +++ /dev/null @@ -1 +0,0 @@ -../LICENSE \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/nginx-sys/README.md b/source/rust/vendor/ngx-rust/nginx-sys/README.md deleted file mode 100644 index 3750a79..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/README.md +++ /dev/null @@ -1,173 +0,0 @@ -# nginx-sys - -The `nginx-sys` crate provides low-level bindings for the nginx C API, allowing -Rust applications to interact with nginx servers and modules. - -## Usage - -Add `nginx-sys` as a dependency in your `Cargo.toml`: - -```toml -[dependencies] -nginx-sys = "0.5.0" -``` - -Set the path to your nginx sources and build directory using the -[environment variables](#input-variables), or enable the `nginx-sys/vendored` -feature to use a downloaded copy of the nginx sources. - -Note that it is recommended to use the exact source and `configure` arguments -of the nginx build you are planning to use in production. -`configure` arguments alter the APIs and the symbols visible to the Rust code, -and some OS distributions are known to ship nginx packages with API-breaking -patches applied. - -## Features - -- `http` - **Enabled** by default. Allows generation of bindings for the HTTP - module, `ngx_http.h`. - The feature will be ignored if NGINX is configured without HTTP support, - thus it may be necessary to check for `http` in - [`DEP_NGINX_FEATURES`](#dep_nginx_features). - -- `mail`: Allows generation of bindings for the Mail module, `ngx_mail.h`. - The feature will be ignored if NGINX is configured without Mail support, - thus it may be necessary to check for `mail` in - [`DEP_NGINX_FEATURES`](#dep_nginx_features). - -- `stream`: Allows generation of bindings for the Stream module, `ngx_stream.h`. - The feature will be ignored if NGINX is configured without Stream support, - thus it may be necessary to check for `stream` in - [`DEP_NGINX_FEATURES`](#dep_nginx_features). - -- `vendored`: Enables the build scripts to download and build a copy of nginx - source and link against it. - See `nginx-src` crate documentation for additional details. - -## Input variables - -`NGINX_SOURCE_DIR`, `NGINX_BUILD_DIR` control paths to an external nginx source -tree and a configured build directory. Normally, specifying either of these is -sufficient, as the build directory defaults to `objs` under the source dir. - -However, it's possible to set the latter to any valid path with -`configure --builddir=<...>`, and we need _both_ paths to support such -configuration. - -The variables above are optional, but take preference when the `vendored` crate -feature is enabled. - -## Output variables - -Following metadata variables are passed to the build scripts of any **direct** -dependents of the package. - -Check the [using another sys crate] and the [links manifest key] sections of the -Cargo Book for more details about passing metadata between packages. - -### `DEP_NGINX_FEATURES` - -nginx has various configuration options that may affect the availability of -functions, constants and structure fields. This is not something that can be -detected at runtime, as an attempt to use a symbol unavailable in the bindings -would result in compilation error. - -`DEP_NGINX_FEATURES_CHECK` contains the full list of feature flags supported -by `nginx-sys`, i.e. everything that can be used for feature checks. -The most common use for this variable is to specify [`cargo::rustc-check-cfg`]. - -`DEP_NGINX_FEATURES` contains the list of features enabled in the version of -nginx being built against. - -An example of a build script with these variables: - -```rust -// Specify acceptable values for `ngx_feature`. -println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES_CHECK"); -println!( - "cargo::rustc-check-cfg=cfg(ngx_feature, values({}))", - std::env::var("DEP_NGINX_FEATURES_CHECK").unwrap_or("any()".to_string()) -); -// Read feature flags detected by nginx-sys and pass to the compiler. -println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES"); -if let Ok(features) = std::env::var("DEP_NGINX_FEATURES") { - for feature in features.split(',').map(str::trim) { - println!("cargo::rustc-cfg=ngx_feature=\"{}\"", feature); - } -} -``` - -And an usage example: - -```rust -#[cfg(ngx_feature = "debug")] -println!("this nginx binary was built with debug logging enabled"); -``` - -### `DEP_NGINX_OS` - -Version, as detected by the nginx configuration script. - -`DEP_NGINX_OS_CHECK` contains the full list of supported values, and -`DEP_NGINX_OS` the currently detected one. - -Usage examples: - -```rust -// Specify acceptable values for `ngx_os` -println!("cargo::rerun-if-env-changed=DEP_NGINX_OS_CHECK"); -println!( - "cargo::rustc-check-cfg=cfg(ngx_os, values({}))", - std::env::var("DEP_NGINX_OS_CHECK").unwrap_or("any()".to_string()) -); -// Read operating system detected by nginx-sys and pass to the compiler. -println!("cargo::rerun-if-env-changed=DEP_NGINX_OS"); -if let Ok(os) = std::env::var("DEP_NGINX_OS") { - println!("cargo::rustc-cfg=ngx_os=\"{}\"", os); -} -``` - -```rust -#[cfg(ngx_os = "freebsd")] -println!("this nginx binary was built on FreeBSD"); -``` - -### Version and build information - -- `DEP_NGINX_VERSION_NUMBER`: - a numeric representation with 3 digits for each component: `1026002` -- `DEP_NGINX_VERSION`: - human-readable string in a product/version format: `nginx/1.26.2` -- `DEP_NGINX_BUILD`: - version string with the optional build name (`--build=`) included: - `nginx/1.25.5 (nginx-plus-r32)` - -Usage example: - -```rust -println!("cargo::rustc-check-cfg=cfg(nginx1_27_0)"); -println!("cargo::rerun-if-env-changed=DEP_NGINX_VERSION_NUMBER"); -if let Ok(version) = std::env::var("DEP_NGINX_VERSION_NUMBER") { - let version: u64 = version.parse().unwrap(); - - if version >= 1_027_000 { - println!("cargo::rustc-cfg=nginx1_27_0"); - } -} -``` - -## Examples - -### Get nginx Version - -This example demonstrates how to retrieve the version of the nginx server. - -```rust,no_run -use nginx_sys::nginx_version; - -println!("nginx version: {}", nginx_version); -``` - -[using another sys crate]: https://doc.rust-lang.org/nightly/cargo/reference/build-script-examples.html#using-another-sys-crate -[links manifest key]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#the-links-manifest-key -[`cargo::rustc-check-cfg`]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#rustc-check-cfg diff --git a/source/rust/vendor/ngx-rust/nginx-sys/build/main.rs b/source/rust/vendor/ngx-rust/nginx-sys/build/main.rs deleted file mode 100644 index 8f85bd0..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/build/main.rs +++ /dev/null @@ -1,484 +0,0 @@ -extern crate bindgen; - -use std::env; -use std::error::Error as StdError; -use std::fs::{read_to_string, File}; -use std::io::Write; -use std::path::{Path, PathBuf}; - -const ENV_VARS_TRIGGERING_RECOMPILE: &[&str] = &["OUT_DIR", "NGINX_BUILD_DIR", "NGINX_SOURCE_DIR"]; - -/// The feature flags set by the nginx configuration script. -/// -/// This list is a subset of NGX_/NGX_HAVE_ macros known to affect the structure layout or module -/// avialiability. -/// -/// The flags will be exposed to the buildscripts of _direct_ dependendents of this crate as -/// `DEP_NGINX_FEATURES` environment variable. -/// The list of recognized values will be exported as `DEP_NGINX_FEATURES_CHECK`. -const NGX_CONF_FEATURES: &[&str] = &[ - "compat", - "debug", - "have_epollrdhup", - "have_file_aio", - "have_kqueue", - "have_memalign", - "have_posix_memalign", - "have_sched_yield", - "have_variadic_macros", - "http", - "http_cache", - "http_dav", - "http_gzip", - "http_realip", - "http_ssi", - "http_ssl", - "http_upstream_zone", - "http_v2", - "http_v3", - "http_x_forwarded_for", - "pcre", - "pcre2", - "quic", - "ssl", - "stream", - "stream_ssl", - "stream_upstream_zone", - "threads", -]; - -/// The operating systems supported by the nginx configuration script -/// -/// The detected value will be exposed to the buildsrcipts of _direct_ dependents of this crate as -/// `DEP_NGINX_OS` environment variable. -/// The list of recognized values will be exported as `DEP_NGINX_OS_CHECK`. -const NGX_CONF_OS: &[&str] = &[ - "darwin", "freebsd", "gnu_hurd", "hpux", "linux", "solaris", "tru64", "win32", -]; - -type BoxError = Box; - -/// Function invoked when `cargo build` is executed. -/// This function will download NGINX and all supporting dependencies, verify their integrity, -/// extract them, execute autoconf `configure` for NGINX, compile NGINX and finally install -/// NGINX in a subdirectory with the project. -fn main() -> Result<(), BoxError> { - // Hint cargo to rebuild if any of the these environment variables values change - // because they will trigger a recompilation of NGINX with different parameters - for var in ENV_VARS_TRIGGERING_RECOMPILE { - println!("cargo:rerun-if-env-changed={var}"); - } - println!("cargo:rerun-if-changed=build/main.rs"); - println!("cargo:rerun-if-changed=build/wrapper.h"); - - let nginx = NginxSource::from_env(); - println!( - "cargo:rerun-if-changed={}", - nginx.build_dir.join("Makefile").to_string_lossy() - ); - println!( - "cargo:rerun-if-changed={}", - nginx.build_dir.join("ngx_auto_config.h").to_string_lossy() - ); - // Read autoconf generated makefile for NGINX and generate Rust bindings based on its includes - generate_binding(&nginx); - Ok(()) -} - -pub struct NginxSource { - source_dir: PathBuf, - build_dir: PathBuf, -} - -impl NginxSource { - pub fn new(source_dir: impl AsRef, build_dir: impl AsRef) -> Self { - let source_dir = NginxSource::check_source_dir(source_dir).expect("source directory"); - let build_dir = NginxSource::check_build_dir(build_dir).expect("build directory"); - - Self { - source_dir, - build_dir, - } - } - - pub fn from_env() -> Self { - match ( - env::var_os("NGINX_SOURCE_DIR"), - env::var_os("NGINX_BUILD_DIR"), - ) { - (Some(source_dir), Some(build_dir)) => NginxSource::new(source_dir, build_dir), - (Some(source_dir), None) => Self::from_source_dir(source_dir), - (None, Some(build_dir)) => Self::from_build_dir(build_dir), - _ => Self::from_vendored(), - } - } - - pub fn from_source_dir(source_dir: impl AsRef) -> Self { - let build_dir = source_dir.as_ref().join("objs"); - - // todo!("Build from source"); - - Self::new(source_dir, build_dir) - } - - pub fn from_build_dir(build_dir: impl AsRef) -> Self { - let source_dir = build_dir - .as_ref() - .parent() - .expect("source directory") - .to_owned(); - Self::new(source_dir, build_dir) - } - - #[cfg(feature = "vendored")] - pub fn from_vendored() -> Self { - nginx_src::print_cargo_metadata(); - - let out_dir = env::var("OUT_DIR").unwrap(); - let build_dir = PathBuf::from(out_dir).join("objs"); - let (source_dir, build_dir) = nginx_src::build(build_dir).expect("nginx-src build"); - - Self { - source_dir, - build_dir, - } - } - - #[cfg(not(feature = "vendored"))] - pub fn from_vendored() -> Self { - panic!( - "\"nginx-sys/vendored\" feature is disabled and neither NGINX_SOURCE_DIR nor \ - NGINX_BUILD_DIR is set" - ); - } - - fn check_source_dir(source_dir: impl AsRef) -> Result { - match dunce::canonicalize(&source_dir) { - Ok(path) if path.join("src/core/nginx.h").is_file() => Ok(path), - Err(err) => Err(format!( - "Invalid nginx source directory: {:?}. {}", - source_dir.as_ref(), - err - ) - .into()), - _ => Err(format!( - "Invalid nginx source directory: {:?}. NGINX_SOURCE_DIR is not specified or \ - contains invalid value.", - source_dir.as_ref() - ) - .into()), - } - } - - fn check_build_dir(build_dir: impl AsRef) -> Result { - match dunce::canonicalize(&build_dir) { - Ok(path) if path.join("ngx_auto_config.h").is_file() => Ok(path), - Err(err) => Err(format!( - "Invalid nginx build directory: {:?}. {}", - build_dir.as_ref(), - err - ) - .into()), - _ => Err(format!( - "Invalid NGINX build directory: {:?}. NGINX_BUILD_DIR is not specified or \ - contains invalid value.", - build_dir.as_ref() - ) - .into()), - } - } -} - -/// Generates Rust bindings for NGINX -fn generate_binding(nginx: &NginxSource) { - let autoconf_makefile_path = nginx.build_dir.join("Makefile"); - let (includes, defines) = parse_makefile(&autoconf_makefile_path); - let includes: Vec<_> = includes - .into_iter() - .map(|path| { - if path.is_absolute() { - path - } else { - nginx.source_dir.join(path) - } - }) - .collect(); - let mut clang_args: Vec = includes - .iter() - .map(|path| format!("-I{}", path.to_string_lossy())) - .collect(); - - clang_args.extend(defines.iter().map(|(n, ov)| { - if let Some(v) = ov { - format!("-D{n}={v}") - } else { - format!("-D{n}") - } - })); - - print_cargo_metadata(nginx, &includes, &defines).expect("cargo dependency metadata"); - - // bindgen targets the latest known stable by default - let rust_target: bindgen::RustTarget = env::var("CARGO_PKG_RUST_VERSION") - .expect("rust-version set in Cargo.toml") - .parse() - .expect("rust-version is valid and supported by bindgen"); - - let bindings = bindgen::Builder::default() - // Bindings will not compile on Linux without block listing this item - // It is worth investigating why this is - .blocklist_item("IPPORT_RESERVED") - // will be restored later in build.rs - .blocklist_item("NGX_ALIGNMENT") - .generate_cstr(true) - // The input header we would like to generate bindings for. - .header("build/wrapper.h") - .clang_args(clang_args) - .layout_tests(false) - .rust_target(rust_target) - .use_core() - .generate() - .expect("Unable to generate bindings"); - - // Write the bindings to the $OUT_DIR/bindings.rs file. - let out_dir_env = - env::var("OUT_DIR").expect("The required environment variable OUT_DIR was not set"); - let out_path = PathBuf::from(out_dir_env); - bindings - .write_to_file(out_path.join("bindings.rs")) - .expect("Couldn't write bindings!"); -} - -/// Reads through the makefile generated by autoconf and finds all of the includes -/// and definitions used to compile nginx. This is used to generate the correct bindings -/// for the nginx source code. -pub fn parse_makefile( - nginx_autoconf_makefile_path: &PathBuf, -) -> (Vec, Vec<(String, Option)>) { - fn parse_line( - includes: &mut Vec, - defines: &mut Vec<(String, Option)>, - line: &str, - ) { - let mut words = shlex::Shlex::new(line); - - while let Some(word) = words.next() { - if let Some(inc) = word.strip_prefix("-I") { - let value = if inc.is_empty() { - words.next().expect("-I argument") - } else { - inc.to_string() - }; - includes.push(value); - } else if let Some(def) = word.strip_prefix("-D") { - let def = if def.is_empty() { - words.next().expect("-D argument") - } else { - def.to_string() - }; - - if let Some((name, value)) = def.split_once("=") { - defines.push((name.to_string(), Some(value.to_string()))); - } else { - defines.push((def.to_string(), None)); - } - } - } - } - - let mut all_incs = vec![]; - let mut cflags_includes = vec![]; - - let mut defines = vec![]; - - let makefile_contents = match read_to_string(nginx_autoconf_makefile_path) { - Ok(path) => path, - Err(e) => { - panic!( - "Unable to read makefile from path [{}]. Error: {}", - nginx_autoconf_makefile_path.to_string_lossy(), - e - ); - } - }; - - let lines = makefile_contents.lines(); - let mut line: String = "".to_string(); - for l in lines { - if let Some(part) = l.strip_suffix("\\") { - line += part; - continue; - } - - line += l; - - if let Some(tail) = line.strip_prefix("ALL_INCS") { - parse_line(&mut all_incs, &mut defines, tail); - } else if let Some(tail) = line.strip_prefix("CFLAGS") { - parse_line(&mut cflags_includes, &mut defines, tail); - } - - line.clear(); - } - - cflags_includes.extend(all_incs); - - ( - cflags_includes.into_iter().map(PathBuf::from).collect(), - defines, - ) -} - -/// Collect info about the nginx configuration and expose it to the dependents via -/// `DEP_NGINX_...` variables. -pub fn print_cargo_metadata>( - nginx: &NginxSource, - includes: &[T], - defines: &[(String, Option)], -) -> Result<(), Box> { - // Unquote and merge C string constants - let unquote_re = regex::Regex::new(r#""(.*?[^\\])"\s*"#).unwrap(); - let unquote = |data: &str| -> String { - unquote_re - .captures_iter(data) - .map(|c| c.get(1).unwrap().as_str()) - .collect::>() - .concat() - }; - - let mut ngx_features: Vec = vec![]; - let mut ngx_os = String::new(); - - let expanded = expand_definitions(includes, defines)?; - for line in String::from_utf8(expanded)?.lines() { - let Some((name, value)) = line - .trim() - .strip_prefix("RUST_CONF_") - .and_then(|x| x.split_once('=')) - else { - continue; - }; - - let name = name.trim().to_ascii_lowercase(); - let value = value.trim(); - - if name == "nginx_build" { - println!("cargo::metadata=build={}", unquote(value)); - } else if name == "nginx_version" { - println!("cargo::metadata=version={}", unquote(value)); - } else if name == "nginx_version_number" { - println!("cargo::metadata=version_number={value}"); - } else if NGX_CONF_OS.contains(&name.as_str()) { - ngx_os = name; - } else if NGX_CONF_FEATURES.contains(&name.as_str()) && value != "0" { - ngx_features.push(name); - } - } - - println!( - "cargo::metadata=build_dir={}", - nginx.build_dir.to_str().expect("Unicode build path") - ); - - println!( - "cargo::metadata=include={}", - // The str conversion is necessary because cargo directives must be valid UTF-8 - env::join_paths(includes.iter().map(|x| x.as_ref()))? - .to_str() - .expect("Unicode include paths") - ); - - println!( - "cargo:metadata=cflags={}", - defines - .iter() - .map(|(n, ov)| if let Some(v) = ov { - format!("-D{n}={v}") - } else { - format!("-D{n}") - }) - .collect::>() - .join(" ") - ); - - // A quoted list of all recognized features to be passed to rustc-check-cfg. - let values = NGX_CONF_FEATURES.join("\",\""); - println!("cargo::metadata=features_check=\"{values}\""); - println!("cargo::rustc-check-cfg=cfg(ngx_feature, values(\"{values}\"))"); - - // A list of features enabled in the nginx build we're using - println!("cargo::metadata=features={}", ngx_features.join(",")); - for feature in ngx_features { - println!("cargo::rustc-cfg=ngx_feature=\"{feature}\""); - } - - // A quoted list of all recognized operating systems to be passed to rustc-check-cfg. - let values = NGX_CONF_OS.join("\",\""); - println!("cargo::metadata=os_check=\"{values}\""); - println!("cargo::rustc-check-cfg=cfg(ngx_os, values(\"{values}\"))"); - // Current detected operating system - println!("cargo::metadata=os={ngx_os}"); - println!("cargo::rustc-cfg=ngx_os=\"{ngx_os}\""); - - Ok(()) -} - -fn expand_definitions>( - includes: &[T], - defines: &[(String, Option)], -) -> Result, Box> { - let path = PathBuf::from(env::var("OUT_DIR")?).join("expand.c"); - let mut writer = std::io::BufWriter::new(File::create(&path)?); - - write!( - writer, - " -#include -#include - -/* C23 or Clang/GCC/MSVC >= 15.3 extension */ -#if defined(__has_include) - -#if __has_include() -RUST_CONF_HTTP=1 -#endif - -#if __has_include() -RUST_CONF_STREAM=1 -#endif - -#else -/* fallback */ -RUST_CONF_HTTP=1 -#endif - -RUST_CONF_NGINX_BUILD=NGINX_VER_BUILD -RUST_CONF_NGINX_VERSION=NGINX_VER -RUST_CONF_NGINX_VERSION_NUMBER=nginx_version -" - )?; - - for flag in NGX_CONF_FEATURES.iter().chain(NGX_CONF_OS.iter()) { - let flag = flag.to_ascii_uppercase(); - write!( - writer, - " -#if defined(NGX_{flag}) -RUST_CONF_{flag}=NGX_{flag} -#endif" - )?; - } - - writer.flush()?; - drop(writer); - - let mut builder = cc::Build::new(); - - builder.includes(includes).file(path); - - for def in defines { - builder.define(&def.0, def.1.as_deref()); - } - - Ok(builder.try_expand()?) -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/build/wrapper.h b/source/rust/vendor/ngx-rust/nginx-sys/build/wrapper.h deleted file mode 100644 index 552a793..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/build/wrapper.h +++ /dev/null @@ -1,34 +0,0 @@ -#include -#include - -/* __has_include was a compiler-specific extension until C23, - * but it's safe to assume that bindgen supports it via libclang. - */ -#if defined(__has_include) - -#if __has_include() -#include -#endif - -#if __has_include() -#include -#endif - -#else -#include -#endif - -const char *NGX_RS_MODULE_SIGNATURE = NGX_MODULE_SIGNATURE; - -// NGX_ALIGNMENT could be defined as a constant or an expression, with the -// latter being unsupported by bindgen. -const size_t NGX_RS_ALIGNMENT = NGX_ALIGNMENT; - -// `--prefix=` results in not emitting the declaration -#ifndef NGX_PREFIX -#define NGX_PREFIX "" -#endif - -#ifndef NGX_CONF_PREFIX -#define NGX_CONF_PREFIX NGX_PREFIX -#endif diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/detail.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/detail.rs deleted file mode 100644 index c2cbe3f..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/detail.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Implementation details shared between nginx-sys and ngx. -#![allow(missing_docs)] - -use core::fmt; -use core::ptr::copy_nonoverlapping; - -use crate::bindings::{ngx_pnalloc, ngx_pool_t, u_char}; - -/// Convert a byte slice to a raw pointer (`*mut u_char`) allocated in the given nginx memory pool. -/// -/// # Safety -/// -/// The caller must provide a valid pointer to the memory pool. -pub unsafe fn bytes_to_uchar(pool: *mut ngx_pool_t, data: &[u8]) -> Option<*mut u_char> { - let ptr: *mut u_char = unsafe { ngx_pnalloc(pool, data.len()) as _ }; - if ptr.is_null() { - return None; - } - unsafe { copy_nonoverlapping(data.as_ptr(), ptr, data.len()) }; - Some(ptr) -} - -/// Convert a string slice (`&str`) to a raw pointer (`*mut u_char`) allocated in the given nginx -/// memory pool. -/// -/// # Arguments -/// -/// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`). -/// * `data` - The string slice to convert to a raw pointer. -/// -/// # Safety -/// This function is marked as unsafe because it involves raw pointer manipulation and direct memory -/// allocation using `ngx_pnalloc`. -/// -/// # Returns -/// A raw pointer (`*mut u_char`) to the allocated memory containing the converted string data. -/// -/// # Example -/// ```rust,ignore -/// let pool: *mut ngx_pool_t = ...; // Obtain a pointer to the nginx memory pool -/// let data: &str = "example"; // The string to convert -/// let ptr = str_to_uchar(pool, data); -/// ``` -pub unsafe fn str_to_uchar(pool: *mut ngx_pool_t, data: &str) -> *mut u_char { - let ptr: *mut u_char = unsafe { ngx_pnalloc(pool, data.len()) as _ }; - debug_assert!(!ptr.is_null()); - unsafe { copy_nonoverlapping(data.as_ptr(), ptr, data.len()) }; - ptr -} - -#[inline] -pub fn debug_bytes(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result { - if f.alternate() { - match bytes.len() { - 0 => Ok(()), - 1 => write!(f, "{:02x}", bytes[0]), - x => { - for b in &bytes[..x - 1] { - write!(f, "{b:02x},")?; - } - write!(f, "{:02x}", bytes[x - 1]) - } - } - } else { - f.write_str("\"")?; - display_bytes(f, bytes)?; - f.write_str("\"") - } -} - -#[inline] -pub fn display_bytes(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result { - // The implementation is similar to an inlined `String::from_utf8_lossy`, with two - // important differences: - // - // - it writes directly to the Formatter instead of allocating a temporary String - // - invalid sequences are represented as escaped individual bytes - for chunk in bytes.utf8_chunks() { - f.write_str(chunk.valid())?; - for byte in chunk.invalid() { - write!(f, "\\x{byte:02x}")?; - } - } - - Ok(()) -} - -#[cfg(test)] -mod tests { - extern crate alloc; - use alloc::format; - use alloc::string::ToString; - - use super::*; - - struct TestStr(&'static [u8]); - - impl fmt::Debug for TestStr { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("TestStr(")?; - debug_bytes(f, self.0)?; - f.write_str(")") - } - } - - impl fmt::Display for TestStr { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - display_bytes(f, self.0) - } - } - - #[test] - fn test_display() { - let cases: &[(&[u8], &str)] = &[ - (b"", ""), - (b"Ferris the \xf0\x9f\xa6\x80", "Ferris the 🦀"), - (b"\xF0\x90\x80", "\\xf0\\x90\\x80"), - (b"\xF0\x90\x80Hello World", "\\xf0\\x90\\x80Hello World"), - (b"Hello \xF0\x90\x80World", "Hello \\xf0\\x90\\x80World"), - (b"Hello World\xF0\x90\x80", "Hello World\\xf0\\x90\\x80"), - ]; - - for (bytes, expected) in cases { - let str = TestStr(bytes); - assert_eq!(str.to_string(), *expected); - } - - // Check that the formatter arguments are ignored correctly - for (bytes, expected) in &cases[2..3] { - let str = TestStr(bytes); - assert_eq!(format!("{str:12.12}"), *expected); - } - } - - #[test] - fn test_debug() { - let cases: &[(&[u8], &str, &str)] = &[ - (b"", "TestStr(\"\")", "TestStr()"), - (b"a", "TestStr(\"a\")", "TestStr(61)"), - ( - b"Ferris the \xf0\x9f\xa6\x80", - "TestStr(\"Ferris the 🦀\")", - "TestStr(46,65,72,72,69,73,20,74,68,65,20,f0,9f,a6,80)", - ), - (b"\xF0\x90\x80", "TestStr(\"\\xf0\\x90\\x80\")", "TestStr(f0,90,80)"), - ]; - for (bytes, expected, alternate) in cases { - let str = TestStr(bytes); - assert_eq!(format!("{str:?}"), *expected); - assert_eq!(format!("{str:#?}"), *alternate); - } - } -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/event.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/event.rs deleted file mode 100644 index af7c0ff..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/event.rs +++ /dev/null @@ -1,85 +0,0 @@ -use core::ptr; - -use crate::{ - NGX_TIMER_LAZY_DELAY, ngx_current_msec, ngx_event_t, ngx_event_timer_rbtree, ngx_msec_t, - ngx_queue_insert_before, ngx_queue_remove, ngx_queue_t, ngx_rbtree_delete, ngx_rbtree_insert, -}; - -/// Sets a timeout for an event. -/// -/// # Safety -/// -///`ev` must be a valid pointer to an `ngx_event_t`. -#[inline] -pub unsafe fn ngx_add_timer(ev: *mut ngx_event_t, timer: ngx_msec_t) { - unsafe { - let key: ngx_msec_t = ngx_current_msec.wrapping_add(timer); - - if (*ev).timer_set() != 0 { - /* - * Use a previous timer value if difference between it and a new - * value is less than NGX_TIMER_LAZY_DELAY milliseconds: this allows - * to minimize the rbtree operations for fast connections. - */ - if key.abs_diff((*ev).timer.key) < NGX_TIMER_LAZY_DELAY as _ { - return; - } - - ngx_del_timer(ev); - } - - (*ev).timer.key = key; - - ngx_rbtree_insert(&raw mut ngx_event_timer_rbtree, &raw mut (*ev).timer); - - (*ev).set_timer_set(1); - } -} - -/// Deletes a previously set timeout. -/// -/// # Safety -/// -/// `ev` must be a valid pointer to an `ngx_event_t`, previously armed with [ngx_add_timer]. -#[inline] -pub unsafe fn ngx_del_timer(ev: *mut ngx_event_t) { - unsafe { - ngx_rbtree_delete(&raw mut ngx_event_timer_rbtree, &raw mut (*ev).timer); - - (*ev).timer.left = ptr::null_mut(); - (*ev).timer.right = ptr::null_mut(); - (*ev).timer.parent = ptr::null_mut(); - - (*ev).set_timer_set(0); - } -} - -/// Post the event `ev` to the post queue `q`. -/// -/// # Safety -/// -/// `ev` must be a valid pointer to an `ngx_event_t`. -/// `q` is a valid pointer to a queue head. -#[inline] -pub unsafe fn ngx_post_event(ev: *mut ngx_event_t, q: *mut ngx_queue_t) { - unsafe { - if (*ev).posted() == 0 { - (*ev).set_posted(1); - ngx_queue_insert_before(q, &raw mut (*ev).queue); - } - } -} - -/// Deletes the event `ev` from the queue it's currently posted in. -/// -/// # Safety -/// -/// `ev` must be a valid pointer to an `ngx_event_t`. -/// `ev.queue` is initialized with `ngx_queue_init`. -#[inline] -pub unsafe fn ngx_delete_posted_event(ev: *mut ngx_event_t) { - unsafe { - (*ev).set_posted(0); - ngx_queue_remove(&raw mut (*ev).queue); - } -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/http.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/http.rs deleted file mode 100644 index 435cc79..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/http.rs +++ /dev/null @@ -1,18 +0,0 @@ -use core::mem::offset_of; - -use crate::bindings::ngx_http_conf_ctx_t; - -/// The offset of the `main_conf` field in the `ngx_http_conf_ctx_t` struct. -/// -/// This is used to access the main configuration context for an HTTP module. -pub const NGX_HTTP_MAIN_CONF_OFFSET: usize = offset_of!(ngx_http_conf_ctx_t, main_conf); - -/// The offset of the `srv_conf` field in the `ngx_http_conf_ctx_t` struct. -/// -/// This is used to access the server configuration context for an HTTP module. -pub const NGX_HTTP_SRV_CONF_OFFSET: usize = offset_of!(ngx_http_conf_ctx_t, srv_conf); - -/// The offset of the `loc_conf` field in the `ngx_http_conf_ctx_t` struct. -/// -/// This is used to access the location configuration context for an HTTP module. -pub const NGX_HTTP_LOC_CONF_OFFSET: usize = offset_of!(ngx_http_conf_ctx_t, loc_conf); diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/lib.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/lib.rs deleted file mode 100644 index a3e3454..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/lib.rs +++ /dev/null @@ -1,352 +0,0 @@ -#![doc = include_str!("../README.md")] -#![warn(missing_docs)] -#![no_std] - -pub mod detail; -mod event; -#[cfg(all(feature = "http", ngx_feature = "http"))] -mod http; -#[cfg(all(feature = "mail", ngx_feature = "mail"))] -mod mail; -mod queue; -mod rbtree; -#[cfg(all(feature = "stream", ngx_feature = "stream"))] -mod stream; -mod string; - -use core::ptr; - -#[doc(hidden)] -mod bindings { - #![allow(unknown_lints)] // unnecessary_transmutes - #![allow(missing_docs)] - #![allow(non_upper_case_globals)] - #![allow(non_camel_case_types)] - #![allow(non_snake_case)] - #![allow(dead_code)] - #![allow(clippy::all)] - #![allow(improper_ctypes)] - #![allow(rustdoc::broken_intra_doc_links)] - #![allow(unnecessary_transmutes)] - include!(concat!(env!("OUT_DIR"), "/bindings.rs")); -} -#[doc(no_inline)] -pub use bindings::*; -pub use event::*; -#[cfg(all(feature = "http", ngx_feature = "http"))] -pub use http::*; -#[cfg(all(feature = "mail", ngx_feature = "mail"))] -pub use mail::*; -pub use queue::*; -pub use rbtree::*; -#[cfg(all(feature = "stream", ngx_feature = "stream"))] -pub use stream::*; - -/// Default alignment for pool allocations. -pub const NGX_ALIGNMENT: usize = NGX_RS_ALIGNMENT; - -/// Sentinel returned by `ngx_resolve_start()` when no resolver is configured. -/// -/// nginx's `NGX_NO_RESOLVER` macro expands to `(void *) -1`, which bindgen does -/// not emit. It is an address-only sentinel that must never be dereferenced; -/// callers compare the `ngx_resolve_start()` return value against it. -pub const NGX_NO_RESOLVER: *mut ngx_resolver_ctx_t = ptr::without_provenance_mut(usize::MAX); - -// Check if the allocations made with ngx_palloc are properly aligned. -// If the check fails, objects allocated from `ngx_pool` can violate Rust pointer alignment -// requirements. -const _: () = assert!(core::mem::align_of::() <= NGX_ALIGNMENT); - -impl ngx_array_t { - /// Returns the contents of this array as a slice of `T`. - /// - /// # Safety - /// - /// The array must be a valid, initialized array containing elements of type T or compatible in - /// layout with T (e.g. `#[repr(transparent)]` wrappers). - pub unsafe fn as_slice(&self) -> &[T] { - debug_assert_eq!( - core::mem::size_of::(), - self.size, - "ngx_array_t::as_slice(): element size mismatch" - ); - if self.nelts == 0 { - &[] - } else { - // SAFETY: in a valid array, `elts` is a valid well-aligned pointer to at least `nelts` - // elements of size `size` - unsafe { core::slice::from_raw_parts(self.elts.cast(), self.nelts) } - } - } - - /// Returns the contents of this array as a mutable slice of `T`. - /// - /// # Safety - /// - /// The array must be a valid, initialized array containing elements of type T or compatible in - /// layout with T (e.g. `#[repr(transparent)]` wrappers). - pub unsafe fn as_slice_mut(&mut self) -> &mut [T] { - debug_assert_eq!( - core::mem::size_of::(), - self.size, - "ngx_array_t::as_slice_mut(): element size mismatch" - ); - if self.nelts == 0 { - &mut [] - } else { - // SAFETY: in a valid array, `elts` is a valid well-aligned pointer to at least `nelts` - // elements of size `size` - unsafe { core::slice::from_raw_parts_mut(self.elts.cast(), self.nelts) } - } - } -} - -impl ngx_command_t { - /// Creates a new empty [`ngx_command_t`] instance. - /// - /// This method replaces the `ngx_null_command` C macro. This is typically used to terminate an - /// array of configuration directives. - /// - /// [`ngx_command_t`]: https://nginx.org/en/docs/dev/development_guide.html#config_directives - pub const fn empty() -> Self { - Self { - name: ngx_str_t::empty(), - type_: 0, - set: None, - conf: 0, - offset: 0, - post: ptr::null_mut(), - } - } -} - -impl ngx_module_t { - /// Create a new `ngx_module_t` instance with default values. - pub const fn default() -> Self { - Self { - ctx_index: ngx_uint_t::MAX, - index: ngx_uint_t::MAX, - name: ptr::null_mut(), - spare0: 0, - spare1: 0, - version: nginx_version as ngx_uint_t, - signature: NGX_RS_MODULE_SIGNATURE.as_ptr(), - ctx: ptr::null_mut(), - commands: ptr::null_mut(), - type_: 0, - init_master: None, - init_module: None, - init_process: None, - init_thread: None, - exit_thread: None, - exit_process: None, - exit_master: None, - spare_hook0: 0, - spare_hook1: 0, - spare_hook2: 0, - spare_hook3: 0, - spare_hook4: 0, - spare_hook5: 0, - spare_hook6: 0, - spare_hook7: 0, - } - } -} - -impl ngx_variable_value_t { - /// Returns the contents of this variable value as a byte slice. - pub fn as_bytes(&self) -> &[u8] { - match self.len() { - 0 => &[], - // SAFETY: data for non-empty value must be a valid well-aligned pointer. - len => unsafe { core::slice::from_raw_parts(self.data, len as usize) }, - } - } -} - -impl AsRef<[u8]> for ngx_variable_value_t { - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } -} - -/// Returns the error code of the last failed operation (`errno`). -#[inline] -pub fn ngx_errno() -> ngx_err_t { - // SAFETY: GetLastError takes no arguments and reads a thread-local variable - #[cfg(windows)] - let err = unsafe { GetLastError() }; - - #[cfg(not(windows))] - let err = errno::errno().0; - - err as ngx_err_t -} - -/// Sets the error code (`errno`). -#[inline] -pub fn ngx_set_errno(err: ngx_err_t) { - #[cfg(windows)] - // SAFETY: SetLastError takes one argument by value and updates a thread-local variable - unsafe { - SetLastError(err as _) - } - #[cfg(not(windows))] - errno::set_errno(errno::Errno(err as _)) -} - -/// Returns the error code of the last failed sockets operation. -#[inline] -pub fn ngx_socket_errno() -> ngx_err_t { - // SAFETY: WSAGetLastError takes no arguments and reads a thread-local variable - #[cfg(windows)] - let err = unsafe { WSAGetLastError() }; - - #[cfg(not(windows))] - let err = errno::errno().0; - - err as ngx_err_t -} - -/// Sets the error code of the sockets operation. -#[inline] -pub fn ngx_set_socket_errno(err: ngx_err_t) { - #[cfg(windows)] - // SAFETY: WSaSetLastError takes one argument by value and updates a thread-local variable - unsafe { - WSASetLastError(err as _) - } - #[cfg(not(windows))] - errno::set_errno(errno::Errno(err as _)) -} - -/// Returns a non cryptograhpically-secure pseudo-random integer. -#[inline] -pub fn ngx_random() -> core::ffi::c_long { - #[cfg(windows)] - unsafe { - // Emulate random() as Microsoft CRT does not provide it. - // rand() should be thread-safe in the multi-threaded CRT we link to, but will not be seeded - // outside of the main thread. - let x: u32 = ((rand() as u32) << 16) ^ ((rand() as u32) << 8) ^ (rand() as u32); - (0x7fffffff & x) as _ - } - #[cfg(not(windows))] - unsafe { - random() - } -} - -/// Causes the calling thread to relinquish the CPU. -#[inline] -pub fn ngx_sched_yield() { - #[cfg(windows)] - unsafe { - SwitchToThread() - }; - #[cfg(all(not(windows), ngx_feature = "have_sched_yield"))] - unsafe { - sched_yield() - }; - #[cfg(not(any(windows, ngx_feature = "have_sched_yield")))] - unsafe { - usleep(1) - } -} - -/// Returns cached timestamp in seconds, updated at the start of the event loop iteration. -/// -/// Can be stale when accessing from threads, see [ngx_time_update]. -#[inline] -pub fn ngx_time() -> time_t { - // SAFETY: ngx_cached_time is initialized before any module code can run - unsafe { (*ngx_cached_time).sec } -} - -/// Returns cached time, updated at the start of the event loop iteration. -/// -/// Can be stale when accessing from threads, see [ngx_time_update]. -/// A cached reference to the ngx_timeofday() result is guaranteed to remain unmodified for the next -/// NGX_TIME_SLOTS seconds. -#[inline] -pub fn ngx_timeofday() -> &'static ngx_time_t { - // SAFETY: ngx_cached_time is initialized before any module code can run - unsafe { &*ngx_cached_time } -} - -/// Initialize a list, using a pool for the backing memory, with capacity to store the given number -/// of elements and element size. -/// -/// # Safety -/// * `list` must be non-null -/// * `pool` must be a valid pool -#[inline] -pub unsafe fn ngx_list_init( - list: *mut ngx_list_t, - pool: *mut ngx_pool_t, - n: ngx_uint_t, - size: usize, -) -> ngx_int_t { - unsafe { - (*list).part.elts = ngx_palloc(pool, n * size); - if (*list).part.elts.is_null() { - return NGX_ERROR as ngx_int_t; - } - (*list).part.nelts = 0; - (*list).part.next = ptr::null_mut(); - (*list).last = &raw mut (*list).part; - (*list).size = size; - (*list).nalloc = n; - (*list).pool = pool; - NGX_OK as ngx_int_t - } -} - -/// Add a key-value pair to an nginx table entry (`ngx_table_elt_t`) in the given nginx memory pool. -/// -/// # Arguments -/// -/// * `table` - A pointer to the nginx table entry (`ngx_table_elt_t`) to modify. -/// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`) for memory allocation. -/// * `key` - The key string to add to the table entry. -/// * `value` - The value string to add to the table entry. -/// -/// # Safety -/// This function is marked as unsafe because it involves raw pointer manipulation and direct memory -/// allocation using `str_to_uchar`. -/// -/// # Returns -/// An `Option<()>` representing the result of the operation. `Some(())` indicates success, while -/// `None` indicates a null table pointer. -/// -/// # Example -/// ```rust -/// # use nginx_sys::*; -/// # unsafe fn example(pool: *mut ngx_pool_t, headers: *mut ngx_list_t) { -/// // Obtain a pointer to the nginx table entry -/// let table: *mut ngx_table_elt_t = ngx_list_push(headers).cast(); -/// assert!(!table.is_null()); -/// let key: &str = "key"; // The key to add -/// let value: &str = "value"; // The value to add -/// let result = add_to_ngx_table(table, pool, key, value); -/// # } -/// ``` -pub unsafe fn add_to_ngx_table( - table: *mut ngx_table_elt_t, - pool: *mut ngx_pool_t, - key: impl AsRef<[u8]>, - value: impl AsRef<[u8]>, -) -> Option<()> { - if let Some(table) = unsafe { table.as_mut() } { - let key = key.as_ref(); - table.key = unsafe { ngx_str_t::from_bytes(pool, key)? }; - table.value = unsafe { ngx_str_t::from_bytes(pool, value.as_ref())? }; - table.lowcase_key = unsafe { ngx_pnalloc(pool, table.key.len).cast() }; - if table.lowcase_key.is_null() { - return None; - } - table.hash = unsafe { ngx_hash_strlow(table.lowcase_key, table.key.data, table.key.len) }; - return Some(()); - } - None -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/mail.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/mail.rs deleted file mode 100644 index 7415fbe..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/mail.rs +++ /dev/null @@ -1,13 +0,0 @@ -use core::mem::offset_of; - -use crate::bindings::ngx_mail_conf_ctx_t; - -/// The offset of the `main_conf` field in the `ngx_mail_conf_ctx_t` struct. -/// -/// This is used to access the main configuration context for a MAIL module. -pub const NGX_MAIL_MAIN_CONF_OFFSET: usize = offset_of!(ngx_mail_conf_ctx_t, main_conf); - -/// The offset of the `srv_conf` field in the `ngx_mail_conf_ctx_t` struct. -/// -/// This is used to access the server configuration context for a MAIL module. -pub const NGX_MAIL_SRV_CONF_OFFSET: usize = offset_of!(ngx_mail_conf_ctx_t, srv_conf); diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/queue.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/queue.rs deleted file mode 100644 index 7dd3432..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/queue.rs +++ /dev/null @@ -1,265 +0,0 @@ -use core::ptr; - -use crate::bindings::ngx_queue_t; - -/// Get a reference to the beginning of a queue node data structure, -/// considering the queue field offset in it. -/// -/// # Safety -/// -/// `$q` must be a valid pointer to the field `$link` in the struct `$type` -#[macro_export] -macro_rules! ngx_queue_data { - ($q:expr, $type:path, $link:ident) => { - $q.byte_sub(::core::mem::offset_of!($type, $link)).cast::<$type>() - }; -} - -/// Initializes the queue head before use. -/// -/// # Safety -/// -/// `q` must be a valid pointer to [ngx_queue_t]. -#[inline] -pub unsafe fn ngx_queue_init(q: *mut ngx_queue_t) { - unsafe { - (*q).prev = q; - (*q).next = q; - } -} - -/// Returns `true` if the queue contains no elements. -/// -/// # Safety -/// -/// `q` must be a valid pointer to [ngx_queue_t], initialized with [ngx_queue_init]. -#[inline] -pub unsafe fn ngx_queue_empty(q: *const ngx_queue_t) -> bool { - unsafe { ptr::eq(q, (*q).prev) } -} - -/// Inserts a new node after the current. -/// -/// # Safety -/// -/// Both `q` and `x` must be valid pointers to [ngx_queue_t] -#[inline] -pub unsafe fn ngx_queue_insert_after(q: *mut ngx_queue_t, x: *mut ngx_queue_t) { - unsafe { - (*x).next = (*q).next; - (*(*x).next).prev = x; - (*x).prev = q; - (*q).next = x; - } -} - -/// Inserts a new node before the current. -/// -/// # Safety -/// -/// Both `q` and `x` must be valid pointers to [ngx_queue_t]. -#[inline] -pub unsafe fn ngx_queue_insert_before(q: *mut ngx_queue_t, x: *mut ngx_queue_t) { - unsafe { - (*x).prev = (*q).prev; - (*(*x).prev).next = x; - (*x).next = q; - (*q).prev = x; - } -} - -/// Removes a node from the queue. -/// -/// # Safety -/// -/// `q` must be a valid pointer to an [ngx_queue_t] node. -#[inline] -pub unsafe fn ngx_queue_remove(q: *mut ngx_queue_t) { - unsafe { - (*(*q).next).prev = (*q).prev; - (*(*q).prev).next = (*q).next; - (*q).prev = ptr::null_mut(); - (*q).next = ptr::null_mut(); - } -} - -/// Splits a queue at a node, returning the queue tail in a separate queue. -/// -/// # Safety -/// -/// `h` must be a valid pointer to a head queue node. -/// `q` must be a node in the queue `h`. -/// `n` must be a valid pointer to [ngx_queue_t]. -#[inline] -pub unsafe fn ngx_queue_split(h: *mut ngx_queue_t, q: *mut ngx_queue_t, n: *mut ngx_queue_t) { - unsafe { - (*n).prev = (*h).prev; - (*(*n).prev).next = n; - (*n).next = q; - (*h).prev = (*q).prev; - (*(*h).prev).next = h; - (*q).prev = n; - } -} - -/// Adds a second queue to the first queue. -/// -/// # Safety -/// -/// Both `h` and `n` must be valid pointers to queue heads, initialized with [ngx_queue_init]. -/// `n` will be left in invalid state, pointing to the subrange of `h` without back references. -#[inline] -pub unsafe fn ngx_queue_add(h: *mut ngx_queue_t, n: *mut ngx_queue_t) { - unsafe { - (*(*h).prev).next = (*n).next; - (*(*n).next).prev = (*h).prev; - (*h).prev = (*n).prev; - (*(*h).prev).next = h; - } -} - -impl ngx_queue_t { - /// Returns `true` if the queue contains no elements. - pub fn is_empty(&self) -> bool { - unsafe { ngx_queue_empty(self) } - } -} - -impl Default for ngx_queue_t { - fn default() -> ngx_queue_t { - ngx_queue_t { prev: ptr::null_mut(), next: ptr::null_mut() } - } -} - -#[cfg(test)] -mod tests { - extern crate alloc; - use alloc::boxed::Box; - - use super::*; - - struct TestData { - value: usize, - queue: ngx_queue_t, - } - - impl TestData { - pub fn new(value: usize) -> *mut Self { - // We should be using `ngx_pool_t` here, but that is not possible without linking to - // the nginx - let mut x = Box::new(Self { value, queue: Default::default() }); - unsafe { ngx_queue_init(&raw mut x.queue) }; - Box::into_raw(x) - } - - pub unsafe fn free(x: *mut Self) { - unsafe { - let _ = Box::from_raw(x); - } - } - } - - impl Drop for TestData { - fn drop(&mut self) { - if !self.queue.next.is_null() && !self.queue.is_empty() { - unsafe { ngx_queue_remove(&raw mut self.queue) }; - } - } - } - - struct Iter { - h: *mut ngx_queue_t, - q: *mut ngx_queue_t, - next: fn(*mut ngx_queue_t) -> *mut ngx_queue_t, - } - - impl Iter { - pub fn new(h: *mut ngx_queue_t) -> Self { - let next = |x: *mut ngx_queue_t| unsafe { (*x).next }; - Self { h, q: next(h), next } - } - - pub fn new_reverse(h: *mut ngx_queue_t) -> Self { - let next = |x: *mut ngx_queue_t| unsafe { (*x).prev }; - Self { h, q: next(h), next } - } - } - - impl Iterator for Iter { - type Item = *mut ngx_queue_t; - - fn next(&mut self) -> Option { - if ptr::eq(self.h, self.q) { - return None; - } - - let item = self.q; - self.q = (self.next)(self.q); - Some(item) - } - } - - #[test] - fn test_queue() { - fn value(q: *mut ngx_queue_t) -> usize { - unsafe { (*ngx_queue_data!(q, TestData, queue)).value } - } - - // Check forward and reverse iteration - fn cmp(h: *mut ngx_queue_t, other: &[usize]) -> bool { - Iter::new(h).map(value).eq(other.iter().cloned()) - && Iter::new_reverse(h).map(value).eq(other.iter().rev().cloned()) - } - - // Note how this test does not use references or borrows to avoid triggering UBs - // detectable by Miri. This does not mean that the code is safe or sound. - unsafe { - // Initialize and fill the queue - - let mut h1 = ngx_queue_t::default(); - ngx_queue_init(&raw mut h1); - - let mut h2 = ngx_queue_t::default(); - ngx_queue_init(&raw mut h2); - - for i in 1..=5 { - let elem = TestData::new(i); - ngx_queue_insert_before(&raw mut h1, &raw mut (*elem).queue); - - let elem = TestData::new(i); - ngx_queue_insert_after(&raw mut h2, &raw mut (*elem).queue); - } - - // Iterate and test the values - - assert!(cmp(&raw mut h1, &[1, 2, 3, 4, 5])); - assert!(cmp(&raw mut h2, &[5, 4, 3, 2, 1])); - - // Move nodes from h2 to h1 - - // h2 still points to the subrange of h1 after this operation - ngx_queue_add(&raw mut h1, &raw mut h2); - - assert!(cmp(&raw mut h1, &[1, 2, 3, 4, 5, 5, 4, 3, 2, 1])); - - ngx_queue_split(&raw mut h1, (*h2.next).next, &raw mut h2); - - assert!(cmp(&raw mut h1, &[1, 2, 3, 4, 5, 5])); - assert!(cmp(&raw mut h2, &[4, 3, 2, 1])); - - // Cleanup - - for q in Iter::new(&raw mut h1) { - let td = ngx_queue_data!(q, TestData, queue); - TestData::free(td); - } - assert!(h1.is_empty()); - - for q in Iter::new(&raw mut h2) { - let td = ngx_queue_data!(q, TestData, queue); - TestData::free(td); - } - assert!(h2.is_empty()); - }; - } -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/rbtree.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/rbtree.rs deleted file mode 100644 index daa28c4..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/rbtree.rs +++ /dev/null @@ -1,85 +0,0 @@ -use core::ptr; - -use crate::bindings::{ngx_rbtree_insert_pt, ngx_rbtree_node_t, ngx_rbtree_t}; - -/// Get a reference to the beginning of a tree element data structure, -/// considering the link field offset in it. -/// -/// # Safety -/// -/// `$node` must be a valid pointer to the field `$link` in the struct `$type` -#[macro_export] -macro_rules! ngx_rbtree_data { - ($node:expr, $type:path, $link:ident) => { - $node.byte_sub(::core::mem::offset_of!($type, $link)).cast::<$type>() - }; -} - -/// Initializes the RbTree with specified sentinel and insert function. -/// -/// # Safety -/// -/// All of the pointers passed must be valid. -/// `sentinel` is expected to be valid for the whole lifetime of the `tree`. -pub unsafe fn ngx_rbtree_init( - tree: *mut ngx_rbtree_t, - sentinel: *mut ngx_rbtree_node_t, - insert: ngx_rbtree_insert_pt, -) { - unsafe { - ngx_rbtree_sentinel_init(sentinel); - (*tree).root = sentinel; - (*tree).sentinel = sentinel; - (*tree).insert = insert; - } -} - -/// Marks the tree node as red. -/// -/// # Safety -/// -/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. -#[inline] -pub unsafe fn ngx_rbt_red(node: *mut ngx_rbtree_node_t) { - unsafe { (*node).color = 1 } -} - -/// Marks the tree node as black. -/// -/// # Safety -/// -/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. -#[inline] -pub unsafe fn ngx_rbt_black(node: *mut ngx_rbtree_node_t) { - unsafe { (*node).color = 0 } -} - -/// Initializes the sentinel node. -/// -/// # Safety -/// -/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. -#[inline] -pub unsafe fn ngx_rbtree_sentinel_init(node: *mut ngx_rbtree_node_t) { - unsafe { ngx_rbt_black(node) } -} - -/// Returns the least (leftmost) node of the tree. -/// -/// # Safety -/// -/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. -/// `sentinel` must be a valid pointer to the sentinel node in the same Red-Black tree. -#[inline] -pub unsafe fn ngx_rbtree_min( - mut node: *mut ngx_rbtree_node_t, - sentinel: *mut ngx_rbtree_node_t, -) -> *mut ngx_rbtree_node_t { - unsafe { - while !ptr::addr_eq((*node).left, sentinel) { - node = (*node).left; - } - - node - } -} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/stream.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/stream.rs deleted file mode 100644 index 6288fd4..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/stream.rs +++ /dev/null @@ -1,13 +0,0 @@ -use core::mem::offset_of; - -use crate::bindings::ngx_stream_conf_ctx_t; - -/// The offset of the `main_conf` field in the `ngx_stream_conf_ctx_t` struct. -/// -/// This is used to access the main configuration context for a STREAM module. -pub const NGX_STREAM_MAIN_CONF_OFFSET: usize = offset_of!(ngx_stream_conf_ctx_t, main_conf); - -/// The offset of the `srv_conf` field in the `ngx_stream_conf_ctx_t` struct. -/// -/// This is used to access the server configuration context for a STREAM module. -pub const NGX_STREAM_SRV_CONF_OFFSET: usize = offset_of!(ngx_stream_conf_ctx_t, srv_conf); diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/string.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/string.rs deleted file mode 100644 index a05d285..0000000 --- a/source/rust/vendor/ngx-rust/nginx-sys/src/string.rs +++ /dev/null @@ -1,233 +0,0 @@ -use core::cmp; -use core::fmt; -use core::hash; -use core::ptr; -use core::slice; -use core::str; - -use crate::bindings::{ngx_pool_t, ngx_str_t}; -use crate::detail; - -impl ngx_str_t { - /// Returns the contents of this `ngx_str_t` as a byte slice. - /// - /// The returned slice will **not** contain the optional nul terminator that `ngx_str_t.data` - /// may have. - #[inline] - pub fn as_bytes(&self) -> &[u8] { - if self.is_empty() { - &[] - } else { - // SAFETY: `ngx_str_t` with non-zero len must contain a valid correctly aligned pointer - unsafe { slice::from_raw_parts(self.data, self.len) } - } - } - - /// Returns the contents of this `ngx_str_t` as a mutable byte slice. - #[inline] - pub fn as_bytes_mut(&mut self) -> &mut [u8] { - if self.is_empty() { - &mut [] - } else { - // SAFETY: `ngx_str_t` with non-zero len must contain a valid correctly aligned pointer - unsafe { slice::from_raw_parts_mut(self.data, self.len) } - } - } - - /// Returns `true` if the string has a length of 0. - #[inline] - pub fn is_empty(&self) -> bool { - self.len == 0 - } - - /// Returns the contents of this `ngx_str_t` a string slice (`&str`) if - /// the contents are utf-8 encoded. - /// - /// # Returns - /// A string slice (`&str`) representing the nginx string, or else a - /// Utf8Error. - pub fn to_str(&self) -> Result<&str, str::Utf8Error> { - str::from_utf8(self.as_bytes()) - } - - /// Creates an empty `ngx_str_t` instance. - /// - /// This method replaces the `ngx_null_string` C macro. - pub const fn empty() -> Self { - ngx_str_t { len: 0, data: ptr::null_mut() } - } - - /// Create an `ngx_str_t` instance from a byte slice. - /// - /// # Safety - /// - /// The caller must provide a valid pointer to a memory pool. - pub unsafe fn from_bytes(pool: *mut ngx_pool_t, src: &[u8]) -> Option { - unsafe { detail::bytes_to_uchar(pool, src).map(|data| Self { data, len: src.len() }) } - } - - /// Create an `ngx_str_t` instance from a string slice (`&str`). - /// - /// # Arguments - /// - /// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`). - /// * `data` - The string slice from which to create the nginx string. - /// - /// # Safety - /// This function is marked as unsafe because it accepts a raw pointer argument. There is no - /// way to know if `pool` is pointing to valid memory. The caller must provide a valid pool to - /// avoid indeterminate behavior. - /// - /// # Returns - /// An `ngx_str_t` instance representing the given string slice. - pub unsafe fn from_str(pool: *mut ngx_pool_t, data: &str) -> Self { - unsafe { ngx_str_t { data: detail::str_to_uchar(pool, data), len: data.len() } } - } - - /// Divides one `ngx_str_t` into two at an index. - /// - /// # Safety - /// - /// The results will reference the original string; be wary of the ownership and lifetime. - pub fn split_at(&self, mid: usize) -> Option<(ngx_str_t, ngx_str_t)> { - if mid > self.len { - return None; - } - - Some(( - ngx_str_t { data: self.data, len: mid }, - ngx_str_t { data: unsafe { self.data.add(mid) }, len: self.len - mid }, - )) - } - - /// Returns an `ngx_str_t` with the prefix removed. - /// - /// If the string starts with the byte sequence `prefix`, returns the substring after the - /// prefix, wrapped in `Some`. The resulting substring can be empty. - /// - /// # Safety - /// - /// The result will reference the original string; be wary of the ownership and lifetime. - /// - /// The method is not marked as `unsafe` as everything it does is possible via safe interfaces. - pub fn strip_prefix(&self, prefix: impl AsRef<[u8]>) -> Option { - let prefix = prefix.as_ref(); - if self.as_bytes().starts_with(prefix) { - self.split_at(prefix.len()).map(|x| x.1) - } else { - None - } - } - - /// Returns an `ngx_str_t` with the suffix removed. - /// - /// If the string ends with the byte sequence `suffix`, returns the substring before the - /// suffix, wrapped in `Some`. The resulting substring can be empty. - /// - /// # Safety - /// - /// The result will reference the original string; be wary of the ownership and lifetime. - /// - /// The method is not marked as `unsafe` as everything it does is possible via safe interfaces. - pub fn strip_suffix(&self, suffix: impl AsRef<[u8]>) -> Option { - let suffix = suffix.as_ref(); - if self.as_bytes().ends_with(suffix) { - self.split_at(self.len - suffix.len()).map(|x| x.0) - } else { - None - } - } -} - -impl AsRef<[u8]> for ngx_str_t { - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } -} - -impl AsMut<[u8]> for ngx_str_t { - fn as_mut(&mut self) -> &mut [u8] { - self.as_bytes_mut() - } -} - -impl Default for ngx_str_t { - fn default() -> Self { - Self::empty() - } -} - -impl fmt::Display for ngx_str_t { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - detail::display_bytes(f, self.as_bytes()) - } -} - -impl From for &[u8] { - fn from(s: ngx_str_t) -> Self { - if s.len == 0 || s.data.is_null() { - return Default::default(); - } - unsafe { slice::from_raw_parts(s.data, s.len) } - } -} - -impl hash::Hash for ngx_str_t { - fn hash(&self, state: &mut H) { - self.as_bytes().hash(state) - } -} - -impl PartialEq for ngx_str_t { - fn eq(&self, other: &Self) -> bool { - PartialEq::eq(self.as_bytes(), other.as_bytes()) - } -} - -impl Eq for ngx_str_t {} - -impl PartialOrd for ngx_str_t { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for ngx_str_t { - fn cmp(&self, other: &Self) -> cmp::Ordering { - Ord::cmp(self.as_bytes(), other.as_bytes()) - } -} - -impl TryFrom for &str { - type Error = str::Utf8Error; - - fn try_from(s: ngx_str_t) -> Result { - str::from_utf8(s.into()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn ngx_str_prefix() { - let s = "key=value"; - let s = ngx_str_t { data: s.as_ptr().cast_mut(), len: s.len() }; - - assert_eq!( - s.strip_prefix("key=").as_ref().map(ngx_str_t::as_bytes), - Some("value".as_bytes()) - ); - - assert_eq!(s.strip_prefix("test"), None); - - assert_eq!( - s.strip_suffix("value").as_ref().map(ngx_str_t::as_bytes), - Some("key=".as_bytes()) - ); - - assert_eq!(s.strip_suffix("test"), None); - } -} diff --git a/source/rust/vendor/ngx-rust/rustfmt.toml b/source/rust/vendor/ngx-rust/rustfmt.toml deleted file mode 100644 index f1b45de..0000000 --- a/source/rust/vendor/ngx-rust/rustfmt.toml +++ /dev/null @@ -1,9 +0,0 @@ -edition = "2024" -max_width = 100 -use_small_heuristics = "Max" - -# unstable options: -# comment_width = 100 -# group_imports = "StdExternalCrate" -# format_strings = true -# wrap_comments = true \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/src/allocator.rs b/source/rust/vendor/ngx-rust/src/allocator.rs deleted file mode 100644 index d5702ff..0000000 --- a/source/rust/vendor/ngx-rust/src/allocator.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! The allocator module. -//! -//! The module provides custom memory allocator support traits and utilities based on the unstable -//! [feature(allocator_api)]. -//! -//! Currently implemented as a reexport of parts of the [allocator_api2]. -//! -//! [feature(allocator_api)]: https://github.com/rust-lang/rust/issues/32838 - -use ::core::alloc::Layout; -use ::core::mem; -use ::core::ptr::{self, NonNull}; -pub use allocator_api2::alloc::{AllocError, Allocator}; -#[cfg(feature = "alloc")] -pub use allocator_api2::{alloc::Global, boxed::Box, unsize_box}; - -/// Explicitly duplicate an object using the specified Allocator. -pub trait TryCloneIn: Sized { - /// Target type, generic over an allocator. - type Target; - - /// Attempts to copy the value using `alloc` as an underlying Allocator. - fn try_clone_in(&self, alloc: A) -> Result, AllocError>; -} - -/// Moves `value` to the memory backed by `alloc` and returns a pointer. -/// -/// This should be similar to `Box::into_raw(Box::try_new_in(value, alloc)?)`, except without -/// `alloc` requirement and intermediate steps. -/// -/// # Note -/// -/// The resulting pointer has no owner. The caller is responsible for destroying `T` and releasing -/// the memory. -pub fn allocate(value: T, alloc: &A) -> Result, AllocError> -where - A: Allocator, -{ - let layout = Layout::for_value(&value); - let ptr: NonNull = alloc.allocate(layout)?.cast(); - - // SAFETY: the allocator succeeded and gave us a correctly aligned pointer to an uninitialized - // data - unsafe { ptr.cast::>().as_mut().write(value) }; - - Ok(ptr) -} -/// -/// Creates a [NonNull] that is dangling, but well-aligned for this [Layout]. -/// -/// See also [::core::alloc::Layout::dangling()] -#[inline(always)] -pub(crate) const fn dangling_for_layout(layout: &Layout) -> NonNull { - unsafe { - let ptr = ptr::null_mut::().byte_add(layout.align()); - NonNull::new_unchecked(ptr) - } -} - -#[cfg(feature = "alloc")] -mod impls { - use allocator_api2::boxed::Box; - - use super::*; - - impl TryCloneIn for Box - where - T: TryCloneIn, - OA: Allocator, - { - type Target = Box<::Target, A>; - - fn try_clone_in( - &self, - alloc: A, - ) -> Result, AllocError> { - let x = self.as_ref().try_clone_in(alloc.clone())?; - Box::try_new_in(x, alloc) - } - } -} diff --git a/source/rust/vendor/ngx-rust/src/async_/mod.rs b/source/rust/vendor/ngx-rust/src/async_/mod.rs deleted file mode 100644 index 3ec7832..0000000 --- a/source/rust/vendor/ngx-rust/src/async_/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! Async runtime and set of utilities on top of the NGINX event loop. -pub use self::sleep::{Sleep, sleep}; -pub use self::spawn::{Task, spawn}; - -pub mod resolver; - -mod sleep; -mod spawn; diff --git a/source/rust/vendor/ngx-rust/src/async_/resolver.rs b/source/rust/vendor/ngx-rust/src/async_/resolver.rs deleted file mode 100644 index 53bf55c..0000000 --- a/source/rust/vendor/ngx-rust/src/async_/resolver.rs +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright (c) F5, Inc. -// -// This source code is licensed under the Apache License, Version 2.0 license found in the -// LICENSE file in the root directory of this source tree. - -//! Wrapper for the nginx resolver. -//! -//! See . - -use alloc::string::{String, ToString}; -use core::ffi::c_void; -use core::fmt; -use core::num::NonZero; -use core::pin::Pin; -use core::ptr::NonNull; -use core::task::{Context, Poll, Waker}; - -use nginx_sys::{ - NGX_NO_RESOLVER, NGX_RESOLVE_FORMERR, NGX_RESOLVE_NOTIMP, NGX_RESOLVE_NXDOMAIN, - NGX_RESOLVE_REFUSED, NGX_RESOLVE_SERVFAIL, NGX_RESOLVE_TIMEDOUT, -}; - -use crate::{ - allocator::Box, - collections::Vec, - core::{Pool, Status}, - ffi::{ - ngx_addr_t, ngx_msec_t, ngx_resolve_name, ngx_resolve_start, ngx_resolver_ctx_t, - ngx_resolver_t, ngx_str_t, - }, -}; - -/// Error type for all uses of `Resolver`. -#[derive(Debug)] -pub enum Error { - /// No resolver configured - NoResolver, - /// Resolver error, with context of name being resolved - Resolver(ResolverError, String), - /// Allocation failed - AllocationFailed, - /// Unknown internal error while starting name resolution - Internal, -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Error::NoResolver => write!(f, "No resolver configured"), - Error::Resolver(err, context) => write!(f, "{err}: resolving `{context}`"), - Error::AllocationFailed => write!(f, "Allocation failed"), - Error::Internal => write!(f, "Internal error"), - } - } -} -impl core::error::Error for Error {} - -/// These cases directly reflect the NGX_RESOLVE_ error codes, -/// plus a timeout, and a case for an unknown error where a known -/// NGX_RESOLVE_ should be. -#[derive(Debug)] -pub enum ResolverError { - /// Format error (NGX_RESOLVE_FORMERR) - FormErr, - /// Server failure (NGX_RESOLVE_SERVFAIL) - ServFail, - /// Host not found (NGX_RESOLVE_NXDOMAIN) - NXDomain, - /// Unimplemented (NGX_RESOLVE_NOTIMP) - NotImp, - /// Operation refused (NGX_RESOLVE_REFUSED) - Refused, - /// Timed out (NGX_RESOLVE_TIMEDOUT) - TimedOut, - /// Unknown NGX_RESOLVE error - Unknown(isize), -} -impl fmt::Display for ResolverError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - ResolverError::FormErr => write!(f, "Format error"), - ResolverError::ServFail => write!(f, "Server Failure"), - ResolverError::NXDomain => write!(f, "Host not found"), - ResolverError::NotImp => write!(f, "Unimplemented"), - ResolverError::Refused => write!(f, "Refused"), - ResolverError::TimedOut => write!(f, "Timed out"), - ResolverError::Unknown(code) => write!(f, "Unknown NGX_RESOLVE error {code}"), - } - } -} -impl core::error::Error for ResolverError {} - -/// Convert from the NGX_RESOLVE_ error codes. -impl From> for ResolverError { - fn from(code: NonZero) -> ResolverError { - match code.get() as u32 { - NGX_RESOLVE_FORMERR => ResolverError::FormErr, - NGX_RESOLVE_SERVFAIL => ResolverError::ServFail, - NGX_RESOLVE_NXDOMAIN => ResolverError::NXDomain, - NGX_RESOLVE_NOTIMP => ResolverError::NotImp, - NGX_RESOLVE_REFUSED => ResolverError::Refused, - NGX_RESOLVE_TIMEDOUT => ResolverError::TimedOut, - _ => ResolverError::Unknown(code.get()), - } - } -} - -type Res = Result, Error>; - -/// A wrapper for an ngx_resolver_t which provides an async Rust API -pub struct Resolver { - resolver: NonNull, - timeout: ngx_msec_t, -} - -impl Resolver { - /// Create a new `Resolver` from existing pointer to `ngx_resolver_t` and - /// timeout. - pub fn from_resolver(resolver: NonNull, timeout: ngx_msec_t) -> Self { - Self { resolver, timeout } - } - - /// Resolve a name into a set of addresses. - pub async fn resolve_name(&self, name: &ngx_str_t, pool: &Pool) -> Res { - let mut resolver = Resolution::new(name, &ngx_str_t::empty(), self, pool)?; - resolver.as_mut().await - } - - /// Resolve a service into a set of addresses. - pub async fn resolve_service(&self, name: &ngx_str_t, service: &ngx_str_t, pool: &Pool) -> Res { - let mut resolver = Resolution::new(name, service, self, pool)?; - resolver.as_mut().await - } -} - -struct Resolution<'a> { - // Storage for the result of the resolution `Res`. Populated by the - // callback handler, and taken by the Future::poll impl. - complete: Option, - // Storage for a pending Waker. Populated by the Future::poll impl, - // and taken by the callback handler. - waker: Option, - // Pool used for allocating `Vec` contents in `Res`. Read by - // the callback handler. - pool: &'a Pool, - // Owned pointer to the ngx_resolver_ctx_t. - ctx: Option, -} - -impl<'a> Resolution<'a> { - pub fn new( - name: &ngx_str_t, - service: &ngx_str_t, - resolver: &Resolver, - pool: &'a Pool, - ) -> Result>, Error> { - // Create a pinned Resolution on the Pool, so that we can make - // a stable pointer to the Resolution struct. - let mut this = - Box::pin_in(Resolution { complete: None, waker: None, pool, ctx: None }, pool.clone()); - - // Set up the ctx with everything the resolver needs to resolve a - // name, and the handler callback which is called on completion. - let mut ctx = ResolverCtx::new(resolver.resolver)?; - ctx.name = *name; - ctx.service = *service; - ctx.timeout = resolver.timeout; - ctx.set_cancelable(1); - ctx.handler = Some(Self::handler); - - { - // Safety: Self::handler, Future::poll, and Drop::drop will have - // access to &mut Resolution. Nginx is single-threaded and we are - // assured only one of those is on the stack at a time, except if - // Self::handler wakes a task which polls or drops the Future, - // which it only does after use of &mut Resolution is complete. - let ptr: &mut Resolution = unsafe { Pin::into_inner_unchecked(this.as_mut()) }; - ctx.data = ptr as *mut Resolution as *mut c_void; - } - - // Neither ownership nor borrows are tracked for this pointer, - // and ctxp will not be used after the ctx destruction. - let ctxp = ctx.0; - this.ctx = Some(ctx); - - // Start name resolution using the ctx. If the name is in the dns - // cache, the handler may get called from this stack. Otherwise, it - // will be called later by nginx when it gets a dns response or a - // timeout. - let ret = unsafe { Status(ngx_resolve_name(ctxp.as_ptr())) }; - if !ret.is_ok() { - // ngx_resolve_name will free the context on error. - core::mem::forget(this.ctx.take()); - return Err(Error::Internal); - } - - Ok(this) - } - - // Nginx will call this handler when name resolution completes. If the - // result is in the cache, this could be called from inside ngx_resolve_name. - // Otherwise, it will be called later on the event loop. - unsafe extern "C" fn handler(ctx: *mut ngx_resolver_ctx_t) { - let mut data = unsafe { NonNull::new_unchecked((*ctx).data as *mut Resolution) }; - let this: &mut Resolution = unsafe { data.as_mut() }; - - if let Some(ctx) = this.ctx.take() { - this.complete = Some(ctx.into_result(this.pool)); - } - - // Wake last, after all use of &mut Resolution, because wake may - // poll Resolution future on current stack. - if let Some(waker) = this.waker.take() { - waker.wake(); - } - } -} - -impl core::future::Future for Resolution<'_> { - type Output = Result, Error>; - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - // Resolution is Unpin, so we can use it as just a &mut Resolution - let this: &mut Resolution = self.get_mut(); - - // The handler populates this.complete, and we consume it here: - match this.complete.take() { - Some(res) => Poll::Ready(res), - None => { - // If the handler has not yet fired, populate the waker field, - // which the handler will consume: - match &mut this.waker { - None => { - this.waker = Some(cx.waker().clone()); - } - Some(w) => w.clone_from(cx.waker()), - } - Poll::Pending - } - } - } -} - -/// An owned ngx_resolver_ctx_t. -struct ResolverCtx(NonNull); - -impl core::ops::Deref for ResolverCtx { - type Target = ngx_resolver_ctx_t; - - fn deref(&self) -> &Self::Target { - // SAFETY: this wrapper is always constructed with a valid non-empty resolve context - unsafe { self.0.as_ref() } - } -} - -impl core::ops::DerefMut for ResolverCtx { - fn deref_mut(&mut self) -> &mut Self::Target { - // SAFETY: this wrapper is always constructed with a valid non-empty resolve context - unsafe { self.0.as_mut() } - } -} - -impl Drop for ResolverCtx { - fn drop(&mut self) { - unsafe { - nginx_sys::ngx_resolve_name_done(self.0.as_mut()); - } - } -} - -impl ResolverCtx { - /// Creates a new resolver context. - /// - /// This implementation currently passes a null for the second argument `temp`. A non-null - /// `temp` provides a fast, non-callback-based path for immediately returning an addr if - /// `temp` contains a name which is textual form of an addr. - pub fn new(resolver: NonNull) -> Result { - let ctx = unsafe { ngx_resolve_start(resolver.as_ptr(), core::ptr::null_mut()) }; - if ctx == NGX_NO_RESOLVER { - return Err(Error::NoResolver); - } - NonNull::new(ctx).map(Self).ok_or(Error::AllocationFailed) - } - - /// Take the results in a ctx and make an owned copy as a - /// Result, Error>, where the Vec and the internals - /// of the ngx_addr_t are allocated on the given Pool - pub fn into_result(self, pool: &Pool) -> Result, Error> { - if let Some(e) = NonZero::new(self.state) { - return Err(Error::Resolver(ResolverError::from(e), self.name.to_string())); - } - if self.addrs.is_null() { - Err(Error::AllocationFailed)?; - } - - let mut out = Vec::new_in(pool.clone()); - - if self.naddrs > 0 { - out.try_reserve_exact(self.naddrs).map_err(|_| Error::AllocationFailed)?; - - for addr in unsafe { core::slice::from_raw_parts(self.addrs, self.naddrs) } { - out.push(copy_resolved_addr(addr, pool)?); - } - } - - Ok(out) - } -} - -/// Take the contents of an ngx_resolver_addr_t and make an owned copy as -/// an ngx_addr_t, using the Pool for allocation of the internals. -fn copy_resolved_addr( - addr: &nginx_sys::ngx_resolver_addr_t, - pool: &Pool, -) -> Result { - let sockaddr = pool.alloc(addr.socklen as usize) as *mut nginx_sys::sockaddr; - if sockaddr.is_null() { - Err(Error::AllocationFailed)?; - } - unsafe { - addr.sockaddr.cast::().copy_to_nonoverlapping(sockaddr.cast(), addr.socklen as usize) - }; - - let name = unsafe { ngx_str_t::from_bytes(pool.as_ptr(), addr.name.as_bytes()) } - .ok_or(Error::AllocationFailed)?; - - Ok(ngx_addr_t { sockaddr, socklen: addr.socklen, name }) -} diff --git a/source/rust/vendor/ngx-rust/src/async_/sleep.rs b/source/rust/vendor/ngx-rust/src/async_/sleep.rs deleted file mode 100644 index 39feded..0000000 --- a/source/rust/vendor/ngx-rust/src/async_/sleep.rs +++ /dev/null @@ -1,135 +0,0 @@ -use core::future::Future; -use core::mem; -use core::pin::Pin; -use core::ptr::NonNull; -use core::task::{self, Poll}; -use core::time::Duration; - -use nginx_sys::{ngx_add_timer, ngx_del_timer, ngx_event_t, ngx_log_t, ngx_msec_int_t, ngx_msec_t}; -use pin_project_lite::pin_project; - -use crate::{ngx_container_of, ngx_log_debug}; - -/// Maximum duration that can be achieved using [ngx_add_timer]. -const NGX_TIMER_DURATION_MAX: Duration = Duration::from_millis(ngx_msec_int_t::MAX as _); - -/// Puts the current task to sleep for at least the specified amount of time. -/// -/// The function is a shorthand for [Sleep::new] using the global logger for debug output. -#[inline] -pub fn sleep(duration: Duration) -> Sleep { - Sleep::new(duration, crate::log::ngx_cycle_log()) -} - -pin_project! { -/// Future returned by [sleep]. -pub struct Sleep { - #[pin] - timer: TimerEvent, - duration: Duration, -} -} - -impl Sleep { - /// Creates a new Sleep with the specified duration and logger for debug messages. - pub fn new(duration: Duration, log: NonNull) -> Self { - let timer = TimerEvent::new(log); - ngx_log_debug!(timer.event.log, "async: sleep for {duration:?}"); - Sleep { timer, duration } - } -} - -impl Future for Sleep { - type Output = (); - - #[cfg(not(target_pointer_width = "32"))] - fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll { - let msec = self.duration.min(NGX_TIMER_DURATION_MAX).as_millis() as ngx_msec_t; - let this = self.project(); - this.timer.poll_sleep(msec, cx) - } - - #[cfg(target_pointer_width = "32")] - fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll { - if self.duration.is_zero() { - return Poll::Ready(()); - } - let step = self.duration.min(NGX_TIMER_DURATION_MAX); - - let mut this = self.project(); - // Handle ngx_msec_t overflow on 32-bit platforms. - match this.timer.as_mut().poll_sleep(step.as_millis() as _, cx) { - // Last step - Poll::Ready(()) if this.duration == &step => Poll::Ready(()), - Poll::Ready(()) => { - *this.duration = this.duration.saturating_sub(step); - this.timer.event.set_timedout(0); // rearm - this.timer.as_mut().poll_sleep(step.as_millis() as _, cx) - } - x => x, - } - } -} - -struct TimerEvent { - event: ngx_event_t, - waker: Option, -} - -// SAFETY: Timer will only be used in a single-threaded environment -unsafe impl Send for TimerEvent {} -unsafe impl Sync for TimerEvent {} - -impl TimerEvent { - pub fn new(log: NonNull) -> Self { - static IDENT: [usize; 4] = [ - 0, 0, 0, 0x4153594e, // ASYN - ]; - - let mut ev: ngx_event_t = unsafe { mem::zeroed() }; - // The data is only used for `ngx_event_ident` and will not be mutated. - ev.data = (&raw const IDENT).cast_mut().cast(); - ev.handler = Some(Self::timer_handler); - ev.log = log.as_ptr(); - ev.set_cancelable(1); - - Self { event: ev, waker: None } - } - - pub fn poll_sleep( - mut self: Pin<&mut Self>, - duration: ngx_msec_t, - context: &mut task::Context<'_>, - ) -> Poll<()> { - if self.event.timedout() != 0 { - Poll::Ready(()) - } else if self.event.timer_set() != 0 { - if let Some(waker) = self.waker.as_mut() { - waker.clone_from(context.waker()); - } else { - self.waker = Some(context.waker().clone()); - } - Poll::Pending - } else { - unsafe { ngx_add_timer(&raw mut self.event, duration) }; - self.waker = Some(context.waker().clone()); - Poll::Pending - } - } - - unsafe extern "C" fn timer_handler(ev: *mut ngx_event_t) { - let timer = ngx_container_of!(ev, Self, event); - - if let Some(waker) = unsafe { (*timer).waker.take() } { - waker.wake(); - } - } -} - -impl Drop for TimerEvent { - fn drop(&mut self) { - if self.event.timer_set() != 0 { - unsafe { ngx_del_timer(&raw mut self.event) }; - } - } -} diff --git a/source/rust/vendor/ngx-rust/src/async_/spawn.rs b/source/rust/vendor/ngx-rust/src/async_/spawn.rs deleted file mode 100644 index fa6008f..0000000 --- a/source/rust/vendor/ngx-rust/src/async_/spawn.rs +++ /dev/null @@ -1,146 +0,0 @@ -use alloc::collections::vec_deque::VecDeque; -use core::cell::UnsafeCell; -use core::future::Future; -use core::mem; -use core::ptr::{self, NonNull}; - -pub use async_task::Task; -use async_task::{Runnable, ScheduleInfo, WithInfo}; -use nginx_sys::{ - ngx_del_timer, ngx_delete_posted_event, ngx_event_t, ngx_post_event, ngx_posted_next_events, -}; - -use crate::log::ngx_cycle_log; -use crate::{ngx_container_of, ngx_log_debug}; - -static SCHEDULER: Scheduler = Scheduler::new(); - -struct Scheduler(UnsafeCell); - -// SAFETY: Scheduler must only be used from the main thread of a worker process. -unsafe impl Send for Scheduler {} -unsafe impl Sync for Scheduler {} - -impl Scheduler { - const fn new() -> Self { - Self(SchedulerInner::new()) - } - - pub fn schedule(&self, runnable: Runnable) { - // SAFETY: the cell is not empty, and we have exclusive access due to being a - // single-threaded application. - let inner = unsafe { &mut *UnsafeCell::raw_get(&raw const self.0) }; - inner.send(runnable) - } -} - -#[repr(C)] -struct SchedulerInner { - _ident: [usize; 4], // `ngx_event_ident` compatibility - event: ngx_event_t, - queue: VecDeque, -} - -impl SchedulerInner { - const fn new() -> UnsafeCell { - let mut event: ngx_event_t = unsafe { mem::zeroed() }; - event.handler = Some(Self::scheduler_event_handler); - - UnsafeCell::new(Self { - _ident: [ - 0, 0, 0, 0x4153594e, // ASYN - ], - event, - queue: VecDeque::new(), - }) - } - - pub fn send(&mut self, runnable: Runnable) { - // Cached `ngx_cycle.log` can be invalidated when reloading configuration in a single - // process mode. Update `log` every time to avoid using stale log pointer. - self.event.log = ngx_cycle_log().as_ptr(); - - // While this event is not used as a timer at the moment, we still want to ensure that it is - // compatible with `ngx_event_ident`. - if self.event.data.is_null() { - self.event.data = ptr::from_mut(self).cast(); - } - - // FIXME: VecDeque::push could panic on an allocation failure, switch to a datastructure - // which will not and propagate the failure. - self.queue.push_back(runnable); - unsafe { ngx_post_event(&raw mut self.event, &raw mut ngx_posted_next_events) } - } - - /// This event handler is called by ngx_event_process_posted at the end of - /// ngx_process_events_and_timers. - extern "C" fn scheduler_event_handler(ev: *mut ngx_event_t) { - let mut runnables = { - // SAFETY: - // This handler always receives a non-null pointer to an event embedded into a - // UnsafeCell instance. We modify the contents of the `UnsafeCell`, - // but we ensured that: - // - we access the cell correctly, as documented in https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html#memory-layout - // - the access is unique due to being single-threaded - // - the reference is dropped before we start processing queued runnables. - let cell: NonNull> = - ngx_container_of!(unsafe { NonNull::new_unchecked(ev) }, Self, event).cast(); - let this = unsafe { &mut *UnsafeCell::raw_get(cell.as_ptr()) }; - - ngx_log_debug!( - this.event.log, - "async: processing {} deferred wakeups", - this.queue.len() - ); - - // Move runnables to a new queue to avoid borrowing from the SchedulerInner and limit - // processing to already queued wakeups. This ensures that we correctly handle tasks - // that keep scheduling themselves (e.g. using yield_now() in a loop). - // We can't use drain() as it borrows from self and breaks aliasing rules. - mem::take(&mut this.queue) - }; - - for runnable in runnables.drain(..) { - runnable.run(); - } - } -} - -impl Drop for SchedulerInner { - fn drop(&mut self) { - if self.event.posted() != 0 { - unsafe { ngx_delete_posted_event(&raw mut self.event) }; - } - - if self.event.timer_set() != 0 { - unsafe { ngx_del_timer(&raw mut self.event) }; - } - } -} - -fn schedule(runnable: Runnable, _info: ScheduleInfo) { - // Always defer the wake via `ngx_post_event`; never re-poll synchronously. - // - // `Waker::wake()` may fire from arbitrary contexts, including a future's - // `Drop` while a lock is held (e.g. h2's `Streams::drop` wakes its parked - // `Connection` task while holding `Arc>`). A synchronous - // re-poll would re-enter the task and deadlock on that lock. Deferring - // costs one event-loop tick: `ngx_event_process_posted` drains the queue - // at the end of each cycle. - SCHEDULER.schedule(runnable); -} - -/// Creates a new task running on the NGINX event loop. -pub fn spawn(future: F) -> Task -where - F: Future + 'static, - T: 'static, -{ - ngx_log_debug!(ngx_cycle_log().as_ptr(), "async: spawning new task"); - let scheduler = WithInfo(schedule); - // Safety: single threaded embedding takes care of send/sync requirements for future and - // scheduler. Future and scheduler are both 'static. - let (runnable, task) = unsafe { async_task::spawn_unchecked(future, scheduler) }; - runnable.schedule(); - task -} diff --git a/source/rust/vendor/ngx-rust/src/collections/mod.rs b/source/rust/vendor/ngx-rust/src/collections/mod.rs deleted file mode 100644 index ce36eb3..0000000 --- a/source/rust/vendor/ngx-rust/src/collections/mod.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Collection types. -//! -//! This module provides common collection types, mostly implemented as wrappers over the -//! corresponding NGINX types. - -#[cfg(feature = "alloc")] -pub use allocator_api2::{ - collections::{TryReserveError, TryReserveErrorKind}, - vec, // reexport both the module and the macro - vec::Vec, -}; -pub use queue::Queue; -pub use rbtree::RbTreeMap; - -pub mod queue; -pub mod rbtree; diff --git a/source/rust/vendor/ngx-rust/src/collections/queue.rs b/source/rust/vendor/ngx-rust/src/collections/queue.rs deleted file mode 100644 index 3adfe2a..0000000 --- a/source/rust/vendor/ngx-rust/src/collections/queue.rs +++ /dev/null @@ -1,419 +0,0 @@ -//! Types and utilities for working with [ngx_queue_t], an intrusive doubly-linked list. -//! -//! This module provides both the tools for interaction with the existing `ngx_queue_t` objects in -//! the NGINX, and useful high-level types built on top of the `ngx_queue_t`. -//! -//! See . - -use core::alloc::Layout; -use core::marker::PhantomData; -use core::mem; -use core::ptr::{self, NonNull}; - -use nginx_sys::{ - ngx_queue_data, ngx_queue_empty, ngx_queue_init, ngx_queue_insert_after, - ngx_queue_insert_before, ngx_queue_remove, ngx_queue_t, -}; - -use crate::allocator::{AllocError, Allocator}; - -/// Trait for pointer conversions between the queue entry and its container. -/// -/// # Safety -/// -/// This trait must only be implemented on types that contain a queue link or wrappers with -/// compatible layout. The type then can be used to access elements of a raw queue type -/// [NgxQueue] linked via specified field. -/// -/// If the struct can belong to several queues through multiple embedded `ngx_queue_t` fields, -/// a separate [NgxQueueEntry] implementation via wrapper type should be used for each queue. -pub unsafe trait NgxQueueEntry { - /// Gets a container pointer from queue node. - fn from_queue(queue: NonNull) -> NonNull; - /// Gets a queue node from a container reference. - fn to_queue(&mut self) -> &mut ngx_queue_t; -} - -unsafe impl NgxQueueEntry for ngx_queue_t { - fn from_queue(queue: NonNull) -> NonNull { - queue - } - - fn to_queue(&mut self) -> &mut ngx_queue_t { - self - } -} - -/// A wrapper over a raw `ngx_queue_t`, an intrusive doubly-linked list. -/// -/// This wrapper is defined in terms of type `T` that embeds and can be converted from or to the -/// list entries. -/// -/// Example: -/// ```rust,no_run -/// # use core::ptr::NonNull; -/// # use nginx_sys::{ngx_event_t, ngx_posted_events, ngx_queue_data, ngx_queue_t}; -/// # use ngx::collections::queue::{NgxQueue, NgxQueueEntry}; -/// // We need a wrapper type to define [NgxQueueEntry] on. -/// #[repr(transparent)] -/// struct PostedEvent(ngx_event_t); -/// -/// unsafe impl NgxQueueEntry for PostedEvent { -/// fn from_queue(queue: NonNull) -> NonNull { -/// // We can safely cast obtained ngx_event_t to a transparent wrapper. -/// unsafe { ngx_queue_data!(queue, ngx_event_t, queue) }.cast() -/// } -/// -/// fn to_queue(&mut self) -> &mut ngx_queue_t { -/// &mut self.0.queue -/// } -/// } -/// -/// // SAFETY: `ngx_posted_events` global static is a list of `ngx_event_t` linked via -/// // `ngx_event_t.queue`. -/// // NGINX is single-threaded, so we get exclusive access to the static. -/// let posted: &mut NgxQueue = -/// unsafe { NgxQueue::from_ptr_mut(&raw mut ngx_posted_events) }; -/// ``` -/// -/// See . -#[derive(Debug)] -#[repr(transparent)] -pub struct NgxQueue { - head: ngx_queue_t, - _type: PhantomData, -} - -impl NgxQueue -where - T: NgxQueueEntry, -{ - /// Creates a queue reference from a pointer to [ngx_queue_t]. - /// - /// # Safety - /// - /// `head` is a valid pointer to a list head, and `T::from_queue` on the list entries results in - /// valid pointers to `T`. - pub unsafe fn from_ptr<'a>(head: *const ngx_queue_t) -> &'a Self { - unsafe { &*head.cast() } - } - - /// Creates a mutable queue reference from a pointer to [ngx_queue_t]. - /// - /// # Safety - /// - /// `head` is a valid pointer to a list head, and `T::from_queue` on the list entries results in - /// valid pointers to `T`. - pub unsafe fn from_ptr_mut<'a>(head: *mut ngx_queue_t) -> &'a mut Self { - unsafe { &mut *head.cast() } - } - - /// Returns `true` if the queue contains no elements. - pub fn is_empty(&self) -> bool { - self.head.prev.is_null() || unsafe { ngx_queue_empty(&raw const self.head) } - } - - /// Appends an element to the end of the queue. - pub fn push_back(&mut self, entry: &mut T) { - if self.head.prev.is_null() { - unsafe { ngx_queue_init(&raw mut self.head) } - } - - unsafe { ngx_queue_insert_before(&raw mut self.head, entry.to_queue()) } - } - - /// Appends an element to the beginning of the queue. - pub fn push_front(&mut self, entry: &mut T) { - if self.head.prev.is_null() { - unsafe { ngx_queue_init(&raw mut self.head) } - } - - unsafe { ngx_queue_insert_after(&raw mut self.head, entry.to_queue()) } - } - - /// Returns an iterator over the entries of the queue. - pub fn iter(&self) -> NgxQueueIter<'_, T> { - NgxQueueIter::new(&self.head) - } - - /// Returns a mutable iterator over the entries of the queue. - pub fn iter_mut(&mut self) -> NgxQueueIterMut<'_, T> { - NgxQueueIterMut::new(&mut self.head) - } -} - -/// An iterator for the queue. -pub struct NgxQueueIter<'a, T> { - head: NonNull, - current: NonNull, - _lifetime: PhantomData<&'a T>, -} - -impl<'a, T> NgxQueueIter<'a, T> -where - T: NgxQueueEntry, -{ - /// Creates a new queue iterator. - pub fn new(head: &'a ngx_queue_t) -> Self { - let head = NonNull::from(head); - NgxQueueIter { head, current: head, _lifetime: PhantomData } - } -} - -impl<'a, T> Iterator for NgxQueueIter<'a, T> -where - T: NgxQueueEntry + 'a, -{ - type Item = &'a T; - - fn next(&mut self) -> Option { - unsafe { - let next = NonNull::new(self.current.as_ref().next)?; - if next == self.head { - return None; - } - - self.current = next; - Some(T::from_queue(self.current).as_ref()) - } - } -} - -/// A mutable iterator for the queue. -pub struct NgxQueueIterMut<'a, T> { - head: NonNull, - current: NonNull, - _lifetime: PhantomData<&'a T>, -} - -impl<'a, T> NgxQueueIterMut<'a, T> -where - T: NgxQueueEntry, -{ - /// Creates a new mutable queue iterator. - pub fn new(head: &'a mut ngx_queue_t) -> Self { - let head = NonNull::from(head); - NgxQueueIterMut { head, current: head, _lifetime: PhantomData } - } -} - -impl<'a, T> Iterator for NgxQueueIterMut<'a, T> -where - T: NgxQueueEntry + 'a, -{ - type Item = &'a mut T; - - fn next(&mut self) -> Option { - unsafe { - let next = NonNull::new(self.current.as_ref().next)?; - if next == self.head { - return None; - } - - self.current = next; - Some(T::from_queue(self.current).as_mut()) - } - } -} - -/// A doubly-linked list that owns elements of type `T` backed by the specified allocator `A`. -#[derive(Debug)] -pub struct Queue -where - A: Allocator, -{ - // The address of the NgxQueue with queue head has to be stable, as the queue elements will - // contain pointers to the head. - raw: NonNull>>, - len: usize, - alloc: A, -} - -impl Drop for Queue -where - A: Allocator, -{ - fn drop(&mut self) { - while self.pop_front().is_some() {} - - let layout = Layout::for_value(unsafe { self.raw.as_ref() }); - unsafe { self.allocator().deallocate(self.raw.cast(), layout) }; - } -} - -unsafe impl Send for Queue -where - A: Send + Allocator, - T: Send, -{ -} - -unsafe impl Sync for Queue -where - A: Sync + Allocator, - T: Sync, -{ -} - -impl Queue { - /// Creates a new list with specified allocator. - pub fn try_new_in(alloc: A) -> Result { - let raw = NgxQueue { head: unsafe { mem::zeroed() }, _type: PhantomData }; - let raw = crate::allocator::allocate(raw, &alloc)?; - Ok(Self { raw, len: 0, alloc }) - } - - /// Returns a reference to the underlying allocator. - pub fn allocator(&self) -> &A { - &self.alloc - } - - /// Returns `true` if the list contains no elements. - pub fn is_empty(&self) -> bool { - self.raw().is_empty() - } - - /// Returns the number of elements in the queue. - pub fn len(&self) -> usize { - self.len - } - - /// Returns an iterator over the entries of the list. - pub fn iter(&self) -> QueueIter<'_, T> { - QueueIter::new(&self.raw().head) - } - - /// Returns a mutable iterator over the entries of the list. - pub fn iter_mut(&mut self) -> QueueIterMut<'_, T> { - QueueIterMut::new(&mut self.raw_mut().head) - } - - /// Removes the last element and returns it or `None` if the list is empty. - pub fn pop_back(&mut self) -> Option { - if self.is_empty() { - return None; - } - let node = NonNull::new(self.raw_mut().head.prev)?; - Some(unsafe { self.remove(node) }) - } - - /// Removes the first element and returns it or `None` if the list is empty. - pub fn pop_front(&mut self) -> Option { - if self.is_empty() { - return None; - } - let node = NonNull::new(self.raw_mut().head.next)?; - Some(unsafe { self.remove(node) }) - } - - /// Appends an element to the end of the list. - pub fn push_back(&mut self, item: T) -> Result<&mut T, AllocError> { - let mut entry = QueueEntry::new_in(item, self.allocator())?; - let entry = unsafe { entry.as_mut() }; - self.raw_mut().push_back(entry); - self.len += 1; - Ok(&mut entry.item) - } - - /// Appends an element to the beginning of the list. - pub fn push_front(&mut self, item: T) -> Result<&mut T, AllocError> { - let mut entry = QueueEntry::new_in(item, self.allocator())?; - let entry = unsafe { entry.as_mut() }; - self.raw_mut().push_front(entry); - self.len += 1; - Ok(&mut entry.item) - } - - fn raw(&self) -> &NgxQueue> { - // SAFETY: we allocated this pointer as well-aligned and convertible to reference. - unsafe { self.raw.as_ref() } - } - - fn raw_mut(&mut self) -> &mut NgxQueue> { - // SAFETY: we allocated this pointer as well-aligned and convertible to reference. - unsafe { self.raw.as_mut() } - } - - /// Removes a node from the queue and returns the contained value. - /// - /// # Safety - /// - /// `node` must be an element of this list. - unsafe fn remove(&mut self, node: NonNull) -> T { - unsafe { ngx_queue_remove(node.as_ptr()) }; - self.len -= 1; - - let entry = QueueEntry::::from_queue(node); - let copy = unsafe { entry.read() }; - // Skip drop as QueueEntry is already copied to `x`. - unsafe { self.allocator().deallocate(entry.cast(), Layout::for_value(entry.as_ref())) }; - copy.item - } -} - -#[derive(Debug)] -struct QueueEntry { - queue: ngx_queue_t, - item: T, -} - -unsafe impl NgxQueueEntry for QueueEntry { - fn from_queue(queue: NonNull) -> NonNull { - unsafe { ngx_queue_data!(queue, Self, queue) } - } - - fn to_queue(&mut self) -> &mut ngx_queue_t { - &mut self.queue - } -} - -impl QueueEntry { - pub fn new_in(item: T, alloc: &impl Allocator) -> Result, AllocError> { - let p: NonNull = alloc.allocate(Layout::new::())?.cast(); - - unsafe { - let u = p.cast::>().as_mut(); - // does not read the uninitialized data - ngx_queue_init(&raw mut u.assume_init_mut().queue); - ptr::write(&raw mut u.assume_init_mut().item, item); - } - - Ok(p) - } -} - -/// An iterator for the linked list [Queue]. -pub struct QueueIter<'a, T>(NgxQueueIter<'a, QueueEntry>); - -impl<'a, T> QueueIter<'a, T> { - /// Creates a new iterator for the linked list. - pub fn new(head: &'a ngx_queue_t) -> Self { - Self(NgxQueueIter::new(head)) - } -} - -impl<'a, T> Iterator for QueueIter<'a, T> { - type Item = &'a T; - - fn next(&mut self) -> Option { - Some(&self.0.next()?.item) - } -} - -/// A mutable iterator for the linked list [Queue]. -pub struct QueueIterMut<'a, T>(NgxQueueIterMut<'a, QueueEntry>); - -impl<'a, T> QueueIterMut<'a, T> { - /// Creates a new mutable iterator for the linked list. - pub fn new(head: &'a mut ngx_queue_t) -> Self { - Self(NgxQueueIterMut::new(head)) - } -} - -impl<'a, T> Iterator for QueueIterMut<'a, T> { - type Item = &'a mut T; - - fn next(&mut self) -> Option { - Some(&mut self.0.next()?.item) - } -} diff --git a/source/rust/vendor/ngx-rust/src/collections/rbtree.rs b/source/rust/vendor/ngx-rust/src/collections/rbtree.rs deleted file mode 100644 index 64692d5..0000000 --- a/source/rust/vendor/ngx-rust/src/collections/rbtree.rs +++ /dev/null @@ -1,472 +0,0 @@ -//! Types and utilities for working with [ngx_rbtree_t]. -//! -//! This module provides both the tools for interaction with the existing `ngx_rbtree_t` objects in -//! the NGINX, and useful high-level types built on top of the `ngx_rbtree_t`. -//! -//! See . - -use core::alloc::Layout; -use core::cmp::Ordering; -use core::hash::{self, BuildHasher, Hash}; -use core::marker::PhantomData; -use core::ptr::{self, NonNull}; -use core::{borrow, mem}; - -use nginx_sys::{ - ngx_rbt_red, ngx_rbtree_data, ngx_rbtree_delete, ngx_rbtree_init, ngx_rbtree_insert, - ngx_rbtree_key_t, ngx_rbtree_min, ngx_rbtree_next, ngx_rbtree_node_t, ngx_rbtree_t, -}; - -use crate::allocator::{self, AllocError, Allocator}; - -/// Trait for pointer conversions between the tree entry and its container. -/// -/// # Safety -/// -/// This trait must only be implemented on types that contain a tree node or wrappers with -/// compatible layout. The type then can be used to access elements of a raw rbtree type -/// [NgxRbTree] linked via specified field. -/// -/// If the struct can belong to several trees through multiple embedded `ngx_rbtree_node_t` fields, -/// a separate [NgxRbTreeEntry] implementation via wrapper type should be used for each tree. -pub unsafe trait NgxRbTreeEntry { - /// Gets a container pointer from tree node. - fn from_rbtree_node(node: NonNull) -> NonNull; - /// Gets an rbtree node from a container reference. - fn to_rbtree_node(&mut self) -> &mut ngx_rbtree_node_t; -} - -unsafe impl NgxRbTreeEntry for ngx_rbtree_node_t { - fn from_rbtree_node(node: NonNull) -> NonNull { - node - } - - fn to_rbtree_node(&mut self) -> &mut ngx_rbtree_node_t { - self - } -} - -/// A wrapper over a raw `ngx_rbtree_t`, a red-black tree implementation. -/// -/// This wrapper is defined in terms of type `T` that embeds and can be converted from or to the -/// tree nodes. -/// -/// See . -#[derive(Debug)] -#[repr(transparent)] -pub struct NgxRbTree { - inner: ngx_rbtree_t, - _type: PhantomData, -} - -impl NgxRbTree -where - T: NgxRbTreeEntry, -{ - /// Creates a tree reference from a pointer to [ngx_rbtree_t]. - /// - /// # Safety - /// - /// `tree` is a valid pointer to [ngx_rbtree_t], and `T::from_rbtree_node` on the tree nodes - /// results in valid pointers to `T`. - pub unsafe fn from_ptr<'a>(tree: *const ngx_rbtree_t) -> &'a Self { - unsafe { &*tree.cast() } - } - - /// Creates a mutable tree reference from a pointer to [ngx_rbtree_t]. - /// - /// # Safety - /// - /// `tree` is a valid pointer to [ngx_rbtree_t], and `T::from_rbtree_node` on the tree nodes - /// results in valid pointers to `T`. - pub unsafe fn from_ptr_mut<'a>(tree: *mut ngx_rbtree_t) -> &'a mut Self { - unsafe { &mut *tree.cast() } - } - - /// Returns `true` if the tree contains no elements. - pub fn is_empty(&self) -> bool { - ptr::addr_eq(self.inner.root, self.inner.sentinel) - } - - /// Appends a node to the tree. - pub fn insert(&mut self, node: &mut T) { - unsafe { ngx_rbtree_insert(&raw mut self.inner, node.to_rbtree_node()) }; - } - - /// Removes the specified node from the tree. - pub fn remove(&mut self, node: &mut T) { - unsafe { ngx_rbtree_delete(&raw mut self.inner, node.to_rbtree_node()) }; - } - - /// Returns an iterator over the nodes of the tree. - pub fn iter(&self) -> NgxRbTreeIter<'_> { - unsafe { NgxRbTreeIter::new(NonNull::from(&self.inner)) } - } - - /// Returns a mutable iterator over the nodes of the tree. - pub fn iter_mut(&mut self) -> NgxRbTreeIter<'_> { - unsafe { NgxRbTreeIter::new(NonNull::from(&mut self.inner)) } - } -} - -/// Raw iterator over the `ngx_rbtree_t` nodes. -/// -/// This iterator type can be used to access elements of any correctly initialized `ngx_rbtree_t` -/// instance, including those already embedded in the nginx structures. The iterator stores pointer -/// to the next node and thus remains valid and usable even if the last returned item is removed -/// from the tree. -pub struct NgxRbTreeIter<'a> { - tree: NonNull, - node: *mut ngx_rbtree_node_t, - _lifetime: PhantomData<&'a ()>, -} - -impl NgxRbTreeIter<'_> { - /// Creates an iterator for the `ngx_rbtree_t`. - /// - /// # Safety - /// - /// The tree must outlive the iterator. - pub unsafe fn new(tree: NonNull) -> Self { - let t = unsafe { tree.as_ref() }; - let node = if ptr::addr_eq(t.root, t.sentinel) { - // empty tree - ptr::null_mut() - } else { - unsafe { ngx_rbtree_min(t.root, t.sentinel) } - }; - - Self { tree, node, _lifetime: PhantomData } - } -} - -impl Iterator for NgxRbTreeIter<'_> { - type Item = NonNull; - - fn next(&mut self) -> Option { - let item = NonNull::new(self.node)?; - // ngx_rbtree_next does not mutate the tree - self.node = unsafe { ngx_rbtree_next(self.tree.as_mut(), self.node) }; - Some(item) - } -} - -#[allow(deprecated)] -type BuildMapHasher = core::hash::BuildHasherDefault; - -/// A map type based on the `ngx_rbtree_t`. -/// -/// This map implementation owns the stored keys and values and ensures that the data is dropped. -/// The order of the elements is an undocumented implementation detail. -/// -/// This is a `ngx`-specific high-level type with no direct counterpart in the NGINX code. -#[derive(Debug)] -pub struct RbTreeMap -where - A: Allocator, -{ - tree: NgxRbTree>, - sentinel: NonNull, - alloc: A, -} - -/// Entry type for the [RbTreeMap]. -/// -/// The struct is used from the Rust code only and thus does not need to be compatible with C. -#[derive(Debug)] -struct MapEntry { - node: ngx_rbtree_node_t, - key: K, - value: V, -} - -impl MapEntry -where - K: Hash, -{ - fn new(key: K, value: V) -> Self { - let mut node: ngx_rbtree_node_t = unsafe { mem::zeroed() }; - node.key = BuildMapHasher::default().hash_one(&key) as ngx_rbtree_key_t; - - Self { node, key, value } - } - - fn into_kv(self) -> (K, V) { - (self.key, self.value) - } -} - -unsafe impl NgxRbTreeEntry for MapEntry { - fn from_rbtree_node(node: NonNull) -> NonNull { - unsafe { ngx_rbtree_data!(node, Self, node) } - } - - fn to_rbtree_node(&mut self) -> &mut ngx_rbtree_node_t { - &mut self.node - } -} - -/// An iterator for the [RbTreeMap]. -pub struct MapIter<'a, K: 'a, V: 'a>(NgxRbTreeIter<'a>, PhantomData<(K, V)>); - -impl<'a, K: 'a, V: 'a> MapIter<'a, K, V> { - /// Creates an iterator for the [RbTreeMap]. - pub fn new(tree: &'a RbTreeMap) -> Self { - // msrv(1.89.0): NonNull::from_ref() - let rbtree = NonNull::from(&tree.tree.inner); - // SAFETY: Iter borrows from the tree, ensuring that the tree would outlive it. - Self(unsafe { NgxRbTreeIter::new(rbtree) }, Default::default()) - } -} - -impl<'a, K: 'a, V: 'a> Iterator for MapIter<'a, K, V> { - type Item = (&'a K, &'a V); - - fn next(&mut self) -> Option { - let item = self.0.next()?; - let item = unsafe { ngx_rbtree_data!(item, MapEntry, node).as_ref() }; - Some((&item.key, &item.value)) - } -} - -/// A mutable iterator for the [RbTreeMap]. -pub struct MapIterMut<'a, K: 'a, V: 'a>(NgxRbTreeIter<'a>, PhantomData<(K, V)>); - -impl<'a, K: 'a, V: 'a> MapIterMut<'a, K, V> { - /// Creates an iterator for the [RbTreeMap]. - pub fn new(tree: &'a mut RbTreeMap) -> Self { - // msrv(1.89.0): NonNull::from_mut() - let rbtree = NonNull::from(&mut tree.tree.inner); - // SAFETY: IterMut borrows from the tree, ensuring that the tree would outlive it. - Self(unsafe { NgxRbTreeIter::new(rbtree) }, Default::default()) - } -} - -impl<'a, K: 'a, V: 'a> Iterator for MapIterMut<'a, K, V> { - type Item = (&'a K, &'a mut V); - - fn next(&mut self) -> Option { - let mut item = MapEntry::::from_rbtree_node(self.0.next()?); - let item = unsafe { item.as_mut() }; - Some((&item.key, &mut item.value)) - } -} - -impl RbTreeMap -where - A: Allocator, -{ - /// Returns a reference to the underlying allocator. - pub fn allocator(&self) -> &A { - &self.alloc - } - - /// Clears the tree, removing all elements. - pub fn clear(&mut self) { - // SAFETY: the iter lives until the end of the scope - let iter = unsafe { NgxRbTreeIter::new(NonNull::from(&self.tree.inner)) }; - let layout = Layout::new::>(); - - for node in iter { - unsafe { - let mut data = MapEntry::::from_rbtree_node(node); - - ngx_rbtree_delete(&raw mut self.tree.inner, &raw mut data.as_mut().node); - ptr::drop_in_place(data.as_mut()); - self.allocator().deallocate(data.cast(), layout) - } - } - } - - /// Returns true if the tree contains no entries. - pub fn is_empty(&self) -> bool { - self.tree.is_empty() - } - - /// Returns an iterator over the entries of the tree. - #[inline] - pub fn iter(&self) -> MapIter<'_, K, V> { - MapIter::new(self) - } - - /// Returns a mutable iterator over the entries of the tree. - #[inline] - pub fn iter_mut(&mut self) -> MapIterMut<'_, K, V> { - MapIterMut::new(self) - } -} - -impl RbTreeMap -where - A: Allocator, - K: Hash + Ord, -{ - /// Attempts to create and initialize a new RbTreeMap with specified allocator. - pub fn try_new_in(alloc: A) -> Result { - let layout = Layout::new::(); - let sentinel: NonNull = alloc.allocate_zeroed(layout)?.cast(); - - let tree = NgxRbTree { inner: unsafe { mem::zeroed() }, _type: PhantomData }; - - let mut this = RbTreeMap { tree, sentinel, alloc }; - - unsafe { - ngx_rbtree_init(&raw mut this.tree.inner, this.sentinel.as_ptr(), Some(Self::insert)) - }; - - Ok(this) - } - - /// Returns a reference to the value corresponding to the key. - pub fn get(&self, key: &Q) -> Option<&V> - where - K: borrow::Borrow, - Q: Hash + Ord + ?Sized, - { - self.lookup(key).map(|x| unsafe { &x.as_ref().value }) - } - - /// Returns a mutable reference to the value corresponding to the key. - pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> - where - K: borrow::Borrow, - Q: Hash + Ord + ?Sized, - { - self.lookup(key).map(|mut x| unsafe { &mut x.as_mut().value }) - } - - /// Removes a key from the tree, returning the value at the key if the key was previously in the - /// tree. - pub fn remove(&mut self, key: &Q) -> Option - where - K: borrow::Borrow, - Q: Hash + Ord + ?Sized, - { - self.remove_entry(key).map(|(_, v)| v) - } - - /// Removes a key from the tree, returning the stored key and value if the key was previously in - /// the tree. - pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> - where - K: borrow::Borrow, - Q: Hash + Ord + ?Sized, - { - let mut node = self.lookup(key)?; - unsafe { - self.tree.remove(node.as_mut()); - - let layout = Layout::for_value(node.as_ref()); - // SAFETY: we make a bitwise copy of the node and dispose of the original value without - // dropping it. - let copy = node.as_ptr().read(); - self.allocator().deallocate(node.cast(), layout); - Some(copy.into_kv()) - } - } - - /// Attempts to insert a new element into the tree. - pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, AllocError> { - let mut node = if let Some(mut node) = self.lookup(&key) { - unsafe { node.as_mut().value = value }; - node - } else { - let node = MapEntry::new(key, value); - let mut node = allocator::allocate(node, self.allocator())?; - self.tree.insert(unsafe { node.as_mut() }); - node - }; - - Ok(unsafe { &mut node.as_mut().value }) - } - - extern "C" fn insert( - mut temp: *mut ngx_rbtree_node_t, - node: *mut ngx_rbtree_node_t, - sentinel: *mut ngx_rbtree_node_t, - ) { - let n = unsafe { &mut *ngx_rbtree_data!(node, MapEntry, node) }; - - loop { - let t = unsafe { &mut *ngx_rbtree_data!(temp, MapEntry, node) }; - let p = match Ord::cmp(&n.node.key, &t.node.key) { - Ordering::Less => &mut t.node.left, - Ordering::Greater => &mut t.node.right, - Ordering::Equal => match Ord::cmp(&n.key, &t.key) { - Ordering::Less => &mut t.node.left, - Ordering::Greater => &mut t.node.right, - // should be handled in try_insert - Ordering::Equal => &mut t.node.right, - }, - }; - - if ptr::addr_eq(*p, sentinel) { - *p = node; - break; - } - - temp = *p; - } - - n.node.parent = temp; - n.node.left = sentinel; - n.node.right = sentinel; - unsafe { ngx_rbt_red(node) }; - } - - fn lookup(&self, key: &Q) -> Option>> - where - K: borrow::Borrow, - Q: Hash + Ord + ?Sized, - { - let mut node = self.tree.inner.root; - let hash = BuildMapHasher::default().hash_one(key) as ngx_rbtree_key_t; - - while !ptr::addr_eq(node, self.tree.inner.sentinel) { - let n = unsafe { NonNull::new_unchecked(ngx_rbtree_data!(node, MapEntry, node)) }; - let nr = unsafe { n.as_ref() }; - - node = match Ord::cmp(&hash, &nr.node.key) { - Ordering::Less => nr.node.left, - Ordering::Greater => nr.node.right, - Ordering::Equal => match Ord::cmp(key, nr.key.borrow()) { - Ordering::Less => nr.node.left, - Ordering::Greater => nr.node.right, - Ordering::Equal => return Some(n), - }, - } - } - - None - } -} - -impl Drop for RbTreeMap -where - A: Allocator, -{ - fn drop(&mut self) { - self.clear(); - - unsafe { - self.allocator() - .deallocate(self.sentinel.cast(), Layout::for_value(self.sentinel.as_ref())) - }; - } -} - -unsafe impl Send for RbTreeMap -where - A: Send + Allocator, - K: Send, - V: Send, -{ -} - -unsafe impl Sync for RbTreeMap -where - A: Sync + Allocator, - K: Sync, - V: Sync, -{ -} diff --git a/source/rust/vendor/ngx-rust/src/core/buffer.rs b/source/rust/vendor/ngx-rust/src/core/buffer.rs deleted file mode 100644 index cfd1282..0000000 --- a/source/rust/vendor/ngx-rust/src/core/buffer.rs +++ /dev/null @@ -1,129 +0,0 @@ -use core::slice; - -use crate::ffi::*; - -/// The `Buffer` trait provides methods for working with an nginx buffer (`ngx_buf_t`). -/// -/// See -pub trait Buffer { - /// Returns a raw pointer to the underlying `ngx_buf_t` of the buffer. - fn as_ngx_buf(&self) -> *const ngx_buf_t; - - /// Returns a mutable raw pointer to the underlying `ngx_buf_t` of the buffer. - fn as_ngx_buf_mut(&mut self) -> *mut ngx_buf_t; - - /// Returns the buffer contents as a byte slice. - fn as_bytes(&self) -> &[u8] { - let buf = self.as_ngx_buf(); - unsafe { slice::from_raw_parts((*buf).pos, self.len()) } - } - - /// Returns the length of the buffer contents. - fn len(&self) -> usize { - let buf = self.as_ngx_buf(); - unsafe { - let pos = (*buf).pos; - let last = (*buf).last; - assert!(last >= pos); - usize::wrapping_sub(last as _, pos as _) - } - } - - /// Returns `true` if the buffer is empty, i.e., it has zero length. - fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Sets the `last_buf` flag of the buffer. - /// - /// # Arguments - /// - /// * `last` - A boolean indicating whether the buffer is the last buffer in a request. - fn set_last_buf(&mut self, last: bool) { - let buf = self.as_ngx_buf_mut(); - unsafe { - (*buf).set_last_buf(if last { 1 } else { 0 }); - } - } - - /// Sets the `last_in_chain` flag of the buffer. - /// - /// # Arguments - /// - /// * `last` - A boolean indicating whether the buffer is the last buffer in a chain of buffers. - fn set_last_in_chain(&mut self, last: bool) { - let buf = self.as_ngx_buf_mut(); - unsafe { - (*buf).set_last_in_chain(if last { 1 } else { 0 }); - } - } -} - -/// The `MutableBuffer` trait extends the `Buffer` trait and provides methods for working with a -/// mutable buffer. -pub trait MutableBuffer: Buffer { - /// Returns a mutable reference to the buffer contents as a byte slice. - fn as_bytes_mut(&mut self) -> &mut [u8] { - let buf = self.as_ngx_buf_mut(); - unsafe { slice::from_raw_parts_mut((*buf).pos, self.len()) } - } -} - -/// Wrapper struct for a temporary buffer, providing methods for working with an `ngx_buf_t`. -pub struct TemporaryBuffer(*mut ngx_buf_t); - -impl TemporaryBuffer { - /// Creates a new `TemporaryBuffer` from an `ngx_buf_t` pointer. - /// - /// # Panics - /// Panics if the given buffer pointer is null. - pub fn from_ngx_buf(buf: *mut ngx_buf_t) -> TemporaryBuffer { - assert!(!buf.is_null()); - TemporaryBuffer(buf) - } -} - -impl Buffer for TemporaryBuffer { - /// Returns the underlying `ngx_buf_t` pointer as a raw pointer. - fn as_ngx_buf(&self) -> *const ngx_buf_t { - self.0 - } - - /// Returns a mutable reference to the underlying `ngx_buf_t` pointer. - fn as_ngx_buf_mut(&mut self) -> *mut ngx_buf_t { - self.0 - } -} - -impl MutableBuffer for TemporaryBuffer { - /// Returns a mutable reference to the buffer contents as a byte slice. - fn as_bytes_mut(&mut self) -> &mut [u8] { - unsafe { slice::from_raw_parts_mut((*self.0).pos, self.len()) } - } -} - -/// Wrapper struct for a memory buffer, providing methods for working with an `ngx_buf_t`. -pub struct MemoryBuffer(*mut ngx_buf_t); - -impl MemoryBuffer { - /// Creates a new `MemoryBuffer` from an `ngx_buf_t` pointer. - /// - /// # Panics - /// Panics if the given buffer pointer is null. - pub fn from_ngx_buf(buf: *mut ngx_buf_t) -> MemoryBuffer { - assert!(!buf.is_null()); - MemoryBuffer(buf) - } -} - -impl Buffer for MemoryBuffer { - /// Returns the underlying `ngx_buf_t` pointer as a raw pointer. - fn as_ngx_buf(&self) -> *const ngx_buf_t { - self.0 - } - - /// Returns a mutable reference to the underlying `ngx_buf_t` pointer. - fn as_ngx_buf_mut(&mut self) -> *mut ngx_buf_t { - self.0 - } -} diff --git a/source/rust/vendor/ngx-rust/src/core/conf.rs b/source/rust/vendor/ngx-rust/src/core/conf.rs deleted file mode 100644 index 6da4c47..0000000 --- a/source/rust/vendor/ngx-rust/src/core/conf.rs +++ /dev/null @@ -1,179 +0,0 @@ -use core::ptr::NonNull; - -use crate::ffi::{ngx_core_conf_t, ngx_module_t}; - -/// Trait for core-style modules. -/// -/// This is the foundational trait that identifies a type as representing a -/// concrete NGINX core module. -pub trait CoreModule { - /// Returns the global `ngx_module_t` describing this module. - fn module() -> &'static ngx_module_t; -} - -/// Raw access to core module main configuration slots. -/// -/// This trait is implemented for NGINX-owned types such as `ngx_cycle_t` and `ngx_conf_t` -/// that carry configuration context pointers. It exposes the low-level lookup step that -/// retrieves a module's main configuration as an untyped pointer. -/// -/// Most callers should not use this trait directly. Prefer `CoreModuleMainConf` to obtain a -/// typed reference for a specific core module. -pub trait CoreModuleConfExt { - /// Get a non-null pointer to a core module's main configuration. - /// - /// # Safety - /// Caller must ensure that type `T` matches the configuration type for the specified module. - /// Supplying the wrong type will produce an invalid typed pointer. - #[inline] - unsafe fn core_main_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { - None - } -} - -impl CoreModuleConfExt for crate::ffi::ngx_cycle_t { - #[inline] - unsafe fn core_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let conf_ctx = NonNull::new(self.conf_ctx)?; - let conf = unsafe { *conf_ctx.as_ptr().add(module.index) }; - NonNull::new(conf.cast()) - } -} - -impl CoreModuleConfExt for crate::ffi::ngx_conf_t { - #[inline] - unsafe fn core_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.cycle.as_ref()?.core_main_conf_unchecked(module) } - } -} - -/// Typed access to a core module's main configuration. -/// -/// Implement this trait for a concrete core-style module to associate it with its main -/// configuration type and global `ngx_module_t`. The provided default methods build on top of -/// `CoreModuleConfExt` to turn the raw configuration slot lookup into typed references. -/// -/// # Safety -/// Caller must ensure that type `CoreModuleMainConf::MainConf` matches the configuration type -/// for the specified module. -pub unsafe trait CoreModuleMainConf: CoreModule { - /// Concrete type of this module's main configuration. - type MainConf; - - /// Get a typed shared reference to this module's main configuration. - fn main_conf(o: &impl CoreModuleConfExt) -> Option<&'static Self::MainConf> { - unsafe { Some(o.core_main_conf_unchecked(Self::module())?.as_ref()) } - } - - /// Get a typed mutable reference to this module's main configuration. - fn main_conf_mut(o: &impl CoreModuleConfExt) -> Option<&'static mut Self::MainConf> { - unsafe { Some(o.core_main_conf_unchecked(Self::module())?.as_mut()) } - } -} - -/// Auxiliary structure to access `ngx_core_module` configuration. -pub struct NgxCoreModule; - -impl CoreModule for NgxCoreModule { - fn module() -> &'static ngx_module_t { - unsafe { &*core::ptr::addr_of!(nginx_sys::ngx_core_module) } - } -} - -unsafe impl CoreModuleMainConf for NgxCoreModule { - type MainConf = ngx_core_conf_t; -} - -#[cfg(test)] -mod tests { - extern crate alloc; - extern crate std; - - use alloc::boxed::Box; - use core::ffi::c_void; - use core::mem::MaybeUninit; - - use super::{CoreModule, CoreModuleConfExt, CoreModuleMainConf}; - use crate::ffi::{ngx_conf_t, ngx_cycle_t, ngx_module_t}; - - type CoreConfSlot = *mut *mut *mut c_void; - - fn module_with_index(index: usize) -> ngx_module_t { - let mut module = ngx_module_t::default(); - module.index = index; - module - } - - #[test] - fn null_conf_ctx_returns_none() { - let cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; - let module = module_with_index(0); - assert!(unsafe { cycle.core_main_conf_unchecked::(&module) }.is_none()); - } - - #[test] - fn missing_module_slot_returns_none() { - let mut slots: [CoreConfSlot; 2] = [core::ptr::null_mut(); 2]; - let mut cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; - cycle.conf_ctx = slots.as_mut_ptr(); - - let module = module_with_index(1); - assert!(unsafe { cycle.core_main_conf_unchecked::(&module) }.is_none()); - } - - #[test] - fn populated_slot_returns_typed_reference() { - let mut value: u32 = 42; - let mut slots: [CoreConfSlot; 1] = [(&raw mut value).cast()]; - - let mut cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; - cycle.conf_ctx = slots.as_mut_ptr(); - - let mut conf: ngx_conf_t = unsafe { MaybeUninit::zeroed().assume_init() }; - conf.cycle = &raw mut cycle; - - let module = module_with_index(0); - - let got = unsafe { conf.core_main_conf_unchecked::(&module).map(|v| *v.as_ref()) }; - assert_eq!(got, Some(42)); - - let got_mut = - unsafe { conf.core_main_conf_unchecked::(&module).map(|mut v| v.as_mut()) }; - assert!(got_mut.is_some()); - if let Some(v) = got_mut { - *v = 99; - } - assert_eq!(value, 99); - } - - struct TestCoreModule; - - impl CoreModule for TestCoreModule { - fn module() -> &'static ngx_module_t { - Box::leak(Box::new(module_with_index(0))) - } - } - - unsafe impl CoreModuleMainConf for TestCoreModule { - type MainConf = u32; - } - - #[test] - fn main_conf_trait_accessors_return_typed_references() { - let mut value: u32 = 42; - let mut slots: [CoreConfSlot; 1] = [(&raw mut value).cast()]; - - let mut cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; - cycle.conf_ctx = slots.as_mut_ptr(); - - let mut conf: ngx_conf_t = unsafe { MaybeUninit::zeroed().assume_init() }; - conf.cycle = &raw mut cycle; - - assert_eq!(TestCoreModule::main_conf(&conf).copied(), Some(42)); - - if let Some(v) = TestCoreModule::main_conf_mut(&conf) { - *v = 99; - } - assert_eq!(value, 99); - } -} diff --git a/source/rust/vendor/ngx-rust/src/core/mod.rs b/source/rust/vendor/ngx-rust/src/core/mod.rs deleted file mode 100644 index 9b9a778..0000000 --- a/source/rust/vendor/ngx-rust/src/core/mod.rs +++ /dev/null @@ -1,27 +0,0 @@ -mod buffer; -mod conf; -mod pool; -pub mod slab; -mod status; -mod string; - -pub use buffer::*; -pub use conf::*; -pub use pool::*; -pub use slab::SlabPool; -pub use status::*; -pub use string::*; - -/// Gets an outer object pointer from a pointer to one of its fields. -/// While there is no corresponding C macro, the pattern is common in the NGINX source. -/// -/// # Safety -/// -/// `$ptr` must be a valid pointer to the field `$field` of `$type`. -#[macro_export] -macro_rules! ngx_container_of { - ($ptr:expr, $type:path, $field:ident) => {{ - let ptr = $ptr; - unsafe { ptr.byte_sub(::core::mem::offset_of!($type, $field)) }.cast::<$type>() - }}; -} diff --git a/source/rust/vendor/ngx-rust/src/core/pool.rs b/source/rust/vendor/ngx-rust/src/core/pool.rs deleted file mode 100644 index efb283e..0000000 --- a/source/rust/vendor/ngx-rust/src/core/pool.rs +++ /dev/null @@ -1,337 +0,0 @@ -use core::alloc::Layout; -use core::ffi::c_void; -use core::mem; -use core::ptr::{self, NonNull}; - -use nginx_sys::{ - NGX_ALIGNMENT, ngx_buf_t, ngx_create_temp_buf, ngx_palloc, ngx_pcalloc, ngx_pfree, - ngx_pmemalign, ngx_pnalloc, ngx_pool_cleanup_add, ngx_pool_t, -}; - -use crate::allocator::{AllocError, Allocator, dangling_for_layout}; -use crate::core::buffer::{Buffer, MemoryBuffer, TemporaryBuffer}; - -/// Non-owning wrapper for an [`ngx_pool_t`] pointer, providing methods for working with memory -/// pools. -/// -/// See -#[derive(Clone, Debug)] -#[repr(transparent)] -pub struct Pool(NonNull); - -unsafe impl Allocator for Pool { - fn allocate(&self, layout: Layout) -> Result, AllocError> { - // SAFETY: - // * This wrapper should be constructed with a valid pointer to ngx_pool_t. - // * The Pool type is !Send, thus we expect exclusive access for this call. - // * Pointers are considered mutable unless obtained from an immutable reference. - let ptr = if layout.size() == 0 { - // We can guarantee alignment <= NGX_ALIGNMENT for allocations of size 0 made with - // ngx_palloc_small. Any other cases are implementation-defined, and we can't tell which - // one will be used internally. - return Ok(NonNull::slice_from_raw_parts(dangling_for_layout(&layout), layout.size())); - } else if layout.align() == 1 { - unsafe { ngx_pnalloc(self.0.as_ptr(), layout.size()) } - } else if layout.align() <= NGX_ALIGNMENT { - unsafe { ngx_palloc(self.0.as_ptr(), layout.size()) } - } else if cfg!(any(ngx_feature = "have_posix_memalign", ngx_feature = "have_memalign")) { - // ngx_pmemalign is always defined, but does not guarantee the requested alignment - // unless memalign/posix_memalign exists. - unsafe { ngx_pmemalign(self.0.as_ptr(), layout.size(), layout.align()) } - } else { - return Err(AllocError); - }; - - // Verify the alignment of the result - debug_assert_eq!(ptr.align_offset(layout.align()), 0); - - let ptr = NonNull::new(ptr.cast()).ok_or(AllocError)?; - Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) - } - - unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - // ngx_pfree is noop for small allocations unless NGX_DEBUG_PALLOC is set. - // - // Note: there should be no cleanup handlers for the allocations made using this API. - // Violating that could result in the following issues: - // - use-after-free on large allocation - // - multiple cleanup handlers attached to a dangling ptr (these are not unique) - if layout.size() > 0 // 0 is dangling ptr - && (layout.size() > self.as_ref().max || layout.align() > NGX_ALIGNMENT) - { - unsafe { ngx_pfree(self.0.as_ptr(), ptr.as_ptr().cast()) }; - } - } - - unsafe fn grow( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - debug_assert!( - new_layout.size() >= old_layout.size(), - "`new_layout.size()` must be greater than or equal to `old_layout.size()`" - ); - unsafe { self.resize(ptr, old_layout, new_layout) } - } - - unsafe fn grow_zeroed( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - debug_assert!( - new_layout.size() >= old_layout.size(), - "`new_layout.size()` must be greater than or equal to `old_layout.size()`" - ); - unsafe { - #[allow(clippy::manual_inspect)] - self.resize(ptr, old_layout, new_layout).map(|new_ptr| { - new_ptr - .cast::() - .byte_add(old_layout.size()) - .write_bytes(0, new_layout.size() - old_layout.size()); - new_ptr - }) - } - } - - unsafe fn shrink( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - debug_assert!( - new_layout.size() <= old_layout.size(), - "`new_layout.size()` must be smaller than or equal to `old_layout.size()`" - ); - unsafe { self.resize(ptr, old_layout, new_layout) } - } -} - -impl AsRef for Pool { - #[inline] - fn as_ref(&self) -> &ngx_pool_t { - // SAFETY: this wrapper should be constructed with a valid pointer to ngx_pool_t - unsafe { self.0.as_ref() } - } -} - -impl AsMut for Pool { - #[inline] - fn as_mut(&mut self) -> &mut ngx_pool_t { - // SAFETY: this wrapper should be constructed with a valid pointer to ngx_pool_t - unsafe { self.0.as_mut() } - } -} - -impl Pool { - /// Creates a new `Pool` from an `ngx_pool_t` pointer. - /// - /// # Safety - /// The caller must ensure that a valid `ngx_pool_t` pointer is provided, pointing to valid - /// memory and non-null. A null argument will cause an assertion failure and panic. - pub unsafe fn from_ngx_pool(pool: *mut ngx_pool_t) -> Pool { - unsafe { - debug_assert!(!pool.is_null()); - debug_assert!(pool.is_aligned()); - Pool(NonNull::new_unchecked(pool)) - } - } - - /// Expose the underlying `ngx_pool_t` pointer, for use with `ngx::ffi` - /// functions. - pub fn as_ptr(&self) -> *mut ngx_pool_t { - self.0.as_ptr() - } - - /// Creates a buffer of the specified size in the memory pool. - /// - /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if - /// allocation fails. - pub fn create_buffer(&self, size: usize) -> Option { - let buf = unsafe { ngx_create_temp_buf(self.0.as_ptr(), size) }; - if buf.is_null() { - return None; - } - - Some(TemporaryBuffer::from_ngx_buf(buf)) - } - - /// Creates a buffer from a string in the memory pool. - /// - /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if - /// allocation fails. - pub fn create_buffer_from_str(&self, str: &str) -> Option { - let mut buffer = self.create_buffer(str.len())?; - unsafe { - let buf = buffer.as_ngx_buf_mut(); - ptr::copy_nonoverlapping(str.as_ptr(), (*buf).pos, str.len()); - (*buf).last = (*buf).pos.add(str.len()); - } - Some(buffer) - } - - /// Creates a buffer from a static string in the memory pool. - /// - /// Returns `Some(MemoryBuffer)` if the buffer is successfully created, or `None` if allocation - /// fails. - pub fn create_buffer_from_static_str(&self, str: &'static str) -> Option { - let buf = self.calloc_type::(); - if buf.is_null() { - return None; - } - - // We cast away const, but buffers with the memory flag are read-only - let start = str.as_ptr() as *mut u8; - let end = unsafe { start.add(str.len()) }; - - unsafe { - (*buf).start = start; - (*buf).pos = start; - (*buf).last = end; - (*buf).end = end; - (*buf).set_memory(1); - } - - Some(MemoryBuffer::from_ngx_buf(buf)) - } - - /// Adds a cleanup handler for a value in the memory pool. - /// - /// Returns `Ok(())` if the cleanup handler is successfully added, or `Err(())` if the cleanup - /// handler cannot be added. - /// - /// # Safety - /// This function is marked as unsafe because it involves raw pointer manipulation. - unsafe fn add_cleanup_for_value(&self, value: *mut T) -> Result<(), ()> { - let cln = unsafe { ngx_pool_cleanup_add(self.0.as_ptr(), 0) }; - if cln.is_null() { - return Err(()); - } - - unsafe { - (*cln).handler = Some(cleanup_type::); - (*cln).data = value as *mut c_void; - } - - Ok(()) - } - - /// Allocates memory from the pool of the specified size. - /// The resulting pointer is aligned to a platform word size. - /// - /// Returns a raw pointer to the allocated memory. - pub fn alloc(&self, size: usize) -> *mut c_void { - unsafe { ngx_palloc(self.0.as_ptr(), size) } - } - - /// Allocates memory for a type from the pool. - /// The resulting pointer is aligned to a platform word size. - /// - /// Returns a typed pointer to the allocated memory. - pub fn alloc_type(&self) -> *mut T { - self.alloc(mem::size_of::()) as *mut T - } - - /// Allocates zeroed memory from the pool of the specified size. - /// The resulting pointer is aligned to a platform word size. - /// - /// Returns a raw pointer to the allocated memory. - pub fn calloc(&self, size: usize) -> *mut c_void { - unsafe { ngx_pcalloc(self.0.as_ptr(), size) } - } - - /// Allocates zeroed memory for a type from the pool. - /// The resulting pointer is aligned to a platform word size. - /// - /// Returns a typed pointer to the allocated memory. - pub fn calloc_type(&self) -> *mut T { - self.calloc(mem::size_of::()) as *mut T - } - - /// Allocates unaligned memory from the pool of the specified size. - /// - /// Returns a raw pointer to the allocated memory. - pub fn alloc_unaligned(&self, size: usize) -> *mut c_void { - unsafe { ngx_pnalloc(self.0.as_ptr(), size) } - } - - /// Allocates unaligned memory for a type from the pool. - /// - /// Returns a typed pointer to the allocated memory. - pub fn alloc_type_unaligned(&self) -> *mut T { - self.alloc_unaligned(mem::size_of::()) as *mut T - } - - /// Allocates memory for a value of a specified type and adds a cleanup handler to the memory - /// pool. - /// - /// Returns a typed pointer to the allocated memory if successful, or a null pointer if - /// allocation or cleanup handler addition fails. - pub fn allocate(&self, value: T) -> *mut T { - unsafe { - let p = self.alloc(mem::size_of::()) as *mut T; - ptr::write(p, value); - if self.add_cleanup_for_value(p).is_err() { - ptr::drop_in_place(p); - return ptr::null_mut(); - }; - p - } - } - - /// Resizes a memory allocation in place if possible. - /// - /// If resizing is requested for the last allocation in the pool, it may be - /// possible to adjust pool data and avoid any real allocations. - /// - /// # Safety - /// `ptr` must point to allocated address and `old_layout` must match the current layout - /// of the allocation. - #[inline(always)] - unsafe fn resize( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - if unsafe { - ptr.byte_add(old_layout.size()).as_ptr() == self.as_ref().d.last - && ptr.byte_add(new_layout.size()).as_ptr() <= self.as_ref().d.end - && ptr.align_offset(new_layout.align()) == 0 - } { - let pool = self.0.as_ptr(); - unsafe { (*pool).d.last = ptr.byte_add(new_layout.size()).as_ptr() }; - Ok(NonNull::slice_from_raw_parts(ptr, new_layout.size())) - } else { - let size = core::cmp::min(old_layout.size(), new_layout.size()); - let new_ptr = ::allocate(self, new_layout)?; - unsafe { - ptr.copy_to_nonoverlapping(new_ptr.cast(), size); - self.deallocate(ptr, old_layout); - } - Ok(new_ptr) - } - } -} - -/// Cleanup handler for a specific type `T`. -/// -/// This function is called when cleaning up a value of type `T` in an FFI context. -/// -/// # Safety -/// This function is marked as unsafe due to the raw pointer manipulation and the assumption that -/// `data` is a valid pointer to `T`. -/// -/// # Arguments -/// -/// * `data` - A raw pointer to the value of type `T` to be cleaned up. -unsafe extern "C" fn cleanup_type(data: *mut c_void) { - unsafe { - ptr::drop_in_place(data as *mut T); - } -} diff --git a/source/rust/vendor/ngx-rust/src/core/slab.rs b/source/rust/vendor/ngx-rust/src/core/slab.rs deleted file mode 100644 index 56bfb4e..0000000 --- a/source/rust/vendor/ngx-rust/src/core/slab.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Wrapper for the nginx slab pool allocator. -//! -//! See . -use core::alloc::Layout; -use core::cmp; -use core::ptr::NonNull; - -use nginx_sys::{ - ngx_shm_zone_t, ngx_shmtx_lock, ngx_shmtx_unlock, ngx_slab_alloc_locked, ngx_slab_free_locked, - ngx_slab_pool_t, -}; - -use crate::allocator::{AllocError, Allocator, dangling_for_layout}; - -/// Non-owning wrapper for an [`ngx_slab_pool_t`] pointer, providing methods for working with -/// shared memory slab pools. -/// -/// See . -#[derive(Clone, Debug)] -pub struct SlabPool(NonNull); - -unsafe impl Send for SlabPool {} -unsafe impl Sync for SlabPool {} - -unsafe impl Allocator for SlabPool { - #[inline] - fn allocate(&self, layout: Layout) -> Result, AllocError> { - self.lock().allocate(layout) - } - - #[inline] - unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - unsafe { self.lock().deallocate(ptr, layout) } - } - - #[inline] - fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { - self.lock().allocate_zeroed(layout) - } - - #[inline] - unsafe fn grow( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - unsafe { self.lock().grow(ptr, old_layout, new_layout) } - } - - #[inline] - unsafe fn grow_zeroed( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - unsafe { self.lock().grow_zeroed(ptr, old_layout, new_layout) } - } - - #[inline] - unsafe fn shrink( - &self, - ptr: NonNull, - old_layout: Layout, - new_layout: Layout, - ) -> Result, AllocError> { - unsafe { self.lock().shrink(ptr, old_layout, new_layout) } - } -} - -impl AsRef for SlabPool { - #[inline] - fn as_ref(&self) -> &ngx_slab_pool_t { - // SAFETY: this wrapper should be constructed with a valid pointer to ngx_slab_pool_t - unsafe { self.0.as_ref() } - } -} - -impl AsMut for SlabPool { - #[inline] - fn as_mut(&mut self) -> &mut ngx_slab_pool_t { - // SAFETY: this wrapper should be constructed with a valid pointer to ngx_slab_pool_t - unsafe { self.0.as_mut() } - } -} - -impl SlabPool { - /// Creates a new `SlabPool` from an initialized shared zone. - /// - /// # Safety - /// - /// Shared zones are initialized and safe to use: - /// * between the zone init callback and configuration reload in the master process - /// * during the whole lifetime of a worker process. - /// - /// After the configuration reload (notably, in the cycle pool cleanup handlers), zone addresses - /// in the old cycle may become unmapped. - pub unsafe fn from_shm_zone(shm_zone: &ngx_shm_zone_t) -> Option { - let ptr = NonNull::new(shm_zone.shm.addr)?.cast(); - Some(Self(ptr)) - } - - /// Locks the slab pool mutex. - #[inline] - pub fn lock(&self) -> LockedSlabPool { - let shpool = self.0.as_ptr(); - unsafe { ngx_shmtx_lock(&raw mut (*shpool).mutex) }; - LockedSlabPool(self.0) - } -} - -/// Wrapper for a locked [`ngx_slab_pool_t`] pointer. -pub struct LockedSlabPool(NonNull); - -unsafe impl Allocator for LockedSlabPool { - fn allocate(&self, layout: Layout) -> Result, AllocError> { - if layout.size() == 0 { - return Ok(NonNull::slice_from_raw_parts(dangling_for_layout(&layout), layout.size())); - } - - // Small slab allocations (size <= ngx_pagesize / 2) are always aligned to the size rounded - // up to the nearest power of 2. - // If the requested alignment exceeds size, we can guarantee the alignment by allocating - // `align()` bytes. - let size = cmp::max(layout.size(), layout.align()); - - let ptr = unsafe { ngx_slab_alloc_locked(self.0.as_ptr(), size) }; - let ptr = NonNull::new(ptr.cast()).ok_or(AllocError)?; - - if ptr.align_offset(layout.align()) != 0 { - unsafe { self.deallocate(ptr, layout) }; - return Err(AllocError); - } - - Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) - } - - unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { - if layout.size() != 0 { - unsafe { ngx_slab_free_locked(self.0.as_ptr(), ptr.as_ptr().cast()) } - } - } -} - -impl Drop for LockedSlabPool { - fn drop(&mut self) { - let shpool = unsafe { self.0.as_mut() }; - unsafe { ngx_shmtx_unlock(&raw mut shpool.mutex) } - } -} diff --git a/source/rust/vendor/ngx-rust/src/core/status.rs b/source/rust/vendor/ngx-rust/src/core/status.rs deleted file mode 100644 index 4cab884..0000000 --- a/source/rust/vendor/ngx-rust/src/core/status.rs +++ /dev/null @@ -1,70 +0,0 @@ -use core::ffi::c_char; -use core::fmt; -use core::ptr; - -use crate::ffi::*; - -/// Status -/// -/// Rust native wrapper for NGINX status codes. -#[derive(Ord, PartialOrd, Eq, PartialEq)] -pub struct Status(pub ngx_int_t); - -impl Status { - /// Is this Status equivalent to NGX_OK? - pub fn is_ok(&self) -> bool { - self == &Status::NGX_OK - } -} - -impl fmt::Debug for Status { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self.0, f) - } -} - -impl From for ngx_int_t { - fn from(val: Status) -> Self { - val.0 - } -} - -macro_rules! ngx_codes { - ( - $( - $(#[$docs:meta])* - ($konst:ident); - )+ - ) => { - impl Status { - $( - $(#[$docs])* - pub const $konst: Status = Status($konst as ngx_int_t); - )+ - - } - } -} - -ngx_codes! { - /// NGX_OK - Operation succeeded. - (NGX_OK); - /// NGX_ERROR - Operation failed. - (NGX_ERROR); - /// NGX_AGAIN - Operation incomplete; call the function again. - (NGX_AGAIN); - /// NGX_BUSY - Resource is not available. - (NGX_BUSY); - /// NGX_DONE - Operation complete or continued elsewhere. Also used as an alternative success code. - (NGX_DONE); - /// NGX_DECLINED - Operation rejected, for example, because it is disabled in the configuration. - /// This is never an error. - (NGX_DECLINED); - /// NGX_ABORT - Function was aborted. Also used as an alternative error code. - (NGX_ABORT); -} - -/// An error occurred while parsing and validating configuration. -pub const NGX_CONF_ERROR: *mut c_char = ptr::null_mut::().wrapping_offset(-1); -/// Configuration handler succeeded. -pub const NGX_CONF_OK: *mut c_char = ptr::null_mut(); diff --git a/source/rust/vendor/ngx-rust/src/core/string.rs b/source/rust/vendor/ngx-rust/src/core/string.rs deleted file mode 100644 index ad245df..0000000 --- a/source/rust/vendor/ngx-rust/src/core/string.rs +++ /dev/null @@ -1,633 +0,0 @@ -#[cfg(feature = "alloc")] -use alloc::{borrow::Cow, string::String}; -use core::cmp; -use core::fmt; -use core::str::{self, Utf8Error}; - -use crate::ffi::{ngx_str_t, u_char}; - -/// Static string initializer for [`ngx_str_t`]. -/// -/// The resulting byte string is always nul-terminated (just like a C string). -/// -/// [`ngx_str_t`]: https://nginx.org/en/docs/dev/development_guide.html#string_overview -#[macro_export] -macro_rules! ngx_string { - ($s:expr) => {{ $crate::ffi::ngx_str_t { len: $s.len() as _, data: concat!($s, "\0").as_ptr() as *mut u8 } }}; -} - -#[cfg(feature = "alloc")] -pub use self::_alloc::NgxString; - -/// Representation of a borrowed [Nginx string]. -/// -/// [Nginx string]: https://nginx.org/en/docs/dev/development_guide.html#string_overview -#[derive(Hash, PartialEq, Eq, PartialOrd, Ord)] -#[repr(transparent)] -pub struct NgxStr([u_char]); - -impl NgxStr { - /// Create an [`NgxStr`] from an [`ngx_str_t`]. - /// - /// [`ngx_str_t`]: https://nginx.org/en/docs/dev/development_guide.html#string_overview - /// - /// # Safety - /// - /// The caller has provided a valid `ngx_str_t` with a `data` pointer that points - /// to range of bytes of at least `len` bytes, whose content remains valid and doesn't - /// change for the lifetime of the returned `NgxStr`. - pub unsafe fn from_ngx_str<'a>(str: ngx_str_t) -> &'a NgxStr { - unsafe { - let bytes: &[u8] = str.as_bytes(); - &*(bytes as *const [u8] as *const NgxStr) - } - } - - /// Create an [NgxStr] from a borrowed byte slice. - #[inline] - pub fn from_bytes(bytes: &[u8]) -> &Self { - // SAFETY: An `NgxStr` is identical to a `[u8]` slice, given `u_char` is an alias for `u8` - unsafe { &*(bytes as *const [u8] as *const NgxStr) } - } - - /// Create a mutable [NgxStr] from a borrowed byte slice. - #[inline] - pub fn from_bytes_mut(bytes: &mut [u8]) -> &mut Self { - // SAFETY: An `NgxStr` is identical to a `[u8]` slice, given `u_char` is an alias for `u8` - unsafe { &mut *(bytes as *mut [u8] as *mut NgxStr) } - } - - /// Access the [`NgxStr`] as a byte slice. - pub fn as_bytes(&self) -> &[u8] { - &self.0 - } - - /// Yields a `&str` slice if the [`NgxStr`] contains valid UTF-8. - pub fn to_str(&self) -> Result<&str, Utf8Error> { - str::from_utf8(self.as_bytes()) - } - - /// Converts an [`NgxStr`] into a [`Cow`], replacing invalid UTF-8 sequences. - /// - /// See [`String::from_utf8_lossy`]. - #[cfg(feature = "alloc")] - pub fn to_string_lossy(&self) -> Cow<'_, str> { - String::from_utf8_lossy(self.as_bytes()) - } - - /// Returns `true` if the [`NgxStr`] is empty, otherwise `false`. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } -} - -impl AsRef<[u8]> for NgxStr { - #[inline] - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } -} - -impl AsMut<[u8]> for NgxStr { - #[inline] - fn as_mut(&mut self) -> &mut [u8] { - &mut self.0 - } -} - -impl fmt::Debug for NgxStr { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // XXX: Use debug_tuple() and feature(debug_closure_helpers) once it's stabilized - f.write_str("NgxStr(")?; - nginx_sys::detail::debug_bytes(f, &self.0)?; - f.write_str(")") - } -} - -impl Default for &NgxStr { - fn default() -> Self { - NgxStr::from_bytes(&[]) - } -} - -impl fmt::Display for NgxStr { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - nginx_sys::detail::display_bytes(f, &self.0) - } -} - -macro_rules! impl_partial_ord_eq_from { - ($self:ty, $other:ty) => { impl_partial_ord_eq_from!($self, $other;); }; - - ($self:ty, $other:ty; $($args:tt)*) => { - impl<'a, $($args)*> From<$other> for &'a NgxStr { - #[inline] - fn from(other: $other) -> Self { - let other: &[u8] = other.as_ref(); - NgxStr::from_bytes(other) - } - } - - impl_partial_eq!($self, $other; $($args)*); - impl_partial_ord!($self, $other; $($args)*); - }; -} - -macro_rules! impl_partial_eq { - ($self:ty, $other:ty) => { impl_partial_eq!($self, $other;); }; - - ($self:ty, $other:ty; $($args:tt)*) => { - impl<'a, $($args)*> PartialEq<$other> for $self { - #[inline] - fn eq(&self, other: &$other) -> bool { - let other: &[u8] = other.as_ref(); - PartialEq::eq(self.as_bytes(), other) - } - } - - impl<'a, $($args)*> PartialEq<$self> for $other { - #[inline] - fn eq(&self, other: &$self) -> bool { - let this: &[u8] = self.as_ref(); - PartialEq::eq(this, other.as_bytes()) - } - } - }; -} - -macro_rules! impl_partial_ord { - ($self:ty, $other:ty) => { impl_partial_ord!($self, $other;); }; - - ($self:ty, $other:ty; $($args:tt)*) => { - impl<'a, $($args)*> PartialOrd<$other> for $self { - #[inline] - fn partial_cmp(&self, other: &$other) -> Option { - let other: &[u8] = other.as_ref(); - PartialOrd::partial_cmp(self.as_bytes(), other) - } - } - - impl<'a, $($args)*> PartialOrd<$self> for $other { - #[inline] - fn partial_cmp(&self, other: &$self) -> Option { - let this: &[u8] = self.as_ref(); - PartialOrd::partial_cmp(this, other.as_bytes()) - } - } - }; -} - -impl_partial_eq!(NgxStr, [u8]); -impl_partial_eq!(NgxStr, [u8; N]; const N: usize); -impl_partial_eq!(NgxStr, str); -impl_partial_eq!(NgxStr, ngx_str_t); -impl_partial_eq!(&'a NgxStr, ngx_str_t); -impl_partial_ord!(NgxStr, [u8]); -impl_partial_ord!(NgxStr, [u8; N]; const N: usize); -impl_partial_ord!(NgxStr, str); -impl_partial_ord!(NgxStr, ngx_str_t); -impl_partial_ord!(&'a NgxStr, ngx_str_t); -impl_partial_ord_eq_from!(NgxStr, &'a [u8]); -impl_partial_ord_eq_from!(NgxStr, &'a [u8; N]; const N: usize); -impl_partial_ord_eq_from!(NgxStr, &'a str); - -#[cfg(feature = "alloc")] -mod _alloc { - use core::borrow::Borrow; - use core::hash; - use core::ops; - use core::ptr; - - use super::*; - use crate::allocator::{self, Allocator}; - use crate::collections::{TryReserveError, Vec}; - - /// Owned byte string type with Allocator support. - /// - /// Inspired by [bstr] and unstable [feature(bstr)], with two important differences: - /// - Allocator always have to be specified, - /// - any allocating methods are failible and require explicit handling of the result. - /// - /// [bstr]: https://docs.rs/bstr/latest/bstr/ - /// [feature(bstr)]: https://github.com/rust-lang/rust/issues/134915 - #[derive(Clone)] - #[repr(transparent)] - pub struct NgxString(Vec) - where - A: Allocator + Clone; - - impl NgxString - where - A: Allocator + Clone, - { - /// Constructs a new, empty `NgxString`. - /// - /// No allocations will be made until data is added to the string. - pub fn new_in(alloc: A) -> Self { - Self(Vec::new_in(alloc)) - } - - /// Tries to construct a new `NgxString` from a byte slice. - #[inline] - pub fn try_from_bytes_in( - bytes: impl AsRef<[u8]>, - alloc: A, - ) -> Result { - let mut this = Self::new_in(alloc); - this.try_reserve_exact(bytes.as_ref().len())?; - this.0.extend_from_slice(bytes.as_ref()); - Ok(this) - } - - /// Returns a reference to the underlying allocator - #[inline] - pub fn allocator(&self) -> &A { - self.0.allocator() - } - - /// Returns this `NgxString`'s capacity, in bytes. - #[inline] - pub fn capacity(&self) -> usize { - self.0.capacity() - } - - /// Returns `true` if this `NgxString` has a length of zero, and `false` otherwise. - #[inline] - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - - /// Return this `NgxString`'s length, in bytes. - #[inline] - pub fn len(&self) -> usize { - self.0.len() - } - - /// Appends bytes if there is sufficient spare capacity. - /// - /// Returns the number of remaining bytes on overflow. - #[inline] - pub fn append_within_capacity(&mut self, other: impl AsRef<[u8]>) -> Result<(), usize> { - let other = other.as_ref(); - if self.0.len() == self.0.capacity() { - return Err(other.len()); - } - - let n = cmp::min(self.0.capacity() - self.0.len(), other.len()); - unsafe { - // SAFETY: - // - self.0 has at least n writable bytes allocated past self.0.len(), - // - other has at least n bytes available for reading. - // - self.0 internal buffer will be initialized until len + n after this operation - // - other is not borrowed from `self` - let p = self.0.as_mut_ptr().add(self.0.len()); - ptr::copy_nonoverlapping(other.as_ptr(), p, n); - self.0.set_len(self.0.len() + n); - } - - match other.len() - n { - 0 => Ok(()), - x => Err(x), - } - } - - /// Tries to append the bytes to the `NgxString`. - #[inline] - pub fn try_append(&mut self, other: impl AsRef<[u8]>) -> Result<(), TryReserveError> { - let other = other.as_ref(); - self.0.try_reserve_exact(other.len())?; - self.0.extend_from_slice(other); - Ok(()) - } - - /// Tries to reserve capacity for at least `additional` more bytes. - #[inline] - pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { - self.0.try_reserve(additional) - } - - /// Tries to reserve the minimum capacity for at least `additional` more bytes. - #[inline] - pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { - self.0.try_reserve_exact(additional) - } - - #[inline] - pub(crate) fn as_bytes(&self) -> &[u8] { - &self.0 - } - - #[inline] - pub(crate) fn as_bytes_mut(&mut self) -> &mut [u8] { - &mut self.0 - } - - #[inline] - pub(crate) fn as_ngx_str(&self) -> &NgxStr { - NgxStr::from_bytes(self.0.as_slice()) - } - - #[inline] - pub(crate) fn as_ngx_str_mut(&mut self) -> &mut NgxStr { - NgxStr::from_bytes_mut(self.0.as_mut_slice()) - } - - /// Creates NgxString directly from a pointer, a capacity, a length and an allocator. - /// - /// # Safety - /// - /// See [Vec::from_raw_parts_in] - #[inline] - pub unsafe fn from_raw_parts( - ptr: *mut u8, - length: usize, - capacity: usize, - alloc: A, - ) -> Self { - unsafe { Self(Vec::from_raw_parts_in(ptr, length, capacity, alloc)) } - } - - /// Splits the NgxString into its raw components. - /// - /// The caller becomes responsible for the memory previously managed by this NgxString. - #[inline] - pub fn into_raw_parts(self) -> (*mut u8, usize, usize, A) { - self.0.into_raw_parts_with_alloc() - } - } - - impl AsRef for NgxString - where - A: Allocator + Clone, - { - fn as_ref(&self) -> &NgxStr { - self.as_ngx_str() - } - } - - impl AsMut for NgxString - where - A: Allocator + Clone, - { - fn as_mut(&mut self) -> &mut NgxStr { - self.as_ngx_str_mut() - } - } - - impl AsRef<[u8]> for NgxString - where - A: Allocator + Clone, - { - #[inline] - fn as_ref(&self) -> &[u8] { - self.as_bytes() - } - } - - impl AsMut<[u8]> for NgxString - where - A: Allocator + Clone, - { - #[inline] - fn as_mut(&mut self) -> &mut [u8] { - self.as_bytes_mut() - } - } - - impl Borrow for NgxString - where - A: Allocator + Clone, - { - fn borrow(&self) -> &NgxStr { - self.as_ngx_str() - } - } - - impl Borrow<[u8]> for NgxString - where - A: Allocator + Clone, - { - fn borrow(&self) -> &[u8] { - self.0.as_slice() - } - } - - impl fmt::Debug for NgxString - where - A: Allocator + Clone, - { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // XXX: Use debug_tuple() and feature(debug_closure_helpers) once it's stabilized - f.write_str("NgxString(")?; - nginx_sys::detail::debug_bytes(f, &self.0)?; - f.write_str(")") - } - } - - impl ops::Deref for NgxString - where - A: Allocator + Clone, - { - type Target = NgxStr; - - fn deref(&self) -> &Self::Target { - self.as_ngx_str() - } - } - - impl ops::DerefMut for NgxString - where - A: Allocator + Clone, - { - fn deref_mut(&mut self) -> &mut Self::Target { - self.as_ngx_str_mut() - } - } - - impl fmt::Display for NgxString - where - A: Allocator + Clone, - { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(self.as_ngx_str(), f) - } - } - - impl hash::Hash for NgxString - where - A: Allocator + Clone, - { - fn hash(&self, state: &mut H) { - self.0.hash(state); - } - } - - // `NgxString`'s with different allocators should be comparable - - impl PartialEq> for NgxString - where - A1: Allocator + Clone, - A2: Allocator + Clone, - { - fn eq(&self, other: &NgxString) -> bool { - PartialEq::eq(self.as_bytes(), other.as_bytes()) - } - } - - impl Eq for NgxString where A: Allocator + Clone {} - - impl PartialOrd> for NgxString - where - A1: Allocator + Clone, - A2: Allocator + Clone, - { - fn partial_cmp(&self, other: &NgxString) -> Option { - Some(Ord::cmp(self.as_bytes(), other.as_bytes())) - } - } - - impl Ord for NgxString - where - A: Allocator + Clone, - { - fn cmp(&self, other: &Self) -> cmp::Ordering { - Ord::cmp(self.as_bytes(), other.as_bytes()) - } - } - - impl allocator::TryCloneIn for NgxString { - type Target = NgxString; - - fn try_clone_in( - &self, - alloc: A, - ) -> Result, allocator::AllocError> { - NgxString::try_from_bytes_in(self.as_bytes(), alloc).map_err(|_| allocator::AllocError) - } - } - - impl fmt::Write for NgxString - where - A: Allocator + Clone, - { - fn write_str(&mut self, s: &str) -> fmt::Result { - self.append_within_capacity(s).map_err(|_| fmt::Error) - } - } - - // Implement byte comparisons directly, leave the rest to Deref. - - impl_partial_eq!(NgxString, &'a [u8]; A: Allocator + Clone); - impl_partial_eq!(NgxString, &'a [u8; N]; A: Allocator + Clone, const N: usize); - impl_partial_eq!(NgxString, &'a NgxStr; A: Allocator + Clone); - impl_partial_eq!(NgxString, ngx_str_t; A: Allocator + Clone); - - impl_partial_ord!(NgxString, &'a [u8]; A: Allocator + Clone); - impl_partial_ord!(NgxString, &'a [u8; N]; A: Allocator + Clone, const N: usize); - impl_partial_ord!(NgxString, &'a NgxStr; A: Allocator + Clone); - impl_partial_ord!(NgxString, ngx_str_t; A: Allocator + Clone); - - impl_partial_eq!(NgxStr, String); - impl_partial_eq!(&'a NgxStr, String); - impl_partial_ord!(NgxStr, String); - impl_partial_ord!(&'a NgxStr, String); - impl_partial_ord_eq_from!(NgxStr, &'a String); -} - -#[cfg(test)] -mod tests { - extern crate alloc; - - use alloc::string::ToString; - - use super::*; - - #[test] - fn test_str_comparisons() { - let string = "test".to_string(); - let ngx_string = ngx_str_t { data: string.as_ptr().cast_mut(), len: string.len() }; - let ns: &NgxStr = string.as_bytes().into(); - - #[cfg(feature = "alloc")] - assert_eq!(string, ns); - assert_eq!(ngx_string, ns); - assert_eq!(string.as_bytes(), ns); - assert_eq!(string.as_str(), ns); - assert_eq!(b"test", ns); - assert_eq!("test", ns); - - #[cfg(feature = "alloc")] - assert_eq!(ns, string); - assert_eq!(ns, ngx_string); - assert_eq!(ns, string.as_bytes()); - assert_eq!(ns, string.as_str()); - assert_eq!(ns, b"test"); - assert_eq!(ns, "test"); - } - - #[test] - #[cfg(feature = "alloc")] - fn test_string_comparisons() { - use crate::allocator::Global; - - let string = "test".to_string(); - let ngx_string = ngx_str_t { data: string.as_ptr().cast_mut(), len: string.len() }; - let borrowed: &NgxStr = string.as_bytes().into(); - let owned = NgxString::try_from_bytes_in(&string, Global).unwrap(); - - assert_eq!(string.as_bytes(), owned); - assert_eq!(ngx_string, owned); - assert_eq!(borrowed, owned); - assert_eq!(b"test", owned); - assert_eq!(owned, string.as_bytes()); - assert_eq!(owned, ngx_string); - assert_eq!(owned, borrowed); - assert_eq!(owned, b"test"); - - // String comparisons via Deref - assert_eq!(string, *owned); - assert_eq!(string.as_str(), *owned); - assert_eq!("test", *owned); - assert_eq!(*owned, string); - assert_eq!(*owned, string.as_str()); - assert_eq!(*owned, "test"); - } - - #[test] - #[cfg(feature = "alloc")] - fn test_string_write() { - use core::fmt::Write; - - use crate::allocator::Global; - - let h = NgxStr::from_bytes(b"Hello"); - let w = NgxStr::from_bytes(b"world"); - - let mut s = NgxString::new_in(Global); - s.try_reserve(16).expect("reserve"); - - // Remember ptr and len of internal buffer - let saved = (s.as_bytes().as_ptr(), s.capacity()); - - write!(s, "{h} {w}!").expect("write"); - - assert_eq!(s, b"Hello world!"); - assert_eq!((s.as_bytes().as_ptr(), s.capacity()), saved); - } - - #[test] - fn test_lifetimes() { - let a: &NgxStr = "Hello World!".into(); - - let s = "Hello World!".to_string(); - let b: &NgxStr = s.as_bytes().into(); - - // The compiler should detect that s is borrowed and fail. - // drop(s); // ☢️ - - assert_eq!(a.0, b.0); - } -} diff --git a/source/rust/vendor/ngx-rust/src/ffi/mod.rs b/source/rust/vendor/ngx-rust/src/ffi/mod.rs deleted file mode 100644 index 887a73e..0000000 --- a/source/rust/vendor/ngx-rust/src/ffi/mod.rs +++ /dev/null @@ -1 +0,0 @@ -pub use nginx_sys::*; diff --git a/source/rust/vendor/ngx-rust/src/http/conf.rs b/source/rust/vendor/ngx-rust/src/http/conf.rs deleted file mode 100644 index c6e9d10..0000000 --- a/source/rust/vendor/ngx-rust/src/http/conf.rs +++ /dev/null @@ -1,373 +0,0 @@ -use ::core::ptr::NonNull; - -use crate::ffi::{ - ngx_http_conf_ctx_t, ngx_http_core_srv_conf_t, ngx_http_request_t, - ngx_http_upstream_srv_conf_t, ngx_module_t, -}; -use crate::http::HttpModule; - -/// Utility trait for types containing HTTP module configuration -pub trait HttpModuleConfExt { - /// Get a non-null reference to the main configuration structure for HTTP module - /// - /// # Safety - /// Caller must ensure that type `T` matches the configuration type for the specified module. - #[inline] - unsafe fn http_main_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { - None - } - - /// Get a non-null reference to the server configuration structure for HTTP module - /// - /// # Safety - /// Caller must ensure that type `T` matches the configuration type for the specified module. - #[inline] - unsafe fn http_server_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { - None - } - - /// Get a non-null reference to the location configuration structure for HTTP module - /// - /// Applies to a single `location`, `if` or `limit_except` block - /// - /// # Safety - /// Caller must ensure that type `T` matches the configuration type for the specified module. - #[inline] - unsafe fn http_location_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { - None - } -} - -impl HttpModuleConfExt for crate::ffi::ngx_http_conf_ctx_t { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - NonNull::new(unsafe { *self.main_conf.add(module.ctx_index) }.cast()) - } - - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - NonNull::new(unsafe { *self.srv_conf.add(module.ctx_index) }.cast()) - } - - #[inline] - unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - NonNull::new(unsafe { *self.loc_conf.add(module.ctx_index) }.cast()) - } -} - -impl HttpModuleConfExt for crate::ffi::ngx_cycle_t { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let http_conf = unsafe { self.conf_ctx.add(nginx_sys::ngx_http_module.index).as_ref()? }; - let conf_ctx = (*http_conf).cast::(); - unsafe { conf_ctx.as_ref()?.http_main_conf_unchecked(module) } - } -} - -impl HttpModuleConfExt for crate::ffi::ngx_conf_t { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let conf_ctx = self.ctx.cast::(); - unsafe { conf_ctx.as_ref()?.http_main_conf_unchecked(module) } - } - - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let conf_ctx = self.ctx.cast::(); - unsafe { - let conf_ctx = conf_ctx.as_ref()?; - NonNull::new((*conf_ctx.srv_conf.add(module.ctx_index)).cast()) - } - } - - #[inline] - unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let conf_ctx = self.ctx.cast::(); - unsafe { conf_ctx.as_ref()?.http_location_conf_unchecked(module) } - } -} - -impl HttpModuleConfExt for crate::ffi::ngx_http_connection_t { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.conf_ctx.as_ref()?.http_main_conf_unchecked(module) } - } - - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.conf_ctx.as_ref()?.http_server_conf_unchecked(module) } - } - - #[inline] - unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.conf_ctx.as_ref()?.http_location_conf_unchecked(module) } - } -} - -impl HttpModuleConfExt for ngx_http_core_srv_conf_t { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.ctx.as_ref()?.http_main_conf_unchecked(module) } - } - - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.ctx.as_ref()?.http_server_conf_unchecked(module) } - } - - #[inline] - unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { self.ctx.as_ref()?.http_location_conf_unchecked(module) } - } -} - -impl HttpModuleConfExt for ngx_http_request_t { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - NonNull::new(unsafe { *self.main_conf.add(module.ctx_index) }.cast()) - } - - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - NonNull::new(unsafe { *self.srv_conf.add(module.ctx_index) }.cast()) - } - - #[inline] - unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - NonNull::new(unsafe { *self.loc_conf.add(module.ctx_index) }.cast()) - } -} - -impl HttpModuleConfExt for ngx_http_upstream_srv_conf_t { - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let conf = self.srv_conf; - if conf.is_null() { - return None; - } - NonNull::new(unsafe { *conf.add(module.ctx_index) }.cast()) - } -} - -/// Trait to define and access main module configuration -/// -/// # Safety -/// Caller must ensure that type `HttpModuleMainConf::MainConf` matches the configuration type -/// for the specified module. -pub unsafe trait HttpModuleMainConf: HttpModule { - /// Type for main module configuration - type MainConf; - /// Get reference to main module configuration - fn main_conf(o: &impl HttpModuleConfExt) -> Option<&'static Self::MainConf> { - unsafe { Some(o.http_main_conf_unchecked(Self::module())?.as_ref()) } - } - /// Get mutable reference to main module configuration - fn main_conf_mut(o: &impl HttpModuleConfExt) -> Option<&'static mut Self::MainConf> { - unsafe { Some(o.http_main_conf_unchecked(Self::module())?.as_mut()) } - } -} - -/// Trait to define and access server-specific module configuration -/// -/// # Safety -/// Caller must ensure that type `HttpModuleServerConf::ServerConf` matches the configuration type -/// for the specified module. -pub unsafe trait HttpModuleServerConf: HttpModule { - /// Type for server-specific module configuration - type ServerConf; - /// Get reference to server-specific module configuration - fn server_conf(o: &impl HttpModuleConfExt) -> Option<&'static Self::ServerConf> { - unsafe { Some(o.http_server_conf_unchecked(Self::module())?.as_ref()) } - } - /// Get mutable reference to server-specific module configuration - fn server_conf_mut(o: &impl HttpModuleConfExt) -> Option<&'static mut Self::ServerConf> { - unsafe { Some(o.http_server_conf_unchecked(Self::module())?.as_mut()) } - } -} - -/// Trait to define and access location-specific module configuration -/// -/// Applies to a single `location`, `if` or `limit_except` block -/// -/// # Safety -/// Caller must ensure that type `HttpModuleLocationConf::LocationConf` matches the configuration -/// type for the specified module. -pub unsafe trait HttpModuleLocationConf: HttpModule { - /// Type for location-specific module configuration - type LocationConf; - /// Get reference to location-specific module configuration - fn location_conf(o: &impl HttpModuleConfExt) -> Option<&'static Self::LocationConf> { - unsafe { Some(o.http_location_conf_unchecked(Self::module())?.as_ref()) } - } - /// Get mutable reference to location-specific module configuration - fn location_conf_mut(o: &impl HttpModuleConfExt) -> Option<&'static mut Self::LocationConf> { - unsafe { Some(o.http_location_conf_unchecked(Self::module())?.as_mut()) } - } -} - -mod core { - use crate::allocator::AllocError; - use crate::{ - ffi::{ - ngx_http_core_loc_conf_t, ngx_http_core_main_conf_t, ngx_http_core_module, - ngx_http_core_srv_conf_t, - }, - http::{HttpModuleMainConf, HttpRequestHandler}, - ngx_conf_log_error, - }; - - /// Auxiliary structure to access `ngx_http_core_module` configuration. - pub struct NgxHttpCoreModule; - - impl crate::http::HttpModule for NgxHttpCoreModule { - fn module() -> &'static crate::ffi::ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_core_module) } - } - } - unsafe impl crate::http::HttpModuleMainConf for NgxHttpCoreModule { - type MainConf = ngx_http_core_main_conf_t; - } - unsafe impl crate::http::HttpModuleServerConf for NgxHttpCoreModule { - type ServerConf = ngx_http_core_srv_conf_t; - } - unsafe impl crate::http::HttpModuleLocationConf for NgxHttpCoreModule { - type LocationConf = ngx_http_core_loc_conf_t; - } - - /// HTTP phases in which a module can register handlers. - #[repr(usize)] - pub enum HttpPhase { - /// Post-read phase - PostRead = crate::ffi::ngx_http_phases_NGX_HTTP_POST_READ_PHASE as _, - /// Server rewrite phase - ServerRewrite = crate::ffi::ngx_http_phases_NGX_HTTP_SERVER_REWRITE_PHASE as _, - /// Find configuration phase - FindConfig = crate::ffi::ngx_http_phases_NGX_HTTP_FIND_CONFIG_PHASE as _, - /// Rewrite phase - Rewrite = crate::ffi::ngx_http_phases_NGX_HTTP_REWRITE_PHASE as _, - /// Post-rewrite phase - PostRewrite = crate::ffi::ngx_http_phases_NGX_HTTP_POST_REWRITE_PHASE as _, - /// Pre-access phase - Preaccess = crate::ffi::ngx_http_phases_NGX_HTTP_PREACCESS_PHASE as _, - /// Access phase - Access = crate::ffi::ngx_http_phases_NGX_HTTP_ACCESS_PHASE as _, - /// Post-access phase - PostAccess = crate::ffi::ngx_http_phases_NGX_HTTP_POST_ACCESS_PHASE as _, - /// Pre-content phase - PreContent = crate::ffi::ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE as _, - /// Content phase - Content = crate::ffi::ngx_http_phases_NGX_HTTP_CONTENT_PHASE as _, - /// Log phase - Log = crate::ffi::ngx_http_phases_NGX_HTTP_LOG_PHASE as _, - } - - /// Register a request handler for a specified phase. - /// This function must be called from the module's `postconfiguration()` function. - pub fn add_phase_handler(cf: &mut nginx_sys::ngx_conf_t) -> Result<(), AllocError> - where - H: HttpRequestHandler, - { - let cmcf = NgxHttpCoreModule::main_conf_mut(cf).expect("http core main conf"); - let h: *mut nginx_sys::ngx_http_handler_pt = unsafe { - nginx_sys::ngx_array_push(&raw mut cmcf.phases[H::PHASE as usize].handlers).cast() - }; - if h.is_null() { - ngx_conf_log_error!( - nginx_sys::NGX_LOG_EMERG, - cf, - "failed to register {} handler", - H::name(), - ); - return Err(AllocError); - } - // set an H::PHASE phase handler - unsafe { - *h = Some(crate::http::raw_handler::); - } - Ok(()) - } -} - -pub use core::{HttpPhase, NgxHttpCoreModule, add_phase_handler}; - -#[cfg(ngx_feature = "http_ssl")] -mod ssl { - use crate::ffi::{ngx_http_ssl_module, ngx_http_ssl_srv_conf_t}; - - /// Auxiliary structure to access `ngx_http_ssl_module` configuration. - pub struct NgxHttpSslModule; - - impl crate::http::HttpModule for NgxHttpSslModule { - fn module() -> &'static crate::ffi::ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_ssl_module) } - } - } - unsafe impl crate::http::HttpModuleServerConf for NgxHttpSslModule { - type ServerConf = ngx_http_ssl_srv_conf_t; - } -} -#[cfg(ngx_feature = "http_ssl")] -pub use ssl::NgxHttpSslModule; - -mod upstream { - use crate::ffi::{ - ngx_http_upstream_main_conf_t, ngx_http_upstream_module, ngx_http_upstream_srv_conf_t, - }; - - /// Auxiliary structure to access `ngx_http_upstream_module` configuration. - pub struct NgxHttpUpstreamModule; - - impl crate::http::HttpModule for NgxHttpUpstreamModule { - fn module() -> &'static crate::ffi::ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_upstream_module) } - } - } - unsafe impl crate::http::HttpModuleMainConf for NgxHttpUpstreamModule { - type MainConf = ngx_http_upstream_main_conf_t; - } - unsafe impl crate::http::HttpModuleServerConf for NgxHttpUpstreamModule { - type ServerConf = ngx_http_upstream_srv_conf_t; - } -} - -pub use upstream::NgxHttpUpstreamModule; - -#[cfg(all(nginx1_25_1, ngx_feature = "http_v2"))] -mod http_v2 { - use crate::ffi::{ngx_http_v2_module, ngx_http_v2_srv_conf_t}; - - /// Auxiliary structure to access `ngx_http_v2_module` configuration. - pub struct NgxHttpV2Module; - - impl crate::http::HttpModule for NgxHttpV2Module { - fn module() -> &'static crate::ffi::ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_v2_module) } - } - } - unsafe impl crate::http::HttpModuleServerConf for NgxHttpV2Module { - type ServerConf = ngx_http_v2_srv_conf_t; - } -} -// ngx_http_v2_module was not exposed by default until aefd862a -#[cfg(all(nginx1_25_1, ngx_feature = "http_v2"))] -pub use http_v2::NgxHttpV2Module; - -#[cfg(ngx_feature = "http_v3")] -mod http_v3 { - use crate::ffi::{ngx_http_v3_module, ngx_http_v3_srv_conf_t}; - - /// Auxiliary structure to access `ngx_http_v3_module` configuration. - pub struct NgxHttpV3Module; - - impl crate::http::HttpModule for NgxHttpV3Module { - fn module() -> &'static crate::ffi::ngx_module_t { - unsafe { &*::core::ptr::addr_of!(ngx_http_v3_module) } - } - } - unsafe impl crate::http::HttpModuleServerConf for NgxHttpV3Module { - type ServerConf = ngx_http_v3_srv_conf_t; - } -} - -#[cfg(ngx_feature = "http_v3")] -pub use http_v3::NgxHttpV3Module; diff --git a/source/rust/vendor/ngx-rust/src/http/mod.rs b/source/rust/vendor/ngx-rust/src/http/mod.rs deleted file mode 100644 index 00c329a..0000000 --- a/source/rust/vendor/ngx-rust/src/http/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -mod conf; -mod module; -mod request; -mod status; -mod upstream; - -pub use conf::*; -pub use module::*; -pub use request::*; -pub use status::*; diff --git a/source/rust/vendor/ngx-rust/src/http/module.rs b/source/rust/vendor/ngx-rust/src/http/module.rs deleted file mode 100644 index 7a9292c..0000000 --- a/source/rust/vendor/ngx-rust/src/http/module.rs +++ /dev/null @@ -1,173 +0,0 @@ -use core::error; -use core::ffi::{c_char, c_void}; -use core::fmt; -use core::ptr; - -use crate::core::NGX_CONF_ERROR; -use crate::core::*; -use crate::ffi::*; - -/// MergeConfigError - configuration cannot be merged with levels above. -#[derive(Debug)] -pub enum MergeConfigError { - /// No value provided for configuration argument - NoValue, -} - -impl error::Error for MergeConfigError {} - -impl fmt::Display for MergeConfigError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match self { - MergeConfigError::NoValue => "no value".fmt(fmt), - } - } -} - -/// The `Merge` trait provides a method for merging configuration down through each level. -/// -/// A module configuration should implement this trait for setting its configuration throughout -/// each level. -pub trait Merge { - /// Module merge function. - /// - /// # Returns - /// Result, Ok on success or MergeConfigError on failure. - fn merge(&mut self, prev: &Self) -> Result<(), MergeConfigError>; -} - -impl Merge for () { - fn merge(&mut self, _prev: &Self) -> Result<(), MergeConfigError> { - Ok(()) - } -} - -/// The `HTTPModule` trait provides the NGINX configuration stage interface. -/// -/// These functions allocate structures, initialize them, and merge through the configuration -/// layers. -/// -/// See for details. -pub trait HttpModule { - /// Returns reference to a global variable of type [ngx_module_t] created for this module. - fn module() -> &'static ngx_module_t; - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn preconfiguration(_cf: *mut ngx_conf_t) -> ngx_int_t { - Status::NGX_OK.into() - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn postconfiguration(_cf: *mut ngx_conf_t) -> ngx_int_t { - Status::NGX_OK.into() - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn create_main_conf(cf: *mut ngx_conf_t) -> *mut c_void - where - Self: super::HttpModuleMainConf, - Self::MainConf: Default, - { - unsafe { - let pool = Pool::from_ngx_pool((*cf).pool); - pool.allocate::(Default::default()) as *mut c_void - } - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn init_main_conf(_cf: *mut ngx_conf_t, _conf: *mut c_void) -> *mut c_char - where - Self: super::HttpModuleMainConf, - Self::MainConf: Default, - { - ptr::null_mut() - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void - where - Self: super::HttpModuleServerConf, - Self::ServerConf: Default, - { - unsafe { - let pool = Pool::from_ngx_pool((*cf).pool); - pool.allocate::(Default::default()) as *mut c_void - } - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn merge_srv_conf( - _cf: *mut ngx_conf_t, - prev: *mut c_void, - conf: *mut c_void, - ) -> *mut c_char - where - Self: super::HttpModuleServerConf, - Self::ServerConf: Merge, - { - unsafe { - let prev = &mut *(prev as *mut Self::ServerConf); - let conf = &mut *(conf as *mut Self::ServerConf); - match conf.merge(prev) { - Ok(_) => ptr::null_mut(), - Err(_) => NGX_CONF_ERROR as _, - } - } - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn create_loc_conf(cf: *mut ngx_conf_t) -> *mut c_void - where - Self: super::HttpModuleLocationConf, - Self::LocationConf: Default, - { - unsafe { - let pool = Pool::from_ngx_pool((*cf).pool); - pool.allocate::(Default::default()) as *mut c_void - } - } - - /// # Safety - /// - /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must - /// guard against null inputs or risk runtime errors. - unsafe extern "C" fn merge_loc_conf( - _cf: *mut ngx_conf_t, - prev: *mut c_void, - conf: *mut c_void, - ) -> *mut c_char - where - Self: super::HttpModuleLocationConf, - Self::LocationConf: Merge, - { - unsafe { - let prev = &mut *(prev as *mut Self::LocationConf); - let conf = &mut *(conf as *mut Self::LocationConf); - match conf.merge(prev) { - Ok(_) => ptr::null_mut(), - Err(_) => NGX_CONF_ERROR as _, - } - } - } -} diff --git a/source/rust/vendor/ngx-rust/src/http/request.rs b/source/rust/vendor/ngx-rust/src/http/request.rs deleted file mode 100644 index 64d7e6e..0000000 --- a/source/rust/vendor/ngx-rust/src/http/request.rs +++ /dev/null @@ -1,802 +0,0 @@ -use core::error; -use core::ffi::c_void; -use core::fmt; -use core::ptr::NonNull; -use core::slice; -use core::str::FromStr; - -use crate::core::*; -use crate::ffi::*; -use crate::http::HttpPhase; -use crate::http::status::*; - -/// Define a static request handler. -/// -/// Handlers are expected to take a single [`Request`] argument and return a [`Status`]. -#[macro_export] -macro_rules! http_request_handler { - ( $name: ident, $handler: expr ) => { - extern "C" fn $name(r: *mut $crate::ffi::ngx_http_request_t) -> $crate::ffi::ngx_int_t { - let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; - let status: $crate::core::Status = $handler(request); - status.0 - } - }; -} - -/// Define a static post subrequest handler. -/// -/// Handlers are expected to take a single [`Request`] argument and return a [`Status`]. -#[macro_export] -macro_rules! http_subrequest_handler { - ( $name: ident, $handler: expr ) => { - unsafe extern "C" fn $name( - r: *mut $crate::ffi::ngx_http_request_t, - data: *mut ::core::ffi::c_void, - rc: $crate::ffi::ngx_int_t, - ) -> $crate::ffi::ngx_int_t { - $handler(r, data, rc) - } - }; -} - -/// Define a static variable setter. -/// -/// The set handler allows setting the property referenced by the variable. -/// The set handler expects a [`Request`], [`mut ngx_variable_value_t`], and a [`usize`]. -/// Variables: -#[macro_export] -macro_rules! http_variable_set { - ( $name: ident, $handler: expr ) => { - unsafe extern "C" fn $name( - r: *mut $crate::ffi::ngx_http_request_t, - v: *mut $crate::ffi::ngx_variable_value_t, - data: usize, - ) { - let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; - $handler(request, v, data); - } - }; -} - -/// Define a static variable evaluator. -/// -/// The get handler is responsible for evaluating a variable in the context of a specific request. -/// Variable evaluators accept a [`Request`] input argument and two output -/// arguments: [`ngx_variable_value_t`] and [`usize`]. -/// Variables: -#[macro_export] -macro_rules! http_variable_get { - ( $name: ident, $handler: expr ) => { - unsafe extern "C" fn $name( - r: *mut $crate::ffi::ngx_http_request_t, - v: *mut $crate::ffi::ngx_variable_value_t, - data: usize, - ) -> $crate::ffi::ngx_int_t { - let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; - let status: $crate::core::Status = $handler(request, v, data); - status.0 - } - }; -} - -/// Trait for converting handler return types into `ngx_int_t`. -/// Any desired error handling / logging logic can be implemented -/// in the `into_handler_status` method. -/// -/// There are predefined implementations for `ngx_int_t`, [`Status`], [`HTTPStatus`], -/// [`Option`] with value type implementing [`IntoHandlerStatus`]. -pub trait IntoHandlerStatus -where - Self: Sized, -{ - /// Convert the handler return type into an `ngx_int_t`. - fn into_handler_status(self, _r: &Request) -> ngx_int_t; -} - -impl IntoHandlerStatus for Option -where - T: IntoHandlerStatus, -{ - #[inline] - fn into_handler_status(self, r: &Request) -> ngx_int_t { - self.map(|val| val.into_handler_status(r)).unwrap_or(NGX_ERROR as _) - } -} - -impl IntoHandlerStatus for ngx_int_t { - #[inline] - fn into_handler_status(self, _r: &Request) -> ngx_int_t { - self - } -} - -impl IntoHandlerStatus for Status { - #[inline] - fn into_handler_status(self, _r: &Request) -> ngx_int_t { - self.0 - } -} - -impl IntoHandlerStatus for HTTPStatus { - #[inline] - fn into_handler_status(self, _r: &Request) -> ngx_int_t { - self.0 as _ - } -} - -/// Trait for static request handler. -pub trait HttpRequestHandler { - /// The phase in which the handler is invoked. - const PHASE: HttpPhase; - /// The return type of the handler. - type Output: IntoHandlerStatus; - /// The handler function. - fn handler(request: &mut Request) -> Self::Output; - /// Handler name for logging purposes. - /// [`core::any::type_name`] is used by default. - fn name() -> &'static str { - core::any::type_name::() - } -} - -/// The C-compatible handler wrapper function. -/// -/// # Safety -/// -/// The caller has provided a valid non-null pointer to an [`ngx_http_request_t`]. -pub(crate) unsafe extern "C" fn raw_handler(r: *mut ngx_http_request_t) -> ngx_int_t -where - H: HttpRequestHandler, -{ - let r = unsafe { Request::from_ngx_http_request(r) }; - H::handler(r).into_handler_status(r) -} - -/// Wrapper struct for an [`ngx_http_request_t`] pointer, providing methods for working with HTTP -/// requests. -/// -/// See -#[repr(transparent)] -pub struct Request(ngx_http_request_t); - -impl<'a> From<&'a Request> for *const ngx_http_request_t { - fn from(request: &'a Request) -> Self { - &raw const request.0 - } -} - -impl<'a> From<&'a mut Request> for *mut ngx_http_request_t { - fn from(request: &'a mut Request) -> Self { - &raw mut request.0 - } -} - -impl AsRef for Request { - fn as_ref(&self) -> &ngx_http_request_t { - &self.0 - } -} - -impl AsMut for Request { - fn as_mut(&mut self) -> &mut ngx_http_request_t { - &mut self.0 - } -} - -impl Request { - /// Create a [`Request`] from an [`ngx_http_request_t`]. - /// - /// # Safety - /// - /// The caller has provided a valid non-null pointer to a valid `ngx_http_request_t` - /// which shares the same representation as `Request`. - pub unsafe fn from_ngx_http_request<'a>(r: *mut ngx_http_request_t) -> &'a mut Request { - unsafe { &mut *r.cast::() } - } - - /// Is this the main request (as opposed to a subrequest)? - pub fn is_main(&self) -> bool { - let main = self.0.main.cast(); - core::ptr::eq(self, main) - } - - /// Request pool. - pub fn pool(&self) -> Pool { - // SAFETY: This request is allocated from `pool`, thus must be a valid pool. - unsafe { Pool::from_ngx_pool(self.0.pool) } - } - - /// Returns the result as an `Option` if it exists, otherwise `None`. - /// - /// The option wraps an ngx_http_upstream_t instance, it will be none when the underlying NGINX - /// request does not have a pointer to a [`ngx_http_upstream_t`] upstream structure. - /// - /// [`ngx_http_upstream_t`] is best described in - /// - pub fn upstream(&self) -> Option<*mut ngx_http_upstream_t> { - if self.0.upstream.is_null() { - return None; - } - Some(self.0.upstream) - } - - /// Pointer to a [`ngx_connection_t`] client connection object. - /// - /// [`ngx_connection_t`]: https://nginx.org/en/docs/dev/development_guide.html#connection - pub fn connection(&self) -> *mut ngx_connection_t { - self.0.connection - } - - /// Pointer to a [`ngx_log_t`]. - /// - /// [`ngx_log_t`]: https://nginx.org/en/docs/dev/development_guide.html#logging - pub fn log(&self) -> *mut ngx_log_t { - unsafe { (*self.connection()).log } - } - - /// Get Module context pointer - fn get_module_ctx_ptr(&self, module: &ngx_module_t) -> *mut c_void { - unsafe { *self.0.ctx.add(module.ctx_index) } - } - - /// Get Module context - pub fn get_module_ctx(&self, module: &ngx_module_t) -> Option<&T> { - let ctx = self.get_module_ctx_ptr(module).cast::(); - // SAFETY: ctx is either NULL or allocated with ngx_p(c)alloc and - // explicitly initialized by the module - unsafe { ctx.as_ref() } - } - - /// Sets the value as the module's context. - /// - /// See - pub fn set_module_ctx(&self, value: *mut c_void, module: &ngx_module_t) { - unsafe { - *self.0.ctx.add(module.ctx_index) = value; - }; - } - - /// Get the value of a [complex value]. - /// - /// [complex value]: https://nginx.org/en/docs/dev/development_guide.html#http_complex_values - pub fn get_complex_value(&self, cv: &ngx_http_complex_value_t) -> Option<&NgxStr> { - let r = (self as *const Request as *mut Request).cast(); - let val = cv as *const ngx_http_complex_value_t as *mut ngx_http_complex_value_t; - // SAFETY: `ngx_http_complex_value` does not mutate `r` or `val` and guarentees that - // a valid Nginx string is stored in `value` if it successfully returns. - unsafe { - let mut value = ngx_str_t::default(); - if ngx_http_complex_value(r, val, &raw mut value) != NGX_OK as ngx_int_t { - return None; - } - Some(NgxStr::from_ngx_str(value)) - } - } - - /// Discard (read and ignore) the [request body]. - /// - /// [request body]: https://nginx.org/en/docs/dev/development_guide.html#http_request_body - pub fn discard_request_body(&mut self) -> Status { - unsafe { Status(ngx_http_discard_request_body(&raw mut self.0)) } - } - - /// Client HTTP [User-Agent]. - /// - /// [User-Agent]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent - pub fn user_agent(&self) -> Option<&NgxStr> { - if !self.0.headers_in.user_agent.is_null() { - unsafe { Some(NgxStr::from_ngx_str((*self.0.headers_in.user_agent).value)) } - } else { - None - } - } - - /// Set HTTP status of response. - pub fn set_status(&mut self, status: HTTPStatus) { - self.0.headers_out.status = status.into(); - } - - /// Add header to the `headers_in` object. - /// - /// See - pub fn add_header_in(&mut self, key: &str, value: &str) -> Option<()> { - let table: *mut ngx_table_elt_t = - unsafe { ngx_list_push(&raw mut self.0.headers_in.headers).cast() }; - unsafe { add_to_ngx_table(table, self.0.pool, key, value) } - } - - /// Add header to the `headers_out` object. - /// - /// See - pub fn add_header_out(&mut self, key: &str, value: &str) -> Option<()> { - let table: *mut ngx_table_elt_t = - unsafe { ngx_list_push(&raw mut self.0.headers_out.headers).cast() }; - unsafe { add_to_ngx_table(table, self.0.pool, key, value) } - } - - /// Set response body [Content-Length]. - /// - /// [Content-Length]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length - pub fn set_content_length_n(&mut self, n: usize) { - self.0.headers_out.content_length_n = n as off_t; - } - - /// Send the output header. - /// - /// Do not call this function until all output headers are set. - pub fn send_header(&mut self) -> Status { - unsafe { Status(ngx_http_send_header(&raw mut self.0)) } - } - - /// Flag indicating that the output does not require a body. - /// - /// For example, this flag is used by `HTTP HEAD` requests. - pub fn header_only(&self) -> bool { - self.0.header_only() != 0 - } - - /// request method - pub fn method(&self) -> Method { - Method::from_ngx(self.0.method) - } - - /// path part of request only - pub fn path(&self) -> &NgxStr { - unsafe { NgxStr::from_ngx_str(self.0.uri) } - } - - /// full uri - containing path and args - pub fn unparsed_uri(&self) -> &NgxStr { - unsafe { NgxStr::from_ngx_str(self.0.unparsed_uri) } - } - - /// Send the [response body]. - /// - /// This function can be called multiple times. - /// Set the `last_buf` flag in the last body buffer. - /// - /// [response body]: https://nginx.org/en/docs/dev/development_guide.html#http_request_body - pub fn output_filter(&mut self, body: &mut ngx_chain_t) -> Status { - unsafe { Status(ngx_http_output_filter(&raw mut self.0, body)) } - } - - /// Perform internal redirect to a location - pub fn internal_redirect(&self, location: &str) -> Status { - assert!(!location.is_empty(), "uri location is empty"); - let uri_ptr = unsafe { &mut ngx_str_t::from_str(self.0.pool, location) as *mut _ }; - - // FIXME: check status of ngx_http_named_location or ngx_http_internal_redirect - if location.starts_with('@') { - unsafe { - ngx_http_named_location((self as *const Request as *mut Request).cast(), uri_ptr); - } - } else { - unsafe { - ngx_http_internal_redirect( - (self as *const Request as *mut Request).cast(), - uri_ptr, - core::ptr::null_mut(), - ); - } - } - Status::NGX_DONE - } - - /// Send a subrequest - pub fn subrequest( - &self, - uri: &str, - module: &ngx_module_t, - post_callback: unsafe extern "C" fn( - *mut ngx_http_request_t, - *mut c_void, - ngx_int_t, - ) -> ngx_int_t, - ) -> Status { - let uri_ptr = unsafe { &mut ngx_str_t::from_str(self.0.pool, uri) as *mut _ }; - // ------------- - // allocate memory and set values for ngx_http_post_subrequest_t - let sub_ptr = self.pool().alloc(core::mem::size_of::()); - - // assert!(sub_ptr.is_null()); - let post_subreq = - sub_ptr as *const ngx_http_post_subrequest_t as *mut ngx_http_post_subrequest_t; - unsafe { - (*post_subreq).handler = Some(post_callback); - // WARN: safety! ensure that ctx is already set - (*post_subreq).data = self.get_module_ctx_ptr(module); - } - // ------------- - - let mut psr: *mut ngx_http_request_t = core::ptr::null_mut(); - let r = unsafe { - ngx_http_subrequest( - (self as *const Request as *mut Request).cast(), - uri_ptr, - core::ptr::null_mut(), - &raw mut psr, - sub_ptr as *mut _, - NGX_HTTP_SUBREQUEST_WAITED as _, - ) - }; - - // previously call of ngx_http_subrequest() would ensure that the pointer is not null - // anymore - let sr = unsafe { &mut *psr }; - - /* - * allocate fake request body to avoid attempts to read it and to make - * sure real body file (if already read) won't be closed by upstream - */ - sr.request_body = - self.pool().alloc(core::mem::size_of::()) as *mut _; - - if sr.request_body.is_null() { - return Status::NGX_ERROR; - } - sr.set_header_only(1 as _); - Status(r) - } - - /// Iterate over headers_in - /// each header item is (&str, &str) (borrowed) - pub fn headers_in_iterator(&self) -> NgxListIterator<'_> { - unsafe { list_iterator(&self.0.headers_in.headers) } - } - - /// Iterate over headers_out - /// each header item is (&str, &str) (borrowed) - pub fn headers_out_iterator(&self) -> NgxListIterator<'_> { - unsafe { list_iterator(&self.0.headers_out.headers) } - } -} - -impl crate::http::HttpModuleConfExt for Request { - #[inline] - unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { - // SAFETY: main_conf[module.ctx_index] is either NULL or allocated with ngx_p(c)alloc - // and explicitly initialized by the module - NonNull::new((*self.0.main_conf.add(module.ctx_index)).cast()) - } - } - - #[inline] - unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { - // SAFETY: srv_conf[module.ctx_index] is either NULL or allocated with ngx_p(c)alloc and - // explicitly initialized by the module - NonNull::new((*self.0.srv_conf.add(module.ctx_index)).cast()) - } - } - - #[inline] - unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - unsafe { - // SAFETY: loc_conf[module.ctx_index] is either NULL or allocated with ngx_p(c)alloc and - // explicitly initialized by the module - NonNull::new((*self.0.loc_conf.add(module.ctx_index)).cast()) - } - } -} - -// trait OnSubRequestDone { - -// } - -impl fmt::Debug for Request { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Request").field("request_", &self.0).finish() - } -} - -/// Iterator for [`ngx_list_t`] types. -/// -/// Implementes the core::iter::Iterator trait. -pub struct NgxListIterator<'a> { - part: Option>, - i: ngx_uint_t, -} -struct ListPart<'a> { - raw: &'a ngx_list_part_t, - arr: &'a [ngx_table_elt_t], -} -impl<'a> From<&'a ngx_list_part_t> for ListPart<'a> { - fn from(raw: &'a ngx_list_part_t) -> Self { - let arr = if raw.nelts != 0 { - unsafe { slice::from_raw_parts(raw.elts.cast(), raw.nelts) } - } else { - &[] - }; - Self { raw, arr } - } -} - -/// Creates new HTTP header iterator -/// -/// # Safety -/// -/// The caller has provided a valid [`ngx_str_t`] which can be dereferenced validly. -pub unsafe fn list_iterator(list: &ngx_list_t) -> NgxListIterator<'_> { - NgxListIterator { part: Some((&list.part).into()), i: 0 } -} - -// iterator for ngx_list_t -impl<'a> Iterator for NgxListIterator<'a> { - // TODO: try to use struct instead of &str pair - // something like pub struct Header(ngx_table_elt_t); - // then header would have key and value - - type Item = (&'a NgxStr, &'a NgxStr); - - fn next(&mut self) -> Option { - let part = self.part.as_mut()?; - if self.i >= part.arr.len() { - if let Some(next_part_raw) = unsafe { part.raw.next.as_ref() } { - // loop back - *part = next_part_raw.into(); - self.i = 0; - } else { - self.part = None; - return None; - } - } - let header = &part.arr[self.i]; - self.i += 1; - unsafe { Some((NgxStr::from_ngx_str(header.key), NgxStr::from_ngx_str(header.value))) } - } -} - -/// A possible error value when converting `Method` -pub struct InvalidMethod { - _priv: (), -} - -/// Request method verb -#[derive(Clone, PartialEq, Eq, Hash)] -pub struct Method(MethodInner); - -impl Method { - /// UNKNOWN - pub const UNKNOWN: Method = Method(MethodInner::Unknown); - - /// GET - pub const GET: Method = Method(MethodInner::Get); - - /// HEAD - pub const HEAD: Method = Method(MethodInner::Head); - - /// POST - pub const POST: Method = Method(MethodInner::Post); - - /// PUT - pub const PUT: Method = Method(MethodInner::Put); - - /// DELETE - pub const DELETE: Method = Method(MethodInner::Delete); - - /// MKCOL - pub const MKCOL: Method = Method(MethodInner::Mkcol); - - /// COPY - pub const COPY: Method = Method(MethodInner::Copy); - - /// MOVE - pub const MOVE: Method = Method(MethodInner::Move); - - /// OPTIONS - pub const OPTIONS: Method = Method(MethodInner::Options); - - /// PROPFIND - pub const PROPFIND: Method = Method(MethodInner::Propfind); - - /// PROPPATCH - pub const PROPPATCH: Method = Method(MethodInner::Proppatch); - - /// LOCK - pub const LOCK: Method = Method(MethodInner::Lock); - - /// UNLOCK - pub const UNLOCK: Method = Method(MethodInner::Unlock); - - /// PATCH - pub const PATCH: Method = Method(MethodInner::Patch); - - /// TRACE - pub const TRACE: Method = Method(MethodInner::Trace); - - /// CONNECT - pub const CONNECT: Method = Method(MethodInner::Connect); - - /// Convert a Method to a &str. - #[inline] - pub fn as_str(&self) -> &str { - match self.0 { - MethodInner::Unknown => "UNKNOWN", - MethodInner::Get => "GET", - MethodInner::Head => "HEAD", - MethodInner::Post => "POST", - MethodInner::Put => "PUT", - MethodInner::Delete => "DELETE", - MethodInner::Mkcol => "MKCOL", - MethodInner::Copy => "COPY", - MethodInner::Move => "MOVE", - MethodInner::Options => "OPTIONS", - MethodInner::Propfind => "PROPFIND", - MethodInner::Proppatch => "PROPPATCH", - MethodInner::Lock => "LOCK", - MethodInner::Unlock => "UNLOCK", - MethodInner::Patch => "PATCH", - MethodInner::Trace => "TRACE", - MethodInner::Connect => "CONNECT", - } - } - - fn from_bytes(_t: &[u8]) -> Result { - todo!() - } - - fn from_ngx(t: ngx_uint_t) -> Method { - let t = t as _; - match t { - crate::ffi::NGX_HTTP_GET => Method(MethodInner::Get), - crate::ffi::NGX_HTTP_HEAD => Method(MethodInner::Head), - crate::ffi::NGX_HTTP_POST => Method(MethodInner::Post), - crate::ffi::NGX_HTTP_PUT => Method(MethodInner::Put), - crate::ffi::NGX_HTTP_DELETE => Method(MethodInner::Delete), - crate::ffi::NGX_HTTP_MKCOL => Method(MethodInner::Mkcol), - crate::ffi::NGX_HTTP_COPY => Method(MethodInner::Copy), - crate::ffi::NGX_HTTP_MOVE => Method(MethodInner::Move), - crate::ffi::NGX_HTTP_OPTIONS => Method(MethodInner::Options), - crate::ffi::NGX_HTTP_PROPFIND => Method(MethodInner::Propfind), - crate::ffi::NGX_HTTP_PROPPATCH => Method(MethodInner::Proppatch), - crate::ffi::NGX_HTTP_LOCK => Method(MethodInner::Lock), - crate::ffi::NGX_HTTP_UNLOCK => Method(MethodInner::Unlock), - crate::ffi::NGX_HTTP_PATCH => Method(MethodInner::Patch), - crate::ffi::NGX_HTTP_TRACE => Method(MethodInner::Trace), - #[cfg(nginx1_21_1)] - crate::ffi::NGX_HTTP_CONNECT => Method(MethodInner::Connect), - _ => Method(MethodInner::Unknown), - } - } -} - -impl AsRef for Method { - #[inline] - fn as_ref(&self) -> &str { - self.as_str() - } -} - -impl<'a> PartialEq<&'a Method> for Method { - #[inline] - fn eq(&self, other: &&'a Method) -> bool { - self == *other - } -} - -impl PartialEq for &Method { - #[inline] - fn eq(&self, other: &Method) -> bool { - *self == other - } -} - -impl PartialEq for Method { - #[inline] - fn eq(&self, other: &str) -> bool { - self.as_ref() == other - } -} - -impl PartialEq for str { - #[inline] - fn eq(&self, other: &Method) -> bool { - self == other.as_ref() - } -} - -impl<'a> PartialEq<&'a str> for Method { - #[inline] - fn eq(&self, other: &&'a str) -> bool { - self.as_ref() == *other - } -} - -impl PartialEq for &str { - #[inline] - fn eq(&self, other: &Method) -> bool { - *self == other.as_ref() - } -} - -impl fmt::Debug for Method { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_ref()) - } -} - -impl fmt::Display for Method { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.write_str(self.as_ref()) - } -} - -impl<'a> From<&'a Method> for Method { - #[inline] - fn from(t: &'a Method) -> Self { - t.clone() - } -} - -impl<'a> TryFrom<&'a [u8]> for Method { - type Error = InvalidMethod; - - #[inline] - fn try_from(t: &'a [u8]) -> Result { - Method::from_bytes(t) - } -} - -impl<'a> TryFrom<&'a str> for Method { - type Error = InvalidMethod; - - #[inline] - fn try_from(t: &'a str) -> Result { - TryFrom::try_from(t.as_bytes()) - } -} - -impl FromStr for Method { - type Err = InvalidMethod; - - #[inline] - fn from_str(t: &str) -> Result { - TryFrom::try_from(t) - } -} - -impl InvalidMethod { - #[allow(dead_code)] - fn new() -> InvalidMethod { - InvalidMethod { _priv: () } - } -} - -impl fmt::Debug for InvalidMethod { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("InvalidMethod") - // skip _priv noise - .finish() - } -} - -impl fmt::Display for InvalidMethod { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("invalid HTTP method") - } -} - -impl error::Error for InvalidMethod {} - -#[derive(Clone, PartialEq, Eq, Hash)] -enum MethodInner { - Unknown, - Get, - Head, - Post, - Put, - Delete, - Mkcol, - Copy, - Move, - Options, - Propfind, - Proppatch, - Lock, - Unlock, - Patch, - Trace, - Connect, -} diff --git a/source/rust/vendor/ngx-rust/src/http/status.rs b/source/rust/vendor/ngx-rust/src/http/status.rs deleted file mode 100644 index a545f65..0000000 --- a/source/rust/vendor/ngx-rust/src/http/status.rs +++ /dev/null @@ -1,208 +0,0 @@ -use core::{error, fmt}; - -use crate::core::Status; -use crate::ffi::*; - -/// Represents an HTTP status code. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct HTTPStatus(pub ngx_uint_t); - -/// A possible error value when converting a `HTTPStatus` from a `u16` or `&str` -/// -/// This error indicates that the supplied input was not a valid number, was less -/// than 100, or was greater than 599. -#[derive(Debug)] -pub struct InvalidHTTPStatusCode { - _priv: (), -} - -impl InvalidHTTPStatusCode { - fn new() -> InvalidHTTPStatusCode { - InvalidHTTPStatusCode { _priv: () } - } -} - -impl fmt::Display for InvalidHTTPStatusCode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("invalid status code") - } -} - -impl error::Error for InvalidHTTPStatusCode {} - -impl From for Status { - fn from(val: HTTPStatus) -> Self { - Status(val.0 as ngx_int_t) - } -} - -impl From for ngx_int_t { - fn from(val: HTTPStatus) -> Self { - val.0 as _ - } -} - -impl From for ngx_uint_t { - fn from(val: HTTPStatus) -> Self { - val.0 - } -} - -impl fmt::Debug for HTTPStatus { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self.0, f) - } -} - -impl HTTPStatus { - /// Convets a u16 to a status code. - #[inline] - pub fn from_u16(src: u16) -> Result { - if !(100..600).contains(&src) { - return Err(InvalidHTTPStatusCode::new()); - } - - Ok(HTTPStatus(src.into())) - } - - /// Converts a &[u8] to a status code. - pub fn from_bytes(src: &[u8]) -> Result { - if src.len() != 3 { - return Err(InvalidHTTPStatusCode::new()); - } - - let a = src[0].wrapping_sub(b'0') as u16; - let b = src[1].wrapping_sub(b'0') as u16; - let c = src[2].wrapping_sub(b'0') as u16; - - if a == 0 || a > 5 || b > 9 || c > 9 { - return Err(InvalidHTTPStatusCode::new()); - } - - let status = (a * 100) + (b * 10) + c; - Ok(HTTPStatus(status.into())) - } -} - -macro_rules! http_status_codes { - ( - $( - $(#[$docs:meta])* - ($num:expr, $konst:ident, $phrase:expr); - )+ - ) => { - impl HTTPStatus { - $( - $(#[$docs])* - pub const $konst: HTTPStatus = HTTPStatus($num); - )+ - - } - } -} - -http_status_codes! { - /// 100 CONTINUE - (100, CONTINUE, "Continue"); - /// 101 SWITCHING_PROTOCOLS - (101, SWITCHING_PROTOCOLS, "Switching Protocols"); - /// 102 PROCESSING - (102, PROCESSING, "Processing"); - /// 200 OK - (200, OK, "OK"); - /// 201 Created - (201, CREATED, "Created"); - /// 202 Accepted - (202, ACCEPTED, "Accepted"); - /// 204 No Content - (204, NO_CONTENT, "No Content"); - /// 206 Partial Content - (206, PARTIAL_CONTENT, "Partial Content"); - - /// 300 SPECIAL_RESPONSE - (300, SPECIAL_RESPONSE, "SPECIAL_RESPONSE"); - /// 301 Moved Permanently - (301, MOVED_PERMANENTLY, "Moved Permanently"); - /// 302 Moved Temporarily - (302, MOVED_TEMPORARILY, "Moved Temporarily"); - /// 303 See Other - (303, SEE_OTHER, "See Other"); - /// 304 Not Modified - (304, NOT_MODIFIED, "Not Modified"); - /// 307 Temporary Redirect - (307, TEMPORARY_REDIRECT, "Temporary Redirect"); - /// 308 Permanent Redirect - (308, PERMANENT_REDIRECT, "Permanent Redirect"); - - /// 400 Bad Request - (400, BAD_REQUEST, "Bad Request"); - /// 401 Unauthorized - (401, UNAUTHORIZED, "Unauthorized"); - /// 403 Forbidden - (403, FORBIDDEN, "Forbidden"); - /// 404 Not Found - (404, NOT_FOUND, "Not Found"); - /// 405 Method Not Allowed - (405, NOT_ALLOWED, "Method Not Allowed"); - /// 408 Request Time Out - (408, REQUEST_TIME_OUT, "Request Time Out"); - /// 409 Conflict - (409, CONFLICT, "Conflict"); - /// 411 Length Required - (411, LENGTH_REQUIRED, "Length Required"); - /// 412 Precondition Failed - (412, PRECONDITION_FAILED, "Precondition Failed"); - /// 413 Payload Too Large - (413, REQUEST_ENTITY_TOO_LARGE, "Payload Too Large"); - /// 414 Request Uri Too Large - (414, REQUEST_URI_TOO_LARGE, "Request Uri Too Large"); - /// 415 Unsupported Media Type - (415, UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); - /// 416 Range Not Satisfiable - (416, RANGE_NOT_SATISFIABLE, "Range Not Satisfiable"); - /// 421 Misdirected Request - (421, MISDIRECTED_REQUEST, "Misdirected Request"); - /// 429 Too Many Requests - (429, TOO_MANY_REQUESTS, "Too Many Requests"); - - // /* Our own HTTP codes */ - // /* The special code to close connection without any response */ - /// 444 CLOSE - (444, CLOSE, "CLOSE"); - - /// 494 NGINX_CODES - (494, NGINX_CODES, "NGINX_CODES"); - - /// 494 REQUEST_HEADER_TOO_LARGE - (494, REQUEST_HEADER_TOO_LARGE, "REQUEST_HEADER_TOO_LARGE"); - - /// 495 NGX_HTTPS_CERT_ERROR - (495, HTTPS_CERT_ERROR, "NGX_HTTPS_CERT_ERROR"); - /// 496 NGX_HTTPS_NO_CERT - (496, HTTPS_NO_CERT, "NGX_HTTPS_NO_CERT"); - - // /* - // * We use the special code for the plain HTTP requests that are sent to - // * HTTPS port to distinguish it from 4XX in an error page redirection - // */ - /// 497 TO_HTTPS - (497, TO_HTTPS, "TO_HTTPS"); - - /// 499 CLIENT_CLOSED_REQUEST - (499, CLIENT_CLOSED_REQUEST, "CLIENT_CLOSED_REQUEST"); - - /// 500 INTERNAL_SERVER_ERROR - (500, INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR"); - /// 501 NOT_IMPLEMENTED - (501, NOT_IMPLEMENTED, "NOT_IMPLEMENTED"); - /// 502 BAD_GATEWAY - (502, BAD_GATEWAY, "BAD_GATEWAY"); - /// 503 SERVICE_UNAVAILABLE - (503, SERVICE_UNAVAILABLE, "SERVICE_UNAVAILABLE"); - /// 504 GATEWAY_TIME_OUT - (504, GATEWAY_TIME_OUT, "GATEWAY_TIME_OUT"); - /// 505 VERSION_NOT_SUPPORTED - (505, VERSION_NOT_SUPPORTED, "VERSION_NOT_SUPPORTED"); - /// 507 INSUFFICIENT_STORAGE - (507, INSUFFICIENT_STORAGE, "INSUFFICIENT_STORAGE"); -} diff --git a/source/rust/vendor/ngx-rust/src/http/upstream.rs b/source/rust/vendor/ngx-rust/src/http/upstream.rs deleted file mode 100644 index cfd3986..0000000 --- a/source/rust/vendor/ngx-rust/src/http/upstream.rs +++ /dev/null @@ -1,24 +0,0 @@ -/// Define a static upstream peer initializer -/// -/// Initializes the upstream 'get', 'free', and 'session' callbacks and gives the module writer an -/// opportunity to set custom data. -/// -/// This macro will define the NGINX callback type: -/// `typedef ngx_int_t (*ngx_http_upstream_init_peer_pt)(ngx_http_request_t *r, -/// ngx_http_upstream_srv_conf_t *us)`, we keep this macro name in-sync with its underlying NGINX -/// type, this callback is required to initialize your peer. -/// -/// Load Balancing: -#[macro_export] -macro_rules! http_upstream_init_peer_pt { - ( $name: ident, $handler: expr ) => { - extern "C" fn $name( - r: *mut $crate::ffi::ngx_http_request_t, - us: *mut $crate::ffi::ngx_http_upstream_srv_conf_t, - ) -> $crate::ffi::ngx_int_t { - let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; - let status: $crate::core::Status = $handler(request, us); - status.0 - } - }; -} diff --git a/source/rust/vendor/ngx-rust/src/lib.rs b/source/rust/vendor/ngx-rust/src/lib.rs deleted file mode 100644 index b0329b4..0000000 --- a/source/rust/vendor/ngx-rust/src/lib.rs +++ /dev/null @@ -1,189 +0,0 @@ -//! # Rust bindings for NGINX -//! -//! The `ngx` crate provides a high-level Rust interface for the [NGINX] C APIs, -//! allowing creation of NGINX dynamic modules completely in Rust. -//! -//! [NGINX]: https://nginx.org/ -//! -//! ## Project status -//! -//! This project is in active development. It is stable enough to be used in our -//! own products, but the APIs are not stabilized and breaking changes are expected. -//! -//! ## Build -//! -//! NGINX modules can be built against a particular version of NGINX. The following -//! environment variables can be used to specify the NGINX build to use: -//! -//! - `NGINX_BUILD_DIR` - absolute path to the NGINX build directory. -//! Usually it's `objs` under the source directory, but can be changed with the -//! `--builddir=` argument of the configure script. -//! -//! - `NGINX_SOURCE_DIR` - absolute path to the NGINX source directory, configured -//! with the [`configure`](https://nginx.org/en/docs/configure.html) command. -//! -//! Only the `./configure` step of the NGINX build is mandatory because bindings -//! generator don't depend on any of the artifacts generated by `make`. -//! -//! For example, this is how you would compile the [examples](#examples) using a -//! specific version of NGINX: -//! -//! ```sh -//! NGINX_BUILD_DIR=/path/to/nginx-1.30.4/objs cargo build --package=examples --examples -//! ``` -//! -//! ### Building with the NGINX build script -//! -//! You can build your Rust-based module as a part of the NGINX build process by -//! providing a `config` script implementation and passing the `--add-module`/ -//! `--add-dynamic-module` options to the configure script. -//! -//! See the following example integration scripts: [`examples/config`] and -//! [`examples/config.make`]. -//! -//! [`examples/config`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config -//! [`examples/config.make`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config.make -//! -//! ### Building with vendored NGINX sources -//! -//! It is possible to build module with a vendored copy of the NGINX sources -//! provided in the `nginx-src` crate by enabling feature `vendored`: -//! -//! By default, this will use the latest stable release of NGINX and require -//! system-wide installation of build dependencies (OpenSSL, PCRE2, Zlib). -//! -//! The behavior of vendored builds can be customized with environment variables, -//! as documented in the [nginx-src] crate README. -//! -//! **NOTE**: We recommend to build the module binaries against the exact source and -//! configuration of the NGINX build that you are planning to use in production, -//! and that is unlikely to be possible with the vendored source. -//! -//! `configure` arguments alter the APIs and the symbols visible to the Rust code, -//! and some OS distributions are known to ship nginx packages with API-breaking -//! patches applied. -//! -//! [nginx-src]: https://docs.rs/nginx-src/ -//! -//! ## Cargo features -//! -//! - `alloc` - **Enabled** by default. This provides APIs that require allocations -//! via the `alloc` crate. -//! - `async` - Enables a minimal async runtime built on top of the NGINX event loop. -//! - `serde` - Enables serialization support for some of the provided and -//! re-exported types. -//! - `std` - **Enabled** by default. This provides APIs that require the standard -//! library. -//! - `vendored`: Enables the build scripts to build a copy of nginx source and link -//! against it. See the [nginx-src] crate documentation for additional details. -//! -//! ## Dependencies -//! -//! The following dependencies are required to build a Rust NGINX module on Linux -//! or BSD platform: -//! -//! - NGINX build dependencies: C compiler, make, OpenSSL, PCRE2, and Zlib. -//! - Rust toolchain (1.85.0 or later) -//! - [libclang] for rust-bindgen -//! -//! The installation process and the package names are system-dependent. Please, -//! consult the documentation for your distribution. -//! -//! Note that on some systems you will need `-devel` or `-dev` versions of the -//! packages. -//! -//! For example, [Dockerfile] contains the installation commands for Debian Linux. -//! -//! [Dockerfile]: https://github.com/nginx/ngx-rust/blob/main/Dockerfile -//! [libclang]: https://rust-lang.github.io/rust-bindgen/requirements.html -//! -//! ### macOS dependencies -//! -//! In order to use the optional GNU make build process on macOS, you will need -//! to install additional tools. This can be done via [homebrew](https://brew.sh/) -//! with the following command: -//! -//! ```sh -//! brew install make openssl grep -//! ``` -//! -//! Additionally, you may need to set up LLVM and clang. Typically, this is done -//! as follows: -//! -//! ```sh -//! # make sure xcode tools are installed -//! xcode-select --install -//! # instal llvm -//! brew install --with-toolchain llvm -//! ``` -#![warn(missing_docs)] -#![no_std] -#[cfg(feature = "alloc")] -extern crate alloc; - -pub mod allocator; -#[cfg(feature = "async")] -pub mod async_; -pub mod collections; - -/// The core module. -/// -/// This module provides fundamental utilities needed to interface with many NGINX primitives. -/// String conversions, the pool (memory interface) object, and buffer APIs are covered here. These -/// utilities will generally align with the NGINX 'core' files and APIs. -pub mod core; - -/// The ffi module. -/// -/// This module provides scoped FFI bindings for NGINX symbols. -pub mod ffi; - -/// The http module. -/// -/// This modules provides wrappers and utilities to NGINX http APIs, such as requests, -/// configuration access, and statuses. -#[cfg(ngx_feature = "http")] -pub mod http; - -/// The log module. -/// -/// This module provides an interface into the NGINX logger framework. -pub mod log; - -pub mod sync; - -/// Define modules exported by this library. -/// -/// These are normally generated by the Nginx module system, but need to be -/// defined when building modules outside of it. -#[macro_export] -macro_rules! ngx_modules { - ($( $mod:ident ),+) => { - #[unsafe(no_mangle)] - #[allow(non_upper_case_globals)] - pub static mut ngx_modules: [*const $crate::ffi::ngx_module_t; $crate::count!($( $mod, )+) + 1] = [ - $( unsafe { &$mod } as *const $crate::ffi::ngx_module_t, )+ - ::core::ptr::null() - ]; - - #[unsafe(no_mangle)] - #[allow(non_upper_case_globals)] - pub static mut ngx_module_names: [*const ::core::ffi::c_char; $crate::count!($( $mod, )+) + 1] = [ - $( concat!(stringify!($mod), "\0").as_ptr() as *const ::core::ffi::c_char, )+ - ::core::ptr::null() - ]; - - #[unsafe(no_mangle)] - #[allow(non_upper_case_globals)] - pub static mut ngx_module_order: [*const ::core::ffi::c_char; 1] = [ - ::core::ptr::null() - ]; - }; -} - -/// Count number of arguments -#[macro_export] -macro_rules! count { - () => { 0usize }; - ($x:tt, $( $xs:tt ),*) => { 1usize + $crate::count!($( $xs, )*) }; -} diff --git a/source/rust/vendor/ngx-rust/src/log.rs b/source/rust/vendor/ngx-rust/src/log.rs deleted file mode 100644 index e461d6b..0000000 --- a/source/rust/vendor/ngx-rust/src/log.rs +++ /dev/null @@ -1,342 +0,0 @@ -use core::cmp; -use core::fmt::{self, Write}; -use core::mem::MaybeUninit; -use core::ptr::NonNull; - -use crate::ffi::{self, NGX_MAX_ERROR_STR, ngx_err_t, ngx_log_t, ngx_uint_t}; - -/// This constant is set to `true` if NGINX is compiled with debug logging (`--with-debug`). -pub const DEBUG: bool = cfg!(ngx_feature = "debug"); - -/// Size of the static buffer used to format log messages. -/// -/// Approximates the remaining space in `u_char[NGX_MAX_ERROR_STR]` after writing the standard -/// prefix -pub const LOG_BUFFER_SIZE: usize = - NGX_MAX_ERROR_STR as usize - b"1970/01/01 00:00:00 [info] 1#1: ".len(); - -/// Obtains a pointer to the global (cycle) log object. -/// -/// The returned pointer is tied to the current cycle lifetime, and will be invalidated by a -/// configuration reload in the master process or in a single-process mode. If you plan to store it, -/// make sure that your storage is also tied to the cycle lifetime (e.g. module configuration or -/// connection/request data). -/// -/// The function may panic if you call it before the main() in nginx creates an initial cycle. -#[inline(always)] -pub fn ngx_cycle_log() -> NonNull { - NonNull::new(unsafe { (*nginx_sys::ngx_cycle).log }).expect("global logger") -} - -/// Utility function to provide typed checking of the mask's field state. -#[inline(always)] -pub fn check_mask(mask: DebugMask, log_level: usize) -> bool { - let mask_bits: u32 = mask.into(); - if log_level & mask_bits as usize == 0 { - return false; - } - true -} - -/// Format args into a provided buffer -// May produce incomplete UTF-8 sequences. But any writes to `ngx_log_t` already can be truncated, -// so nothing we can do here. -#[inline] -pub fn write_fmt<'a>(buf: &'a mut [MaybeUninit], args: fmt::Arguments<'_>) -> &'a [u8] { - if let Some(str) = args.as_str() { - str.as_bytes() - } else { - let mut buf = LogBuf::from(buf); - // nothing we can or want to do on errors - let _ = buf.write_fmt(args); - buf.filled() - } -} - -/// Writes the provided buffer to the nginx logger at a specified level. -/// -/// # Safety -/// Requires a valid log pointer. -#[inline] -pub unsafe fn log_error(level: ngx_uint_t, log: *mut ngx_log_t, err: ngx_err_t, buf: &[u8]) { - unsafe { - #[cfg(ngx_feature = "have_variadic_macros")] - ffi::ngx_log_error_core(level, log, err, c"%*s".as_ptr(), buf.len(), buf.as_ptr()); - #[cfg(not(ngx_feature = "have_variadic_macros"))] - ffi::ngx_log_error(level, log, err, c"%*s".as_ptr(), buf.len(), buf.as_ptr()); - } -} - -/// Writes the provided buffer to the nginx logger at the debug level. -/// -/// # Safety -/// Requires a valid log pointer. -#[inline] -pub unsafe fn log_debug(log: *mut ngx_log_t, err: ngx_err_t, buf: &[u8]) { - unsafe { - #[cfg(ngx_feature = "have_variadic_macros")] - ffi::ngx_log_error_core( - ffi::NGX_LOG_DEBUG as _, - log, - err, - c"%*s".as_ptr(), - buf.len(), - buf.as_ptr(), - ); - #[cfg(not(ngx_feature = "have_variadic_macros"))] - ffi::ngx_log_debug_core(log, err, c"%*s".as_ptr(), buf.len(), buf.as_ptr()); - } -} - -/// Write to logger at a specified level. -/// -/// See [Logging](https://nginx.org/en/docs/dev/development_guide.html#logging) -/// for available log levels. -#[macro_export] -macro_rules! ngx_log_error { - ( $level:expr, $log:expr, $($arg:tt)+ ) => { - let log = $log; - let level = $level as $crate::ffi::ngx_uint_t; - if level <= unsafe { (*log).log_level } { - let mut buf = - [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; - let message = $crate::log::write_fmt(&mut buf, format_args!($($arg)+)); - unsafe { $crate::log::log_error(level, log, 0, message) }; - } - } -} - -/// Write to logger with the context of currently processed configuration file. -#[macro_export] -macro_rules! ngx_conf_log_error { - ( $level:expr, $cf:expr, $($arg:tt)+ ) => { - let cf: *mut $crate::ffi::ngx_conf_t = $cf; - let level = $level as $crate::ffi::ngx_uint_t; - if level <= unsafe { (*(*cf).log).log_level } { - let mut buf = - [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; - let message = $crate::log::write_fmt(&mut buf, format_args!($($arg)+)); - unsafe { - $crate::ffi::ngx_conf_log_error( - level, - cf, - 0, - c"%*s".as_ptr(), - message.len(), - message.as_ptr() - ); - } - } - } -} - -/// Write to logger at debug level. -#[macro_export] -macro_rules! ngx_log_debug { - ( mask: $mask:expr, $log:expr, $($arg:tt)+ ) => { - let log = $log; - if $crate::log::DEBUG && $crate::log::check_mask($mask, unsafe { (*log).log_level }) { - let mut buf = - [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; - let message = $crate::log::write_fmt(&mut buf, format_args!($($arg)+)); - unsafe { $crate::log::log_debug(log, 0, message) }; - } - }; - ( $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::All, $log, $($arg)+); - } -} - -/// Log to request connection log at level [`NGX_LOG_DEBUG_HTTP`]. -/// -/// [`NGX_LOG_DEBUG_HTTP`]: https://nginx.org/en/docs/dev/development_guide.html#logging -#[macro_export] -macro_rules! ngx_log_debug_http { - ( $request:expr, $($arg:tt)+ ) => { - let log = unsafe { (*$request.connection()).log }; - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Http, log, $($arg)+); - } -} - -/// Log with requested debug mask. -/// -/// **NOTE:** This macro supports [`DebugMask::Http`] (`NGX_LOG_DEBUG_HTTP`), however, if you have -/// access to a Request object via an http handler it can be more convenient and readable to use -/// the [`ngx_log_debug_http`] macro instead. -/// -/// See for details and available -/// masks. -#[macro_export] -macro_rules! ngx_log_debug_mask { - ( DebugMask::Core, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Core, $log, $($arg)+); - }; - ( DebugMask::Alloc, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Alloc, $log, $($arg)+); - }; - ( DebugMask::Mutex, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Mutex, $log, $($arg)+); - }; - ( DebugMask::Event, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Event, $log, $($arg)+); - }; - ( DebugMask::Http, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Http, $log, $($arg)+); - }; - ( DebugMask::Mail, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Mail, $log, $($arg)+); - }; - ( DebugMask::Stream, $log:expr, $($arg:tt)+ ) => { - $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Stream, $log, $($arg)+); - }; -} - -/// Debug masks for use with [`ngx_log_debug_mask`], these represent the only accepted values for -/// the mask. -#[derive(Debug)] -pub enum DebugMask { - /// Aligns to the NGX_LOG_DEBUG_CORE mask. - Core, - /// Aligns to the NGX_LOG_DEBUG_ALLOC mask. - Alloc, - /// Aligns to the NGX_LOG_DEBUG_MUTEX mask. - Mutex, - /// Aligns to the NGX_LOG_DEBUG_EVENT mask. - Event, - /// Aligns to the NGX_LOG_DEBUG_HTTP mask. - Http, - /// Aligns to the NGX_LOG_DEBUG_MAIL mask. - Mail, - /// Aligns to the NGX_LOG_DEBUG_STREAM mask. - Stream, - /// Aligns to the NGX_LOG_DEBUG_ALL mask. - All, -} - -impl TryFrom for DebugMask { - type Error = u32; - - fn try_from(value: u32) -> Result { - match value { - crate::ffi::NGX_LOG_DEBUG_CORE => Ok(DebugMask::Core), - crate::ffi::NGX_LOG_DEBUG_ALLOC => Ok(DebugMask::Alloc), - crate::ffi::NGX_LOG_DEBUG_MUTEX => Ok(DebugMask::Mutex), - crate::ffi::NGX_LOG_DEBUG_EVENT => Ok(DebugMask::Event), - crate::ffi::NGX_LOG_DEBUG_HTTP => Ok(DebugMask::Http), - crate::ffi::NGX_LOG_DEBUG_MAIL => Ok(DebugMask::Mail), - crate::ffi::NGX_LOG_DEBUG_STREAM => Ok(DebugMask::Stream), - crate::ffi::NGX_LOG_DEBUG_ALL => Ok(DebugMask::All), - _ => Err(0), - } - } -} - -impl From for u32 { - fn from(value: DebugMask) -> Self { - match value { - DebugMask::Core => crate::ffi::NGX_LOG_DEBUG_CORE, - DebugMask::Alloc => crate::ffi::NGX_LOG_DEBUG_ALLOC, - DebugMask::Mutex => crate::ffi::NGX_LOG_DEBUG_MUTEX, - DebugMask::Event => crate::ffi::NGX_LOG_DEBUG_EVENT, - DebugMask::Http => crate::ffi::NGX_LOG_DEBUG_HTTP, - DebugMask::Mail => crate::ffi::NGX_LOG_DEBUG_MAIL, - DebugMask::Stream => crate::ffi::NGX_LOG_DEBUG_STREAM, - DebugMask::All => crate::ffi::NGX_LOG_DEBUG_ALL, - } - } -} - -/// Minimal subset of unstable core::io::{BorrowedBuf,BorrowedCursor} -struct LogBuf<'data> { - buf: &'data mut [MaybeUninit], - filled: usize, -} - -impl<'data> LogBuf<'data> { - pub fn filled(&self) -> &'data [u8] { - // SAFETY: valid bytes have been written to self.buf[..self.filled] - unsafe { - let buf = self.buf.get_unchecked(..self.filled); - // inlined MaybeUninit::slice_assume_init_ref - &*(buf as *const [MaybeUninit] as *const [u8]) - } - } - - pub fn append(&mut self, buf: &[u8]) -> &mut Self { - let n = cmp::min(self.buf.len() - self.filled, buf.len()); - unsafe { - // SAFETY: The source buf has at least n bytes - let src = buf.get_unchecked(..n); - // SAFETY: &[u8] and &[MaybeUninit] have the same layout - let src: &[MaybeUninit] = core::mem::transmute(src); - // SAFETY: self.buf has at least n bytes available after self.filled - self.buf.get_unchecked_mut(self.filled..self.filled + n).copy_from_slice(src); - } - self.filled += n; - self - } -} - -impl<'data> From<&'data mut [MaybeUninit]> for LogBuf<'data> { - fn from(buf: &'data mut [MaybeUninit]) -> Self { - Self { buf, filled: 0 } - } -} - -impl fmt::Write for LogBuf<'_> { - fn write_str(&mut self, s: &str) -> fmt::Result { - self.append(s.as_bytes()); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - - use super::*; - - #[test] - fn test_mask_lower_bound() { - assert!(>::into(DebugMask::Core) == crate::ffi::NGX_LOG_DEBUG_FIRST); - } - #[test] - fn test_mask_upper_bound() { - assert!( - >::into(DebugMask::Stream) == crate::ffi::NGX_LOG_DEBUG_LAST - ); - } - #[test] - fn test_check_mask() { - struct MockLog { - log_level: usize, - } - let mock = MockLog { log_level: 16 }; - - let mut r = check_mask(DebugMask::Core, mock.log_level); - assert!(r); - - r = check_mask(DebugMask::Alloc, mock.log_level); - assert!(!r); - } - - #[test] - fn log_buffer() { - use core::str; - - let mut buf = [const { MaybeUninit::::uninit() }; 32]; - let mut buf = LogBuf::from(&mut buf[..]); - let words = ["Hello", "World"]; - - // normal write - write!(&mut buf, "{} {}!", words[0], words[1]).unwrap(); - assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World!")); - - // overflow results in truncated output - write!(&mut buf, " This is a test, {}", u64::MAX).unwrap(); - assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World! This is a test, 184")); - - // and any following writes are still safe - write!(&mut buf, "test").unwrap(); - assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World! This is a test, 184")); - } -} diff --git a/source/rust/vendor/ngx-rust/src/sync.rs b/source/rust/vendor/ngx-rust/src/sync.rs deleted file mode 100644 index 258357c..0000000 --- a/source/rust/vendor/ngx-rust/src/sync.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Synchronization primitives over shared memory. -//! -//! This module provides an alternative implementation for the `ngx_atomic_t` type, -//! `ngx_atomic_*`/`ngx_rwlock_*` family of functions and related usage patterns from nginx. -//! -//! `` contains a wide variety of implementation variants for different platforms and -//! build configurations. It's not feasible to properly expose all of these to the Rust code, and we -//! are not going to. The implementation here uses similar logic on the foundation of the -//! [core::sync::atomic] types and is intentionally _not interoperable_ with the nginx atomics. -//! Thus, it's only suitable for use for new shared memory structures instead of, for example, -//! interacting with the upstream zones. -//! -//! One potential pitfall here is that atomics in Rust are specified in terms of threads, and we use -//! the types in this module for interprocess synchronization. This should not be an issue though, -//! as Rust refers to the C/C++11 memory model for atomics, and there's a following note in -//! [atomics.lockfree]: -//! -//! > [Note: Operations that are lock-free should also be address-free. That is, atomic operations -//! > on the same memory location via two different addresses will communicate atomically. The -//! > implementation should not depend on any per-process state. This restriction enables -//! > communication via memory that is mapped into a process more than once and by memory that is -//! > shared between two processes. — end note] -//! -//! In practice, this recommendation is applied in all the implementations that matter to us. -use core::sync::atomic::{self, Ordering}; - -use nginx_sys::ngx_sched_yield; - -const NGX_RWLOCK_SPIN: usize = 2048; -const NGX_RWLOCK_WLOCK: usize = usize::MAX; - -type NgxAtomic = atomic::AtomicUsize; - -/// Raw lock type. -pub struct RawSpinlock(NgxAtomic); - -/// Reader-writer lock over an atomic variable, based on the nginx rwlock implementation. -pub type RwLock = lock_api::RwLock; - -/// RAII structure used to release the shared read access of a lock when dropped. -pub type RwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, RawSpinlock, T>; - -/// RAII structure used to release the exclusive write access of a lock when dropped. -pub type RwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, RawSpinlock, T>; - -unsafe impl lock_api::RawRwLock for RawSpinlock { - // Only used for initialization, will not be mutated - #[allow(clippy::declare_interior_mutable_const)] - const INIT: RawSpinlock = RawSpinlock(NgxAtomic::new(0)); - - type GuardMarker = lock_api::GuardNoSend; - - fn lock_shared(&self) { - loop { - if self.try_lock_shared() { - return; - } - - if unsafe { nginx_sys::ngx_ncpu > 1 } { - for n in 0..NGX_RWLOCK_SPIN { - for _ in 0..n { - core::hint::spin_loop() - } - - if self.try_lock_shared() { - return; - } - } - } - - ngx_sched_yield() - } - } - - fn try_lock_shared(&self) -> bool { - let value = self.0.load(Ordering::Acquire); - - if value == NGX_RWLOCK_WLOCK { - return false; - } - - self.0.compare_exchange(value, value + 1, Ordering::Acquire, Ordering::Relaxed).is_ok() - } - - unsafe fn unlock_shared(&self) { - self.0.fetch_sub(1, Ordering::Release); - } - - fn lock_exclusive(&self) { - loop { - if self.try_lock_exclusive() { - return; - } - - if unsafe { nginx_sys::ngx_ncpu > 1 } { - for n in 0..NGX_RWLOCK_SPIN { - for _ in 0..n { - core::hint::spin_loop() - } - - if self.try_lock_exclusive() { - return; - } - } - } - - ngx_sched_yield() - } - } - - fn try_lock_exclusive(&self) -> bool { - self.0.compare_exchange(0, NGX_RWLOCK_WLOCK, Ordering::Acquire, Ordering::Relaxed).is_ok() - } - - unsafe fn unlock_exclusive(&self) { - self.0.store(0, Ordering::Release) - } -} diff --git a/source/rust/vendor/ngx-rust/tests/conditional-compilation.rs b/source/rust/vendor/ngx-rust/tests/conditional-compilation.rs deleted file mode 100644 index 156401d..0000000 --- a/source/rust/vendor/ngx-rust/tests/conditional-compilation.rs +++ /dev/null @@ -1,23 +0,0 @@ -use ngx::ffi; - -#[test] -fn test_os_symbols() { - #[cfg(ngx_os = "freebsd")] - assert_eq!(ffi::NGX_FREEBSD, 1); - - #[cfg(ngx_os = "linux")] - assert_eq!(ffi::NGX_LINUX, 1); - - #[cfg(ngx_os = "darwin")] - assert_eq!(ffi::NGX_DARWIN, 1); -} - -#[test] -fn test_feature_symbols() { - let ev: ffi::ngx_event_t = unsafe { core::mem::zeroed() }; - - assert_eq!(ev.available, 0); - - #[cfg(ngx_feature = "have_kqueue")] - assert_eq!(ev.kq_errno, 0); -} diff --git a/source/rust/vendor/ngx-rust/tests/config/nginx.conf b/source/rust/vendor/ngx-rust/tests/config/nginx.conf deleted file mode 100644 index 8889ed7..0000000 --- a/source/rust/vendor/ngx-rust/tests/config/nginx.conf +++ /dev/null @@ -1,43 +0,0 @@ -#load_module modules/ngx_http_rust_module.so; - -#user nobody; -worker_processes 1; - -error_log logs/error.log; -#error_log logs/error.log notice; -#error_log logs/error.log info; - -#pid logs/nginx.pid; - - -events { - worker_connections 1024; -} - - -http { - include mime.types; - default_type application/octet-stream; - - - # rust test; - - - - server { - listen 8080; - server_name localhost; - - #charset koi8-r; - - #access_log logs/host.access.log main; - - location / { - root html; - index index.html index.htm; - } - - - } - -} diff --git a/source/rust/vendor/ngx-rust/tests/log_test.rs b/source/rust/vendor/ngx-rust/tests/log_test.rs deleted file mode 100644 index 0610169..0000000 --- a/source/rust/vendor/ngx-rust/tests/log_test.rs +++ /dev/null @@ -1,148 +0,0 @@ -use std::env; -use std::fs; -use std::io; -use std::io::Result; -#[cfg(unix)] -use std::os::unix::ffi::OsStrExt; -use std::path::{Path, PathBuf}; -use std::process::Command; -use std::process::Output; - -const NGINX_BINARY_NAME: &str = "nginx"; - -/// Convert a CStr to a PathBuf -pub fn cstr_to_path(val: &core::ffi::CStr) -> Option { - if val.is_empty() { - return None; - } - - #[cfg(unix)] - let str = std::ffi::OsStr::from_bytes(val.to_bytes()); - #[cfg(not(unix))] - let str = std::str::from_utf8(val.to_bytes()).ok()?; - - Some(PathBuf::from(str)) -} - -/// Find nginx binary in the build directory -pub fn find_nginx_binary() -> io::Result { - let path = [ - // TEST_NGINX_BINARY is specified for tests - env::var("TEST_NGINX_BINARY").ok().map(PathBuf::from), - // The module is built against an external NGINX source tree - env::var("NGINX_BUILD_DIR").map(PathBuf::from).map(|x| x.join(NGINX_BINARY_NAME)).ok(), - env::var("NGINX_SOURCE_DIR") - .map(PathBuf::from) - .map(|x| x.join("objs").join(NGINX_BINARY_NAME)) - .ok(), - // Fallback to the build directory exposed by nginx-sys - option_env!("DEP_NGINX_BUILD_DIR").map(PathBuf::from).map(|x| x.join(NGINX_BINARY_NAME)), - ] - .into_iter() - .flatten() - .find(|x| x.is_file()) - .ok_or(io::ErrorKind::NotFound)?; - - Ok(path) -} - -/// harness to test nginx -pub struct Nginx { - pub prefix: tempfile::TempDir, - pub bin_path: PathBuf, - pub config_path: PathBuf, -} - -impl Default for Nginx { - /// create nginx with default - fn default() -> Nginx { - let binary = find_nginx_binary().expect("nginx binary"); - Nginx::new(binary).expect("test harness") - } -} - -impl Nginx { - pub fn new(binary: impl AsRef) -> io::Result { - let prefix = tempfile::tempdir()?; - let config = prefix.path().join("nginx.conf"); - - fs::create_dir(prefix.path().join("logs"))?; - - Ok(Nginx { prefix, bin_path: binary.as_ref().to_owned(), config_path: config }) - } - - /// start nginx process with arguments - pub fn cmd(&self, args: &[&str]) -> Result { - let prefix = self.prefix.path().to_string_lossy(); - let config_path = self.config_path.to_string_lossy(); - let args = [&["-p", &prefix, "-c", &config_path], args].concat(); - let result = Command::new(&self.bin_path).args(args).output(); - - match result { - Err(e) => Err(e), - - Ok(output) => { - println!("status: {}", output.status); - println!("stdout: {}", String::from_utf8_lossy(&output.stdout)); - println!("stderr: {}", String::from_utf8_lossy(&output.stderr)); - Ok(output) - } - } - } - - /// complete stop the nginx binary - pub fn stop(&mut self) -> Result { - self.cmd(&["-s", "stop"]) - } - - /// start the nginx binary - pub fn start(&mut self) -> Result { - self.cmd(&[]) - } - - // make sure we stop existing nginx and start new master process - // intentinally ignore failure in stop - pub fn restart(&mut self) -> Result { - let _ = self.stop(); - self.start() - } - - // replace config with another config - pub fn replace_config>(&mut self, from: P) -> Result { - println!("copying config from: {:?} to: {:?}", from.as_ref(), self.config_path); // replace with logging - fs::copy(from, &self.config_path) - } -} - -#[cfg(test)] -mod tests { - use std::env; - - use super::*; - - const TEST_NGINX_CONFIG: &str = "tests/nginx.conf"; - - #[test] - fn test() { - let mut nginx = Nginx::default(); - - let current_dir = env::current_dir().expect("Unable to get current directory"); - let test_config_path = current_dir.join(TEST_NGINX_CONFIG); - - assert!( - test_config_path.exists(), - "Config file not found: {}\nCurrent directory: {}", - test_config_path.to_string_lossy(), - current_dir.to_string_lossy() - ); - - nginx.replace_config(&test_config_path).unwrap_or_else(|_| { - panic!("Unable to load config file: {}", test_config_path.to_string_lossy()) - }); - let output = nginx.restart().expect("Unable to restart NGINX"); - assert!(output.status.success()); - - let output = nginx.stop().expect("Unable to stop NGINX"); - assert!(output.status.success()); - } -} diff --git a/source/rust/vendor/ngx-rust/tests/module/config b/source/rust/vendor/ngx-rust/tests/module/config deleted file mode 100644 index 88b592a..0000000 --- a/source/rust/vendor/ngx-rust/tests/module/config +++ /dev/null @@ -1,12 +0,0 @@ -ngx_addon_name=ngx_http_rust_module - -ngx_module_type=HTTP_FILTER -ngx_module_name=ngx_http_rust_module -ngx_module_srcs="$ngx_addon_dir/ngx_http_rust_module.c" -ngx_module_deps="cargo" -ngx_module_libs="$ngx_addon_dir/../target/debug/libngx_rust.a" - - -. auto/module - - diff --git a/source/rust/vendor/ngx-rust/tests/module/config.make b/source/rust/vendor/ngx-rust/tests/module/config.make deleted file mode 100644 index 23559e8..0000000 --- a/source/rust/vendor/ngx-rust/tests/module/config.make +++ /dev/null @@ -1,7 +0,0 @@ - -cat << END >> $NGX_MAKEFILE - -cargo: - cargo build --manifest-path $ngx_addon_dir/../Cargo.toml --lib - -END diff --git a/source/rust/vendor/ngx-rust/tests/module/ngx_http_rust_module.c b/source/rust/vendor/ngx-rust/tests/module/ngx_http_rust_module.c deleted file mode 100644 index 374a606..0000000 --- a/source/rust/vendor/ngx-rust/tests/module/ngx_http_rust_module.c +++ /dev/null @@ -1,92 +0,0 @@ -/** - * @file ngx_rust.c - * @author Sehyo Chang - * @date - * - * @brief Dummy module - * - * @section LICENSE - * - * Copyright (C) 2011 by Nginx - * - */ -#include -#include -#include - - -/** - * @brief element mixer configuration - */ -typedef struct { - ngx_str_t name; /**< test name */ -} ngx_http_rust_main_conf_t; - - - -static void *ngx_http_rust_create_main_conf(ngx_conf_t *cf); - - -/* - * dummy rust - */ -static ngx_command_t ngx_http_rust_commands[] = { - { - ngx_string("rust"), /* dummy directive */ - NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, // server takes 1 // - ngx_conf_set_str_slot, /* configuration setup function */ - NGX_HTTP_MAIN_CONF_OFFSET, - offsetof(ngx_http_rust_main_conf_t, name), - NULL - }, - ngx_null_command /* command termination */ -}; - - -/* The module context. */ -static ngx_http_module_t ngx_http_rust_module_ctx = { - NULL, /* preconfiguration */ - NULL, /* postconfiguration */ - ngx_http_rust_create_main_conf, /* create main configuration */ - NULL, /* init main configuration */ - - NULL, /* create server configuration */ - NULL, /* merge server configuration */ - - NULL, - NULL -}; - -/* Module definition. */ -ngx_module_t ngx_http_rust_module = { - NGX_MODULE_V1, - &ngx_http_rust_module_ctx, /* module context */ - ngx_http_rust_commands, /* module directives */ - NGX_HTTP_MODULE, /* module type */ - NULL, /* init master */ - NULL, /* init module */ - NULL, /* init process */ - NULL, /* init thread */ - NULL, /* exit thread */ - NULL, /* exit process */ - NULL, /* exit master */ - NGX_MODULE_V1_PADDING -}; - - - -static void *ngx_http_rust_create_main_conf(ngx_conf_t *cf) -{ - ngx_http_rust_main_conf_t *conf; - - ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "setting up main config"); - - - conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_rust_main_conf_t)); - if (conf == NULL) { - return NULL; - } - - - return conf; -} \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/tests/nginx.conf b/source/rust/vendor/ngx-rust/tests/nginx.conf deleted file mode 100644 index be3e9c9..0000000 --- a/source/rust/vendor/ngx-rust/tests/nginx.conf +++ /dev/null @@ -1,42 +0,0 @@ -#load_module modules/ngx_http_rust_module.so; - -#user nobody; -worker_processes 1; - -error_log logs/error.log; -#error_log logs/error.log notice; -#error_log logs/error.log info; - -#pid logs/nginx.pid; - - -events { - worker_connections 1024; -} - - -http { - default_type application/octet-stream; - - - # rust test; - - - - server { - listen 30000; - server_name localhost; - - #charset koi8-r; - - #access_log logs/host.access.log main; - - location / { - root html; - index index.html index.htm; - } - - - } - -} diff --git a/tests/domain-e2e.sh b/tests/domain-e2e.sh deleted file mode 100755 index 3f42f52..0000000 --- a/tests/domain-e2e.sh +++ /dev/null @@ -1,289 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================ -# 域名插件端到端验证(plugin-domain) -# -# 覆盖: -# - 鉴权:管理态要登录会话,账号态要 X-API-Key(未带 / 带错一律 401) -# - 管理员自助创建:自动生成 `i<8位数字>dm` 子域名,创建即放行 -# - 转发生效:Host=<子域名>.mayishangshu.cn 经 18094 转发到配置的后端 -# - 未知子域名 / 待审核 / 已删除 → 404(热路径不回源,不泄漏存在性) -# - 参数校验:保留名、非法字符、非法 backend(缺端口 / 端口越界) -# - 占用冲突:同子域名重复创建被拒 -# - 用户申请 → pending(无临时授权权限时不自动放行)→ 管理员审核放行 -# - 越权:不能删除别人的域名;不能重复审核同一条申请 -# - 删除后立刻停止转发(写穿共享内存,不靠重启) -# - purge 清理过期/陈旧记录 -# -# 前置:网关以 source/conf/nginx.test.conf 运行(见 scripts/run-local-e2e.sh) -# 依赖:curl、python3 -# -# 用法:bash tests/domain-e2e.sh [IDP_BASE] [DOMAIN_BASE] [DATA_DIR] -# ADMIN_USER / ADMIN_PASS 可覆盖(默认取 .env 的 ADMIN_USER / ADMIN_PASSWORD) -# ============================================================================ -set -u -# 口令等敏感值从项目根 .env 读(不进 git);已存在的环境变量优先。 -_ENV_HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -. "$_ENV_HERE/../scripts/load-env.sh" -unset _ENV_HERE - -BASE="${1:-http://127.0.0.1:18098}" -DOMAIN_BASE="${2:-http://127.0.0.1:18094}" -ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -DATA_DIR="${3:-$ROOT/source/data}" -ADMIN_USER="${ADMIN_USER:-admin}" -ADMIN_PASS="${ADMIN_PASS:-${ADMIN_PASSWORD:-123456}}" - -# 域名插件固定的企业域名 zone —— 必须与 crates/plugin-domain/src/keys.rs -# 的 ENTERPRISE_ZONE 一致,否则转发侧永远 404(改 keys.rs 时同步这里) -ZONE="mayishangshu.cn" -BACKEND="127.0.0.1:18093" - -PYTHON="${PYTHON:-python3}" - -JAR="$(mktemp -t sso_domain_cookies.XXXXXX.txt)" -trap 'rm -f "$JAR"' EXIT - -PASS=0; FAIL=0 -ok() { echo " ✅ $1"; PASS=$((PASS+1)); } -bad() { echo " ❌ $1"; FAIL=$((FAIL+1)); } -need() { command -v "$1" >/dev/null 2>&1 || { echo "缺少依赖: $1"; exit 2; }; } -need curl; need python3 - -echo "==> IdP: $BASE" -echo "==> domain: $DOMAIN_BASE (zone=$ZONE)" -echo "==> data: $DATA_DIR" - -jget() { printf '%s' "$1" | "$PYTHON" -c " -import sys,json -path=[k for k in sys.argv[1].split('.') if k] -try: d=json.loads(sys.stdin.read()) -except Exception: print(''); raise SystemExit -for k in path: - if isinstance(d,dict): d=d.get(k) - elif isinstance(d,list) and k.isdigit(): d=d[int(k)] if int(k) [JSON] - local m="$1" p="$2" b="${3:-}" - if [ -n "$b" ]; then - curl -s -b "$JAR" -X "$m" "$BASE$p" -H 'Content-Type: application/json' -d "$b" - else - curl -s -b "$JAR" -X "$m" "$BASE$p" - fi -} - -# 账号态请求(带 X-API-Key) -ureq() { # [JSON] - local m="$1" p="$2" b="${3:-}" - if [ -n "$b" ]; then - curl -s -X "$m" "$BASE$p" -H "X-API-Key: $ALICE_KEY" -H 'Content-Type: application/json' -d "$b" - else - curl -s -X "$m" "$BASE$p" -H "X-API-Key: $ALICE_KEY" - fi -} - -# ---- 转发侧断言 ------------------------------------------------------------ -# Host 以 .$ZONE 结尾才是本插件管辖;不结尾的请求插件直接放行(不归它管) -fwd_code() { # → HTTP 状态码 - curl -s -o /dev/null -w '%{http_code}' --max-time 5 \ - "$DOMAIN_BASE/" -H "Host: $1.$ZONE" -} -fwd_body() { # → 响应体 - curl -s --max-time 5 "$DOMAIN_BASE/" -H "Host: $1.$ZONE" -} -# 取某条记录(管理态列表里按 subdomain 找) -entry_id() { # → id - areq GET /api/admin/domains | "$PYTHON" -c " -import sys,json -d=json.load(sys.stdin).get('data',{}) -for e in d.get('items',[]): - if e['subdomain']==sys.argv[1]: print(e['id']); break -else: print('') -" "$1" -} -entry_field() { # - areq GET /api/admin/domains | "$PYTHON" -c " -import sys,json -d=json.load(sys.stdin).get('data',{}) -for e in d.get('items',[]): - if e['subdomain']==sys.argv[1]: - print(e.get(sys.argv[2],'')); break -else: print('__MISSING__') -" "$1" "$2" -} -# 清掉上一轮残留(域名是自动生成子域名的,不清理会越积越多) -cleanup_domains() { - areq GET /api/admin/domains | "$PYTHON" -c " -import sys,json -d=json.load(sys.stdin).get('data',{}) -for e in d.get('items',[]): print(e['id']) -" | while read -r id; do - [ -n "$id" ] && areq POST /api/admin/domains/delete "{\"id\":\"$id\"}" > /dev/null - done -} - -# --------------------------------------------------------------------------- -echo "==> [0] 鉴权" -code="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/admin/domains")" -[ "$code" = "401" ] && ok "未登录访问管理态 → 401" || bad "未登录管理态应为 401,实际 $code" - -code="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/v1/domains")" -[ "$code" = "401" ] && ok "账号态缺 X-API-Key → 401" || bad "缺 Key 应为 401,实际 $code" - -code="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/v1/domains" -H 'X-API-Key: sk_deadbeef')" -[ "$code" = "401" ] && ok "账号态 Key 错误 → 401" || bad "错 Key 应为 401,实际 $code" - -# --------------------------------------------------------------------------- -echo "==> [1] 管理员登录" -LOGIN="$(curl -s -c "$JAR" -X POST "$BASE/api/admin/login" -H 'Content-Type: application/json' \ - -d "{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}")" -[ "$(jget "$LOGIN" code)" = "200" ] && ok "登录成功" || { bad "登录失败:$LOGIN"; exit 1; } - -echo "==> [1b] 清理上轮残留" -cleanup_domains -[ "$(areq GET /api/admin/domains | "$PYTHON" -c "import sys,json;print(len(json.load(sys.stdin)['data']['items']))")" = "0" ] \ - && ok "域名表已清空" || bad "域名表仍有残留" - -# alice 的 API Key(账号态接口的凭据;种子数据里就有) -ALICE_KEY="$("$PYTHON" -c " -import json,sys -print(json.load(open(sys.argv[1]))['alice']['api_key']) -" "$DATA_DIR/users.json")" -[ -n "$ALICE_KEY" ] && ok "取到 alice 的 API Key" || { bad "取不到 alice 的 API Key"; exit 1; } - -# --------------------------------------------------------------------------- -echo "==> [2] 管理员自助创建:自动生成子域名并直接放行" -R="$(areq POST /api/admin/domains/create "{\"backend\":\"$BACKEND\",\"type\":\"long\"}")" -[ "$(jget "$R" code)" = "200" ] && ok "创建成功:$(jget "$R" msg)" || { bad "创建失败:$R"; exit 1; } -SUB_AUTO="$(jget "$R" data.subdomain)" -echo "$SUB_AUTO" | grep -Eq '^i[0-9]{8}dm$' && ok "子域名形状 i<8位数字>dm(${SUB_AUTO})" || bad "子域名形状异常:$SUB_AUTO" -[ "$(jget "$R" data.host)" = "$SUB_AUTO.$ZONE" ] && ok "完整域名 = $SUB_AUTO.$ZONE" || bad "host 异常:$(jget "$R" data.host)" -[ "$(jget "$R" data.status)" = "approved" ] && ok "创建即 approved" || bad "状态异常:$(jget "$R" data.status)" - -code="$(fwd_code "$SUB_AUTO")" -[ "$code" = "200" ] && ok "转发生效:$SUB_AUTO.$ZONE → 200" || bad "转发应 200,实际 $code" -fwd_body "$SUB_AUTO" | grep -q '"backend":"18093"' && ok "确实打到了配置的后端(18093)" || bad "未打到后端:$(fwd_body "$SUB_AUTO")" - -# Host 带端口也应解析(插件剥离 :port) -code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$DOMAIN_BASE/" -H "Host: $SUB_AUTO.$ZONE:18094")" -[ "$code" = "200" ] && ok "Host 带端口仍可解析" || bad "Host 带端口应 200,实际 $code" - -# --------------------------------------------------------------------------- -echo "==> [3] 未放行的子域名 → 404(不回源,不泄漏存在性)" -code="$(fwd_code "i00000000dm")" -[ "$code" = "404" ] && ok "未知子域名 → 404" || bad "未知子域名应 404,实际 $code" -[ "$(fwd_body "i00000000dm")" != "NO_BACKEND" ] && ok "该 404 由插件发出(非转发层兜底)" || bad "该 404 来自转发层兜底,说明插件没拦住" - -# zone 外的 Host:上游语义下同样由插件 access 未命中直接 404(不 decline、 -# 不落转发层兜底)——与「未知子域名」行为一致,均不泄漏存在性。 -# conf 里的 error_page NO_BACKEND 兜底仅作为转发层最后的保险,正常不会触发。 -code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$DOMAIN_BASE/" -H "Host: other.example.com")" -body="$(curl -s --max-time 5 "$DOMAIN_BASE/" -H "Host: other.example.com")" -{ [ "${code}" = "404" ] && [ "${body}" != "NO_BACKEND" ]; } \ - && ok "zone 外的 Host → 插件直接 404(上游未命中语义)" || bad "zone 外 Host 处理异常:code=${code} body=${body}" - -# --------------------------------------------------------------------------- -echo "==> [4] 参数校验" -R="$(areq POST /api/admin/domains/create "{\"subdomain\":\"www\",\"backend\":\"$BACKEND\"}")" -[ "$(jget "$R" code)" != "200" ] && ok "保留名被拒:$(jget "$R" msg)" || bad "保留名应被拒" - -R="$(areq POST /api/admin/domains/create "{\"subdomain\":\"Bad_Name\",\"backend\":\"$BACKEND\"}")" -[ "$(jget "$R" code)" != "200" ] && ok "非法字符子域名被拒:$(jget "$R" msg)" || bad "非法子域名应被拒" - -R="$(areq POST /api/admin/domains/create '{"subdomain":"okname","backend":"127.0.0.1"}')" -[ "$(jget "$R" code)" != "200" ] && ok "backend 缺端口被拒:$(jget "$R" msg)" || bad "缺端口应被拒" - -R="$(areq POST /api/admin/domains/create '{"subdomain":"okname","backend":"127.0.0.1:99999"}')" -[ "$(jget "$R" code)" != "200" ] && ok "端口越界被拒:$(jget "$R" msg)" || bad "端口越界应被拒" - -R="$(areq POST /api/admin/domains/create '{"subdomain":"okname","backend":"127.0.0.1:18093","owner":"no-such-user"}')" -[ "$(jget "$R" code)" != "200" ] && ok "归属账号不存在被拒:$(jget "$R" msg)" || bad "未知归属账号应被拒" - -# --------------------------------------------------------------------------- -echo "==> [5] 占用冲突" -R="$(areq POST /api/admin/domains/create "{\"subdomain\":\"$SUB_AUTO\",\"backend\":\"$BACKEND\"}")" -[ "$(jget "$R" code)" != "200" ] && ok "同子域名重复创建被拒:$(jget "$R" msg)" || bad "占用冲突应被拒" - -# --------------------------------------------------------------------------- -echo "==> [6] 账号态申请:无临时授权权限 → pending,且暂不转发" -SUB_USER="u$(date +%s | tail -c 7)dm" -R="$(ureq POST /api/v1/domains/apply "{\"subdomain\":\"$SUB_USER\",\"backend\":\"$BACKEND\",\"type\":\"temp\"}")" -[ "$(jget "$R" code)" = "200" ] && ok "申请已受理:$(jget "$R" msg)" || { bad "申请失败:$R"; exit 1; } -[ "$(jget "$R" data.status)" = "pending" ] && ok "无临时授权权限 → pending(不自动放行)" || bad "状态应为 pending:$(jget "$R" data.status)" -ID_USER="$(jget "$R" data.id)" - -code="$(fwd_code "$SUB_USER")" -[ "$code" = "404" ] && ok "待审核期间不转发 → 404" || bad "待审核应 404,实际 $code" - -# --------------------------------------------------------------------------- -echo "==> [7] 账号态可见性:只看得到自己的" -R="$(ureq GET /api/v1/domains)" -echo "$R" | grep -q "$SUB_USER" && ok "自己的域名在列表里" || bad "自己的域名不在列表:$R" -echo "$R" | grep -q "$SUB_AUTO" && bad "看到了别人的域名(${SUB_AUTO})" || ok "看不到别人的域名(隔离正确)" - -# --------------------------------------------------------------------------- -echo "==> [8] 越权:不能删别人的" -R="$(ureq POST /api/v1/domains/delete "{\"id\":\"$(entry_id "$SUB_AUTO")\"}")" -[ "$(jget "$R" code)" != "200" ] && ok "删除他人域名被拒:$(jget "$R" msg)" || bad "越权删除应被拒" -[ "$(fwd_code "$SUB_AUTO")" = "200" ] && ok "被拒后他人域名仍可用" || bad "被拒后他人域名被误删" - -# --------------------------------------------------------------------------- -echo "==> [9] 管理员审核放行" -R="$(areq POST /api/admin/domains/review "{\"id\":\"$ID_USER\",\"action\":\"approve\"}")" -[ "$(jget "$R" code)" = "200" ] && ok "审核通过:$(jget "$R" msg)" || bad "审核失败:$R" -[ "$(jget "$R" data.status)" = "approved" ] && ok "状态变为 approved" || bad "状态异常:$(jget "$R" data.status)" -[ "$(jget "$R" data.expires_left)" != "0" ] && ok "临时域名带剩余有效期($(jget "$R" data.expires_left_text))" || bad "临时域名未设有效期" - -code="$(fwd_code "$SUB_USER")" -[ "$code" = "200" ] && ok "审核通过后立刻可转发(写穿共享内存)" || bad "通过后应 200,实际 $code" - -# --------------------------------------------------------------------------- -echo "==> [10] 重复审核被拒" -R="$(areq POST /api/admin/domains/review "{\"id\":\"$ID_USER\",\"action\":\"approve\"}")" -[ "$(jget "$R" code)" != "200" ] && ok "重复审核被拒:$(jget "$R" msg)" || bad "重复审核应被拒" - -R="$(areq POST /api/admin/domains/review "{\"id\":\"$ID_USER\",\"action\":\"maybe\"}")" -[ "$(jget "$R" code)" != "200" ] && ok "非法 action 被拒:$(jget "$R" msg)" || bad "非法 action 应被拒" - -# --------------------------------------------------------------------------- -echo "==> [11] 审核驳回 → 不转发" -SUB_REJ="r$(date +%s | tail -c 7)dm" -R="$(ureq POST /api/v1/domains/apply "{\"subdomain\":\"$SUB_REJ\",\"backend\":\"$BACKEND\",\"type\":\"long\"}")" -ID_REJ="$(jget "$R" data.id)" -R="$(areq POST /api/admin/domains/review "{\"id\":\"$ID_REJ\",\"action\":\"reject\"}")" -[ "$(jget "$R" code)" = "200" ] && ok "已驳回" || bad "驳回失败:$R" -[ "$(fwd_code "$SUB_REJ")" = "404" ] && ok "驳回后不转发 → 404" || bad "驳回后不应转发" - -# --------------------------------------------------------------------------- -echo "==> [12] 用户删除自己的域名 → 立刻停止转发" -R="$(ureq POST /api/v1/domains/delete "{\"id\":\"$ID_USER\"}")" -[ "$(jget "$R" code)" = "200" ] && ok "已删除:$(jget "$R" msg)" || bad "删除失败:$R" -[ "$(fwd_code "$SUB_USER")" = "404" ] && ok "删除后立刻 404(共享内存同步失效)" || bad "删除后仍在转发" - -# --------------------------------------------------------------------------- -echo "==> [13] 管理员删除任意域名" -R="$(areq POST /api/admin/domains/delete "{\"id\":\"$(entry_id "$SUB_AUTO")\"}")" -[ "$(jget "$R" code)" = "200" ] && ok "管理员删除成功" || bad "管理员删除失败:$R" -[ "$(fwd_code "$SUB_AUTO")" = "404" ] && ok "删除后立刻 404" || bad "删除后仍在转发" - -# --------------------------------------------------------------------------- -echo "==> [14] purge 清理" -R="$(areq POST /api/admin/purge)" -[ "$(jget "$R" code)" = "200" ] && ok "purge 可用:$(jget "$R" msg)" || bad "purge 失败:$R" -# 被驳回且未过保留期的记录不应被清掉(保留期 7 天) -[ "$(entry_field "$SUB_REJ" status)" = "rejected" ] && ok "保留期内驳回记录未被误清" || bad "驳回记录被误清" - -# --------------------------------------------------------------------------- -echo "==> [15] 收尾清理" -cleanup_domains -[ "$(areq GET /api/admin/domains | "$PYTHON" -c "import sys,json;print(len(json.load(sys.stdin)['data']['items']))")" = "0" ] \ - && ok "域名表已清空" || bad "收尾清理失败" - -echo -echo "==> 域名插件 e2e:PASS=$PASS FAIL=$FAIL" -[ "$FAIL" = "0" ] || exit 1 -exit 0