Skip to content

Commit

Permalink
Sanity check for empty service type name (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
keepsimple1 authored Dec 26, 2023
1 parent 7e27e28 commit 2c3f7e5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
9 changes: 8 additions & 1 deletion examples/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//! Options:
//! "--unregister": automatically unregister after 2 seconds.
use mdns_sd::{ServiceDaemon, ServiceInfo};
use mdns_sd::{DaemonEvent, ServiceDaemon, ServiceInfo};
use std::{env, thread, time::Duration};

fn main() {
Expand Down Expand Up @@ -85,6 +85,13 @@ fn main() {
// Monitor the daemon events.
while let Ok(event) = monitor.recv() {
println!("Daemon event: {:?}", &event);
match event {
DaemonEvent::Error(e) => {
println!("Failed: {}", e);
break;
}
_ => {}
}
}
}
}
Expand Down
19 changes: 17 additions & 2 deletions src/service_daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2136,6 +2136,11 @@ const DOMAIN_LEN: usize = "._tcp.local.".len();

/// Validate the length of "service_name" in a "_<service_name>.<domain_name>." string.
fn check_service_name_length(ty_domain: &str, limit: u8) -> Result<()> {
if ty_domain.len() <= DOMAIN_LEN + 1 {
// service name cannot be empty or only '_'.
return Err(e_fmt!("Service type name cannot be empty: {}", ty_domain));
}

let service_name_len = ty_domain.len() - DOMAIN_LEN - 1; // exclude the leading `_`
if service_name_len > limit as usize {
return Err(e_fmt!("Service name length must be <= {} bytes", limit));
Expand Down Expand Up @@ -2266,8 +2271,9 @@ fn valid_instance_name(name: &str) -> bool {
#[cfg(test)]
mod tests {
use super::{
broadcast_dns_on_intf, my_ip_interfaces, new_socket_bind, valid_instance_name, IntfSock,
ServiceDaemon, ServiceEvent, ServiceInfo, GROUP_ADDR_V4, MDNS_PORT,
broadcast_dns_on_intf, check_service_name_length, my_ip_interfaces, new_socket_bind,
valid_instance_name, IntfSock, ServiceDaemon, ServiceEvent, ServiceInfo, GROUP_ADDR_V4,
MDNS_PORT,
};
use crate::dns_parser::{
DnsOutgoing, DnsPointer, CLASS_IN, FLAGS_AA, FLAGS_QR_RESPONSE, TYPE_PTR,
Expand All @@ -2288,6 +2294,15 @@ mod tests {
assert_eq!(valid_instance_name("_printer._tcp.local."), false);
}

#[test]
fn test_check_service_name_length() {
let result = check_service_name_length("_tcp", 100);
assert!(result.is_err());
if let Err(e) = result {
println!("{}", e);
}
}

#[test]
fn service_with_temporarily_invalidated_ptr() {
// Create a daemon
Expand Down

0 comments on commit 2c3f7e5

Please sign in to comment.