Refactor users to use &str as main type

This commit is contained in:
George Hilliard committed 2020-07-18 15:12:26 -05:00
1 parent 3d866a482e
commit bae4182bf5
3 files changed
+54 -78

No files matched your search

+8 -6
View File
@@ -74,13 +74,12 @@ pub struct CameraConfig {
#[derive(Debug, Deserialize, Validate, Clone)]
pub struct UserConfig {
#[validate(required, custom = "validate_username")]
#[validate(custom = "validate_username")]
#[serde(alias = "username")]
pub name: Option<String>,
pub name: String,
#[validate(required)]
#[serde(alias = "password")]
pub pass: Option<String>,
pub pass: String,
}
fn default_bind_addr() -> String {
@@ -107,9 +106,12 @@ fn default_tls_client_auth() -> String {
"none".to_string()
}
pub static RESERVED_NAMES: &[&str] = &["anyone", "anonymous"];
fn validate_username(name: &str) -> Result<(), ValidationError> {
let reserved_names = vec!["anyone", "anonymous"];
if reserved_names.contains(&name) {
if name.trim().is_empty() {
return Err(ValidationError::new("username cannot be empty"))
}
if RESERVED_NAMES.contains(&name) {
return Err(ValidationError::new("This is a reserved username"));
}
Ok(())
+12 -13
View File
@@ -14,7 +14,7 @@ use gstreamer_rtsp_server::{
RTSP_PERM_MEDIA_FACTORY_ACCESS, RTSP_PERM_MEDIA_FACTORY_CONSTRUCT,
RTSP_TOKEN_MEDIA_FACTORY_ROLE,
};
use log::debug;
use log::*;
use std::collections::HashSet;
use std::fs;
use std::io;
@@ -45,7 +45,7 @@ impl RtspServer {
&self,
paths: &[&str],
stream_format: &StreamFormat,
permitted_users: &HashSet<String>,
permitted_users: &HashSet<&str>,
) -> Result<MaybeAppSrc> {
let mounts = self
.server
@@ -63,7 +63,7 @@ impl RtspServer {
debug!(
"Permitting {} to access {}",
// This is hashmap or (iter) equivalent of join, it requres itertools
permitted_users.iter().cloned().intersperse(", ".to_string()).collect::<String>(),
permitted_users.iter().cloned().intersperse(", ").collect::<String>(),
paths.join(", ")
);
self.add_permitted_roles(&factory, permitted_users);
@@ -107,10 +107,10 @@ impl RtspServer {
Ok(maybe_app_src)
}
pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &HashSet<String>) {
pub fn add_permitted_roles(&self, factory: &RTSPMediaFactory, permitted_roles: &HashSet<&str>) {
for permitted_role in permitted_roles {
factory.add_role_from_structure(&Structure::new(
permitted_role.as_str(),
permitted_role,
&[
(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true),
(*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true),
@@ -131,7 +131,7 @@ impl RtspServer {
// FYI: If no RTSP_PERM_MEDIA_FACTORY_ACCESS then server returns 404 not found
// If yes RTSP_PERM_MEDIA_FACTORY_ACCESS but no RTSP_PERM_MEDIA_FACTORY_CONSTRUCT
// server returns 401 not authourised
if !permitted_roles.contains(&"anonymous".to_string()) {
if !permitted_roles.contains(&"anonymous") {
factory.add_role_from_structure(&Structure::new(
"anonymous",
&[(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true)],
@@ -139,7 +139,7 @@ impl RtspServer {
}
}
pub fn set_credentials(&self, credentials: &Vec<Option<(&str, &str)>>) -> Result<()> {
pub fn set_credentials(&self, credentials: &[(&str, &str)]) -> Result<()> {
let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new());
auth.set_supported_methods(RTSPAuthMethod::Basic);
@@ -147,12 +147,11 @@ impl RtspServer {
auth.set_default_token(Some(&mut un_authtoken));
for credential in credentials {
if let Some((user, pass)) = credential {
debug!("Setting credentials for user {}", user);
let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]);
let basic = RTSPAuth::make_basic(user, pass);
auth.add_basic(basic.as_str(), &token);
}
let (user, pass) = credential;
trace!("Setting credentials for user {}", user);
let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, user)]);
let basic = RTSPAuth::make_basic(user, pass);
auth.add_basic(basic.as_str(), &token);
}
self.server.set_auth(Some(&auth));
+34 -59
View File
@@ -59,18 +59,20 @@ fn main() -> Result<(), Error> {
custom_format @ _ => StreamFormat::Custom(custom_format.to_string()),
};
// The substream always seems to be H264, even on B800 cameras
let substream_format = match &*camera.format {
"h264" | "H264" | "h265" | "H265" => StreamFormat::H264,
custom_format @ _ => StreamFormat::Custom(custom_format.to_string()),
};
let permitted_user = get_permitted_users(&config.users, &camera.permitted_users);
// Let subthreads share the camera object; in principle I think they could share
// the object as it sits in the config.cameras block, but I have not figured out the
// syntax for that.
let arc_cam = Arc::new(camera);
// The substream always seems to be H264, even on B800 cameras
let substream_format = match &*arc_cam.format {
"h264" | "H264" | "h265" | "H265" => StreamFormat::H264,
custom_format @ _ => StreamFormat::Custom(custom_format.to_string()),
};
let permitted_users = get_permitted_users(
config.users.as_slice(),
&arc_cam.permitted_users);
// Set up each main and substream according to all the RTSP mount paths we support
if ["both", "mainStream"].iter().any(|&e| e == arc_cam.stream) {
let paths = &[
@@ -78,7 +80,7 @@ fn main() -> Result<(), Error> {
&*format!("/{}/mainStream", arc_cam.name),
];
let mut output = rtsp
.add_stream(paths, &stream_format, &permitted_user)
.add_stream(paths, &stream_format, &permitted_users)
.unwrap();
let main_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut output));
@@ -86,7 +88,7 @@ fn main() -> Result<(), Error> {
if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) {
let paths = &[&*format!("/{}/subStream", arc_cam.name)];
let mut output = rtsp
.add_stream(paths, &substream_format, &permitted_user)
.add_stream(paths, &substream_format, &permitted_users)
.unwrap();
let sub_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut output));
@@ -155,61 +157,34 @@ fn set_up_tls(config: &Config, rtsp: &RtspServer) {
}
}
fn set_up_users(users: &Vec<UserConfig>, rtsp: &RtspServer) {
fn set_up_users(users: &[UserConfig], rtsp: &RtspServer) {
// Setting up users
let mut credentials = vec![];
for user in users {
let name = &user.name;
let pass = &user.pass;
let user_pass = match (name, pass) {
(Some(name), Some(pass)) => Some((&name as &str, &pass as &str)),
(Some(_), None) | (None, Some(_)) => {
warn!("Username and password must be supplied together - ignoring [[users]] entry");
None
}
_ => None,
};
credentials.push(user_pass);
}
rtsp.set_credentials(&credentials)
.expect("Failed to set up users.");
let credentials: Vec<_> = users.iter().map(|user| (&*user.name, &*user.pass)).collect();
rtsp.set_credentials(&credentials).expect("Failed to set up users");
}
fn get_permitted_users(
users: &Vec<UserConfig>,
permitted_users: &Option<Vec<String>>,
) -> HashSet<String> {
let current_permitted_users = match permitted_users {
Some(permitted_users) => permitted_users.clone().to_owned(),
None => {
// If None then the users didn't specify permitted_users
// In this case we do either
// - Any authourised user if [[users]] was specified
// - Any connecting user if [[users]] was not added
if users.len() > 0 {
vec!("anyone".to_string())
} else {
vec!("anonymous".to_string())
}
}
fn get_permitted_users<'a>(
users: &'a [UserConfig],
// not idiomatic as a function argument, but this fn translates the config struct directly:
permitted_users: &'a Option<Vec<String>>,
) -> HashSet<&'a str> {
// Helper to build hashset of all users in `users`:
let all_users_hash = || {
users.iter().map(|u| u.name.as_str()).collect()
};
// This is required to handle the special case of "anyone"
// ===Special set up of "anyone"===
// If in the camera config there is the user "anyone"
// Then we add all users to the cameras config. including unauth
let mut new_permitted_users = HashSet::new();
if current_permitted_users.contains(&"anyone".to_string()) {
for credentials in users {
if let Some(user) = &credentials.name {
new_permitted_users.insert(user.to_string());
}
}
} else {
for user in current_permitted_users {
new_permitted_users.insert(user.to_string());
}
match permitted_users {
// If in the camera config there is the user "anyone", or if none is specified but users
// are defined at all, then we add all users to the camera's allowed list.
Some(p) if p.iter().any(|u| u == "anyone") => all_users_hash(),
None if !users.is_empty() => all_users_hash(),
// The user specified permitted_users
Some(p) => p.iter().map(String::as_str).collect(),
// The user didn't specify permitted_users, and there are none defined anyway
None => ["anonymous"].iter().cloned().collect(),
}
new_permitted_users
}
fn camera_main(