Apply suggestions from code review

This commit is contained in:
Andrew King authored and GitHub committed 2021-09-08 16:29:03 +07:00
1 parent 79e012647a
commit a301944298
6 files changed
+51 -7

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@ impl BcCamera {
///
/// # Parameters
///
/// * `host` - The address of the camera either ip address, hostname string
/// * `host` - The address of the camera either ip address or hostname string
///
/// * `channel_id` - The channel ID this is usually zero unless using a NVR
///
@@ -15,6 +15,7 @@ pub struct UdpDiscover {
}
impl UdpDiscover {
// Sends data on a UDP socket until aborted or max retries reached
fn retrying_send_to<T: ToSocketAddrs>(
socket: &UdpSocket,
buf: &[u8],
@@ -27,6 +28,8 @@ impl UdpDiscover {
Self::retrying_send_to_multi(socket, buf, &[addr])
}
// Sends data to multiple destinations using a UDP socket
// until aborted or max retries reached
fn retrying_send_to_multi<T: ToSocketAddrs>(
socket: &UdpSocket,
buf: &[u8],
@@ -72,6 +75,11 @@ impl UdpDiscover {
Ok((bytes_send, handle))
}
// Performs local discovery
//
// This involves broadcasting a C2dC
// Bc Discovery packet to ports 2015 and 2018
// and awaiting a D2cCr reply
fn discover_from_uuid_local(socket: &UdpSocket, uid: &str, timeout: Duration) -> Result<Self> {
let mut rng = thread_rng();
// If tid is too large it will overflow during encrypt so we just use a random u8
@@ -171,6 +179,12 @@ impl UdpDiscover {
})
}
// This function will contact the p2p relay servers
//
// It will ask each of the servers for details on a specific UID
//
// On success it returns the M2cQr that the p2p relay
// server has about the UID
fn get_register(
uid: &str,
socket: &UdpSocket,
@@ -218,6 +232,9 @@ impl UdpDiscover {
},
})) if m2c_q_r.reg.port == 0 || m2c_q_r.reg.ip.is_empty() => {
// This register is empty
// Sometimes a registery will return a M2cQr but it's port and addr
// will be 0
// In this case we ignore this server and contact another
abort.abort();
break;
}
@@ -250,6 +267,16 @@ impl UdpDiscover {
Err(Error::ConnectionUnavaliable)
}
// This will start remote discovery against the reolink p2p servers
//
// It has the following stages
// - Contact the p2p register: This will get the register, relay and log server ip addresses
// - Register the client ip address to the register (This can probably be used for NAT holepunching if the camera
// tries to connect to us using this data, currently we don't register a real address though, just `0.0.0.0`)
// - The register will return the camera ip/port and SID
// - Connect to the camera using register's provided ip/port and negotiate a cid and did
// - Send a message to the reolink log server that we will connect locally
// - Send a message to the camera that we could connect remotely
fn discover_from_uuid_remote(
socket: &UdpSocket,
uid: &str,
@@ -97,6 +97,7 @@ impl ClientSent {
// }
// }
// This function translates the `UdpAck` payload directly
fn acknoledge_from_ack_data(&self, start: u32, payload: Vec<u8>) {
let mut locked = self.buffer.lock().unwrap();
locked.retain(|&k, _| k > start);
@@ -174,6 +175,7 @@ impl ClientRecieved {
let _ = locked.entry(packet_id).or_insert(payload);
}
// This gets the needed payload to form a `UdpAck` packet
fn get_needed_packets(&self) -> Option<(u32, Vec<u8>)> {
let locked = self.buffer.lock().unwrap();
let packet_id_loc = self.consumed.lock().unwrap();
@@ -190,6 +192,9 @@ impl ClientRecieved {
// Find last packet in buffer
let vec = if let Some(end) = locked.keys().max() {
let mut vec = vec![];
// From last contiguous packet to last recieved packet
// create a payload of `00` (unreceived) and `01` (received)
// that can be used to form the `UdpAck` packet
for i in (start + 1)..(end + 1) {
if locked.contains_key(&i) {
vec.push(1)
@@ -236,6 +241,7 @@ impl UdpTransmit {
}) if cid == discovery_result.client_id
&& did == discovery_result.camera_id =>
{
// Camera sent a disconnect
// Reply with C2D_Disc and end
discovery_result.send_client_disconnect(socket);
return Err(TransmitError::Disc);
@@ -259,7 +265,6 @@ impl UdpTransmit {
packet_id,
payload,
}) if cid == discovery_result.client_id => {
// Seperated as let/if due to clippy recommend
trace!("Recieving UdpData packet {}", packet_id);
self.client_recieved.receive(packet_id, payload);
+1 -1
View File
@@ -142,7 +142,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> {
let (buf, payload) = if payload_size > 0 {
let (buf, t_payload) = take!(buf, payload_size)?; // It is a binary payload of
// `00 01 01 01 01 00 01`
// Probably a truth map of missing packets
// This is a truth map of missing packets
// since last contigious packet_id up
// to the last packet we sent and it recieved
(buf, t_payload.to_vec())
+15 -3
View File
@@ -46,7 +46,7 @@ of `0x00000000` and an xorout of `0x00000000`.
## Payload
- The XML payloads and encrypted with a simple xor algorithm. See the full
- The XML payloads are encrypted with a simple xor algorithm. See the full
source in neolink for details.
## Start Discovery payload
@@ -172,6 +172,16 @@ Client then replies with this.
Camera replies with this payload on the port specified in `C2D_C`
```xml
<P2P>
<D2C_T>
<sid>62097899</sid>
<conn>local</conn>
<cid>82000</cid>
<did>528</did>
</D2C_T>
</P2P>
```
**Login**
The client can now login over UDP
@@ -221,7 +231,7 @@ Some cameras seem to also send this before login
# UDP Ack
These messages are sent to acknowledge receipt of message. They are header only.
These messages are sent to acknowledge receipt of message
## Header 28 Bytes
@@ -236,7 +246,9 @@ These messages are sent to acknowledge receipt of message. They are header only.
**To Investigate:**
- Why does the unknown byte change. It starts at zero and remains that way
for a second. Then seems to change and remain at the new value for another second
for a second. Then seems to change and remain at the new value for another second.
This may be some metric such as average ttl for the last second, or some calculation
of the jitter
Here's an example of a UDP Ack payload (size 203 bytes)
+1 -1
View File
@@ -23,7 +23,7 @@ impl AddressOrUid {
pub(crate) fn new(address: &Option<String>, uid: &Option<String>) -> Result<Self, Error> {
match (address, uid) {
(None, None) => Err(anyhow!("Neither address or uid given")),
(Some(_), Some(_)) => Err(anyhow!("Either address of uid should be given not both")),
(Some(_), Some(_)) => Err(anyhow!("Either address or uid should be given not both")),
(Some(host), None) => Ok(AddressOrUid::Address(host.clone())),
(None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())),
}