├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── Makefile ├── README.md ├── build.rs ├── src ├── bindings.rs ├── helpers.rs ├── lib.rs └── log.rs └── wrapper.h /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | 3 | language: rust 4 | 5 | rust: 6 | - stable 7 | 8 | os: 9 | - linux 10 | 11 | before_install: 12 | - sudo apt-get update 13 | - sudo apt-get install -y -qq clang 14 | 15 | script: 16 | - RUSTFLAGS=-Awarnings cargo build -j`nproc` 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "nginx" 3 | version = "0.15.0" 4 | authors = ["Navid "] 5 | license = "MIT/Apache-2.0" 6 | readme = "README.md" 7 | keywords = ["nginx"] 8 | repository = "https://github.com/arvancloud/nginx-rs" 9 | homepage = "https://github.com/arvancloud/nginx-rs" 10 | documentation = "https://arvancloud.github.io/nginx-rs" 11 | description = "Rust bindings for NGINX API" 12 | categories = ["api-bindings", "external-ffi-bindings"] 13 | 14 | [lib] 15 | crate-type = ["staticlib", "rlib"] 16 | 17 | [badges] 18 | travis-ci = { repository = "arvancloud/nginx-rs" } 19 | 20 | [build-dependencies] 21 | bindgen = "0.59" 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 ArvanCloud 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | NGX_OPTS = \ 2 | --with-compat --with-threads --with-http_addition_module --with-http_v2_module \ 3 | --with-http_auth_request_module --with-http_gunzip_module --with-http_gzip_static_module \ 4 | --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module \ 5 | --with-http_slice_module --with-http_stub_status_module --with-http_sub_module \ 6 | --with-stream --with-stream_realip_module --with-stream_ssl_preread_module \ 7 | --with-file-aio --with-http_ssl_module --with-stream_ssl_module \ 8 | --with-cc-opt='-g -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fPIC' \ 9 | --with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -pie' 10 | 11 | prepare-nginx: 12 | curl -o $(OUT_DIR)/nginx.tar.gz http://nginx.org/download/nginx-$(NGINX_VERSION).tar.gz 13 | mkdir -p $(OUT_DIR)/nginx 14 | tar -C $(OUT_DIR)/nginx -xzf $(OUT_DIR)/nginx.tar.gz --strip-components 1 15 | rm $(OUT_DIR)/nginx.tar.gz 16 | cd $(OUT_DIR)/nginx && ./configure $(NGX_OPTS) 17 | 18 | prepare-nginx-local: 19 | cd $(NGINX_PATH) && auto/configure $(NGX_OPTS) 20 | 21 | doc: 22 | rm -rf target/doc 23 | RUSTFLAGS=-Awarnings cargo doc --no-deps --quiet -j`nproc` 24 | echo "" > target/doc/index.html 25 | 26 | publish-doc: doc 27 | ghp-import -n target/doc 28 | git push -fq https://${GITHUB_TOKEN}@github.com/arvancloud/nginx-rs.git gh-pages 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nginx-rs 2 | 3 | [![crates.io](https://img.shields.io/crates/v/nginx.svg)](https://crates.io/crates/nginx) [![Documentation](https://img.shields.io/badge/Docs-nginx-blue.svg)](https://arvancloud.github.io/nginx-rs) [![Build Status](https://travis-ci.org/arvancloud/nginx-rs.svg?branch=master)](https://travis-ci.org/arvancloud/nginx-rs) ![Crates.io](https://img.shields.io/crates/l/rustc-serialize.svg) ![Nginx](https://img.shields.io/badge/nginx-1.19.3-orange.svg) 4 | 5 | This crate provides [nginx](https://nginx.org/) bindings for Rust. Currently, only Linux is supported. 6 | 7 | ## How to Use 8 | 9 | 1. Add `nginx` crate to Cargo.toml 10 | 11 | ```toml 12 | [dependencies] 13 | nginx = { git = "https://github.com/arvancloud/nginx-rs.git", tag = "0.15.0" } 14 | ``` 15 | 16 | **Note:** In order to build the crate, `clang` must be installed. 17 | 18 | ## Environment Variables 19 | 20 | - `NGINX_VERSION` Determines the version of nginx, if it is not set, the default version is used. 21 | - `NGINX_PATH` Determines the local absolute path of pre-cloned nginx, if it is not set, nginx is downloaded. 22 | 23 | Some code were copied (and refactored) from [nginxinc/ngx-rust](https://github.com/nginxinc/ngx-rust). 24 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | extern crate bindgen; 2 | 3 | use std::env; 4 | use std::io::Result; 5 | use std::path::{Path, PathBuf}; 6 | use std::process::Command; 7 | 8 | const NGINX_VERSION: &'static str = "1.19.3"; 9 | 10 | fn run_make(rule: &str, cwd: &Path, local_nginx_path: &str) -> Result { 11 | let output = Command::new("make") 12 | .arg(rule) 13 | .env("OUT_DIR", env::var("OUT_DIR").unwrap()) 14 | .env( 15 | "NGINX_VERSION", 16 | env::var("NGINX_VERSION").unwrap_or(NGINX_VERSION.to_string()), 17 | ) 18 | .env("NGINX_PATH", local_nginx_path) 19 | .current_dir(cwd) 20 | .output()?; 21 | Ok(output.status.success()) 22 | } 23 | 24 | fn main() { 25 | println!("cargo:rerun-if-env-changed=NGINX_VERSION"); 26 | println!("cargo:rerun-if-env-changed=NGINX_PATH"); 27 | 28 | let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); 29 | 30 | let cwd = env::current_dir().unwrap(); 31 | let local_nginx_path = env::var("NGINX_PATH").unwrap_or_default(); 32 | 33 | run_make( 34 | if local_nginx_path.is_empty() { 35 | "prepare-nginx" 36 | } else { 37 | "prepare-nginx-local" 38 | }, 39 | cwd.as_path(), 40 | local_nginx_path.as_str(), 41 | ) 42 | .map_err(|e| e.to_string()) 43 | .and_then(|success| { 44 | if success { 45 | Ok(()) 46 | } else { 47 | Err(String::from( 48 | "preparing nginx exited with non-zero status code", 49 | )) 50 | } 51 | }) 52 | .expect("unable to prepare nginx"); 53 | 54 | let nginx_dir_path = out_path.join("nginx"); 55 | let nginx_dir = if local_nginx_path.is_empty() { 56 | nginx_dir_path.to_str().unwrap() 57 | } else { 58 | local_nginx_path.as_str() 59 | }; 60 | 61 | let bindings = bindgen::Builder::default() 62 | .header("wrapper.h") 63 | .layout_tests(false) 64 | .blacklist_item("IPPORT_RESERVED") 65 | .clang_args(vec![ 66 | format!("-I{}/src/core", nginx_dir), 67 | format!("-I{}/src/event", nginx_dir), 68 | format!("-I{}/src/event/modules", nginx_dir), 69 | format!("-I{}/src/os/unix", nginx_dir), 70 | format!("-I{}/objs", nginx_dir), 71 | format!("-I{}/src/http", nginx_dir), 72 | format!("-I{}/src/http/v2", nginx_dir), 73 | format!("-I{}/src/http/modules", nginx_dir), 74 | ]) 75 | .generate() 76 | .expect("Unable to generate bindings"); 77 | 78 | bindings 79 | .write_to_file(out_path.join("bindings.rs")) 80 | .expect("unable to write bindings"); 81 | } 82 | -------------------------------------------------------------------------------- /src/bindings.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_upper_case_globals)] 2 | #![allow(non_camel_case_types)] 3 | #![allow(non_snake_case)] 4 | #![allow(dead_code)] 5 | 6 | include!(concat!(env!("OUT_DIR"), "/bindings.rs")); 7 | 8 | pub const NGX_READ_EVENT: EPOLL_EVENTS = (EPOLL_EVENTS_EPOLLIN | EPOLL_EVENTS_EPOLLRDHUP); 9 | pub const NGX_WRITE_EVENT: EPOLL_EVENTS = EPOLL_EVENTS_EPOLLOUT; 10 | pub const NGX_CLEAR_EVENT: EPOLL_EVENTS = EPOLL_EVENTS_EPOLLET; 11 | 12 | pub fn ngx_add_event(ev: *mut ngx_event_t, event: ngx_int_t, flags: ngx_uint_t) -> ngx_int_t { 13 | unsafe { ngx_event_actions.add.unwrap()(ev, event, flags) } 14 | } 15 | 16 | pub fn ngx_del_event(ev: *mut ngx_event_t, event: ngx_int_t, flags: ngx_uint_t) -> ngx_int_t { 17 | unsafe { ngx_event_actions.del.unwrap()(ev, event, flags) } 18 | } 19 | 20 | #[inline] 21 | pub fn ngx_event_del_timer(ev: *mut ngx_event_t) { 22 | unsafe { 23 | ngx_rbtree_delete(&mut ngx_event_timer_rbtree, &mut (*ev).timer); 24 | (*ev).set_timer_set(0); 25 | } 26 | } 27 | 28 | #[inline] 29 | pub fn ngx_event_add_timer(ev: *mut ngx_event_t, timer: ngx_msec_t) { 30 | let key: ngx_msec_t = unsafe { ngx_current_msec } + timer; 31 | 32 | if unsafe { *ev }.timer_set() != 0 { 33 | /* 34 | * Use a previous timer value if difference between it and a new 35 | * value is less than NGX_TIMER_LAZY_DELAY milliseconds: this allows 36 | * to minimize the rbtree operations for fast connections. 37 | */ 38 | 39 | let diff: ngx_msec_int_t = { key - unsafe { *ev }.timer.key } as _; 40 | 41 | if diff.abs() < NGX_TIMER_LAZY_DELAY as _ { 42 | return; 43 | } 44 | 45 | ngx_event_del_timer(ev); 46 | } 47 | 48 | unsafe { 49 | (*ev).timer.key = key; 50 | ngx_rbtree_insert(&mut ngx_event_timer_rbtree, &mut (*ev).timer); 51 | (*ev).set_timer_set(1); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/helpers.rs: -------------------------------------------------------------------------------- 1 | use bindings::{ 2 | ngx_array_t, ngx_http_headers_in_t, ngx_http_headers_out_t, ngx_list_part_t, ngx_list_push, 3 | ngx_list_t, ngx_palloc, ngx_pool_t, ngx_str_t, ngx_table_elt_t, u_char, 4 | }; 5 | use std::convert::{From, TryFrom}; 6 | use std::ffi::OsStr; 7 | use std::fmt; 8 | use std::ptr::copy_nonoverlapping; 9 | use std::{slice, str}; 10 | 11 | pub struct Header(ngx_table_elt_t); 12 | 13 | impl From for &[u8] { 14 | fn from(s: ngx_str_t) -> Self { 15 | if s.len == 0 || s.data.is_null() { 16 | return Default::default(); 17 | } 18 | unsafe { slice::from_raw_parts(s.data, s.len as usize) } 19 | } 20 | } 21 | 22 | #[cfg(any(unix, target_os = "redox"))] 23 | impl From for &OsStr { 24 | fn from(s: ngx_str_t) -> Self { 25 | std::os::unix::ffi::OsStrExt::from_bytes(s.into()) 26 | } 27 | } 28 | 29 | impl fmt::Display for ngx_str_t { 30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 31 | write!(f, "{}", String::from_utf8_lossy((*self).into())) 32 | } 33 | } 34 | 35 | impl TryFrom for &str { 36 | type Error = str::Utf8Error; 37 | 38 | fn try_from(s: ngx_str_t) -> Result { 39 | str::from_utf8(s.into()) 40 | } 41 | } 42 | 43 | impl TryFrom for String { 44 | type Error = std::string::FromUtf8Error; 45 | 46 | fn try_from(s: ngx_str_t) -> Result { 47 | let bytes: &[u8] = s.into(); 48 | String::from_utf8(bytes.into()) 49 | } 50 | } 51 | 52 | impl ngx_str_t { 53 | pub fn from_string(pool: *mut ngx_pool_t, data: String) -> Self { 54 | ngx_str_t { 55 | data: str_to_uchar(pool, data.as_str()), 56 | len: data.len() as _, 57 | } 58 | } 59 | } 60 | 61 | impl ngx_table_elt_t { 62 | pub fn to_string(&self) -> String { 63 | self.value.to_string() 64 | } 65 | } 66 | 67 | impl ngx_array_t { 68 | pub fn table_elt_to_string_vec(&self) -> Vec { 69 | let mut ret = Vec::new(); 70 | let t = self.elts as *mut *mut ngx_table_elt_t; 71 | if t.is_null() { 72 | return ret; 73 | } 74 | let mut t = unsafe { *t }; 75 | for _ in 0..self.nelts { 76 | if !t.is_null() { 77 | ret.push(unsafe { *t }.value.to_string()); 78 | } 79 | t = unsafe { t.add(1) }; 80 | } 81 | ret 82 | } 83 | } 84 | 85 | impl ngx_http_headers_in_t { 86 | pub fn host_str(&self) -> String { 87 | self.server.to_string() 88 | } 89 | 90 | pub fn add(&mut self, pool: *mut ngx_pool_t, key: &str, value: &str) -> Option<()> { 91 | let table: *mut ngx_table_elt_t = unsafe { ngx_list_push(&mut self.headers) as _ }; 92 | add_to_ngx_table(table, pool, key, value) 93 | } 94 | } 95 | 96 | impl ngx_http_headers_out_t { 97 | pub fn add(&mut self, pool: *mut ngx_pool_t, key: &str, value: &str) -> Option<()> { 98 | let table: *mut ngx_table_elt_t = unsafe { ngx_list_push(&mut self.headers) as _ }; 99 | add_to_ngx_table(table, pool, key, value) 100 | } 101 | } 102 | 103 | fn add_to_ngx_table( 104 | table: *mut ngx_table_elt_t, 105 | pool: *mut ngx_pool_t, 106 | key: &str, 107 | value: &str, 108 | ) -> Option<()> { 109 | if table.is_null() { 110 | return None; 111 | } 112 | unsafe { table.as_mut() }.map(|table| { 113 | table.hash = 1; 114 | table.key.len = key.len() as _; 115 | table.key.data = str_to_uchar(pool, key); 116 | table.value.len = value.len() as _; 117 | table.value.data = str_to_uchar(pool, value); 118 | table.lowcase_key = str_to_uchar(pool, String::from(key).to_ascii_lowercase().as_str()); 119 | }) 120 | } 121 | 122 | impl IntoIterator for ngx_http_headers_in_t { 123 | type Item = Header; 124 | type IntoIter = ListIterator; 125 | 126 | fn into_iter(self) -> Self::IntoIter { 127 | ListIterator::from_ngx_list(self.headers) 128 | } 129 | } 130 | 131 | pub struct ListIterator { 132 | part: ngx_list_part_t, 133 | h: *mut ngx_table_elt_t, 134 | i: isize, 135 | } 136 | 137 | impl ListIterator { 138 | pub fn from_ngx_list(list: ngx_list_t) -> Self { 139 | let part = list.part; 140 | ListIterator { 141 | part: part, 142 | h: part.elts as _, 143 | i: 0, 144 | } 145 | } 146 | } 147 | 148 | impl Iterator for ListIterator { 149 | type Item = Header; 150 | 151 | fn next(&mut self) -> Option { 152 | if self.i >= self.part.nelts as _ { 153 | if let Some(next) = unsafe { self.part.next.as_ref() } { 154 | self.part = *next; 155 | self.h = self.part.elts as _; 156 | self.i = 0; 157 | } else { 158 | return None; 159 | } 160 | } 161 | let header = unsafe { *self.h.offset(self.i) }; 162 | self.i += 1; 163 | Some(Header::from(header)) 164 | } 165 | } 166 | 167 | impl From for Header { 168 | fn from(table: ngx_table_elt_t) -> Self { 169 | Self(table) 170 | } 171 | } 172 | 173 | impl Header { 174 | pub fn key(&self) -> String { 175 | self.0.key.to_string() 176 | } 177 | 178 | pub fn value(&self) -> String { 179 | self.0.value.to_string() 180 | } 181 | 182 | pub fn into_inner(self) -> ngx_table_elt_t { 183 | self.0 184 | } 185 | } 186 | 187 | fn str_to_uchar(pool: *mut ngx_pool_t, data: &str) -> *mut u_char { 188 | let ptr: *mut u_char = unsafe { ngx_palloc(pool, data.len() as _) as _ }; 189 | unsafe { 190 | copy_nonoverlapping(data.as_ptr(), ptr, data.len()); 191 | } 192 | ptr 193 | } 194 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc(html_root_url = "https://arvancloud.github.io/nginx-rs")] 2 | 3 | mod bindings; 4 | mod helpers; 5 | 6 | pub mod log; 7 | 8 | pub use bindings::*; 9 | pub use helpers::*; 10 | -------------------------------------------------------------------------------- /src/log.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! ngx_debug { 3 | ($level:expr,$log:expr,$($arg:tt)*) => { 4 | if (*$log).log_level & $level as usize > 0 { 5 | let c_message = ::std::ffi::CString::new(format!($($arg)*)).unwrap_or_default(); 6 | $crate::ngx_log_error_core($crate::NGX_LOG_DEBUG as usize, $log, 0, c_message.as_ptr()); 7 | } 8 | } 9 | } 10 | 11 | #[macro_export] 12 | macro_rules! ngx_error { 13 | ($($arg:tt)*) => { 14 | unsafe { 15 | if (*(*$crate::ngx_cycle).log).log_level >= $crate::NGX_LOG_ERR as usize { 16 | let c_message = ::std::ffi::CString::new(format!($($arg)*)).unwrap_or_default(); 17 | $crate::ngx_log_error_core( 18 | $crate::NGX_LOG_ERR as usize, 19 | (*$crate::ngx_cycle).log, 20 | 0, 21 | c_message.as_ptr(), 22 | ); 23 | } 24 | } 25 | } 26 | } 27 | 28 | #[macro_export] 29 | macro_rules! ngx_http_debug { 30 | ($request:expr,$($arg:tt)*) => { 31 | unsafe { 32 | ngx_debug!($crate::NGX_LOG_DEBUG_HTTP,(*($request).connection).log,$($arg)*); 33 | } 34 | } 35 | } 36 | 37 | #[macro_export] 38 | macro_rules! ngx_event_debug { 39 | ($($arg:tt)*) => { 40 | unsafe { 41 | ngx_debug!($crate::NGX_LOG_DEBUG_EVENT,(*$crate::ngx_cycle).log,$($arg)*); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /wrapper.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | --------------------------------------------------------------------------------