Merge branch 'MultipleUsers' back into srtp

This commit is contained in:
QuantumEntangledAndy committed 2020-07-03 14:26:46 +07:00
commit 1fbe7e6122
4 files changed
+109 -58

No files matched your search

+10 -1
View File
@@ -75,7 +75,16 @@ You can modify this by changing the `bind` and the `bind_port` parameter.
Use can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the config. This pem should contain by the certificate and the key used for the server. If TLS is enabled all connections must use `rtsps`. You can also control client side TLS with the config option `tls_client_auth = "none|request|require"`, in this case the client should present a certificate signed by the server's CA, this is disabled by default.
Use can enable basic authentication by adding the configuration option `username = "someone"` and `password = "somepass"`. Both username and password must be set for this to work.
Use can enable basic authentication by adding users to the configuration file as:
```
[[users]]
name: someone
pass: somepass
```
you also need to add the allowed users into each camera by adding the following to `[[cameras]]`.
```
permitted_users = ["someone", "someoneelse"]
```
You can change the Neolink log level by setting the `RUST_LOG` environment variable (not in the configuration file) to one of `error`, `warn`, `info`, `debug`, or `trace`:
+19 -12
View File
@@ -26,15 +26,12 @@ pub struct Config {
#[serde(default = "default_certificate")]
pub certificate: Option<String>,
#[serde(default = "default_username")]
pub username: Option<String>,
#[serde(default = "default_password")]
pub password: Option<String>,
#[validate(regex(path = "RE_TLS_CLIENT_AUTH", message = "Incorrect stream format", code = "format"))]
#[serde(default = "default_tls_client_auth")]
pub tls_client_auth: String,
#[validate]
pub users: Vec<UserConfig>,
}
#[derive(Debug, Deserialize, Validate, Clone)]
@@ -56,6 +53,20 @@ pub struct CameraConfig {
#[validate(regex(path = "RE_STREAM_SRC", message = "Incorrect stream source", code = "stream"))]
#[serde(default = "default_stream")]
pub stream: String,
#[serde(default = "default_permitted_users")]
pub permitted_users: Vec<String>,
}
#[derive(Debug, Deserialize, Validate, Clone)]
pub struct UserConfig {
#[validate(required)]
#[serde(alias = "username")]
pub name: Option<String>,
#[validate(required)]
#[serde(alias = "password")]
pub pass: Option<String>,
}
fn default_bind_addr() -> String {
@@ -82,10 +93,6 @@ fn default_tls_client_auth() -> String {
"none".to_string()
}
fn default_username() -> Option<String> {
None
}
fn default_password() -> Option<String> {
None
fn default_permitted_users() -> Vec<String> {
vec!["anyone".to_string()]
}
+24 -24
View File
@@ -35,7 +35,7 @@ impl RtspServer {
}
}
pub fn add_stream(&self, names: &[&str], stream_format: &StreamFormat) -> Result<MaybeAppSrc> {
pub fn add_stream(&self, names: &[&str], stream_format: &StreamFormat, permitted_users: &Vec<String>) -> Result<MaybeAppSrc> {
let mounts = self
.server
.get_mount_points()
@@ -49,15 +49,17 @@ impl RtspServer {
let factory = RTSPMediaFactory::new();
factory.add_role_from_structure(
&Structure::new(
"watcher",
&[
(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true),
(*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true),
]
)
);
for permitted_user in permitted_users {
factory.add_role_from_structure(
&Structure::new(
&permitted_user,
&[
(*RTSP_PERM_MEDIA_FACTORY_ACCESS, &true),
(*RTSP_PERM_MEDIA_FACTORY_CONSTRUCT, &true),
]
)
);
}
//factory.set_protocols(RTSPLowerTrans::TCP);
factory.set_launch(&format!("{}{}{}{}",
@@ -98,24 +100,22 @@ impl RtspServer {
Ok(maybe_app_src)
}
pub fn set_credentials(&self, user_pass: Option<(&str, &str)>) -> Result<()> {
pub fn set_credentials(&self, credentials :&Vec<Option<(&str, &str)>>) -> Result<()> {
let auth = self.server.get_auth().unwrap_or_else(|| RTSPAuth::new());
if let Some((user, pass)) = user_pass {
debug!("Setting credentials for user {}", user);
debug!("Password is {}", pass);
let token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]);
let basic = RTSPAuth::make_basic(user, pass);
auth.set_supported_methods(RTSPAuthMethod::Basic);
auth.add_basic(basic.as_str(), &token);
auth.set_supported_methods(RTSPAuthMethod::Basic);
// Now we have basic auth we stop others from watching
let mut token = RTSPToken::new_empty();
auth.set_default_token(Some(&mut token));
} else {
let mut token = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"watcher")]);
auth.set_default_token(Some(&mut token)); //By default anyone can watch if we don't turn on basic
for credential in credentials {
if let Some((user, pass)) = credential {
debug!("Setting credentials for user {}", user);
debug!("Password is {}", pass);
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 mut un_authtoken = RTSPToken::new(&[(*RTSP_TOKEN_MEDIA_FACTORY_ROLE, &"unauth")]);
auth.set_default_token(Some(&mut un_authtoken));
self.server.set_auth(Some(&auth));
Ok(())
+56 -21
View File
@@ -19,7 +19,7 @@ mod cmdline;
mod config;
use cmdline::Opt;
use config::{CameraConfig, Config};
use config::{UserConfig, CameraConfig, Config};
#[derive(Debug, Error)]
pub enum Error {
@@ -52,25 +52,9 @@ fn main() -> Result<(), Error> {
let rtsp = &RtspServer::new();
let tls_client_auth = match &config.tls_client_auth as &str {
"request" => TlsAuthenticationMode::Requested,
"require" => TlsAuthenticationMode::Required,
"none" => TlsAuthenticationMode::None,
_ => unreachable!(),
};
if let Some(cert_path) = &config.certificate {
rtsp.set_tls(&cert_path, tls_client_auth).expect("Failed to set up TLS");
}
let name = &config.username;
let pass = &config.password;
let user_pass = match (name, pass) {
(Some(name), Some(pass)) => Some((&name as &str, &pass as &str)),
_ => None,
};
rtsp.set_credentials(user_pass).expect("Failed to set up users.");
set_up_tls(&config, &rtsp);
set_up_users(&config.users, &rtsp);
crossbeam::scope(|s| {
for camera in config.cameras {
@@ -79,6 +63,7 @@ fn main() -> Result<(), Error> {
"h265"|"H265" => StreamFormat::H265,
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
@@ -91,13 +76,13 @@ fn main() -> Result<(), Error> {
&arc_cam.name,
&*format!("{}/mainStream", arc_cam.name),
];
let mut output = rtsp.add_stream(paths, &stream_format).unwrap();
let mut output = rtsp.add_stream(paths, &stream_format, &permitted_user).unwrap();
let main_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*main_camera, &mut output));
}
if arc_cam.stream == "both" || arc_cam.stream == "subStream" {
let paths = &[&*format!("{}/subStream", arc_cam.name)];
let mut output = rtsp.add_stream(paths, &stream_format).unwrap();
let mut output = rtsp.add_stream(paths, &stream_format, &permitted_user).unwrap();
let sub_camera = arc_cam.clone();
s.spawn(move |_| camera_loop(&*sub_camera, &mut output));
}
@@ -148,6 +133,56 @@ struct CameraErr {
err: neolink::Error,
}
fn set_up_tls(config: &Config, rtsp: &RtspServer) {
let tls_client_auth = match &config.tls_client_auth as &str {
"request" => TlsAuthenticationMode::Requested,
"require" => TlsAuthenticationMode::Required,
"none" => TlsAuthenticationMode::None,
_ => unreachable!(),
};
if let Some(cert_path) = &config.certificate {
rtsp.set_tls(&cert_path, tls_client_auth).expect("Failed to set up TLS");
}
}
fn set_up_users(users: &Vec<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)),
_ => None,
};
credentials.push(user_pass);
}
rtsp.set_credentials(&credentials).expect("Failed to set up users.");
}
fn get_permitted_users(users: &Vec<UserConfig>, current_permitted_users: &Vec<String>) -> Vec<String> {
// 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 = vec![];
if current_permitted_users.contains(&"anyone".to_string()) {
for credentials in users {
if let Some(user) = &credentials.name {
new_permitted_users.push(user.to_string());
}
}
new_permitted_users.push("unauth".to_string());
} else {
new_permitted_users.append(&mut current_permitted_users.clone());
}
// We also drop duplicated user names
new_permitted_users.sort();
new_permitted_users.dedup();
new_permitted_users
}
fn camera_main(camera_config: &CameraConfig, output: &mut dyn Write) -> Result<Never, CameraErr> {
let mut connected = false;
(|| {