diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000..8728436 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,15 @@ +# 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 diff --git a/examples/async.rs b/examples/async.rs index 94b7df5..43ce3db 100644 --- a/examples/async.rs +++ b/examples/async.rs @@ -7,10 +7,10 @@ use std::time::Instant; use ngx::core; use ngx::ffi::{ - ngx_array_push, ngx_command_t, ngx_conf_t, ngx_connection_t, ngx_event_t, ngx_http_handler_pt, ngx_http_module_t, - ngx_http_phases_NGX_HTTP_ACCESS_PHASE, ngx_int_t, ngx_module_t, ngx_post_event, ngx_posted_events, - ngx_posted_next_events, ngx_str_t, ngx_uint_t, NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, - NGX_HTTP_MODULE, + ngx_array_push, ngx_command_t, ngx_conf_t, ngx_connection_t, ngx_event_t, ngx_http_handler_pt, + ngx_http_module_t, ngx_http_phases_NGX_HTTP_ACCESS_PHASE, ngx_int_t, ngx_module_t, + ngx_post_event, ngx_posted_events, ngx_posted_next_events, ngx_str_t, ngx_uint_t, + NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, }; use ngx::http::{self, HttpModule, MergeConfigError}; use ngx::http::{HttpModuleLocationConf, HttpModuleMainConf, NgxHttpCoreModule}; @@ -29,8 +29,9 @@ impl http::HttpModule for Module { let cf = &mut *cf; let cmcf = NgxHttpCoreModule::main_conf_mut(cf).expect("http core main conf"); - let h = ngx_array_push(&mut cmcf.phases[ngx_http_phases_NGX_HTTP_ACCESS_PHASE as usize].handlers) - as *mut ngx_http_handler_pt; + let h = ngx_array_push( + &mut cmcf.phases[ngx_http_phases_NGX_HTTP_ACCESS_PHASE as usize].handlers, + ) as *mut ngx_http_handler_pt; if h.is_null() { return core::Status::NGX_ERROR.into(); } @@ -104,9 +105,9 @@ unsafe extern "C" fn check_async_work_done(event: *mut ngx_event_t) { // Triggering async_access_handler again ngx_post_event((*c).write, addr_of_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. + // 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. ngx_post_event(event, addr_of_mut!(ngx_posted_next_events)); } } @@ -148,7 +149,9 @@ http_request_handler!(async_access_handler, |request: &mut http::Request| { return core::Status::NGX_DECLINED; } - if let Some(ctx) = unsafe { request.get_module_ctx::(&*addr_of!(ngx_http_async_module)) } { + if let Some(ctx) = + unsafe { request.get_module_ctx::(&*addr_of!(ngx_http_async_module)) } + { if !ctx.done.load(Ordering::Relaxed) { return core::Status::NGX_AGAIN; } @@ -180,12 +183,16 @@ http_request_handler!(async_access_handler, |request: &mut http::Request| { // 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()); + 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) + // 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) })); core::Status::NGX_AGAIN @@ -216,7 +223,10 @@ extern "C" fn ngx_http_async_commands_set_enable( 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 _); + assert_ne!( + unsafe { ngx::ffi::ngx_process }, + ngx::ffi::NGX_PROCESS_MASTER as _ + ); static RUNTIME: OnceLock = OnceLock::new(); RUNTIME.get_or_init(|| { diff --git a/examples/awssig.rs b/examples/awssig.rs index 127b484..384f98d 100644 --- a/examples/awssig.rs +++ b/examples/awssig.rs @@ -4,8 +4,9 @@ use http::HeaderMap; use ngx::core; use ngx::ffi::{ ngx_array_push, ngx_command_t, ngx_conf_t, ngx_http_handler_pt, ngx_http_module_t, - ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t, NGX_CONF_TAKE1, - NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, NGX_HTTP_SRV_CONF, + ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t, + NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, + NGX_HTTP_SRV_CONF, }; use ngx::http::*; use ngx::{http_request_handler, ngx_log_debug_http, ngx_string}; @@ -22,8 +23,9 @@ impl HttpModule for Module { let cf = &mut *cf; let cmcf = NgxHttpCoreModule::main_conf_mut(cf).expect("http core main conf"); - let h = ngx_array_push(&mut cmcf.phases[ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE as usize].handlers) - as *mut ngx_http_handler_pt; + let h = ngx_array_push( + &mut cmcf.phases[ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE as usize].handlers, + ) as *mut ngx_http_handler_pt; if h.is_null() { return core::Status::NGX_ERROR.into(); } diff --git a/examples/curl.rs b/examples/curl.rs index 7ccba61..c8d9d2c 100644 --- a/examples/curl.rs +++ b/examples/curl.rs @@ -3,8 +3,8 @@ use std::ffi::{c_char, c_void}; use ngx::core; use ngx::ffi::{ ngx_array_push, ngx_command_t, ngx_conf_t, ngx_http_handler_pt, ngx_http_module_t, - ngx_http_phases_NGX_HTTP_ACCESS_PHASE, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t, NGX_CONF_TAKE1, - NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, + ngx_http_phases_NGX_HTTP_ACCESS_PHASE, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t, + NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, }; use ngx::http::{self, HttpModule, MergeConfigError}; use ngx::http::{HttpModuleLocationConf, HttpModuleMainConf, NgxHttpCoreModule}; @@ -22,8 +22,9 @@ impl http::HttpModule for Module { let cf = &mut *cf; let cmcf = NgxHttpCoreModule::main_conf_mut(cf).expect("http core main conf"); - let h = ngx_array_push(&mut cmcf.phases[ngx_http_phases_NGX_HTTP_ACCESS_PHASE as usize].handlers) - as *mut ngx_http_handler_pt; + let h = ngx_array_push( + &mut cmcf.phases[ngx_http_phases_NGX_HTTP_ACCESS_PHASE as usize].handlers, + ) as *mut ngx_http_handler_pt; if h.is_null() { return core::Status::NGX_ERROR.into(); } diff --git a/examples/httporigdst.rs b/examples/httporigdst.rs index 771333c..b1f7774 100644 --- a/examples/httporigdst.rs +++ b/examples/httporigdst.rs @@ -4,8 +4,8 @@ use std::ptr::addr_of; use ngx::core; use ngx::ffi::{ 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, INET_ADDRSTRLEN, NGX_HTTP_MODULE, + 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, INET_ADDRSTRLEN, NGX_HTTP_MODULE, }; use ngx::http::{self, HttpModule}; use ngx::{http_variable_get, ngx_log_debug_http, ngx_string}; @@ -33,7 +33,13 @@ impl NgxHttpOrigDstCtx { if port_data.is_null() { return core::Status::NGX_ERROR; } - unsafe { libc::memcpy(port_data, port_str.as_bytes().as_ptr() as *const c_void, port_str.len()) }; + 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; @@ -118,7 +124,9 @@ static mut NGX_HTTP_ORIG_DST_VARS: [ngx_http_variable_t; 2] = [ }, ]; -unsafe fn ngx_get_origdst(request: &mut http::Request) -> Result<(String, in_port_t), core::Status> { +unsafe fn ngx_get_origdst( + request: &mut http::Request, +) -> Result<(String, in_port_t), core::Status> { let c = request.connection(); if (*c).type_ != libc::SOCK_STREAM { @@ -168,7 +176,10 @@ unsafe fn ngx_get_origdst(request: &mut http::Request) -> Result<(String, in_por ) }; if e == 0 { - ngx_log_debug_http!(request, "httporigdst: ngx_sock_ntop failed to convert sockaddr"); + ngx_log_debug_http!( + request, + "httporigdst: ngx_sock_ntop failed to convert sockaddr" + ); return Err(core::Status::NGX_ERROR); } ip.truncate(e); @@ -201,16 +212,24 @@ http_variable_get!( Ok((ip, port)) => { // create context, // set context - let new_ctx = request.pool().allocate::(Default::default()); + let new_ctx = request + .pool() + .allocate::(Default::default()); if new_ctx.is_null() { return core::Status::NGX_ERROR; } - ngx_log_debug_http!(request, "httporigdst: saving ip - {:?}, port - {}", ip, port,); + ngx_log_debug_http!( + request, + "httporigdst: saving ip - {:?}, port - {}", + ip, + port, + ); (*new_ctx).save(&ip, port, &mut request.pool()); (*new_ctx).bind_addr(v); - request.set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module)); + request + .set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module)); } } core::Status::NGX_OK @@ -240,16 +259,24 @@ http_variable_get!( Ok((ip, port)) => { // create context, // set context - let new_ctx = request.pool().allocate::(Default::default()); + let new_ctx = request + .pool() + .allocate::(Default::default()); if new_ctx.is_null() { return core::Status::NGX_ERROR; } - ngx_log_debug_http!(request, "httporigdst: saving ip - {:?}, port - {}", ip, port,); + ngx_log_debug_http!( + request, + "httporigdst: saving ip - {:?}, port - {}", + ip, + port, + ); (*new_ctx).save(&ip, port, &mut request.pool()); (*new_ctx).bind_port(v); - request.set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module)); + request + .set_module_ctx(new_ctx as *mut c_void, &*addr_of!(ngx_http_orig_dst_module)); } } core::Status::NGX_OK diff --git a/examples/upstream.rs b/examples/upstream.rs index 27160a4..b928672 100644 --- a/examples/upstream.rs +++ b/examples/upstream.rs @@ -12,15 +12,19 @@ use std::slice; use ngx::core::{Pool, Status}; use ngx::ffi::{ - 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, 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, + 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, }; 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}; +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)] @@ -161,7 +165,10 @@ http_upstream_init_peer_pt!( // 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 { +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!( @@ -209,7 +216,11 @@ 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, (*cf).log, "CUSTOM UPSTREAM peer init_upstream"); + ngx_log_debug_mask!( + DebugMask::Http, + (*cf).log, + "CUSTOM UPSTREAM peer init_upstream" + ); // SAFETY: this function is called with non-NULL uf always let us = unsafe { &mut *us }; @@ -226,14 +237,22 @@ unsafe extern "C" fn ngx_http_upstream_init_custom( let init_upstream_ptr = hccf.original_init_upstream.unwrap(); if init_upstream_ptr(cf, us) != Status::NGX_OK.into() { - ngx_conf_log_error!(NGX_LOG_EMERG, cf, "CUSTOM UPSTREAM failed calling init_upstream"); + 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, (*cf).log, "CUSTOM UPSTREAM end peer init_upstream"); + ngx_log_debug_mask!( + DebugMask::Http, + (*cf).log, + "CUSTOM UPSTREAM end peer init_upstream" + ); isize::from(Status::NGX_OK) } @@ -252,7 +271,8 @@ unsafe extern "C" fn ngx_http_upstream_commands_set_custom( let ccf = &mut (*(conf as *mut SrvConfig)); if (*cf.args).nelts == 2 { - let value: &[ngx_str_t] = slice::from_raw_parts((*cf.args).elts as *const ngx_str_t, (*cf.args).nelts); + let value: &[ngx_str_t] = + slice::from_raw_parts((*cf.args).elts as *const ngx_str_t, (*cf.args).nelts); let n = ngx_atoi(value[1].data, value[1].len); if n == (NGX_ERROR as isize) || n == 0 { ngx_conf_log_error!( @@ -306,7 +326,11 @@ impl HttpModule for Module { (*conf).max = NGX_CONF_UNSET as u32; - ngx_log_debug_mask!(DebugMask::Http, (*cf).log, "CUSTOM UPSTREAM end create_srv_conf"); + ngx_log_debug_mask!( + DebugMask::Http, + (*cf).log, + "CUSTOM UPSTREAM end create_srv_conf" + ); conf as *mut c_void } } diff --git a/nginx-sys/build/main.rs b/nginx-sys/build/main.rs index e2a7378..a60be7f 100644 --- a/nginx-sys/build/main.rs +++ b/nginx-sys/build/main.rs @@ -85,11 +85,17 @@ impl NginxSource { 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 } + Self { + source_dir, + build_dir, + } } pub fn from_env() -> Self { - match (env::var_os("NGINX_SOURCE_DIR"), env::var_os("NGINX_BUILD_DIR")) { + 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), @@ -106,7 +112,11 @@ impl NginxSource { } pub fn from_build_dir(build_dir: impl AsRef) -> Self { - let source_dir = build_dir.as_ref().parent().expect("source directory").to_owned(); + let source_dir = build_dir + .as_ref() + .parent() + .expect("source directory") + .to_owned(); Self::new(source_dir, build_dir) } @@ -115,20 +125,32 @@ impl NginxSource { let build_dir = vendored::build().expect("vendored build"); let source_dir = build_dir.parent().expect("source directory").to_path_buf(); - Self { source_dir, build_dir } + 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"); + 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(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.", + "Invalid nginx source directory: {:?}. NGINX_SOURCE_DIR is not specified or \ + contains invalid value.", source_dir.as_ref() ) .into()), @@ -138,9 +160,15 @@ impl NginxSource { 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(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.", + "Invalid NGINX build directory: {:?}. NGINX_BUILD_DIR is not specified or \ + contains invalid value.", build_dir.as_ref() ) .into()), @@ -189,7 +217,8 @@ fn generate_binding(nginx: &NginxSource) { .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_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")) @@ -266,7 +295,11 @@ pub fn print_cargo_metadata>(includes: &[T]) -> Result<(), Box>(includes: &[T]) -> Result<(), Box String { } fn pcre_archive_url(version: &String) -> String { - // 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. + // 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_DOWNLOAD_URL_PREFIX}/{version}/pcre-{version}.tar.gz") } else { @@ -203,8 +207,15 @@ fn nginx_archive_url(version: &String) -> String { fn all_archives() -> Vec<(String, String)> { let ngx_version = env::var("NGX_VERSION").unwrap_or_else(|_| NGX_DEFAULT_VERSION.into()); let zlib_version = env::var("ZLIB_VERSION").unwrap_or_else(|_| ZLIB_DEFAULT_VERSION.into()); - // While Nginx 1.22.0 and later support pcre2 and openssl3, earlier ones only support pcre1 and openssl1. Here provides the appropriate (and as latest as possible) versions of these two dependencies as default, switching `***[major_version]_DEFAULT_VERSION` based on `is_after_1_22`. This facilitates to compile backport versions targeted for Nginx ealier than 1.22.0, which are still used in LTS releases of major Linux distributions. - let ngx_version_vec: Vec = ngx_version.split('.').map(|s| s.parse().unwrap_or(-1)).collect(); + // While Nginx 1.22.0 and later support pcre2 and openssl3, earlier ones only support pcre1 and + // openssl1. Here provides the appropriate (and as latest as possible) versions of these two + // dependencies as default, switching `***[major_version]_DEFAULT_VERSION` based on + // `is_after_1_22`. This facilitates to compile backport versions targeted for Nginx ealier than + // 1.22.0, which are still used in LTS releases of major Linux distributions. + let ngx_version_vec: Vec = ngx_version + .split('.') + .map(|s| s.parse().unwrap_or(-1)) + .collect(); let is_after_1_22 = (ngx_version_vec.len() >= 2) && (ngx_version_vec[0] > 1 || (ngx_version_vec[0] == 1 && ngx_version_vec[1] >= 22)); // keep env name `PCRE2_VERSION` for compat @@ -255,7 +266,11 @@ fn nginx_install_dir(base_dir: &Path, target: &str) -> PathBuf { /// Ensure the correct permissions are applied to the local gnupg directory fn ensure_gpg_permissions(cache_dir: &Path) -> Result<(), Box> { - fn change_permissions_recursively(path: &Path, dir_mode: u32, file_mode: u32) -> std::io::Result<()> { + 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))?; @@ -275,7 +290,8 @@ fn ensure_gpg_permissions(cache_dir: &Path) -> Result<(), Box> { } let gnupghome = cache_dir.join(".gnupg"); - change_permissions_recursively(gnupghome.as_path(), 0o700, 0o600).map_err(|e| Box::new(e) as Box) + change_permissions_recursively(gnupghome.as_path(), 0o700, 0o600) + .map_err(|e| Box::new(e) as Box) } /// Iterates through the tuples in `ALL_SERVERS_AND_PUBLIC_KEY_IDS` and returns a map of @@ -310,7 +326,11 @@ fn import_gpg_keys(cache_dir: &Path) -> Result<(), Box> { ensure_gpg_permissions(cache_dir)?; for (server, key_ids) in keys_indexed_by_key_server() { - println!("Importing {} GPG keys for key server: {}", key_ids.len(), server); + println!( + "Importing {} GPG keys for key server: {}", + key_ids.len(), + server + ); let homedir = gnupghome.clone(); let homedir_str = homedir.to_string_lossy().to_string(); @@ -330,8 +350,7 @@ fn import_gpg_keys(cache_dir: &Path) -> Result<(), Box> { if !output.status.success() { eprintln!("{}", String::from_utf8_lossy(&output.stdout)); return Err(format!( - "Command: {:?}\n\ - Failed to import GPG keys: {}", + "Command: {:?}\nFailed to import GPG keys: {}", cmd, key_ids.join(" ") ) @@ -348,7 +367,8 @@ fn make_cache_dir() -> Result> { .unwrap_or_else(|_| env::current_dir().expect("Failed to get current directory")); // Choose `.cache` relative to the manifest directory (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 + // 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")); @@ -375,7 +395,11 @@ fn download(cache_dir: &Path, url: &str) -> Result> { } if !file_path.exists() { - return Err(format!("Downloaded file was not written to the expected location: {}", url).into()); + return Err(format!( + "Downloaded file was not written to the expected location: {}", + url + ) + .into()); } Ok(file_path) } @@ -390,7 +414,13 @@ fn verify_signature_file(cache_dir: &Path, signature_path: &Path) -> Result<(), } if let Some(gpg) = gpg_path() { let gnupghome = cache_dir.join(".gnupg"); - let cmd = cmd!(gpg, "--homedir", &gnupghome, "--list-packets", signature_path); + let cmd = cmd!( + gpg, + "--homedir", + &gnupghome, + "--list-packets", + signature_path + ); let output = cmd.stderr_to_stdout().stdout_capture().unchecked().run()?; if !output.status.success() { @@ -419,7 +449,14 @@ fn verify_archive_signature( ) -> Result<(), Box> { if let Some(gpg) = gpg_path() { let gnupghome = cache_dir.join(".gnupg"); - let cmd = cmd!(gpg, "--homedir", &gnupghome, "--verify", signature_path, archive_path); + let cmd = cmd!( + gpg, + "--homedir", + &gnupghome, + "--verify", + signature_path, + archive_path + ); let output = cmd.stderr_to_stdout().stdout_capture().unchecked().run()?; if !output.status.success() { eprintln!("{}", String::from_utf8_lossy(&output.stdout)); @@ -439,7 +476,11 @@ fn verify_archive_signature( } /// Get a given tarball and signature file from a remote URL and copy it to the `.cache` directory. -fn get_archive(cache_dir: &Path, archive_url: &str, signature_url: &str) -> Result> { +fn get_archive( + cache_dir: &Path, + archive_url: &str, + signature_url: &str, +) -> Result> { let signature_path = download(cache_dir, signature_url)?; if let Err(e) = verify_signature_file(cache_dir, &signature_path) { fs::remove_file(&signature_path)?; @@ -464,8 +505,8 @@ fn extract_archive( 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 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()) @@ -485,7 +526,9 @@ fn extract_archive( .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(); + entry + .unpack(archive_output_dir.join(stripped_path)) + .unwrap(); }); } else { println!( @@ -499,7 +542,10 @@ fn extract_archive( } /// Extract all of the tarballs into subdirectories within the source base directory. -fn extract_all_archives(cache_dir: &Path, target: &str) -> Result, Box> { +fn extract_all_archives( + cache_dir: &Path, + target: &str, +) -> Result, Box> { let archives = all_archives(); let mut sources = Vec::new(); let extract_output_base_dir = source_output_dir(cache_dir, target); @@ -518,7 +564,10 @@ fn extract_all_archives(cache_dir: &Path, target: &str) -> Result Result<(PathBuf, PathBuf), Box> { - fn find_dependency_path<'a>(sources: &'a [(String, PathBuf)], name: &str) -> Result<&'a PathBuf, String> { + fn find_dependency_path<'a>( + sources: &'a [(String, PathBuf)], + name: &str, + ) -> Result<&'a PathBuf, String> { sources .iter() .find(|(n, _)| n == name) @@ -535,9 +584,15 @@ fn compile_nginx(cache_dir: &Path) -> Result<(PathBuf, PathBuf), Box Vec { @@ -647,7 +704,10 @@ fn make(nginx_src_dir: &Path, arg: &str) -> std::io::Result { let make_bin_path = match (which("gmake"), which("make")) { (Ok(path), _) => Ok(path), (_, Ok(path)) => Ok(path), - _ => Err(IoError::new(NotFound, "Unable to find make in path (gmake or make)")), + _ => Err(IoError::new( + NotFound, + "Unable to find make in path (gmake or make)", + )), }?; // Level of concurrency to use when building nginx - cargo nicely provides this information diff --git a/nginx-sys/src/event.rs b/nginx-sys/src/event.rs index 3e59af9..bd08d37 100644 --- a/nginx-sys/src/event.rs +++ b/nginx-sys/src/event.rs @@ -1,8 +1,8 @@ use core::ptr; use crate::{ - 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, 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, NGX_TIMER_LAZY_DELAY, }; /// Sets a timeout for an event. diff --git a/nginx-sys/src/lib.rs b/nginx-sys/src/lib.rs index 80d7f37..ce9064b 100644 --- a/nginx-sys/src/lib.rs +++ b/nginx-sys/src/lib.rs @@ -24,7 +24,6 @@ mod bindings { } #[doc(no_inline)] pub use bindings::*; - pub use event::*; pub use queue::*; @@ -57,7 +56,8 @@ pub unsafe fn bytes_to_uchar(pool: *mut ngx_pool_t, data: &[u8]) -> Option<*mut Some(ptr) } -/// Convert a string slice (`&str`) to a raw pointer (`*mut u_char`) allocated in the given nginx memory pool. +/// Convert a string slice (`&str`) to a raw pointer (`*mut u_char`) allocated in the given nginx +/// memory pool. /// /// # Arguments /// @@ -65,7 +65,8 @@ pub unsafe fn bytes_to_uchar(pool: *mut ngx_pool_t, data: &[u8]) -> Option<*mut /// * `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`. +/// 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. @@ -142,7 +143,10 @@ impl ngx_str_t { /// /// The caller must provide a valid pointer to a memory pool. pub unsafe fn from_bytes(pool: *mut ngx_pool_t, src: &[u8]) -> Option { - bytes_to_uchar(pool, src).map(|data| Self { data, len: src.len() }) + bytes_to_uchar(pool, src).map(|data| Self { + data, + len: src.len(), + }) } /// Create an `ngx_str_t` instance from a string slice (`&str`). @@ -270,10 +274,12 @@ impl ngx_module_t { /// * `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`. +/// 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. +/// An `Option<()>` representing the result of the operation. `Some(())` indicates success, while +/// `None` indicates a null table pointer. /// /// # Example /// ```rust diff --git a/nginx-sys/src/queue.rs b/nginx-sys/src/queue.rs index be18a61..02e2252 100644 --- a/nginx-sys/src/queue.rs +++ b/nginx-sys/src/queue.rs @@ -11,7 +11,8 @@ use crate::bindings::ngx_queue_t; #[macro_export] macro_rules! ngx_queue_data { ($q:expr, $type:path, $link:ident) => { - $q.byte_sub(::core::mem::offset_of!($type, $link)).cast::<$type>() + $q.byte_sub(::core::mem::offset_of!($type, $link)) + .cast::<$type>() }; } @@ -168,12 +169,20 @@ mod tests { 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 } + 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 } + Self { + h, + q: next(h), + next, + } } } @@ -200,7 +209,9 @@ mod tests { // 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()) + && 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 @@ -234,7 +245,11 @@ mod tests { assert!(cmp(ptr::addr_of_mut!(h1), &[1, 2, 3, 4, 5, 5, 4, 3, 2, 1])); - ngx_queue_split(ptr::addr_of_mut!(h1), (*h2.next).next, ptr::addr_of_mut!(h2)); + ngx_queue_split( + ptr::addr_of_mut!(h1), + (*h2.next).next, + ptr::addr_of_mut!(h2), + ); assert!(cmp(ptr::addr_of_mut!(h1), &[1, 2, 3, 4, 5, 5])); assert!(cmp(ptr::addr_of_mut!(h2), &[4, 3, 2, 1])); diff --git a/rustfmt.toml b/rustfmt.toml index 7a60a95..1df56ae 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,8 @@ -# group_imports = "StdExternalCrate" # unstable edition = "2021" -max_width = 120 \ No newline at end of file +max_width = 100 + +# unstable options: +# comment_width = 100 +# group_imports = "StdExternalCrate" +# format_strings = true +# wrap_comments = true \ No newline at end of file diff --git a/src/core/buffer.rs b/src/core/buffer.rs index d0c40ac..cfd1282 100644 --- a/src/core/buffer.rs +++ b/src/core/buffer.rs @@ -59,7 +59,8 @@ pub trait Buffer { } } -/// The `MutableBuffer` trait extends the `Buffer` trait and provides methods for working with a mutable buffer. +/// 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] { diff --git a/src/core/mod.rs b/src/core/mod.rs index 5b32369..a5b87a9 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -17,6 +17,7 @@ pub use string::*; #[macro_export] macro_rules! ngx_container_of { ($ptr:expr, $type:path, $field:ident) => { - $ptr.byte_sub(::core::mem::offset_of!($type, $field)).cast::<$type>() + $ptr.byte_sub(::core::mem::offset_of!($type, $field)) + .cast::<$type>() }; } diff --git a/src/core/pool.rs b/src/core/pool.rs index 3e02cc6..c17ec3b 100644 --- a/src/core/pool.rs +++ b/src/core/pool.rs @@ -13,8 +13,8 @@ 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. + /// 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 { assert!(!pool.is_null()); Pool(pool) @@ -22,7 +22,8 @@ impl Pool { /// 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. + /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if + /// allocation fails. pub fn create_buffer(&mut self, size: usize) -> Option { let buf = unsafe { ngx_create_temp_buf(self.0, size) }; if buf.is_null() { @@ -34,7 +35,8 @@ impl Pool { /// Creates a buffer from a string in the memory pool. /// - /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if allocation fails. + /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if + /// allocation fails. pub fn create_buffer_from_str(&mut self, str: &str) -> Option { let mut buffer = self.create_buffer(str.len())?; unsafe { @@ -47,7 +49,8 @@ impl Pool { /// 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. + /// Returns `Some(MemoryBuffer)` if the buffer is successfully created, or `None` if allocation + /// fails. pub fn create_buffer_from_static_str(&mut self, str: &'static str) -> Option { let buf = self.calloc_type::(); if buf.is_null() { @@ -71,7 +74,8 @@ impl Pool { /// 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. + /// 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. @@ -132,9 +136,11 @@ impl Pool { 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. + /// 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. + /// Returns a typed pointer to the allocated memory if successful, or a null pointer if + /// allocation or cleanup handler addition fails. pub fn allocate(&mut self, value: T) -> *mut T { unsafe { let p = self.alloc(mem::size_of::()) as *mut T; @@ -153,7 +159,8 @@ impl Pool { /// 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`. +/// This function is marked as unsafe due to the raw pointer manipulation and the assumption that +/// `data` is a valid pointer to `T`. /// /// # Arguments /// diff --git a/src/core/string.rs b/src/core/string.rs index ab7f6a3..d7858db 100644 --- a/src/core/string.rs +++ b/src/core/string.rs @@ -1,7 +1,6 @@ -use core::str::{self, Utf8Error}; - #[cfg(all(not(feature = "std"), feature = "alloc"))] use alloc::{borrow::Cow, string::String}; +use core::str::{self, Utf8Error}; #[cfg(feature = "std")] use std::{borrow::Cow, string::String}; diff --git a/src/http/conf.rs b/src/http/conf.rs index 7f467d2..977d22c 100644 --- a/src/http/conf.rs +++ b/src/http/conf.rs @@ -1,7 +1,8 @@ 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, + 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; @@ -40,7 +41,10 @@ pub trait HttpModuleConfExt { impl HttpModuleConfExt for crate::ffi::ngx_cycle_t { #[inline] unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { - let http_conf = self.conf_ctx.add(nginx_sys::ngx_http_module.index).as_ref()?; + let http_conf = self + .conf_ctx + .add(nginx_sys::ngx_http_module.index) + .as_ref()?; let conf_ctx = (*http_conf).cast::(); let conf_ctx = conf_ctx.as_ref()?; NonNull::new((*conf_ctx.main_conf.add(module.ctx_index)).cast()) @@ -159,8 +163,8 @@ pub unsafe trait HttpModuleServerConf: HttpModule { /// 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. +/// 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; @@ -176,7 +180,8 @@ pub unsafe trait HttpModuleLocationConf: HttpModule { mod core { 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, + ngx_http_core_loc_conf_t, ngx_http_core_main_conf_t, ngx_http_core_module, + ngx_http_core_srv_conf_t, }; /// Auxiliary structure to access `ngx_http_core_module` configuration. @@ -220,7 +225,9 @@ mod 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}; + 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; diff --git a/src/http/module.rs b/src/http/module.rs index 858cf41..657a973 100644 --- a/src/http/module.rs +++ b/src/http/module.rs @@ -110,7 +110,11 @@ pub trait HttpModule { /// /// 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 + 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, @@ -140,7 +144,11 @@ pub trait HttpModule { /// /// 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 + 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, diff --git a/src/http/request.rs b/src/http/request.rs index 9bab677..c3a2155 100644 --- a/src/http/request.rs +++ b/src/http/request.rs @@ -84,7 +84,8 @@ macro_rules! http_variable_get { }; } -/// Wrapper struct for an [`ngx_http_request_t`] pointer, providing methods for working with HTTP requests. +/// Wrapper struct for an [`ngx_http_request_t`] pointer, providing methods for working with HTTP +/// requests. /// /// See #[repr(transparent)] @@ -139,8 +140,8 @@ impl Request { /// 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. + /// 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 /// @@ -231,7 +232,8 @@ impl Request { /// /// See pub fn add_header_in(&mut self, key: &str, value: &str) -> Option<()> { - let table: *mut ngx_table_elt_t = unsafe { ngx_list_push(&mut self.0.headers_in.headers) as _ }; + let table: *mut ngx_table_elt_t = + unsafe { ngx_list_push(&mut self.0.headers_in.headers) as _ }; unsafe { add_to_ngx_table(table, self.0.pool, key, value) } } @@ -239,7 +241,8 @@ impl Request { /// /// See pub fn add_header_out(&mut self, key: &str, value: &str) -> Option<()> { - let table: *mut ngx_table_elt_t = unsafe { ngx_list_push(&mut self.0.headers_out.headers) as _ }; + let table: *mut ngx_table_elt_t = + unsafe { ngx_list_push(&mut self.0.headers_out.headers) as _ }; unsafe { add_to_ngx_table(table, self.0.pool, key, value) } } @@ -316,18 +319,26 @@ impl Request { &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, + 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::()); + 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; + 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); - (*post_subreq).data = self.get_module_ctx_ptr(module); // WARN: safety! ensure that ctx is already set + (*post_subreq).data = self.get_module_ctx_ptr(module); // WARN: safety! ensure that ctx + // is already set } // ------------- @@ -343,14 +354,17 @@ impl Request { ) }; - // previously call of ngx_http_subrequest() would ensure that the pointer is not null anymore + // 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 _; + sr.request_body = + self.pool() + .alloc(core::mem::size_of::()) as *mut _; if sr.request_body.is_null() { return Status::NGX_ERROR; @@ -401,7 +415,9 @@ impl crate::http::HttpModuleConfExt for Request { impl fmt::Debug for Request { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Request").field("request_", &self.0).finish() + f.debug_struct("Request") + .field("request_", &self.0) + .finish() } } diff --git a/src/http/upstream.rs b/src/http/upstream.rs index f9ce427..22a0e7e 100644 --- a/src/http/upstream.rs +++ b/src/http/upstream.rs @@ -4,9 +4,9 @@ /// 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. +/// `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] diff --git a/src/log.rs b/src/log.rs index 9572437..b146df0 100644 --- a/src/log.rs +++ b/src/log.rs @@ -8,7 +8,8 @@ use crate::ffi::{self, ngx_err_t, ngx_log_t, ngx_uint_t, NGX_MAX_ERROR_STR}; /// /// 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(); +pub const LOG_BUFFER_SIZE: usize = + NGX_MAX_ERROR_STR as usize - b"1970/01/01 00:00:00 [info] 1#1: ".len(); /// Utility function to provide typed checking of the mask's field state. #[inline(always)] @@ -80,7 +81,8 @@ macro_rules! ngx_log_error { 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 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) }; } @@ -94,10 +96,18 @@ macro_rules! ngx_conf_log_error { 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 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()); + $crate::ffi::ngx_conf_log_error( + level, + cf, + 0, + c"%*s".as_ptr(), + message.len(), + message.as_ptr() + ); } } } @@ -109,7 +119,8 @@ macro_rules! ngx_log_debug { ( mask: $mask:expr, $log:expr, $($arg:tt)+ ) => { let log = $log; if $crate::log::check_mask($mask, unsafe { (*log).log_level }) { - let mut buf = [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; + 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) }; } @@ -275,7 +286,9 @@ mod tests { } #[test] fn test_mask_upper_bound() { - assert!(>::into(DebugMask::Stream) == crate::ffi::NGX_LOG_DEBUG_LAST); + assert!( + >::into(DebugMask::Stream) == crate::ffi::NGX_LOG_DEBUG_LAST + ); } #[test] fn test_check_mask() { @@ -305,10 +318,16 @@ mod tests { // overflow results in truncated output write!(&mut buf, " This is a test, {}", usize::MAX).unwrap(); - assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World! This is a test, 184")); + 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")); + assert_eq!( + str::from_utf8(buf.filled()), + Ok("Hello World! This is a test, 184") + ); } } diff --git a/tests/build.rs b/tests/build.rs index db200c9..81caa36 100644 --- a/tests/build.rs +++ b/tests/build.rs @@ -1,3 +1,6 @@ fn main() { - println!("cargo:rustc-env=TARGET={}", std::env::var("TARGET").unwrap()); + println!( + "cargo:rustc-env=TARGET={}", + std::env::var("TARGET").unwrap() + ); } diff --git a/tests/log_test.rs b/tests/log_test.rs index d219eab..fc15b88 100644 --- a/tests/log_test.rs +++ b/tests/log_test.rs @@ -90,7 +90,11 @@ impl Nginx { // 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 + println!( + "copying config from: {:?} to: {:?}", + from.as_ref(), + self.config_path + ); // replace with logging fs::copy(from, &self.config_path) } } @@ -117,9 +121,12 @@ mod tests { 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())); + 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());