Skip to content

Commit

Permalink
rust/jsonbuilder: make set_uint generic over Into<u64>
Browse files Browse the repository at this point in the history
Allow `set_uint` to accept any number value that can be converted to a
u64. Prevents callers from having to do `as u64`.

This required fixing up any callers that used `.into()` to just pass in
their value without the into conversion.

Most calls using `as u64` can have that cast removed, with the exception
of `usize` values which must still be cast is conversion can't be
guaranteed to be non-fallible.
  • Loading branch information
jasonish committed Dec 18, 2024
1 parent 2c0d3b8 commit a5e80fa
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 67 deletions.
6 changes: 3 additions & 3 deletions rust/src/bittorrent_dht/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ fn log_bittorrent_dht(
js.start_object()?;
js.set_hex("id", &node.id)?;
js.set_string("ip", &print_ip_addr(&node.ip))?;
js.set_uint("port", node.port.into())?;
js.set_uint("port", node.port)?;
js.close()?;
}
js.close()?;
Expand All @@ -105,7 +105,7 @@ fn log_bittorrent_dht(
js.start_object()?;
js.set_hex("id", &node.id)?;
js.set_string("ip", &print_ip_addr(&node.ip))?;
js.set_uint("port", node.port.into())?;
js.set_uint("port", node.port)?;
js.close()?;
}
js.close()?;
Expand All @@ -116,7 +116,7 @@ fn log_bittorrent_dht(
for value in values {
js.start_object()?;
js.set_string("ip", &print_ip_addr(&value.ip))?;
js.set_uint("port", value.port.into())?;
js.set_uint("port", value.port)?;
js.close()?;
}
js.close()?;
Expand Down
32 changes: 17 additions & 15 deletions rust/src/detect/tojson/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,47 +24,49 @@ pub fn detect_uint_to_json<T: DetectIntType>(
where
u64: From<T>,
{
let arg1: u64 = du.arg1.into();
let arg2: u64 = du.arg2.into();
match du.mode {
DetectUintMode::DetectUintModeEqual => {
js.set_uint("equal", du.arg1.into())?;
js.set_uint("equal", arg1)?;
}
DetectUintMode::DetectUintModeNe => {
js.set_uint("diff", du.arg1.into())?;
js.set_uint("diff", arg1)?;
}
DetectUintMode::DetectUintModeLt => {
js.set_uint("lt", du.arg1.into())?;
js.set_uint("lt", arg1)?;
}
DetectUintMode::DetectUintModeLte => {
js.set_uint("lte", du.arg1.into())?;
js.set_uint("lte", arg1)?;
}
DetectUintMode::DetectUintModeGt => {
js.set_uint("gt", du.arg1.into())?;
js.set_uint("gt", arg1)?;
}
DetectUintMode::DetectUintModeGte => {
js.set_uint("gte", du.arg1.into())?;
js.set_uint("gte", arg1)?;
}
DetectUintMode::DetectUintModeRange => {
js.open_object("range")?;
js.set_uint("min", du.arg1.into())?;
js.set_uint("max", du.arg2.into())?;
js.set_uint("min", arg1)?;
js.set_uint("max", arg2)?;
js.close()?;
}
DetectUintMode::DetectUintModeNegRg => {
js.open_object("negated_range")?;
js.set_uint("min", du.arg1.into())?;
js.set_uint("max", du.arg2.into())?;
js.set_uint("min", arg1)?;
js.set_uint("max", arg2)?;
js.close()?;
}
DetectUintMode::DetectUintModeBitmask => {
js.open_object("bitmask")?;
js.set_uint("mask", du.arg1.into())?;
js.set_uint("value", du.arg2.into())?;
js.set_uint("mask", arg1)?;
js.set_uint("value", arg2)?;
js.close()?;
}
DetectUintMode::DetectUintModeNegBitmask => {
js.open_object("negated_bitmask")?;
js.set_uint("mask", du.arg1.into())?;
js.set_uint("value", du.arg2.into())?;
js.set_uint("mask", arg1)?;
js.set_uint("value", arg2)?;
js.close()?;
}
}
Expand All @@ -83,4 +85,4 @@ pub unsafe extern "C" fn SCDetectU32ToJson(
js: &mut JsonBuilder, du: &DetectUintData<u32>,
) -> bool {
return detect_uint_to_json(js, du).is_ok();
}
}
26 changes: 13 additions & 13 deletions rust/src/enip/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ fn log_enip_header(h: &EnipHeader, js: &mut JsonBuilder) -> Result<(), JsonError
js.set_string("status", &format!("unknown-{}", h.status))?;
}
if h.options != 0 {
js.set_uint("options", h.options.into())?;
js.set_uint("options", h.options)?;
}
Ok(())
}
Expand Down Expand Up @@ -1707,7 +1707,7 @@ fn log_cip_path_segment(c: &EnipCipPathSegment) -> Result<JsonBuilder, JsonError
js.set_string("segment_type", &format!("unknown-{}", c.segment_type))?;
}
}
js.set_uint("value", c.value.into())?;
js.set_uint("value", c.value)?;
js.close()?;
Ok(js)
}
Expand Down Expand Up @@ -1819,8 +1819,8 @@ fn log_enip(tx: &EnipTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
}
EnipPayload::RegisterSession(rs) => {
js.open_object("register_session")?;
js.set_uint("protocol_version", rs.protocol_version.into())?;
js.set_uint("options", rs.options.into())?;
js.set_uint("protocol_version", rs.protocol_version)?;
js.set_uint("options", rs.options)?;
js.close()?;
}
_ => {}
Expand All @@ -1833,8 +1833,8 @@ fn log_enip(tx: &EnipTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
match &response.payload {
EnipPayload::RegisterSession(rs) => {
js.open_object("register_session")?;
js.set_uint("protocol_version", rs.protocol_version.into())?;
js.set_uint("options", rs.options.into())?;
js.set_uint("protocol_version", rs.protocol_version)?;
js.set_uint("options", rs.options)?;
js.close()?;
}
EnipPayload::Cip(cip) => {
Expand All @@ -1843,16 +1843,16 @@ fn log_enip(tx: &EnipTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
EnipPayload::ListServices(lsp) if !lsp.is_empty() => {
if let EnipItemPayload::Services(ls) = &lsp[0].payload {
js.open_object("list_services")?;
js.set_uint("protocol_version", ls.protocol_version.into())?;
js.set_uint("capabilities", ls.capabilities.into())?;
js.set_uint("protocol_version", ls.protocol_version)?;
js.set_uint("capabilities", ls.capabilities)?;
js.set_string("service_name", &String::from_utf8_lossy(&ls.service_name))?;
js.close()?;
}
}
EnipPayload::ListIdentity(lip) if !lip.is_empty() => {
if let EnipItemPayload::Identity(li) = &lip[0].payload {
js.open_object("identity")?;
js.set_uint("protocol_version", li.protocol_version.into())?;
js.set_uint("protocol_version", li.protocol_version)?;
js.set_string(
"revision",
&format!("{}.{}", li.revision_major, li.revision_minor),
Expand All @@ -1873,11 +1873,11 @@ fn log_enip(tx: &EnipTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
js.set_string("device_type", &format!("unknown-{}", li.device_type))?;
}
}
js.set_uint("product_code", li.product_code.into())?;
js.set_uint("status", li.status.into())?;
js.set_uint("serial", li.serial.into())?;
js.set_uint("product_code", li.product_code)?;
js.set_uint("status", li.status)?;
js.set_uint("serial", li.serial)?;
js.set_string("product_name", &String::from_utf8_lossy(&li.product_name))?;
js.set_uint("state", li.state.into())?;
js.set_uint("state", li.state)?;
js.close()?;
}
}
Expand Down
13 changes: 10 additions & 3 deletions rust/src/jsonbuilder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,13 @@
#![allow(clippy::missing_safety_doc)]

use base64::{engine::general_purpose::STANDARD, Engine};
use num_traits::Unsigned;
use std::cmp::max;
use std::collections::TryReserveError;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::str::Utf8Error;
use base64::{Engine, engine::general_purpose::STANDARD};

const INIT_SIZE: usize = 4096;

Expand Down Expand Up @@ -637,7 +638,11 @@ impl JsonBuilder {
}

/// Set a key and an unsigned integer type on an object.
pub fn set_uint(&mut self, key: &str, val: u64) -> Result<&mut Self, JsonError> {
pub fn set_uint<T>(&mut self, key: &str, val: T) -> Result<&mut Self, JsonError>
where
T: Unsigned + Into<u64>,
{
let val: u64 = val.into();
match self.current_state() {
State::ObjectNth => {
self.push(',')?;
Expand Down Expand Up @@ -1204,9 +1209,11 @@ mod test {
assert_eq!(js.current_state(), State::ObjectNth);
assert_eq!(js.buf, r#"{"one":"one","two":"two""#);

js.set_uint("three", 3u8)?;

js.close()?;
assert_eq!(js.current_state(), State::None);
assert_eq!(js.buf, r#"{"one":"one","two":"two"}"#);
assert_eq!(js.buf, r#"{"one":"one","two":"two","three":3}"#);

Ok(())
}
Expand Down
14 changes: 7 additions & 7 deletions rust/src/ldap/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fn log_ldap(tx: &LdapTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
if let Some(req) = &tx.request {
let protocol_op_str = req.protocol_op.to_string();
js.open_object("request")?;
js.set_uint("message_id", req.message_id.0.into())?;
js.set_uint("message_id", req.message_id.0)?;
js.set_string("operation", &protocol_op_str)?;

match &req.protocol_op {
Expand Down Expand Up @@ -59,7 +59,7 @@ fn log_ldap(tx: &LdapTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
js.set_string("operation", &protocol_op_str)?;

if tx.request.is_none() {
js.set_uint("message_id", response.message_id.0.into())?;
js.set_uint("message_id", response.message_id.0)?;
}

match &response.protocol_op {
Expand Down Expand Up @@ -88,10 +88,10 @@ fn log_ldap(tx: &LdapTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
fn log_search_request(msg: &SearchRequest, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.open_object("search_request")?;
js.set_string("base_object", &msg.base_object.0)?;
js.set_uint("scope", msg.scope.0.into())?;
js.set_uint("deref_alias", msg.deref_aliases.0.into())?;
js.set_uint("size_limit", msg.size_limit.into())?;
js.set_uint("time_limit", msg.time_limit.into())?;
js.set_uint("scope", msg.scope.0)?;
js.set_uint("deref_alias", msg.deref_aliases.0)?;
js.set_uint("size_limit", msg.size_limit)?;
js.set_uint("time_limit", msg.time_limit)?;
js.set_bool("types_only", msg.types_only)?;
if let Filter::Present(val) = &msg.filter {
js.open_object("filter")?;
Expand All @@ -113,7 +113,7 @@ fn log_search_request(msg: &SearchRequest, js: &mut JsonBuilder) -> Result<(), J

fn log_bind_request(msg: &BindRequest, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.open_object("bind_request")?;
js.set_uint("version", msg.version.into())?;
js.set_uint("version", msg.version)?;
js.set_string("name", &msg.name.0)?;
if let AuthenticationChoice::Sasl(sasl) = &msg.authentication {
js.open_object("sasl")?;
Expand Down
32 changes: 16 additions & 16 deletions rust/src/modbus/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ fn log(tx: &ModbusTransaction, js: &mut JsonBuilder) -> Result<(), JsonError> {
}

fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
js.set_uint("transaction_id", msg.transaction_id.into())?;
js.set_uint("protocol_id", msg.protocol_id.into())?;
js.set_uint("unit_id", msg.unit_id.into())?;
js.set_uint("function_raw", msg.function.raw.into())?;
js.set_uint("transaction_id", msg.transaction_id)?;
js.set_uint("protocol_id", msg.protocol_id)?;
js.set_uint("unit_id", msg.unit_id)?;
js.set_uint("function_raw", msg.function.raw)?;
js.set_string("function_code", &msg.function.code.to_string())?;
js.set_string("access_type", &msg.access_type.to_string())?;
js.set_string("category", &msg.category.to_string())?;
Expand All @@ -59,20 +59,20 @@ fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
match &msg.data {
Data::Exception(exc) => {
js.open_object("exception")?;
js.set_uint("raw", exc.raw.into())?;
js.set_uint("raw", exc.raw)?;
js.set_string("code", &exc.code.to_string())?;
js.close()?;
}
Data::Diagnostic { func, data } => {
js.open_object("diagnostic")?;
js.set_uint("raw", func.raw.into())?;
js.set_uint("raw", func.raw)?;
js.set_string("code", &func.code.to_string())?;
js.set_string_from_bytes("data", data)?;
js.close()?;
}
Data::MEI { mei_type, data } => {
js.open_object("mei")?;
js.set_uint("raw", mei_type.raw.into())?;
js.set_uint("raw", mei_type.raw)?;
js.set_string("code", &mei_type.code.to_string())?;
js.set_string_from_bytes("data", data)?;
js.close()?;
Expand Down Expand Up @@ -107,8 +107,8 @@ fn log_message(msg: &Message, js: &mut JsonBuilder) -> Result<(), JsonError> {
fn log_read(read: &Read, js: &mut JsonBuilder) -> Result<(), JsonError> {
match read {
Read::Request { address, quantity } => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
js.set_uint("address", *address)?;
js.set_uint("quantity", *quantity)?;
}
Read::Response(data) => {
js.set_string_from_bytes("data", data)?;
Expand All @@ -125,22 +125,22 @@ fn log_write(write: &Write, js: &mut JsonBuilder) -> Result<(), JsonError> {
quantity,
data,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("quantity", (*quantity).into())?;
js.set_uint("address", *address)?;
js.set_uint("quantity", *quantity)?;
js.set_string_from_bytes("data", data)?;
}
Write::Mask {
address,
and_mask,
or_mask,
} => {
js.set_uint("address", (*address).into())?;
js.set_uint("and_mask", (*and_mask).into())?;
js.set_uint("or_mask", (*or_mask).into())?;
js.set_uint("address", *address)?;
js.set_uint("and_mask", *and_mask)?;
js.set_uint("or_mask", *or_mask)?;
}
Write::Other { address, data } => {
js.set_uint("address", (*address).into())?;
js.set_uint("data", (*data).into())?;
js.set_uint("address", *address)?;
js.set_uint("data", *data)?;
}
}

Expand Down
12 changes: 6 additions & 6 deletions rust/src/pgsql/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ fn log_request(req: &PgsqlFEMessage, flags: u32) -> Result<JsonBuilder, JsonErro
}
PgsqlFEMessage::CancelRequest(CancelRequestMessage { pid, backend_key }) => {
js.set_string("message", "cancel_request")?;
js.set_uint("process_id", (*pid).into())?;
js.set_uint("secret_key", (*backend_key).into())?;
js.set_uint("process_id", *pid)?;
js.set_uint("secret_key", *backend_key)?;
}
PgsqlFEMessage::Terminate(TerminationMessage {
identifier: _,
Expand Down Expand Up @@ -214,8 +214,8 @@ fn log_response(res: &PgsqlBEMessage, jb: &mut JsonBuilder) -> Result<(), JsonEr
backend_pid,
secret_key,
}) => {
jb.set_uint("process_id", (*backend_pid).into())?;
jb.set_uint("secret_key", (*secret_key).into())?;
jb.set_uint("process_id", *backend_pid)?;
jb.set_uint("secret_key", *secret_key)?;
}
PgsqlBEMessage::ReadyForQuery(ReadyForQueryMessage {
identifier: _,
Expand All @@ -230,7 +230,7 @@ fn log_response(res: &PgsqlBEMessage, jb: &mut JsonBuilder) -> Result<(), JsonEr
field_count,
fields: _,
}) => {
jb.set_uint("field_count", (*field_count).into())?;
jb.set_uint("field_count", *field_count)?;
}
PgsqlBEMessage::ConsolidatedDataRow(ConsolidatedDataRowPacket {
identifier: _,
Expand All @@ -247,7 +247,7 @@ fn log_response(res: &PgsqlBEMessage, jb: &mut JsonBuilder) -> Result<(), JsonEr
channel_name,
payload,
}) => {
jb.set_uint("pid", (*pid).into())?;
jb.set_uint("pid", *pid)?;
jb.set_string_from_bytes("channel_name", channel_name)?;
jb.set_string_from_bytes("payload", payload)?;
}
Expand Down
2 changes: 1 addition & 1 deletion rust/src/quic/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ fn log_quic(tx: &QuicTransaction, js: &mut JsonBuilder) -> Result<(), JsonError>
if let Some(s) = quic_tls_extension_name(etype) {
js.set_string("name", &s)?;
}
js.set_uint("type", etype.into())?;
js.set_uint("type", etype)?;

if !e.values.is_empty() {
js.open_array("values")?;
Expand Down
4 changes: 2 additions & 2 deletions rust/src/smb/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,10 +253,10 @@ fn smb_common_header(jsb: &mut JsonBuilder, state: &SMBState, tx: &SMBTransactio
jsb.set_string("server_guid", &guid_to_string(&x.server_guid))?;

if state.max_read_size > 0 {
jsb.set_uint("max_read_size", state.max_read_size.into())?;
jsb.set_uint("max_read_size", state.max_read_size)?;
}
if state.max_write_size > 0 {
jsb.set_uint("max_write_size", state.max_write_size.into())?;
jsb.set_uint("max_write_size", state.max_write_size)?;
}
},
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
Expand Down
Loading

0 comments on commit a5e80fa

Please sign in to comment.