From e82f70405e12ad93ec326986570fd408897c3313 Mon Sep 17 00:00:00 2001 From: Matthias Liffers Date: Sun, 20 Jun 2021 11:40:56 +0800 Subject: [PATCH 01/56] Add example docker-compose config --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index c583f7a..af071c5 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,22 @@ docker run \ thirtythreeforty/neolink ``` +Here is an example docker-compose: + +``` +--- +version: "2" +services: + neolink: + image: thirtythreeforty/neolink + container_name: neolink + ports: + - 8554:8554 + volumes: + - $PWD/neolink.toml:/etc/neolink.toml + restart: unless-stopped +``` + The Docker image is "best effort" and intended for advanced users; questions about running Docker are outside the scope of Neolink. From e89aca4a31199c8a6bf71a6e450ce5f121be8651 Mon Sep 17 00:00:00 2001 From: Matthias Liffers Date: Mon, 21 Jun 2021 09:02:23 +0800 Subject: [PATCH 02/56] Add yml syntax highlight to docker-compose example Signed-off-by: Matthias Liffers --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af071c5..e29c4dc 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ docker run \ Here is an example docker-compose: -``` +```yml --- version: "2" services: From b7b36bb525b97619580641d57ea9050918176e2a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 19 Apr 2021 14:02:20 +0700 Subject: [PATCH 03/56] Updates to protocol and message documentation --- dissector/messages.md | 305 ++++++++++++++++++++++-------------------- dissector/protocol.md | 105 ++++++++++----- 2 files changed, 230 insertions(+), 180 deletions(-) diff --git a/dissector/messages.md b/dissector/messages.md index bddf73d..a2f2a8f 100644 --- a/dissector/messages.md +++ b/dissector/messages.md @@ -5,6 +5,17 @@ This is an attempt to document the BC messages. It is subject to change and some aspects of it may not be correct. Please feel free to submit a PR to improve it. +Message have zero to two payloads. +- The first payload is after the header and before the payload offset + - This payload always contains Extension xml and so is called `Extension` + in this doc +- The second payload is after the payload offset + - This is either Body xml or binary data. + - If it is binary the extension xml will contain the `1` + tag + - This is called `Payload` in this doc + + - 1: Login Legacy - Client @@ -15,7 +26,7 @@ a PR to improve it. |--------------|--------------|----------------|-------------------|---------|---------|---------------| | f0 de bc 0a | 01 00 00 00 | 2c 07 00 00 | 00 00 00 01 | 01 | dc | 14 65 | - - Body + - Payload Body is hash of user 32 bytes and password 32 bytes and then a lot of zero pads @@ -33,7 +44,7 @@ a PR to improve it. |--------------|--------------|----------------|-------------------|---------|---------|---------------| | f0 de bc 0a | 01 00 00 00 | 91 00 00 00 | 00 00 00 01 | 01 | dd | 14 66 | - - Body + - Payload ```xml @@ -55,11 +66,11 @@ a PR to improve it. - Client - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | f0 de bc 0a | 01 00 00 00 | 28 01 00 00 | 00 00 00 01 | 00 00 | 14 64 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -80,11 +91,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | f0 de bc 0a | 01 00 00 00 | 2e 06 00 00 | 00 00 00 01 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -155,7 +166,13 @@ a PR to improve it. - Client - - Binary + - Header + + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | + |--------------|--------------|----------------|-------------------|-------------------|---------------|----------------| + | f0 de bc 0a | 02 00 00 00 | af 00 00 00 | 00 00 00 09 | 00 00 | 14 64 | 00 00 00 00 | + + - Payload ```xml @@ -174,11 +191,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | f0 de bc 0a | 03 00 00 00 | aa 00 00 00 | 00 00 00 09 | 00 00 | 14 64 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -197,11 +214,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | f0 de bc 0a | 03 00 00 00 | 8a 00 00 00 | 00 00 00 09 | c8 00 | 00 00 | 6a 00 00 00 | - - Body + - Extension ```xml @@ -210,7 +227,7 @@ a PR to improve it. ``` - - Binary + - Payload ```hex 31303032200000000009000010050000000F780A06122422780A061224220000 @@ -223,14 +240,14 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | f0 de bc 0a | 03 00 00 00 | e8 5e 00 00 | 00 00 00 09 | c8 00 | 00 00 | 00 00 00 00 | - - Body + - Payload Body is binary. This binary represents an embedded stream which should - be detailed elsewhere. + is detailed in [mediapacket.md](dissector/mediapacket.md). - 4: `` (stop) @@ -238,11 +255,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 04 | 00 00 00 86 | 2b 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -258,7 +275,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 04 | 00 00 00 00 | 2b 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -268,11 +285,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 0a | 00 00 00 68 | 0b 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -285,11 +302,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 0a | 00 00 01 f7 | 0b 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -321,11 +338,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 12 | 00 00 00 a4 | 1e 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -342,7 +359,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 12 | 00 00 00 00 | 1e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -352,11 +369,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 19 | 00 00 05 c2 | 64 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -365,7 +382,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -453,7 +470,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 19 | 00 00 00 00 | 64 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -464,11 +481,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 1a | 00 00 00 68 | 2d 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -481,11 +498,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 1a | 00 00 05 7c | 2d 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -576,7 +593,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 1f | 00 00 00 00 | 05 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -584,12 +601,12 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 1f | 00 00 00 00 | 05 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - **Notes:** The camera will not send message 33 to the client until - after this msg has been recieved + - **Notes:** Some cameras will not send message 33 to the client until + after this msg has been received - 33: `` @@ -597,11 +614,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 21 | 00 00 00 f0 | 05 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -623,11 +640,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 2c | 00 00 00 68 | 30 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -640,11 +657,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 2c | 00 00 01 df | 30 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -676,11 +693,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 2d | 00 00 02 23 | 32 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -689,7 +706,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -717,7 +734,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 2d | 00 00 00 00 | 32 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -727,11 +744,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 34 | 00 00 00 68 | 36 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -744,11 +761,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 34 | 00 00 00 96 | 36 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -767,11 +784,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 35 | 00 00 01 d7 | 38 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -780,7 +797,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -814,7 +831,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 35 | 00 00 00 00 | 38 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -824,11 +841,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 36 | 00 00 00 68 | 14 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -841,11 +858,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 36 | 00 00 00 ed | 14 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -866,11 +883,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 37 | 00 00 01 3b | 16 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -879,7 +896,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -897,7 +914,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 37 | 00 00 00 00 | 16 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -907,11 +924,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 38 | 00 00 00 68 | 1d 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -924,11 +941,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 38 | 00 00 03 61 | 1d 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -976,11 +993,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 39 | 00 00 02 bc | 1f 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -989,7 +1006,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -1024,7 +1041,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 39 | 00 00 00 00 | 1f 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -1034,11 +1051,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 3a | 00 00 00 6b | 03 00 00 00 | 00 00 | 64 14 | 00 00 00 6b | - - Body + - Extension ```xml @@ -1051,11 +1068,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 3a | 00 00 03 a4 | 03 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1117,11 +1134,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 43 | 00 00 01 00 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | - - Body + - Extension ```xml @@ -1140,7 +1157,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -1148,11 +1165,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 43 | 00 00 94 58 | 00 00 00 00 | 00 00 | 64 14 | 00 00 00 6a | - - Body + - Extension ```xml @@ -1161,7 +1178,7 @@ a PR to improve it. ``` - - Binary + - Payload This contains binary data of the file but stops once the message size reaches 38000 bytes and continues in another packet. There does not appear to @@ -1171,7 +1188,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 43 | 00 00 00 00 | 00 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -1183,7 +1200,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 4c | 00 00 00 00 | 22 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1191,11 +1208,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 4c | 00 00 01 69 | 22 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1225,11 +1242,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 4d | 00 00 01 5b | 25 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1257,7 +1274,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 4d | 00 00 00 00 | 14 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -1267,11 +1284,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 4e | 00 00 00 d3 | 1b 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1292,11 +1309,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 4f | 00 00 01 3b | 1b 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1320,7 +1337,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 50 | 00 00 00 00 | 08 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1328,11 +1345,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 50 | 00 00 01 f0 | 08 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1359,11 +1376,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 51 | 00 00 00 68 | 19 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -1376,11 +1393,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 51 | 00 00 04 30 | 19 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1447,11 +1464,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 52 | 00 00 05 da | 1a 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -1460,7 +1477,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -1542,7 +1559,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 52 | 00 00 00 00 | 1a 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -1552,7 +1569,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 5d | 00 00 00 00 | 17 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1562,7 +1579,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 66 | 00 00 00 00 | 07 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1570,11 +1587,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 66 | 00 00 00 55 | 07 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1589,7 +1606,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 68 | 00 00 00 00 | 0a 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1597,11 +1614,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 68 | 00 00 01 a5 | 0a 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1632,7 +1649,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 73 | 00 00 00 00 | 0c 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1640,11 +1657,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 73 | 00 00 00 75 | 0c 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1661,11 +1678,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 84 | 00 00 00 68 | 65 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -1678,11 +1695,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 84 | 00 00 05 7c | 65 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1773,7 +1790,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 85 | 00 00 00 00 | 06 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1781,11 +1798,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 85 | 00 00 00 7f | 06 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1803,7 +1820,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 92 | 00 00 00 00 | 04 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1811,11 +1828,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 92 | 00 00 02 fc | 04 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1856,11 +1873,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 97 | 00 00 00 a7 | 02 00 00 00 | 00 00 | 64 14 | 00 00 00 a7 | - - Body + - Extension ```xml @@ -1874,11 +1891,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 97 | 00 00 03 ac | 02 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1923,11 +1940,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 be | 00 00 00 68 | 0d 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -1940,11 +1957,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 be | 00 00 00 86 | 0d 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -1962,7 +1979,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 c0 | 00 00 00 00 | 05 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1970,7 +1987,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 c0 | 00 00 00 00 | 05 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | @@ -1980,7 +1997,7 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 c7 | 00 00 00 00 | 02 00 00 00 | 00 00 | 64 14 | 00 00 00 00 | @@ -1988,11 +2005,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 c7 | 00 00 05 f6 | 02 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -2074,11 +2091,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 d0 | 00 00 00 68 | 2e 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -2091,11 +2108,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 d0 | 00 00 00 c2 | 2e 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | - - Binary + - Payload ```xml @@ -2115,11 +2132,11 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 d1 | 00 00 01 10 | 85 00 00 00 | 00 00 | 64 14 | 00 00 00 68 | - - Body + - Extension ```xml @@ -2128,7 +2145,7 @@ a PR to improve it. ``` - - Binary + - Payload ```xml @@ -2145,6 +2162,6 @@ a PR to improve it. - Header - | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | + | Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | |--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| | 0a bc de f0 | 00 00 00 d1 | 00 00 00 00 | 85 00 00 00 | c8 00 | 00 00 | 00 00 00 00 | diff --git a/dissector/protocol.md b/dissector/protocol.md index 55552f1..058b419 100644 --- a/dissector/protocol.md +++ b/dissector/protocol.md @@ -16,9 +16,9 @@ Each message has the general format: The header has the format: -| magic | message id | message length | encryption offset | encrypt | unknown | message class | -|--------------|--------------|----------------|-------------------|---------|---------|---------------| -| f0 de bc 0a | 01 00 00 00 | 2c 07 00 00 | 00 00 00 01 | 01 | dc | 14 65 | +| magic | message id | message length | encryption offset | encrypt | message class | +|--------------|--------------|----------------|-------------------|------------|---------------| +| f0 de bc 0a | 01 00 00 00 | 2c 07 00 00 | 00 00 00 01 | 01 dc | 14 65 | - Magic 4 bytes - ID 4 bytes @@ -30,9 +30,9 @@ The header has the format: Or -| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | -|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| -| f0 de bc 0a | 01 00 00 00 | 28 01 00 00 | 00 00 00 01 | c8 00 | 14 64 | 00 00 00 00 | +| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | +|--------------|--------------|----------------|-------------------|-------------------|---------------|----------------| +| f0 de bc 0a | 01 00 00 00 | 28 01 00 00 | 00 00 00 01 | c8 00 | 14 64 | 00 00 00 00 | - Magic 4 bytes @@ -97,17 +97,24 @@ message_handle 1 byte - client increments per request, replies use request handl #### Encryption Flag -This flag is 0 for unencrypted or non zero for encrypted. +Client will send the number `0xXXdc` and the server will reply `0xXXdd`. +Where `XX` is one of the following. -Clients should decide to use encryption or not based on this byte that the -camera sent during login. Then should use that same setting for all further -messages with the camera. +- 0 Unencrypted +- 1 BC Encryption +- 2 AES Encryption (Camera) +- 3 AES Encryption (Client) -#### Unknown +`dc` means this encryption protol or lower. So `0x01dc` means BC on no encryption +whereas `0x03dc` means AES, BC or Unencrypted. -The purpose of this byte is unknown. -Observed - `dc` = client request, `dd` = device reply -If you figure out what it does please submit a PR. +`dd` is the reply that the camera sends to the `dc` request. It is the chosen +protocol that will be used. + +**Note:** When requesting AES the client sends `0x03dc` and the camera replies `0x02dc`. +We are not sure why. + +Encryption is negotiated in the login request. #### Status Code @@ -129,20 +136,13 @@ and header lengths are known. - 0x0000: "modern" 24 bytes -#### Binary offset +#### Payload offset -For messages that contain the binary offset field this represents where to start -the binary part of the message. The total length of XML + binary is equal -to the message length in the header so Binary Offset is -total_length - this_offset. Where as this field also represents the end of the -XML part of the message. - -Some messages seems to not set this field correctly. For example message ID 1 -sets this to zero meaning that all data in the message is binary, however -it contains XML. This best way to tell is this is binary or XML is to check the -message ID and determine from there. Alternatively you could look for ` @@ -203,7 +205,7 @@ The reply is first a message with the following xml After which all message bodies of type id 3 are binary. -The binary represents a stream of data. It can be interrupted by packet +The binary represents a stream of data that can be interrupted by packet boundaries. Clients should create a buffer and pop bytes for processing when complete media packets are received. Media packets descriptions can be found in the [docs](dissector/mediapacket.md) @@ -213,9 +215,9 @@ the [docs](dissector/mediapacket.md) Other data can be received from the camera by sending the appropriate header to the camera. For example sending the header for ID 78 -| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | -|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| -| f0 de bc 0a | 4e 00 00 00 | d3 00 00 00 | 08 db 9c 00 | c8 00 | 00 00 | 00 00 00 00 | +| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | +|--------------|--------------|----------------|-------------------|-------------------|---------------|----------------| +| f0 de bc 0a | 4e 00 00 00 | d3 00 00 00 | 08 db 9c 00 | c8 00 | 00 00 | 00 00 00 00 | The camera will reply with an xml with brightness and contrast @@ -236,9 +238,9 @@ Some message IDs also require input along with the request header. For example ID 151 which is the users ability info requires the header -| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Binary Offset | -|--------------|--------------|----------------|-------------------|-------------------|---------------|---------------| -| f0 de bc 0a | 97 00 00 00 | a7 00 00 00 | 00 00 00 02 | 00 00 | 14 64 | a7 00 00 00 | +| Magic | Message ID | Message Length | Encryption Offset | Status Code | Message Class | Payload Offset | +|--------------|--------------|----------------|-------------------|-------------------|---------------|----------------| +| f0 de bc 0a | 97 00 00 00 | a7 00 00 00 | 00 00 00 02 | 00 00 | 14 64 | a7 00 00 00 | and the body of @@ -255,3 +257,34 @@ abilities you want to know about. Details of expected formats should be found from the [docs](dissector/messages.md) + +#### AES Encryption + +If the encryption flag returned from the camera is `0x02dd` then AES encryption will be used. + +The cameras use AES cfb128 with an IV of `0123456789abcdef` the key is made as follows + +- Concatenated the `NONCE` from login with a `-` then with your plain text password +- MD5 Hash this concatenated string +- Represent the hash as hex string in all caps +- Take the first 16 characters as the encryption key + + +Here is an example: + +```rust +use aes::Aes128; +use cfb_mode::cipher::{NewStreamCipher, StreamCipher}; +use cfb_mode::Cfb; + +const IV: &[u8] = b"0123456789abcdef"; +let key_phrase = format!("{}-{}", nonce, passwd); +let key_phrase_hash = format!("{:X}\0", md5::compute(&key_phrase)) + .to_uppercase() + .into_bytes(); +let key = key_phrase_hash[0..16]; + +let mut decrypted = encrypted.to_vec(); +Cfb::::new(key.into(), IV.into()).decrypt(&mut decrypted); +return decrypted; +``` From 0dd2eb744d6a71241f5cbdbd00750e2afc833e7e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 18 Aug 2021 16:37:43 +0700 Subject: [PATCH 04/56] Allow missing subcommand line specification --- src/cmdline.rs | 9 ++++++--- src/main.rs | 22 +++++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/src/cmdline.rs b/src/cmdline.rs index 80a65a0..6136dce 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -1,11 +1,14 @@ -use structopt::StructOpt; +use std::path::PathBuf; +use structopt::{clap::AppSettings, StructOpt}; /// A standards-compliant bridge to Reolink IP cameras #[derive(StructOpt, Debug)] -#[structopt(name = "neolink")] +#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))] pub struct Opt { + #[structopt(short, long, parse(from_os_str))] + pub config: Option, #[structopt(subcommand)] - pub cmd: Command, + pub cmd: Option, } #[derive(StructOpt, Debug)] diff --git a/src/main.rs b/src/main.rs index 475475b..263bc38 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,17 +32,29 @@ fn main() -> Result<(), Error> { let opt = Opt::from_args(); - match opt.cmd { - Command::Rtsp(opts) => { + match (opt.cmd, opt.config) { + (None, None) => { + // Should be caught at the clap validation + unreachable!(); + } + (None, Some(config)) => { + warn!( + "Deprecated command line option. Please use: `neolink rtsp --config={:?}`", + config + ); + rtsp::main(rtsp::Opt { config })?; + } + (Some(_), Some(_)) => error!("--config should be given after the subcommand"), + (Some(Command::Rtsp(opts)), None) => { rtsp::main(opts)?; } - Command::StatusLight(opts) => { + (Some(Command::StatusLight(opts)), None) => { statusled::main(opts)?; } - Command::Reboot(opts) => { + (Some(Command::Reboot(opts)), None) => { reboot::main(opts)?; } - Command::Talk(opts) => { + (Some(Command::Talk(opts)), None) => { talk::main(opts)?; } } From 8f1c3ece9df6f0433bc6d34f056bfb9614e6aa3f Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 19 Aug 2021 10:00:12 +0700 Subject: [PATCH 05/56] Use anyhow for application level error --- Cargo.lock | 1 + Cargo.toml | 1 + src/errors.rs | 14 -------- src/main.rs | 5 ++- src/reboot/errors.rs | 20 ----------- src/reboot/mod.rs | 44 +++++++++++++++-------- src/rtsp/errors.rs | 23 ------------ src/rtsp/mod.rs | 76 ++++++++++++++++++++++++++-------------- src/statusled/cmdline.rs | 9 +++-- src/statusled/errors.rs | 24 ------------- src/statusled/mod.rs | 44 +++++++++++++++-------- src/talk/errors.rs | 42 ---------------------- src/talk/gst.rs | 41 ++++++++++++---------- src/talk/mod.rs | 64 +++++++++++++++++++++++---------- 14 files changed, 186 insertions(+), 222 deletions(-) delete mode 100644 src/errors.rs delete mode 100644 src/reboot/errors.rs delete mode 100644 src/rtsp/errors.rs delete mode 100644 src/statusled/errors.rs delete mode 100644 src/talk/errors.rs diff --git a/Cargo.lock b/Cargo.lock index 73f3d64..535f7ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -832,6 +832,7 @@ name = "neolink" version = "0.4.0" dependencies = [ "aes", + "anyhow", "byte-slice-cast", "cfb-mode", "cookie-factory", diff --git a/Cargo.toml b/Cargo.toml index 3a5d3de..3b2de33 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,3 +39,4 @@ xml-rs = "0.8" validator = "0.10" validator_derive = "0.10" byte-slice-cast = "1.0.0" +anyhow = "1.0.42" diff --git a/src/errors.rs b/src/errors.rs deleted file mode 100644 index 009115e..0000000 --- a/src/errors.rs +++ /dev/null @@ -1,14 +0,0 @@ -use err_derive::Error; - -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - #[error(display = "RTSP Error")] - Rtsp(#[error(source)] super::rtsp::Error), - #[error(display = "Status LED Error")] - StatusLight(#[error(source)] super::statusled::Error), - #[error(display = "Reboot Error")] - Reboot(#[error(source)] super::reboot::Error), - #[error(display = "Talk Error")] - Talk(#[error(source)] super::talk::Error), -} diff --git a/src/main.rs b/src/main.rs index 263bc38..64f1f63 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,21 +7,20 @@ //! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras //! that do not nativly support RTSP. //! +use anyhow::Result; use env_logger::Env; use log::*; use structopt::StructOpt; mod cmdline; -mod errors; mod reboot; mod rtsp; mod statusled; mod talk; use cmdline::{Command, Opt}; -use errors::Error; -fn main() -> Result<(), Error> { +fn main() -> Result<()> { env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); info!( diff --git a/src/reboot/errors.rs b/src/reboot/errors.rs deleted file mode 100644 index f973118..0000000 --- a/src/reboot/errors.rs +++ /dev/null @@ -1,20 +0,0 @@ -use err_derive::Error; - -/// The main error for the reboot subcommand -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - /// Raised when the config file fails to deserlize - #[error(display = "Configuration parsing error")] - Config(#[error(source)] toml::de::Error), - /// Raised when `neolink_core` raises an error - #[error(display = "Communication error")] - Protocol(#[error(source)] neolink_core::Error), - /// Raised when there is an IO error such as unable to find - /// config file - #[error(display = "I/O error")] - Io(#[error(source)] std::io::Error), - /// Raised when the config file fails validataion - #[error(display = "Validation error")] - Validation(#[error(source)] validator::ValidationErrors), -} diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index 560c2b5..9219e45 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -11,6 +11,7 @@ /// neolink reboot --config=config.toml CameraName /// ``` /// +use anyhow::{anyhow, Context, Result}; use log::*; use neolink_core::bc_protocol::BcCamera; use std::fs; @@ -18,19 +19,23 @@ use validator::Validate; mod cmdline; mod config; -mod errors; pub(crate) use cmdline::Opt; use config::Config; -pub(crate) use errors::Error; /// Entry point for the reboot subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<(), Error> { - let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - config.validate()?; + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; let mut cam_found = false; for camera_config in &config.cameras { @@ -42,23 +47,34 @@ pub fn main(opt: Opt) -> Result<(), Error> { ); let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); - camera.login(&camera_config.username, camera_config.password.as_deref())?; + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; info!("{}: Connected and logged in", camera_config.name); - camera.reboot()?; + camera + .reboot() + .context("Could not send reboot command to the camera")?; } } if !cam_found { - error!( - "No camera with the name {} was found in the config", - opt.camera - ); + Err(anyhow!( + "Camera {} was not in the config file {:?}", + &opt.camera, + &opt.config + )) + } else { + Ok(()) } - - Ok(()) } diff --git a/src/rtsp/errors.rs b/src/rtsp/errors.rs deleted file mode 100644 index 19d0c68..0000000 --- a/src/rtsp/errors.rs +++ /dev/null @@ -1,23 +0,0 @@ -use err_derive::Error; - -/// The main error for the rtsp subcommand -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - /// Raised when the config file fails to deserlize - #[error(display = "Configuration parsing error")] - Config(#[error(source)] toml::de::Error), - /// Raised when `neolink_core` raises an error - #[error(display = "Communication error")] - Protocol(#[error(source)] neolink_core::Error), - /// Raised when there is an IO error such as unable to find - /// config file - #[error(display = "I/O error")] - Io(#[error(source)] std::io::Error), - /// Raised when the config file fails validataion - #[error(display = "Validation error")] - Validation(#[error(source)] validator::ValidationErrors), - // Raised when there is an ADPCM decoding error - // #[error(display = "ADPCM Decoding Error")] - // AdpcmDecoding(&'static str), -} diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 120b614..ca5a030 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -28,6 +28,7 @@ /// neolink rtsp --config=config.toml /// ``` /// +use anyhow::{Context, Result}; use log::*; use neolink_core::bc_protocol::BcCamera; use neolink_core::Never; @@ -42,21 +43,25 @@ use validator::Validate; mod cmdline; mod config; /// The errors this subcommand can raise -mod errors; mod gst; pub(crate) use cmdline::Opt; use config::{CameraConfig, Config, UserConfig}; -pub(crate) use errors::Error; use gst::{GstOutputs, RtspServer, TlsAuthenticationMode}; /// Entry point for the rtsp subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<(), Error> { - let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - config.validate()?; + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; let rtsp = &RtspServer::new(); @@ -118,7 +123,7 @@ fn camera_loop( stream_name: &str, outputs: &mut GstOutputs, manage: bool, -) -> Result { +) -> Result { let min_backoff = Duration::from_secs(1); let max_backoff = Duration::from_secs(15); let mut current_backoff = min_backoff; @@ -131,20 +136,19 @@ fn camera_loop( if cam_err.connected { current_backoff = min_backoff; } - match cam_err.err { - neolink_core::Error::AuthFailed => { - error!( - "Authentication failed to camera {}, not retrying", - camera_config.name - ); - return Err(cam_err.err.into()); - } - _ => error!( + if cam_err.login_fail { + error!( + "Authentication failed to camera {}, not retrying", + camera_config.name + ); + return Err(cam_err.err); + } else { + error!( "Error streaming from camera {}, will retry in {}s: {:?}", camera_config.name, current_backoff.as_secs(), cam_err.err - ), + ) } std::thread::sleep(current_backoff); @@ -154,7 +158,8 @@ fn camera_loop( struct CameraErr { connected: bool, - err: neolink_core::Error, + login_fail: bool, + err: anyhow::Error, } fn set_up_tls(config: &Config, rtsp: &RtspServer) { @@ -209,8 +214,17 @@ fn camera_main( manage: bool, ) -> Result { let mut connected = false; + let mut login_fail = false; (|| { - let mut camera = BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; + let mut camera = + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; + if camera_config.timeout.is_some() { warn!("The undocumented `timeout` config option has been removed and is no longer needed."); warn!("Please update your config file."); @@ -221,28 +235,36 @@ fn camera_main( camera_config.name, camera_config.camera_addr ); - camera.login(&camera_config.username, camera_config.password.as_deref())?; + info!("{}: Logging in", camera_config.name); + camera.login(&camera_config.username, camera_config.password.as_deref()).map_err(|e| + { + if let neolink_core::Error::AuthFailed = e { + login_fail = true; + } + e + } + ).with_context(|| format!("Failed to login to {}", camera_config.name))?; connected = true; info!("{}: Connected and logged in", camera_config.name); if manage { - do_camera_management(&mut camera, camera_config)?; + do_camera_management(&mut camera, camera_config).context("Failed to manage the camera settings")?; } info!( "{}: Starting video stream {}", camera_config.name, stream_name ); - camera.start_video(outputs, stream_name) - })() - .map_err(|err| CameraErr { connected, err }) + camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name)) + })().map_err(|e| CameraErr{ + connected, + login_fail, + err: e, + }) } -fn do_camera_management( - camera: &mut BcCamera, - camera_config: &CameraConfig, -) -> Result<(), neolink_core::Error> { +fn do_camera_management(camera: &mut BcCamera, camera_config: &CameraConfig) -> Result<()> { let cam_time = camera.get_time()?; if let Some(time) = cam_time { info!( diff --git a/src/statusled/cmdline.rs b/src/statusled/cmdline.rs index 20d7827..e0c448d 100644 --- a/src/statusled/cmdline.rs +++ b/src/statusled/cmdline.rs @@ -1,12 +1,15 @@ -use super::errors::ParseOnOffError; +use anyhow::{anyhow, Result}; use std::path::PathBuf; use structopt::StructOpt; -fn onoff_parse(src: &str) -> Result { +fn onoff_parse(src: &str) -> Result { match src { "true" | "on" | "yes" => Ok(true), "false" | "off" | "no" => Ok(false), - _ => Err(ParseOnOffError), + _ => Err(anyhow!( + "Could not understand {}, check your input, should be true/false, on/off or yes/no", + src + )), } } diff --git a/src/statusled/errors.rs b/src/statusled/errors.rs deleted file mode 100644 index 91b4650..0000000 --- a/src/statusled/errors.rs +++ /dev/null @@ -1,24 +0,0 @@ -use err_derive::Error; - -/// The main error for the status-light subcommand -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - /// Raised when the config file fails to deserlize - #[error(display = "Configuration parsing error")] - Config(#[error(source)] toml::de::Error), - /// Raised when `neolink_core` raises an error - #[error(display = "Communication error")] - Protocol(#[error(source)] neolink_core::Error), - /// Raised when there is an IO error such as unable to find - /// config file - #[error(display = "I/O error")] - Io(#[error(source)] std::io::Error), - /// Raised when the config file fails validataion - #[error(display = "Validation error")] - Validation(#[error(source)] validator::ValidationErrors), -} - -#[derive(Error, Debug)] -#[error(display = "Failed to parse on/off flag")] -pub(super) struct ParseOnOffError; diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index 03572c5..6f32b2a 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -15,6 +15,7 @@ /// neolink status-light --config=config.toml CameraName off /// ``` /// +use anyhow::{anyhow, Context, Result}; use log::*; use neolink_core::bc_protocol::BcCamera; use std::fs; @@ -22,19 +23,23 @@ use validator::Validate; mod cmdline; mod config; -mod errors; pub(crate) use cmdline::Opt; use config::Config; -pub(crate) use errors::Error; /// Entry point for the ledstatus subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<(), Error> { - let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - config.validate()?; + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; let mut cam_found = false; for camera_config in &config.cameras { @@ -46,23 +51,34 @@ pub fn main(opt: Opt) -> Result<(), Error> { ); let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); - camera.login(&camera_config.username, camera_config.password.as_deref())?; + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; info!("{}: Connected and logged in", camera_config.name); - camera.led_light_set(opt.on)?; + camera + .led_light_set(opt.on) + .context("Unable to set camera light state")?; } } if !cam_found { - error!( - "No camera with the name {} was found in the config", - opt.camera - ); + Err(anyhow!( + "Camera {} was not in the config file {:?}", + &opt.camera, + &opt.config + )) + } else { + Ok(()) } - - Ok(()) } diff --git a/src/talk/errors.rs b/src/talk/errors.rs deleted file mode 100644 index af0f3b0..0000000 --- a/src/talk/errors.rs +++ /dev/null @@ -1,42 +0,0 @@ -use err_derive::Error; -use gstreamer::glib; - -/// The main error for the status-light subcommand -#[derive(Debug, Error)] -#[allow(clippy::large_enum_variant)] -pub enum Error { - /// Raised when the config file fails to deserlize - #[error(display = "Configuration parsing error")] - Config(#[error(source)] toml::de::Error), - /// Raised when `neolink_core` raises an error - #[error(display = "Communication error")] - Protocol(#[error(source)] neolink_core::Error), - /// Raised when there is an IO error such as unable to find - /// config file - #[error(display = "I/O error")] - Io(#[error(source)] std::io::Error), - /// Raised when the config file fails validataion - #[error(display = "Validation error")] - Validation(#[error(source)] validator::ValidationErrors), - /// Raised when gstreamer fails to init - #[error(display = "Gstreamer init failed")] - GstreamerInit(#[error(source)] glib::Error), - /// Raised when a needed part of the gsteamer pipeline is not found - /// - /// Usually this means missing pluings - #[error(display = "Gstreamer element not supported. Check your gstreamer plugins")] - GstreamerElement(gstreamer::Element), - /// Raised where there is an issue starting a audio playback in gstraemer - #[error(display = "Gstreamer Unable to play the file")] - GstreamerPlayback(#[error(source)] gstreamer::StateChangeError), - /// Generic gstreamer error - #[error(display = "Gstreamer raised an error")] - Gstreamer { - error: String, - debug: Option, - }, - - /// Raised when talk back is unsupported - #[error(display = "This camera does not support talkback")] - TalkUnsupported, -} diff --git a/src/talk/gst.rs b/src/talk/gst.rs index b0e44b7..f0f9ab7 100644 --- a/src/talk/gst.rs +++ b/src/talk/gst.rs @@ -1,3 +1,4 @@ +use anyhow::{anyhow, Context, Result}; use gstreamer::{ element_error, parse_launch, prelude::*, Caps, ClockTime, FlowError, FlowSuccess, MessageView, Pipeline, ResourceError, State, @@ -5,7 +6,6 @@ use gstreamer::{ use gstreamer_app::{AppSink, AppSinkCallbacks}; use std::sync::mpsc::{sync_channel, Receiver, SyncSender}; -use super::errors::Error; use byte_slice_cast::*; pub(super) fn from_input( @@ -13,12 +13,12 @@ pub(super) fn from_input( volume: f32, block_align: u16, sample_rate: u16, -) -> Result>, Error> { +) -> Result>> { let pipeline = create_pipeline(input_src, volume, block_align, sample_rate)?; input(pipeline) } -fn input(pipeline: Pipeline) -> Result>, Error> { +fn input(pipeline: Pipeline) -> Result>> { let appsink = get_sink(&pipeline)?; let (tx, rx) = sync_channel(30); @@ -31,7 +31,7 @@ fn input(pipeline: Pipeline) -> Result>, Error> { Ok(rx) } -fn start_pipeline(pipeline: Pipeline) -> Result<(), Error> { +fn start_pipeline(pipeline: Pipeline) -> Result<()> { pipeline.set_state(State::Playing)?; let bus = pipeline @@ -42,30 +42,31 @@ fn start_pipeline(pipeline: Pipeline) -> Result<(), Error> { match msg.view() { MessageView::Eos(..) => break, MessageView::Error(err) => { - pipeline.set_state(State::Null)?; + pipeline + .set_state(State::Null) + .context("Error in gstreamer when setting state to Null")?; log::warn!( - "{:?}", - Error::Gstreamer { - error: err.error().to_string(), - debug: err.debug(), - } + "Error from gstreamer when setting the play state {:?} setting to Null instead", + err ); } _ => (), } } - pipeline.set_state(State::Null)?; + pipeline + .set_state(State::Null) + .context("Error in gstreamer when setting state to Null")?; Ok(()) } -fn get_sink(pipeline: &Pipeline) -> Result { +fn get_sink(pipeline: &Pipeline) -> Result { let sink = pipeline .by_name("thesink") .expect("There shoud be a `thesink`"); sink.dynamic_cast::() - .map_err(Error::GstreamerElement) + .map_err(|_| anyhow!("Cannot find appsink in gstreamer, check your gstreamer plugins")) } fn set_data_channel(appsink: &AppSink, tx: SyncSender>) { @@ -131,8 +132,9 @@ fn create_pipeline( volume: f32, block_align: u16, sample_rate: u16, -) -> Result { - gstreamer::init()?; +) -> Result { + gstreamer::init() + .context("Unable to start gstreamer ensure it and all plugins are installed")?; let launch_str = format!( "{} \ @@ -152,10 +154,11 @@ fn create_pipeline( // Parse the pipeline we want to probe from a static in-line string. // Here we give our audiotestsrc a name, so we can retrieve that element // from the resulting pipeline. - let pipeline = parse_launch(&launch_str)?; - let pipeline = pipeline - .dynamic_cast::() - .map_err(Error::GstreamerElement)?; + let pipeline = parse_launch(&launch_str) + .context("Unable to load gstreamer pipeline ensure all gstramer plugins are installed")?; + let pipeline = pipeline.dynamic_cast::().map_err(|_| { + anyhow!("Unable to create gstreamer pipeline ensure all gstramer plugins are installed") + })?; let appsink = get_sink(&pipeline)?; diff --git a/src/talk/mod.rs b/src/talk/mod.rs index c99461b..a2a032a 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -11,6 +11,7 @@ /// neolink status-light --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName /// ``` /// +use anyhow::{anyhow, Context, Result}; use log::*; use neolink_core::{bc::xml::TalkConfig, bc_protocol::BcCamera}; use std::fs; @@ -18,20 +19,24 @@ use validator::Validate; mod cmdline; mod config; -mod errors; mod gst; pub(crate) use cmdline::Opt; use config::Config; -pub(crate) use errors::Error; /// Entry point for the talk subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<(), Error> { - let config: Config = toml::from_str(&fs::read_to_string(opt.config)?)?; +pub fn main(opt: Opt) -> Result<()> { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - config.validate()?; + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; let mut cam_found = false; for camera_config in &config.cameras { @@ -43,19 +48,32 @@ pub fn main(opt: Opt) -> Result<(), Error> { ); let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id)?; + BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_config.camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); - camera.login(&camera_config.username, camera_config.password.as_deref())?; + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; info!("{}: Connected and logged in", camera_config.name); - let talk_ability = camera.talk_ability()?; + let talk_ability = camera + .talk_ability() + .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; if talk_ability.duplex_list.is_empty() || talk_ability.audio_stream_mode_list.is_empty() || talk_ability.audio_config_list.is_empty() { - return Err(Error::TalkUnsupported); + return Err(anyhow!( + "Camera {} does not support talk", + camera_config.name + )); } // Just copy that data from the first talk ability in the config have never seen more @@ -75,7 +93,10 @@ pub fn main(opt: Opt) -> Result<(), Error> { let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; let sample_rate = talk_config.audio_config.sample_rate; if block_size == 0 || sample_rate == 0 { - return Err(Error::TalkUnsupported); + return Err(anyhow!( + "The camera {} does not support talk with adpcm", + camera_config.name + )); } let rx = match (&opt.file_path, &opt.microphone) { @@ -87,23 +108,28 @@ pub fn main(opt: Opt) -> Result<(), Error> { opt.volume, block_size, sample_rate, - )?, + ) + .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, (None, true) => { - gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate)? + gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) + .context("Failed to setup gst using the microphone")? } _ => unreachable!(), }; - camera.talk_stream(rx, talk_config)?; + camera + .talk_stream(rx, talk_config) + .context("Talk stream ended early")?; } } if !cam_found { - error!( - "No camera with the name {} was found in the config", - opt.camera - ); + Err(anyhow!( + "Camera {} was not in the config file {:?}", + &opt.camera, + &opt.config + )) + } else { + Ok(()) } - - Ok(()) } From deece56488f66dba9bbf0a9c6878ffd5d87e5103 Mon Sep 17 00:00:00 2001 From: Morphy99 Date: Thu, 19 Aug 2021 04:09:48 +0100 Subject: [PATCH 06/56] Update README.md (#193) * Update README.md * Update README.md Co-authored-by: Andrew King * Update README.md Co-authored-by: Andrew King * More update to the readme * Correct the indentation in the readme Co-authored-by: Andrew King --- README.md | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e29c4dc..23acc2e 100644 --- a/README.md +++ b/README.md @@ -39,8 +39,8 @@ Builds are provided for the following platforms: - macOS x86_64 ([download][macos-ci-download]) - Ubuntu x86_64 ([download][ubuntu-ci-download]) - Debian x86 ([download][debian-x86-ci-download]) -- Debian aarch64 ([download][debian-aarch-ci-download]) -- Debian armhf ([download][debian-armhf-ci-download]) +- Debian aarch64 (Raspberry Pi 64-bit) ([download][debian-aarch-ci-download]) +- Debian armhf (Raspberry Pi 32-bit) ([download][debian-armhf-ci-download]) - Arch Linux ([AUR](https://aur.archlinux.org/packages/neolink-git/)) - Docker x86 (see below) @@ -48,6 +48,18 @@ Builds are provided for the following platforms: 1. [Install Gstreamer][gstreamer] from the most recent MSI installer on Windows, or your package manager on Linux. + + On Ubuntu/Debian machines gstreamer can be installed with: + + ```bash + sudo apt install \ + libgstrtspserver-1.0-0 \ + libgstreamer1.0-0 \ + libgstreamer-plugins-bad1.0-0 \ + gstreamer1.0-plugins-good \ + gstreamer1.0-plugins-bad + ``` + 2. If you are using Windows, add the following to your `PATH` environment variable: @@ -58,12 +70,17 @@ or your package manager on Linux. **Note:** If you use Chocolatey to install Gstreamer, it does this automatically. -3. Download and extract a [prebuilt binary from continuous integration][ci-download] -(click on the topmost commit for the most recent build). - 3. Download and unpack Neolink from the links above. 1. Note: you can also click on [this link][ci-download] to see all historical builds. - You will need to be logged in to GitHub to download directly from the builds page. + You will need to be logged in to GitHub to download directly from the builds page (wget doesn't work) + + Raspberry Pi OS x64 example: + + ```bash + unzip release-arm64-buster.zip + sudo cp neolink /usr/local/bin/ + sudo chmod +x /usr/local/bin/neolink + ``` 4. Write a configuration file for your cameras. See the section below. 5. Launch Neolink from a shell, passing your configuration file: From ebb6e874c8907af5f850051ee9efc87ad7724c74 Mon Sep 17 00:00:00 2001 From: Andrew King Date: Thu, 26 Aug 2021 11:12:07 +0700 Subject: [PATCH 07/56] Update BI doc image (#200) --- docs/screenshots/new_camera_config.JPG | Bin 94356 -> 159043 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/docs/screenshots/new_camera_config.JPG b/docs/screenshots/new_camera_config.JPG index 7fae3f8ba846432941c07b05cd628814cc2e0fde..a1eafbf3925e9c97ea0282345a6f03fea8cea281 100644 GIT binary patch literal 159043 zcmeFZ1yG$&v?urh7rVH7aF^f~AjrifxVr~;C&A(3?hrh&Phfq?~RUp~O|Dj)&C z!TwYJ`G$KbAOz4q1qlHG9swB%3`RymMh2r|pn_4*QIL_*u+Y#kFfp+(!Km0c*qAsk z*O>nhf%&H;90=*9Atnkk%FD0+i{<$XfQ1BW1ZM;Xg9X51!N6g`Jof{n01N;N2Ll5G z{Ch!wM+Ctk!TwWgi3tGkFV$dV5IQ0}92owe8xTBzfQW^SgNrvuIj@d1tC5<5ucetp z#X(4rFe6snSVGO4){x8}63Xdn!R4XCU0=s%Lc`aIhd4cm%|kO1YQr!os`^9TFG-!NbDC!M_YH791ruh=WQD zN5zB_R~0@XP_2&JIe!MPfI3KAJ<-&Ki$(%}7U3M?*1J{smDViyg2%P~c?Cd)d-=Oq za9F@wpnvrj*UFSX|C7(dGa$azt@{vik0CpC^2s~qcgC4jclJkNVU)0Y+aFj*0*|gg zIeOHDD{trG4nF5QZL<3J3e&%>_TT3_wra}#?fmEZnvGP z+}zMUzouKH>+Gkt+w{${+(qA`p{u#+R>#!ttyf8(zKL9s{2zVrAwawQwnjbc`ukwR z>_dsK&d<-}Q}6z@TRuu3^&iF^=cjCiuXpZ`4)yuQjGW^BcJ=S5{^ixb%j&PN`YTue zYOBAB^?$}((bG*#bf8~J+?J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q6>!Df#6rBAp*8 zG2kJbctizoq23`LEz|zLR>vi#$NcwdR`QT`r74m>;BR4Z+*EmVZzMQJt6;iB8N@=N z`L3YDfRPz0cZt|pQeL_ySl=3=>nUYNnx41z`V{nR_p@Zi8?tvp6$w{(`=ZoFr40ot zFYYoay?E8oGrF+9P~Vpc)!a|E0tlqu0c2|y(GWA=&c3sX0f41Cks+{>j6r_WCWf$M z4Dd<7wmvTZjt?>Y2}j%)*w#8qe+Ov(C(5r)!T}7LMBpKQE&&)QFJf=K{)fUzZE&L6 z8UPAQLjC@(`Eu5t5D;BLA3&CRz=DD({s-;SlaT2j8byz;eOLH|;{oK~{RFatzgf>a zy2gqRFbgMD_(xN}h{;Pq^8Vvi{--;~a0wGS4y2z1+b1hx#q(j2QrEh!FX{ZRjK@!w zr@#28Nub}Jhn;^aBlf0wJd5uh-S(HG8x6i7ax@lx8{~Bc?03>ZFB9%2ke_FLX^*lA z>_k}y&G8$WKWHDlH z__Y;&nUCKL>i-v80sl|L!9sB9|LKmwOWR~7T(xpH1f6P+vodgrbK}N7PKI1-7K>T( WPq-f(S+ubA(uS))X`<`k>%RerdR~A4 From df8c02cd7badbc82c74e4f0d8f8c1fbfe09f48ea Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Thu, 26 Aug 2021 00:25:28 -0500 Subject: [PATCH 08/56] Reorganize readme (#201) * Reorganize readme Remove obsolete note about format, and move usage info to the top. * Add the bash tag in the readme Co-authored-by: Andrew King --- README.md | 69 ++++++++++++++++++++++++++----------------------------- 1 file changed, 32 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index e3f239d..d35c082 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,38 @@ Currently it has been tested on the following cameras: Neolink does not support other cameras such as the RLC-420, since they already [provide native RTSP](https://support.reolink.com/hc/en-us/articles/360007010473-How-to-Live-View-Reolink-Cameras-via-VLC-Media-Player). -## Installation +## Usage + +1. First, write a configuration yaml file describing your cameras. See the +Configuration section below or the provided sample config. + +2. Launch Neolink: +```bash +neolink rtsp --config=your_config.yaml + +3. Then, connect your RTSP viewer to `rtsp://127.0.0.1:8554/your_camera_name`! + +### Additional commands + +Neolink also has some additional command line tools +for controlling the camera. They are all used through neolink subcommands like this: + +```bash +neolink subcommand --config=... +``` + +The currently supported subcommands are + +- **rtsp**: The standard neolink rtsp bridge +- **status-light**: Control the LED status light +- **reboot**: Reboot a camera +- **talk**: Enable talk back through either the microphone or by + reading a sound file. + +For a full list of commands use `neolink help`, or use +`neolink help ` for details on a subcommand of interest. + +## Download & Installation In the future Neolink will be much easier to install. For now, follow these steps. @@ -159,11 +190,6 @@ path you should connect your client to. Currently Neolink cannot auto-detect cameras like the official clients do; you must specify their IP addresses directly. -By default the H265 video format is used. Some cameras, for example E1, provide -H264 streams. To use these you must specify `format = "h264"` in the -`[[cameras]]` config. Soon this will be auto-detected, and you will not have to know or care about -the format. - By default, the HD stream is available at the RTSP path `/name` or `/name/mainStream`, and the SD stream is available at `/name/subStream`. You can use only the HD stream by adding `stream = "mainStream"` to the @@ -295,37 +321,6 @@ Currently the dissector does not attempt to decode the Baichuan "extension" messages except `binaryData`. This will change in the future as reverse engineering needs require. -## Additional Commands - -Neolink also has some additional command line tools -for controlling the camera. They are all used through neolink subcommands like this: - - -```bash -neolink subcommand --config=... -``` - -The currently supported subcommands are - -- **rtsp**: The standard neolink rtsp bridge -- **status-light**: A command to control the LED status light -- **reboot**: Will reboot a camera -- **talk**: Will enable talk back through either the microphone or by - reading a sound file. - -For a full list of commands please use - -```bash -neolink help -``` - -For further details on the subcommands please use the following -where `` is replaced with the subcommand of interest - -```bash -neolink help -``` - ## License Neolink is free software, released under the GNU Affero General Public License From 1d824b80b016cb8ccaa55e8f029a0a936a011d5d Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Thu, 26 Aug 2021 10:22:13 -0500 Subject: [PATCH 09/56] Add missing code block close --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d35c082..fe842b3 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,7 @@ Configuration section below or the provided sample config. 2. Launch Neolink: ```bash neolink rtsp --config=your_config.yaml +``` 3. Then, connect your RTSP viewer to `rtsp://127.0.0.1:8554/your_camera_name`! From ffd869091bcc7cac82e1f6c4ec124de9dcf80e94 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 25 Aug 2021 10:00:44 +0700 Subject: [PATCH 10/56] Added externStream as an option --- crates/core/src/bc_protocol/stream.rs | 8 +++++++- src/rtsp/config.rs | 3 ++- src/rtsp/mod.rs | 13 +++++++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index ba4aebd..0486b80 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -45,6 +45,12 @@ impl BcCamera { _ => 0, }; + let handle = match stream_name { + "mainStream" => 0, + "subStream" => 256, + _ => 1024, + }; + let start_video = Bc::new_from_xml( BcMeta { msg_id: MSG_ID_VIDEO, @@ -58,7 +64,7 @@ impl BcCamera { preview: Some(Preview { version: xml_ver(), channel_id: self.channel_id, - handle: 0, + handle, stream_type: stream_name.to_string(), }), ..Default::default() diff --git a/src/rtsp/config.rs b/src/rtsp/config.rs index 176b434..fb2ead6 100644 --- a/src/rtsp/config.rs +++ b/src/rtsp/config.rs @@ -7,7 +7,8 @@ use validator::{Validate, ValidationError}; use validator_derive::Validate; lazy_static! { - static ref RE_STREAM_SRC: Regex = Regex::new(r"^(mainStream|subStream|both)$").unwrap(); + static ref RE_STREAM_SRC: Regex = + Regex::new(r"^(mainStream|subStream|externStream|both|all)$").unwrap(); static ref RE_TLS_CLIENT_AUTH: Regex = Regex::new(r"^(none|request|require)$").unwrap(); } diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index ca5a030..dfb0b91 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -89,7 +89,7 @@ pub fn main(opt: Opt) -> Result<()> { 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) { + if ["all", "both", "mainStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[ &*format!("/{}", arc_cam.name), &*format!("/{}/mainStream", arc_cam.name), @@ -100,7 +100,7 @@ pub fn main(opt: Opt) -> Result<()> { let main_camera = arc_cam.clone(); s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true)); } - if ["both", "subStream"].iter().any(|&e| e == arc_cam.stream) { + if ["all", "both", "subStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[&*format!("/{}/subStream", arc_cam.name)]; let mut outputs = rtsp .add_stream(paths, &permitted_users) @@ -109,6 +109,15 @@ pub fn main(opt: Opt) -> Result<()> { let manage = arc_cam.stream == "subStream"; s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage)); } + if ["all", "externStream"].iter().any(|&e| e == arc_cam.stream) { + let paths = &[&*format!("/{}/externStream", arc_cam.name)]; + let mut outputs = rtsp + .add_stream(paths, &permitted_users) + .unwrap(); + let sub_camera = arc_cam.clone(); + let manage = arc_cam.stream == "externStream"; + s.spawn(move |_| camera_loop(&*sub_camera, "externStream", &mut outputs, manage)); + } } rtsp.run(&config.bind_addr, config.bind_port); From 38b40fd98957806143179c9a65c09099e05541f5 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 26 Aug 2021 13:16:13 +0700 Subject: [PATCH 11/56] Use an enum for selecting stream quality --- crates/core/src/bc_protocol.rs | 2 +- crates/core/src/bc_protocol/stream.rs | 48 ++++++++++++++++++++++----- src/rtsp/mod.rs | 20 +++++++---- 3 files changed, 53 insertions(+), 17 deletions(-) diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index c6dda1c..9bdcc76 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -25,7 +25,7 @@ mod version; pub use binarysub::BinarySubscriber; pub use errors::Error; pub use ledstate::LightState; -pub use stream::{StreamOutput, StreamOutputError}; +pub use stream::{Stream, StreamOutput, StreamOutputError}; type Result = std::result::Result; diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 0486b80..6599272 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -15,6 +15,20 @@ pub trait StreamOutput { fn write(&mut self, media: BcMedia) -> StreamOutputError; } +/// The stream names supported by BC +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum Stream { + /// This is the HD stream + Main, + /// This is the SD stream + Sub, + /// This stream represents a balance between SD and HD + /// + /// It is only avaliable on some camera. If the camera dosen't + /// support it the stream will be the same as the SD stream + Extern, +} + impl BcCamera { /// /// Starts the video stream @@ -23,13 +37,20 @@ impl BcCamera { /// /// * `data_outs` - This should be a struct that implements the [`StreamOutput`] trait /// - /// * `stream_name` - The name of the stream either `"mainStream"` for HD or `"subStream"` for SD + /// * `stream_name` - This is a [`Stream`] that controls the stream to request from the camera. + /// Selecting [`Stream::Main`] will select the HD stream. + /// Selecting [`Stream::Sub`] will select the SD stream. + /// Selecting [`Stream::Extern`] will select the medium quality stream (only on some camera) /// /// # Returns /// /// This will block forever or return an error when the camera connection is dropped /// - pub fn start_video(&self, data_outs: &mut Outputs, stream_name: &str) -> Result + pub fn start_video( + &self, + data_outs: &mut Outputs, + stream_name: Stream, + ) -> Result where Outputs: StreamOutput, { @@ -40,17 +61,26 @@ impl BcCamera { let sub_video = connection.subscribe(MSG_ID_VIDEO)?; let stream_num = match stream_name { - "mainStream" => 0, - "subStream" => 1, - _ => 0, + Stream::Main => 0, + Stream::Sub => 1, + Stream::Extern => 0, }; + // Theses are the numbers used with the offical client + // connecting to an E1. let handle = match stream_name { - "mainStream" => 0, - "subStream" => 256, - _ => 1024, + Stream::Main => 0, + Stream::Sub => 256, + Stream::Extern => 1024, }; + let stream_type = match stream_name { + Stream::Main => "mainStream", + Stream::Sub => "subStream", + Stream::Extern => "externStream", + } + .to_string(); + let start_video = Bc::new_from_xml( BcMeta { msg_id: MSG_ID_VIDEO, @@ -65,7 +95,7 @@ impl BcCamera { version: xml_ver(), channel_id: self.channel_id, handle, - stream_type: stream_name.to_string(), + stream_type, }), ..Default::default() }, diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index dfb0b91..97dd1fe 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -30,7 +30,7 @@ /// use anyhow::{Context, Result}; use log::*; -use neolink_core::bc_protocol::BcCamera; +use neolink_core::bc_protocol::{BcCamera, Stream}; use neolink_core::Never; use std::collections::HashSet; use std::fs; @@ -98,7 +98,7 @@ pub fn main(opt: Opt) -> Result<()> { .add_stream(paths, &permitted_users) .unwrap(); let main_camera = arc_cam.clone(); - s.spawn(move |_| camera_loop(&*main_camera, "mainStream", &mut outputs, true)); + s.spawn(move |_| camera_loop(&*main_camera, Stream::Main, &mut outputs, true)); } if ["all", "both", "subStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[&*format!("/{}/subStream", arc_cam.name)]; @@ -107,7 +107,7 @@ pub fn main(opt: Opt) -> Result<()> { .unwrap(); let sub_camera = arc_cam.clone(); let manage = arc_cam.stream == "subStream"; - s.spawn(move |_| camera_loop(&*sub_camera, "subStream", &mut outputs, manage)); + s.spawn(move |_| camera_loop(&*sub_camera, Stream::Sub, &mut outputs, manage)); } if ["all", "externStream"].iter().any(|&e| e == arc_cam.stream) { let paths = &[&*format!("/{}/externStream", arc_cam.name)]; @@ -116,7 +116,7 @@ pub fn main(opt: Opt) -> Result<()> { .unwrap(); let sub_camera = arc_cam.clone(); let manage = arc_cam.stream == "externStream"; - s.spawn(move |_| camera_loop(&*sub_camera, "externStream", &mut outputs, manage)); + s.spawn(move |_| camera_loop(&*sub_camera, Stream::Extern, &mut outputs, manage)); } } @@ -129,7 +129,7 @@ pub fn main(opt: Opt) -> Result<()> { fn camera_loop( camera_config: &CameraConfig, - stream_name: &str, + stream_name: Stream, outputs: &mut GstOutputs, manage: bool, ) -> Result { @@ -218,7 +218,7 @@ fn get_permitted_users<'a>( fn camera_main( camera_config: &CameraConfig, - stream_name: &str, + stream_name: Stream, outputs: &mut GstOutputs, manage: bool, ) -> Result { @@ -261,9 +261,15 @@ fn camera_main( do_camera_management(&mut camera, camera_config).context("Failed to manage the camera settings")?; } + let stream_display_name = match stream_name { + Stream::Main => "Main Stream (Clear)", + Stream::Sub => "Sub Stream (Fluent)", + Stream::Extern => "Sub Stream (Balanced)", + }; + info!( "{}: Starting video stream {}", - camera_config.name, stream_name + camera_config.name, stream_display_name ); camera.start_video(outputs, stream_name).with_context(|| format!("Error while streaming {}", camera_config.name)) })().map_err(|e| CameraErr{ From 6bf11047b8cb1b73754220922de29bafcc5ce7ea Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 26 Aug 2021 13:45:39 +0700 Subject: [PATCH 12/56] Fixed typo in stream display name --- src/rtsp/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 97dd1fe..0c45298 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -264,7 +264,7 @@ fn camera_main( let stream_display_name = match stream_name { Stream::Main => "Main Stream (Clear)", Stream::Sub => "Sub Stream (Fluent)", - Stream::Extern => "Sub Stream (Balanced)", + Stream::Extern => "Extern Stream (Balanced)", }; info!( From d471072fc398aed6ad69fc82aab91e4f300f0a41 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 27 Aug 2021 09:50:45 +0700 Subject: [PATCH 13/56] Add further notes and tests about B800 differences --- Cargo.lock | 7 + crates/core/Cargo.toml | 1 + crates/core/src/bc/de.rs | 405 ++++++++++++------ .../src/bc/samples/xml_externstream_b800.bin | Bin 0 -> 199 bytes .../src/bc/samples/xml_mainstream_b800.bin | Bin 0 -> 194 bytes .../src/bc/samples/xml_substream_b800.bin | Bin 0 -> 195 bytes crates/core/src/bc_protocol/stream.rs | 26 +- 7 files changed, 295 insertions(+), 144 deletions(-) create mode 100644 crates/core/src/bc/samples/xml_externstream_b800.bin create mode 100644 crates/core/src/bc/samples/xml_mainstream_b800.bin create mode 100644 crates/core/src/bc/samples/xml_substream_b800.bin diff --git a/Cargo.lock b/Cargo.lock index 535f7ce..f984fd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,12 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + [[package]] name = "atty" version = "0.2.14" @@ -867,6 +873,7 @@ name = "neolink_core" version = "0.4.0" dependencies = [ "aes", + "assert_matches", "cfb-mode", "cookie-factory", "env_logger", diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 2728304..d6a782c 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -20,5 +20,6 @@ yaserde_derive = "0.3.16" xml-rs = "0.8" [dev-dependencies] +assert_matches = "1.5.0" env_logger = "*" indoc = "0.3" diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 6ce7d6f..d546f18 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -232,150 +232,289 @@ fn bc_header(buf: &[u8]) -> IResult<&[u8], BcHeader> { )) } -#[test] -fn test_bc_modern_login() { - let sample = include_bytes!("samples/model_sample_modern_login.bin"); +#[cfg(test)] +mod tests { + use super::*; + use crate::bc::xml::*; + use assert_matches::assert_matches; - let encryption_protocol = - std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); - let mut context = BcContext::new(encryption_protocol); + #[test] + fn test_bc_modern_login() { + let sample = include_bytes!("samples/model_sample_modern_login.bin"); - let (buf, header) = bc_header(&sample[..]).unwrap(); - let (_, body) = bc_body(&mut context, &header, buf).unwrap(); - assert_eq!(header.msg_id, 1); - assert_eq!(header.body_len, 145); - assert_eq!(header.channel_id, 0); - assert_eq!(header.stream_type, 0); - assert_eq!(header.payload_offset, None); - assert_eq!(header.response_code, 0xdd01); - assert_eq!(header.class, 0x6614); - match body { - BcBody::ModernMsg(ModernMsg { - payload: - Some(BcPayloads::BcXml(BcXml { - encryption: Some(encryption), - .. - })), - .. - }) => assert_eq!(encryption.nonce, "9E6D1FCB9E69846D"), - _ => panic!(), - } -} + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); -#[test] -fn test_bc_legacy_login() { - let sample = include_bytes!("samples/model_sample_legacy_login.bin"); - - let encryption_protocol = - std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); - let mut context = BcContext::new(encryption_protocol); - - let (buf, header) = bc_header(&sample[..]).unwrap(); - let (_, body) = bc_body(&mut context, &header, buf).unwrap(); - assert_eq!(header.msg_id, 1); - assert_eq!(header.body_len, 1836); - assert_eq!(header.channel_id, 0); - assert_eq!(header.stream_type, 0); - assert_eq!(header.payload_offset, None); - assert_eq!(header.response_code, 0xdc01); - assert_eq!(header.class, 0x6514); - match body { - BcBody::LegacyMsg(LegacyMsg::LoginMsg { username, password }) => { - assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0"); - assert_eq!(password, EMPTY_LEGACY_PASSWORD); + let (buf, header) = bc_header(&sample[..]).unwrap(); + let (_, body) = bc_body(&mut context, &header, buf).unwrap(); + assert_eq!(header.msg_id, 1); + assert_eq!(header.body_len, 145); + assert_eq!(header.channel_id, 0); + assert_eq!(header.stream_type, 0); + assert_eq!(header.payload_offset, None); + assert_eq!(header.response_code, 0xdd01); + assert_eq!(header.class, 0x6614); + match body { + BcBody::ModernMsg(ModernMsg { + payload: + Some(BcPayloads::BcXml(BcXml { + encryption: Some(encryption), + .. + })), + .. + }) => assert_eq!(encryption.nonce, "9E6D1FCB9E69846D"), + _ => panic!(), } - _ => panic!(), } -} -#[test] -fn test_bc_modern_login_failed() { - let sample = include_bytes!("samples/modern_login_failed.bin"); + #[test] + fn test_bc_legacy_login() { + let sample = include_bytes!("samples/model_sample_legacy_login.bin"); - let encryption_protocol = - std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); - let mut context = BcContext::new(encryption_protocol); + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); - let (buf, header) = bc_header(&sample[..]).unwrap(); - let (_, body) = bc_body(&mut context, &header, buf).unwrap(); - assert_eq!(header.msg_id, 1); - assert_eq!(header.body_len, 0); - assert_eq!(header.channel_id, 0); - assert_eq!(header.stream_type, 0); - assert_eq!(header.payload_offset, Some(0x0)); - assert_eq!(header.response_code, 0x190); // 400 - assert_eq!(header.class, 0x0000); - match body { - BcBody::ModernMsg(ModernMsg { - extension: None, - payload: None, - }) => {} - _ => panic!(), - } -} - -#[test] -fn test_bc_modern_login_success() { - let sample = include_bytes!("samples/modern_login_success.bin"); - - let encryption_protocol = - std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); - let mut context = BcContext::new(encryption_protocol); - - let (buf, header) = bc_header(&sample[..]).unwrap(); - let (_, body) = bc_body(&mut context, &header, buf).unwrap(); - assert_eq!(header.msg_id, 1); - assert_eq!(header.body_len, 2949); - assert_eq!(header.channel_id, 0); - assert_eq!(header.stream_type, 0); - assert_eq!(header.payload_offset, Some(0x0)); - assert_eq!(header.response_code, 0xc8); // 200 - assert_eq!(header.class, 0x0000); - - // Previously, we were not handling payload_offset == 0 (no bin offset) correctly. - // Test that we decoded XML and no binary. - match body { - BcBody::ModernMsg(ModernMsg { - extension: None, - payload: Some(_), - }) => {} - _ => panic!(), - } -} - -#[test] -fn test_bc_binary_mode() { - let sample1 = include_bytes!("samples/modern_video_start1.bin"); - let sample2 = include_bytes!("samples/modern_video_start2.bin"); - - let encryption_protocol = - std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); - let mut context = BcContext::new(encryption_protocol); - - let msg1 = Bc::deserialize(&mut context, &sample1[..]).unwrap(); - match msg1.body { - BcBody::ModernMsg(ModernMsg { - extension: - Some(Extension { - binary_data: Some(1), - .. - }), - payload: Some(BcPayloads::Binary(bin)), - }) => { - assert_eq!(bin.len(), 32); + let (buf, header) = bc_header(&sample[..]).unwrap(); + let (_, body) = bc_body(&mut context, &header, buf).unwrap(); + assert_eq!(header.msg_id, 1); + assert_eq!(header.body_len, 1836); + assert_eq!(header.channel_id, 0); + assert_eq!(header.stream_type, 0); + assert_eq!(header.payload_offset, None); + assert_eq!(header.response_code, 0xdc01); + assert_eq!(header.class, 0x6514); + match body { + BcBody::LegacyMsg(LegacyMsg::LoginMsg { username, password }) => { + assert_eq!(username, "21232F297A57A5A743894A0E4A801FC\0"); + assert_eq!(password, EMPTY_LEGACY_PASSWORD); + } + _ => panic!(), } - _ => panic!(), } - context.in_bin_mode.insert(msg1.meta.msg_num); - let msg2 = Bc::deserialize(&mut context, &sample2[..]).unwrap(); - match msg2.body { - BcBody::ModernMsg(ModernMsg { - extension: None, - payload: Some(BcPayloads::Binary(bin)), - }) => { - assert_eq!(bin.len(), 30344); + #[test] + fn test_bc_modern_login_failed() { + let sample = include_bytes!("samples/modern_login_failed.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let (buf, header) = bc_header(&sample[..]).unwrap(); + let (_, body) = bc_body(&mut context, &header, buf).unwrap(); + assert_eq!(header.msg_id, 1); + assert_eq!(header.body_len, 0); + assert_eq!(header.channel_id, 0); + assert_eq!(header.stream_type, 0); + assert_eq!(header.payload_offset, Some(0x0)); + assert_eq!(header.response_code, 0x190); // 400 + assert_eq!(header.class, 0x0000); + match body { + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: None, + }) => {} + _ => panic!(), } - _ => panic!(), + } + + #[test] + fn test_bc_modern_login_success() { + let sample = include_bytes!("samples/modern_login_success.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let (buf, header) = bc_header(&sample[..]).unwrap(); + let (_, body) = bc_body(&mut context, &header, buf).unwrap(); + assert_eq!(header.msg_id, 1); + assert_eq!(header.body_len, 2949); + assert_eq!(header.channel_id, 0); + assert_eq!(header.stream_type, 0); + assert_eq!(header.payload_offset, Some(0x0)); + assert_eq!(header.response_code, 0xc8); // 200 + assert_eq!(header.class, 0x0000); + + // Previously, we were not handling payload_offset == 0 (no bin offset) correctly. + // Test that we decoded XML and no binary. + match body { + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: Some(_), + }) => {} + _ => panic!(), + } + } + + #[test] + fn test_bc_binary_mode() { + let sample1 = include_bytes!("samples/modern_video_start1.bin"); + let sample2 = include_bytes!("samples/modern_video_start2.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let msg1 = Bc::deserialize(&mut context, &sample1[..]).unwrap(); + match msg1.body { + BcBody::ModernMsg(ModernMsg { + extension: + Some(Extension { + binary_data: Some(1), + .. + }), + payload: Some(BcPayloads::Binary(bin)), + }) => { + assert_eq!(bin.len(), 32); + } + _ => panic!(), + } + + context.in_bin_mode.insert(msg1.meta.msg_num); + let msg2 = Bc::deserialize(&mut context, &sample2[..]).unwrap(); + match msg2.body { + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: Some(BcPayloads::Binary(bin)), + }) => { + assert_eq!(bin.len(), 30344); + } + _ => panic!(), + } + } + + #[test] + // B800 seems to have a different header to the E1 and swann cameras + // the stream_type and message_num do not seem to set in the offical clients + // + // They also have extra streams + fn test_bc_b800_externstream() { + let sample = include_bytes!("samples/xml_externstream_b800.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let e = Bc::deserialize(&mut context, &sample[..]); + assert_matches!( + e, + Ok(Bc { + meta: + BcMeta { + msg_id: 3, + channel_id: 0x8c, + stream_type: 0, + response_code: 0, + msg_num: 0, + class: 0x6414, + }, + body: + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: + Some(BcPayloads::BcXml(BcXml { + preview: + Some(Preview { + version, + channel_id: 0, + handle: 1024, + stream_type, + }), + .. + })), + }), + }) if version == "1.1" && stream_type == "externStream" + ); + } + + #[test] + // B800 seems to have a different header to the E1 and swann cameras + // the stream_type and message_num do not seem to set in the offical clients + // + // They also have extra streams + fn test_bc_b800_substream() { + let sample = include_bytes!("samples/xml_substream_b800.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let e = Bc::deserialize(&mut context, &sample[..]); + assert_matches!( + e, + Ok(Bc { + meta: + BcMeta { + msg_id: 3, + channel_id: 143, + stream_type: 0, + response_code: 0, + msg_num: 0, + class: 0x6414, + }, + body: + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: + Some(BcPayloads::BcXml(BcXml { + preview: + Some(Preview { + version, + channel_id: 0, + handle: 256, + stream_type, + }), + .. + })), + }), + }) if version == "1.1" && stream_type == "subStream" + ); + } + + #[test] + // B800 seems to have a different header to the E1 and swann cameras + // the stream_type and message_num do not seem to set in the offical clients + // + // They also have extra streams + fn test_bc_b800_mainstream() { + let sample = include_bytes!("samples/xml_mainstream_b800.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let e = Bc::deserialize(&mut context, &sample[..]); + assert_matches!( + e, + Ok(Bc { + meta: + BcMeta { + msg_id: 3, + channel_id: 138, + stream_type: 0, + response_code: 0, + msg_num: 0, + class: 0x6414, + }, + body: + BcBody::ModernMsg(ModernMsg { + extension: None, + payload: + Some(BcPayloads::BcXml(BcXml { + preview: + Some(Preview { + version, + channel_id: 0, + handle: 0, + stream_type, + }), + .. + })), + }), + }) if version == "1.1" && stream_type == "mainStream" + ); } } diff --git a/crates/core/src/bc/samples/xml_externstream_b800.bin b/crates/core/src/bc/samples/xml_externstream_b800.bin new file mode 100644 index 0000000000000000000000000000000000000000..2ce1bb90f58a960d93c34c9aeacee60b81bc2c49 GIT binary patch literal 199 zcmexxZx0tU0|Uc)AnpNT1_qH75c%p>kKF&pV~dtdn=A8o&ZKWYu3iiNcK-5;O+B+j z)-^w!JmJKdz|Hge&c14&E&gi$uHS9bC$j!Ja{T#%hBk&@=kERba^;rOMxglC-l?*G zkKF0obo+?^oYgo&rcV_5_x0rV u&9^6VKRq(`OMV$_p_rmy_%8a>e&5E^3B)1>+H)Q;>X3Uu#wjW_0Yhrx`@hBp^Sp&>+H)D z_`}_*u!_DEu9A=IwvLt_{>R^qvDp1g_`}_xxr506L>5^~2tf xtd^2a( - &self, - data_outs: &mut Outputs, - stream_name: Stream, - ) -> Result + pub fn start_video(&self, data_outs: &mut Outputs, stream: Stream) -> Result where Outputs: StreamOutput, { @@ -60,21 +56,29 @@ impl BcCamera { .expect("Must be connected to start video"); let sub_video = connection.subscribe(MSG_ID_VIDEO)?; - let stream_num = match stream_name { + // On an E1: + // - mainStream always has a value of 0 + // - subStream always has a value of 1 + // - There is no externStram + // On a B800: + // - mainStream is 0 + // - subStream is 0 + // - externStream is 0 + let stream_code = match stream { Stream::Main => 0, Stream::Sub => 1, Stream::Extern => 0, }; // Theses are the numbers used with the offical client - // connecting to an E1. - let handle = match stream_name { + // connecting to an B800. + let handle = match stream { Stream::Main => 0, Stream::Sub => 256, Stream::Extern => 1024, }; - let stream_type = match stream_name { + let stream_name = match stream { Stream::Main => "mainStream", Stream::Sub => "subStream", Stream::Extern => "externStream", @@ -86,7 +90,7 @@ impl BcCamera { msg_id: MSG_ID_VIDEO, channel_id: self.channel_id, msg_num: self.new_message_num(), - stream_type: stream_num, + stream_type: stream_code, response_code: 0, class: 0x6414, // IDK why }, @@ -95,7 +99,7 @@ impl BcCamera { version: xml_ver(), channel_id: self.channel_id, handle, - stream_type, + stream_type: stream_name, }), ..Default::default() }, From 5fc92f0bf451a8a7bdc2108d8cad286783c6d281 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 27 Aug 2021 09:52:51 +0700 Subject: [PATCH 14/56] Further notes in stream about the numbers --- crates/core/src/bc_protocol/stream.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/core/src/bc_protocol/stream.rs b/crates/core/src/bc_protocol/stream.rs index 227bd85..0f5cd1d 100644 --- a/crates/core/src/bc_protocol/stream.rs +++ b/crates/core/src/bc_protocol/stream.rs @@ -56,7 +56,7 @@ impl BcCamera { .expect("Must be connected to start video"); let sub_video = connection.subscribe(MSG_ID_VIDEO)?; - // On an E1: + // On an E1 and swann cameras: // - mainStream always has a value of 0 // - subStream always has a value of 1 // - There is no externStram @@ -71,7 +71,14 @@ impl BcCamera { }; // Theses are the numbers used with the offical client - // connecting to an B800. + // On an E1 and swann cameras: + // - mainStream always has a value of 0 + // - subStream always has a value of 1 + // - There is no externStram + // On a B800: + // - mainStream is 0 + // - subStream is 256 + // - externStram is 1024 let handle = match stream { Stream::Main => 0, Stream::Sub => 256, From 09d16deb8cc506bba6df2bbbf51d23eeb88a7736 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 29 Aug 2021 14:57:03 +0700 Subject: [PATCH 15/56] Disable support for unknown 03 encryption --- crates/core/src/bc/de.rs | 41 +++++++++++++++++++++ crates/core/src/bc/samples/battery_enc.bin | Bin 0 -> 195 bytes crates/core/src/bc_protocol/login.rs | 2 +- 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 crates/core/src/bc/samples/battery_enc.bin diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index d546f18..46d998b 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -268,6 +268,47 @@ mod tests { } } + #[test] + // This is an 0xdd03 encryption from an Argus 2 + // + // It is currently unsupported + fn test_03_enc_login() { + let sample = include_bytes!("samples/battery_enc.bin"); + + let encryption_protocol = + std::sync::Arc::new(std::sync::Mutex::new(EncryptionProtocol::BCEncrypt)); + let mut context = BcContext::new(encryption_protocol); + + let (buf, header) = bc_header(&sample[..]).unwrap(); + assert!(bc_body(&mut context, &header, buf).is_err()); + // It should error because we don't support it + // + // The following would be its contents if we + // did support it (maybe one day :) left it here + // for then) + // + // + // let (_, body) = bc_body(&mut context, &header, buf).unwrap(); + // assert_eq!(header.msg_id, 1); + // assert_eq!(header.body_len, 175); + // assert_eq!(header.channel_id, 0); + // assert_eq!(header.stream_type, 0); + // assert_eq!(header.payload_offset, None); + // assert_eq!(header.response_code, 0xdd03); + // assert_eq!(header.class, 0x6614); + // match body { + // BcBody::ModernMsg(ModernMsg { + // payload: + // Some(BcPayloads::BcXml(BcXml { + // encryption: Some(encryption), + // .. + // })), + // .. + // }) => assert_eq!(encryption.nonce, "0-AhnEZyUg6eKrJFIWgXPF"), + // _ => panic!(), + // } + } + #[test] fn test_bc_legacy_login() { let sample = include_bytes!("samples/model_sample_legacy_login.bin"); diff --git a/crates/core/src/bc/samples/battery_enc.bin b/crates/core/src/bc/samples/battery_enc.bin new file mode 100644 index 0000000000000000000000000000000000000000..8c9514c86a838c9184fd3cf18059abc438f46279 GIT binary patch literal 195 zcmexxZx0tE0|Uc)AZB1-WMIB4lBO)=qGsmFH!C+TRK+AD>YSmhT(&*C^n_}cAf0q? z-PMr{ESXhdZeNxCgY}iei|*U=%9P8qOZTS5dMKH)M|4)j`vYm$yL!yLnJLK;Ao=Vn zPnYhr*vL|IUf;t8k*?PE5Pd-Lh{J_WK^peq9+%==gZLN(bZ2OKlv@hu8?LA*&EZXR g6Pr-z7g-wM2{cDgn9qcZt1Ukg=&tah!v+xh0m2wM*Z=?k literal 0 HcmV?d00001 diff --git a/crates/core/src/bc_protocol/login.rs b/crates/core/src/bc_protocol/login.rs index f8550fd..2a61ad0 100644 --- a/crates/core/src/bc_protocol/login.rs +++ b/crates/core/src/bc_protocol/login.rs @@ -35,7 +35,7 @@ impl BcCamera { channel_id: self.channel_id, msg_num: self.new_message_num(), stream_type: 0, - response_code: 0xdc03, + response_code: 0xdc02, class: 0x6514, }, body: BcBody::LegacyMsg(LegacyMsg::LoginMsg { From 996e55a3dd2742a77665df3bb8ebc6961e591902 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 25 Nov 2020 11:42:01 +0700 Subject: [PATCH 16/56] Add UDP dissector Using udp code from jdillenkofer --- dissector/baichuan.lua | 395 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 361 insertions(+), 34 deletions(-) diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 14f38ce..aa543f6 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -20,6 +20,18 @@ f_bin_offset = ProtoField.int32("baichuan.bin_offset", "binOffset", base.DEC) username = ProtoField.string("baichuan.username", "username", base.ASCII) password = ProtoField.string("baichuan.password", "password", base.ASCII) +-- UDP Related content +udp_magic = ProtoField.int32("baichuan.udp_magic", "udp_magic", base.DEC) +udp_type = ProtoField.int8("baichuan.udp_type", "udp_type", base.DEC) +udp_message_id = ProtoField.int8("baichuan.udp_message_id", "udp_message_id", base.DEC) +udp_connection_id = ProtoField.int32("baichuan.udp_connection_id", "udp_connection_id", base.DEC) +udp_unknown = ProtoField.int32("baichuan.udp_unknown", "udp_unknown", base.DEC) +udp_tid = ProtoField.int32("baichuan.udp_tid", "udp_tid", base.DEC) +udp_checksum = ProtoField.int32("baichuan.udp_checksum", "udp_checksum", base.DEC) +udp_packet_count = ProtoField.int32("baichuan.udp_packet_count", "udp_packet_count", base.DEC) +udp_last_ack_packet = ProtoField.int32("baichuan.udp_last_ack_packet", "udp_last_ack_packet", base.DEC) +udp_size = ProtoField.int32("baichuan.udp_size", "udp_size", base.DEC) + bc_protocol.fields = { magic_bytes, message_id, @@ -36,6 +48,16 @@ bc_protocol.fields = { f_bin_offset, username, password, + udp_magic, + udp_type, + udp_message_id, + udp_connection_id, + udp_unknown, + udp_tid, + udp_checksum, + udp_packet_count, + udp_last_ack_packet, + udp_size, } message_types = { @@ -314,9 +336,278 @@ function process_body(header, body_buffer, bc_subtree, pinfo) end end -function bc_protocol.dissector(buffer, pinfo, tree) + +-- UDP CONTENT +udp_fragments = {} + +function rshift(x, by) + return math.floor(x / 2 ^ by) +end + +function udp_decrypt(data, tid) + local result = ByteArray.new() + result:set_size(data:len()) + local key = { + 0x1f2d3c4b, 0x5a6c7f8d, + 0x38172e4b, 0x8271635a, + 0x863f1a2b, 0xa5c6f7d8, + 0x8371e1b4, 0x17f2d3a5 + } + + for i=1, 8 do + key[i] = key[i] + tid + end + + local i = data:len() + 3 + if i < 0 then + i = data:len() + 6 + end + + for x=0, rshift(i, 2) do + local index = bit32.band(x, 7) + local xor_key_word = key[index + 1] + for b=0, 3 do + byte_index = x * 4 + b + local val = data:get_index(byte_index) + local key_byte = bit32.extract(xor_key_word, b*8, 8) + val = bit32.bxor(key_byte, val) + result:set_index(byte_index, val) + if byte_index >= data:len() - 1 then + return result + end + end + end + return result +end + +function xml_encrypt(ba, offset) + local key = "\031\045\060\075\090\105\120\255" -- 1f, 2d, 3c, 4b, 5a, 69, 78 ,ff + local e = ByteArray.new() + e:set_size(ba:len()) + for i=0,ba:len() - 1 do + e:set_index(i, bit32.bxor(bit32.band(offset, 0xFF), bit32.bxor(ba:get_index(i), key:byte(((i + offset) % 8) + 1)))) + end + return e +end + +function get_udp_header_len(buffer) + local udpmagic = buffer(1, 3):le_uint() + if not udpmagic == 0x2a87cf then + return 0 + else + udptype = buffer(0, 1):le_uint() + if udptype == 0x3a then + return 20 + elseif udptype == 0x20 then + return 28 + elseif udptype == 0x10 then + return 20 + else + print("Unknown udp type") + return -1 + end + end +end + +function get_udp_header(buffer) + local udp_class = buffer(0, 1):le_uint() + local udp_magic = buffer(1, 3):le_uint() + local length = get_udp_header_len(buffer) + local udp_size = nil + local udp_unknown1 = nil + local udp_tid = nil + local udp_checksum = nil + local udp_unknown2 = nil + local udp_unknown3 = nil + local udp_unknown4 = nil + local udp_last_ack_packet = nil + local udp_connection_id = nil + local udp_packet_count = nil + if udp_class == 0x3a then + udp_size = buffer(4, 4):le_uint() + udp_unknown1 = buffer(8, 4):le_uint() + udp_tid = buffer(12, 4):le_uint() + udp_checksum = buffer(16, 4):le_uint() + elseif udp_class == 0x20 then + udp_connection_id = buffer(4, 4):le_uint() + udp_unknown1 = buffer(8, 4):le_uint() + udp_unknown2 = buffer(12, 4):le_uint() + udp_last_ack_packet = buffer(16, 4):le_uint() + udp_unknown3 = buffer(20, 4):le_uint() + udp_unknown4 = buffer(24, 4):le_uint() + elseif udp_class == 0x10 then + udp_connection_id = buffer(4, 4):le_uint() + udp_unknown1 = buffer(8, 4):le_uint() + udp_packet_count = buffer(12, 4):le_uint() + udp_size = buffer(16, 4):le_uint() + end + return { + length = length, + class = udp_class, + magic = udp_magic, + payload_size = udp_size, + unknown1 = unknown1, + unknown2 = unknown2, + unknown3 = unknown3, + unknown4 = unknown4, + tid = udp_tid, + checksum = udp_checksum, + connection_id = udp_connection_id, + packet_count = udp_packet_count, + last_ack_packet = udp_last_ack_packet, + } +end + +function process_udp_header(buffer, headers_tree) + local header_data = get_udp_header(buffer) + local header = headers_tree:add(bc_protocol, buffer(0, header_data.length), + "Baichuan UDP Header, length: " .. header_data.length .. ", type " .. header_data.class) + header:add_le(udp_magic, buffer(0,4)) + header:add_le(udp_type, buffer(0,1)) + if header_data.class == 0x3a then + header:add_le(udp_size, buffer(4, 4)) + header:add_le(udp_unknown,buffer(8, 4)) + header:add_le(udp_tid, buffer(12, 4)) + header:add_le(udp_checksum, buffer(16, 4)) + elseif header_data.class == 0x20 then + header:add_le(udp_connection_id, buffer(4, 4)) + header:add_le(udp_unknown, buffer(8, 4)) + header:add_le(udp_unknown, buffer(12, 4)) + header:add_le(udp_last_ack_packet, buffer(16, 4)) + header:add_le(udp_unknown, buffer(20, 4)) + header:add_le(udp_unknown, buffer(24, 4)) + elseif header_data.class == 0x10 then + header:add_le(udp_connection_id, buffer(4, 4)) + header:add_le(udp_unknown, buffer(8, 4)) + header:add_le(udp_packet_count, buffer(12, 4)) + header:add_le(udp_size, buffer(16, 4)) + end + return header_data.length +end + +function udp_reassemple(udp_header, subbuffer, more, pinfo, tree) + -- Cache udp message for later lookup + local con_id = udp_header.connection_id + if udp_fragments[con_id] == nil then + udp_fragments[con_id] = {} + end + local mess_id = udp_header.packet_count + if udp_fragments[con_id][mess_id] == nil then + udp_fragments[con_id][mess_id] = {} + end + udp_fragments[con_id][mess_id]['result'] = more + udp_fragments[con_id][mess_id]['message_id'] = mess_id + udp_fragments[con_id][mess_id]['buffer'] = subbuffer:bytes() + + -- Go backwards from current ID until: + -- I hit a result that is not NOMAGIC + -- Can be myself + local start_idx = mess_id + local start_fragment = udp_fragments[con_id][start_idx] + while start_fragment.result == "NOMAGIC" do + start_idx = start_idx -1 + start_fragment = udp_fragments[con_id][start_idx] + if start_fragment == nil then + break + end + end + + if start_fragment ~= nil then -- Found a starting fragment + local needed = start_fragment.result + if needed == "DONE" then + if start_fragment.message_id == udp_header.packet_count then + process_bc_message(start_fragment.buffer:tvb(), pinfo, tree) + end + elseif needed == "+1" then + -- Cannot handle in UDP... + -- Only happens in off chance not enough data for + -- even the header + -- Never observed to date + else + -- pinfo.cols['info'] = "SEARCHING" + local next_id = start_fragment.message_id + 1 + local reassembled = ByteArray.new() + local total_packet = 1 + reassembled = reassembled .. start_fragment.buffer + local target_len = reassembled:len() + start_fragment.result + while reassembled:len() < target_len do + local next_fragment = udp_fragments[con_id][next_id] + if next_fragment ~= nil then + reassembled = reassembled .. next_fragment.buffer + total_packet = total_packet + 1 + else + break + end + end + if reassembled:len() >= target_len then + start_fragment.result = "DONE" + process_bc_message(reassembled:tvb("Reassembled UDP"), pinfo, tree) + end + end + end +end +--- END UDP CONTENT + +function is_complete_bc_message(buffer) + length = buffer:len() + if length == 0 then + return "DONE" + end + + local sub_buffer = buffer + local table_msg_type_str = {} + local table_msg_type = {} + + local continue_loop = true + while ( continue_loop ) + do + + -- Get min bytes for a magic and header len + if sub_buffer:len() < 20 then + -- Need more bytes but we don't have a header to learn how many bytes + return "+1" + end + header_len = get_header_len(sub_buffer(0, nil)) + + if header_len >= 0 then + -- Valid magic and header found + + -- Ensure min bytes for full header + if sub_buffer:len() < header_len then + -- Need more bytes + return header_len - sub_buffer:len() + end + + + local header = get_header(sub_buffer(0, nil)) + + -- Get full header and body + local full_body_len = header.msg_len + header.header_len + if sub_buffer:len() < full_body_len then + return full_body_len - sub_buffer:len() + end + + local remaining = sub_buffer:len() - header.header_len + if header.header_len < sub_buffer:len() then + local body_buffer = sub_buffer(header.header_len, nil) + remaining = body_buffer:len() - header.msg_len + end + + -- Remaning bytes? + if remaining == 0 then + continue_loop = false + else + sub_buffer = sub_buffer(full_body_len, sub_buffer:len() - full_body_len) + end + else + return "NOMAGIC" + end + end + return "DONE" +end + +function process_bc_message(buffer, pinfo, tree) length = buffer:len() - if length == 0 then return end pinfo.cols.protocol = bc_protocol.name @@ -327,44 +618,16 @@ function bc_protocol.dissector(buffer, pinfo, tree) local continue_loop = true while ( continue_loop ) do - -- Get min bytes for a magic and header len - if sub_buffer:len() < 20 then - -- Need more bytes but we don't have a header to learn how many bytes - pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT - pinfo.desegment_offset = 0 - pinfo.cols['info'] = "Need more header" - return - end - header_len = get_header_len(sub_buffer(0, nil)) + if header_len >= 0 then - pinfo.cols['info'] = "Valid header" -- Valid magic and header found - - -- Ensure min bytes for full header - if sub_buffer:len() < header_len then - pinfo.cols['info'] = "Need even more header" - -- Need more bytes - pinfo.desegment_len = header_len - sub_buffer:len() - pinfo.desegment_offset = 0 - return buffer:len() - end - - local header = get_header(sub_buffer(0, nil)) table.insert(table_msg_type_str, header.msg_type_str) table.insert(table_msg_type, header.msg_type) -- Get full header and body local full_body_len = header.msg_len + header.header_len - if sub_buffer:len() < full_body_len then - -- need more bytes, - -- from https://wiki.wireshark.org/Lua/Dissectors#TCP_reassembly - pinfo.cols['info'] = "Need more body: " .. sub_buffer:len() .. " expected " .. full_body_len - pinfo.desegment_len = full_body_len - sub_buffer:len() - pinfo.desegment_offset = 0 - return buffer:len() - end local remaining = sub_buffer:len() - header.header_len @@ -382,19 +645,83 @@ function bc_protocol.dissector(buffer, pinfo, tree) if remaining == 0 then continue_loop = false else - pinfo.cols['info'] = "Another packet" sub_buffer = sub_buffer(full_body_len, nil) end else - pinfo.cols['info'] = "Invalid magic" - return -- Not a valid header + return end end local msg_type_strs = table.concat(table_msg_type_str, ",") local msg_types = table.concat(table_msg_type, ",") pinfo.cols['info'] = msg_type_strs .. ", type " .. msg_types + return +end + +function bc_protocol.init () + -- print ("(re-)initialise") + fragments = {} +end + +function bc_protocol.dissector(buffer, pinfo, tree) + local subbuffer = nil + local udp_header = nil + if pinfo.can_desegment == 0 then -- UDP + local udp_header_len = get_udp_header_len(buffer) + if udp_header_len > 0 then + udp_header = get_udp_header(buffer(0, udp_header_len)) + process_udp_header(buffer(0, udp_header_len), tree) + if udp_header.class == 0x3a then + decrypted_bytes = udp_decrypt(buffer(udp_header_len, nil):bytes(), udp_header.tid) + decryped_tvb = decrypted_bytes:tvb("UDP Decrypted Message") + local subtree = tree:add(bc_protocol, decryped_tvb, "UDP Message Data") + Dissector.get("xml"):call(decryped_tvb, pinfo, subtree) + pinfo.cols.protocol = bc_protocol.name .. " UDP Heartbeat" + elseif udp_header.class == 0x20 then + pinfo.cols.protocol = bc_protocol.name .. " UDP ACK" + else + subbuffer = buffer(udp_header_len, nil) + end + else + subbuffer = buffer(udp_header_len, nil) + end + else + subbuffer = buffer + end + if subbuffer ~= nil then + local more = is_complete_bc_message(subbuffer) + + if pinfo.can_desegment == 1 then -- TCP can use the desegment method + if more == "DONE" then + process_bc_message(subbuffer, pinfo, tree) + return + elseif more == "+1" then + pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT + pinfo.desegment_offset = 0 + return subbuffer:len() + elseif more == "NOMAGIC" then + return + else + pinfo.desegment_len = more + pinfo.desegment_offset = 0 + return subbuffer:len() + end + else -- UDP can not use the desegment method, must reassemble manually + if udp_header ~= nil then + if udp_header.class == 0x10 then -- Continuable udp class + udp_reassemple(udp_header, subbuffer, more, pinfo, tree) + end + end + end + end end DissectorTable.get("tcp.port"):add(9000, bc_protocol) DissectorTable.get("tcp.port"):add(52941, bc_protocol) -- change to your own custom port + +DissectorTable.get("udp.port"):add(23534, bc_protocol) -- change to your own custom port +DissectorTable.get("udp.port"):add(29237, bc_protocol) +DissectorTable.get("udp.port"):add(39654, bc_protocol) +DissectorTable.get("udp.port"):add(28100, bc_protocol) +DissectorTable.get("udp.port"):add(13154, bc_protocol) +DissectorTable.get("udp.port"):add(2015, bc_protocol) From c3f0a8c0c5c825c14f0875fd56cf83caddd19cfd Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 12 Aug 2021 17:37:25 +0700 Subject: [PATCH 17/56] Serde UDP packets --- crates/core/Cargo.toml | 1 + crates/core/src/bc/model.rs | 8 +- crates/core/src/bc/xml.rs | 2 +- crates/core/src/bcmedia/de.rs | 2 +- crates/core/src/bcudp/crc.rs | 79 ++++ crates/core/src/bcudp/de.rs | 339 ++++++++++++++++++ crates/core/src/bcudp/mod.rs | 32 ++ crates/core/src/bcudp/model.rs | 69 ++++ crates/core/src/bcudp/samples/udp_ack.bin | Bin 0 -> 28 bytes crates/core/src/bcudp/samples/udp_data.bin | Bin 0 -> 1196 bytes crates/core/src/bcudp/samples/udp_multi_0.bin | Bin 0 -> 120 bytes crates/core/src/bcudp/samples/udp_multi_1.bin | Bin 0 -> 122 bytes crates/core/src/bcudp/samples/udp_multi_2.bin | Bin 0 -> 156 bytes crates/core/src/bcudp/samples/udp_multi_3.bin | Bin 0 -> 1350 bytes crates/core/src/bcudp/samples/udp_multi_4.bin | Bin 0 -> 546 bytes crates/core/src/bcudp/samples/udp_multi_5.bin | Bin 0 -> 156 bytes crates/core/src/bcudp/samples/udp_multi_6.bin | Bin 0 -> 156 bytes crates/core/src/bcudp/samples/udp_multi_7.bin | Bin 0 -> 1350 bytes crates/core/src/bcudp/samples/udp_multi_8.bin | Bin 0 -> 156 bytes crates/core/src/bcudp/samples/udp_multi_9.bin | Bin 0 -> 156 bytes .../bcudp/samples/udp_negotiate_camcfm.bin | Bin 0 -> 156 bytes .../src/bcudp/samples/udp_negotiate_camt.bin | Bin 0 -> 120 bytes .../bcudp/samples/udp_negotiate_clientt.bin | Bin 0 -> 122 bytes .../src/bcudp/samples/udp_negotiate_disc.bin | Bin 0 -> 87 bytes .../src/bcudp/samples/xml_crypto_sample1.bin | Bin 0 -> 100 bytes .../samples/xml_crypto_sample1_plaintext.bin | 8 + crates/core/src/bcudp/ser.rs | 183 ++++++++++ crates/core/src/bcudp/xml.rs | 138 +++++++ crates/core/src/bcudp/xml_crypto.rs | 34 ++ crates/core/src/lib.rs | 2 + dissector/udp.md | 283 +++++++++++++++ 31 files changed, 1174 insertions(+), 6 deletions(-) create mode 100644 crates/core/src/bcudp/crc.rs create mode 100644 crates/core/src/bcudp/de.rs create mode 100644 crates/core/src/bcudp/mod.rs create mode 100644 crates/core/src/bcudp/model.rs create mode 100644 crates/core/src/bcudp/samples/udp_ack.bin create mode 100644 crates/core/src/bcudp/samples/udp_data.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_0.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_1.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_2.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_3.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_4.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_5.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_6.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_7.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_8.bin create mode 100644 crates/core/src/bcudp/samples/udp_multi_9.bin create mode 100644 crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin create mode 100644 crates/core/src/bcudp/samples/udp_negotiate_camt.bin create mode 100644 crates/core/src/bcudp/samples/udp_negotiate_clientt.bin create mode 100644 crates/core/src/bcudp/samples/udp_negotiate_disc.bin create mode 100644 crates/core/src/bcudp/samples/xml_crypto_sample1.bin create mode 100644 crates/core/src/bcudp/samples/xml_crypto_sample1_plaintext.bin create mode 100644 crates/core/src/bcudp/ser.rs create mode 100644 crates/core/src/bcudp/xml.rs create mode 100644 crates/core/src/bcudp/xml_crypto.rs create mode 100644 dissector/udp.md diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 2728304..d6a782c 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -20,5 +20,6 @@ yaserde_derive = "0.3.16" xml-rs = "0.8" [dev-dependencies] +assert_matches = "1.5.0" env_logger = "*" indoc = "0.3" diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index 588e282..e4f1215 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -53,7 +53,7 @@ pub struct Bc { #[allow(clippy::large_enum_variant)] pub enum BcBody { /// Legacy is unsupported except for login where it is used - /// to negociate the initial login and upgrade to modern + /// to negotiate the initial login and upgrade to modern LegacyMsg(LegacyMsg), /// Modern is the current reolink protocol it is mostly /// xml based @@ -64,7 +64,7 @@ pub enum BcBody { /// /// The first payload is extension which describes the second payload. If the /// `payload_offset` is `0` then their is no `extension` (usually because it has -/// already been negociated in a previous message) and it is `None` +/// already been negotiated in a previous message) and it is `None` /// /// The second payload contains the actual data of interest and is all bytes after /// the `payload_offset` up to the `body_len`. If `payload_offset` @@ -153,7 +153,7 @@ pub(super) struct BcSendInfo { /// These are the encyption modes supported by the camera /// -/// The mode is negociated during login +/// The mode is negotiated during login #[derive(Debug, Clone)] pub enum EncryptionProtocol { /// Older camera use no encryption @@ -161,7 +161,7 @@ pub enum EncryptionProtocol { /// Camera/Firmwares before 2021 use BCEncrypt which is a simple XOr BCEncrypt, /// Latest cameras/firmwares use Aes with the key derived from - /// the camera's password and the negociated NONCE + /// the camera's password and the negotiated NONCE Aes(Option<[u8; 16]>), } diff --git a/crates/core/src/bc/xml.rs b/crates/core/src/bc/xml.rs index 1aea64a..2ce5a5c 100644 --- a/crates/core/src/bc/xml.rs +++ b/crates/core/src/bc/xml.rs @@ -95,7 +95,7 @@ pub struct Encryption { #[yaserde(rename = "type")] /// The hashing algorithm used. Only observed the value of "md5" pub type_: String, - /// The nonce used to negociate the login and to generate the AES key + /// The nonce used to negotiate the login and to generate the AES key pub nonce: String, } diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index 67de1f9..1fd7e1b 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -312,7 +312,7 @@ fn bcmedia_adpcm(buf: &[u8]) -> IResult<&[u8], BcMediaAdpcm> { #[cfg(test)] mod tests { use super::Error; - use crate::bc_protocol::filesub::FileSubscriber; + use crate::bc_protocol::FileSubscriber; use crate::bcmedia::model::*; use env_logger::Env; use log::*; diff --git a/crates/core/src/bcudp/crc.rs b/crates/core/src/bcudp/crc.rs new file mode 100644 index 0000000..150a0e7 --- /dev/null +++ b/crates/core/src/bcudp/crc.rs @@ -0,0 +1,79 @@ +const TABLE: [u32; 1024] = [ + 0x0, 0x0, 0x0, 0x0, 0x96, 0x30, 0x7, 0x77, 0x2C, 0x61, 0xE, 0xEE, 0xBA, 0x51, 0x9, 0x99, 0x19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, 0x69, 0x49, 0xDB, 0x77, 0x6E, 0x3E, 0x4A, 0x6A, 0xD1, + 0xAE, 0xDC, 0x5A, 0xD6, 0xD9, 0x66, 0xB, 0xDF, 0x40, 0xF0, 0x3B, 0xD8, 0x37, 0x53, 0xAE, 0xBC, + 0xA9, 0xC5, 0x9E, 0xBB, 0xDE, 0x7F, 0xCF, 0xB2, 0x47, 0xE9, 0xFF, 0xB5, 0x30, 0x1C, 0xF2, 0xBD, + 0xBD, 0x8A, 0xC2, 0xBA, 0xCA, 0x30, 0x93, 0xB3, 0x53, 0xA6, 0xA3, 0xB4, 0x24, 0x5, 0x36, 0xD0, + 0xBA, 0x93, 0x6, 0xD7, 0xCD, 0x29, 0x57, 0xDE, 0x54, 0xBF, 0x67, 0xD9, 0x23, 0x2E, 0x7A, 0x66, + 0xB3, 0xB8, 0x4A, 0x61, 0xC4, 0x2, 0x1B, 0x68, 0x5D, 0x94, 0x2B, 0x6F, 0x2A, 0x37, 0xBE, 0xB, + 0xB4, 0xA1, 0x8E, 0xC, 0xC3, 0x1B, 0xDF, 0x5, 0x5A, 0x8D, 0xEF, 0x02, 0x2D, +]; + +pub(crate) fn calc_crc(payload: &[u8]) -> u32 { + let mut r: u32 = 0; + for &val in payload.iter() { + let offset = (((val as u32 ^ r) & 0xFF) << 2) as usize; + let val: u32 = TABLE[offset + 3] << 24 + | TABLE[offset + 2] << 16 + | TABLE[offset + 1] << 8 + | TABLE[offset]; + r = val ^ (r >> 8); + } + r +} diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs new file mode 100644 index 0000000..1b3d6e8 --- /dev/null +++ b/crates/core/src/bcudp/de.rs @@ -0,0 +1,339 @@ +use super::{crc::calc_crc, model::*, xml::*, xml_crypto::decrypt}; +use err_derive::Error; +use nom::IResult; +use nom::{ + combinator::*, + error::{make_error, ErrorKind}, + number::streaming::*, + take, take_str, Err, +}; +use std::io::Read; + +/// The error types used during deserialisation +#[derive(Debug, Error)] +pub enum Error { + /// A Nom parsing error usually a malformed packet + #[error(display = "Parsing error")] + NomError(String), + /// An IO error such as the stream being dropped + #[error(display = "I/O error")] + IoError(#[error(source)] std::io::Error), +} +type NomErrorType<'a> = nom::error::Error<&'a [u8]>; + +impl<'a> From>> for Error { + fn from(k: nom::Err>) -> Self { + let reason = match k { + nom::Err::Error(e) => format!("Nom Error: {:?}", e), + nom::Err::Failure(e) => format!("Nom Error: {:?}", e), + _ => "Unknown Nom error".to_string(), + }; + Error::NomError(reason) + } +} + +fn read_from_reader(mut parser: P, mut rdr: R) -> Result +where + R: Read, + E: for<'a> From>> + From, + P: FnMut(&[u8]) -> nom::IResult<&[u8], O>, +{ + let mut input: Vec = Vec::new(); + loop { + let to_read = match parser(&input) { + Ok((_, parsed)) => return Ok(parsed), + Err(nom::Err::Incomplete(needed)) => { + match needed { + nom::Needed::Unknown => std::num::NonZeroUsize::new(1).unwrap(), // read one byte + nom::Needed::Size(len) => len, + } + } + Err(e) => return Err(e.into()), + }; + + if 0 == (&mut rdr) + .take(to_read.get() as u64) + .read_to_end(&mut input)? + { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } + } +} + +impl BcUdp { + pub(crate) fn deserialize(r: R) -> Result { + // Throw away the nom-specific return types + read_from_reader(|reader| bcudp(reader), r) + } +} + +fn bcudp(buf: &[u8]) -> IResult<&[u8], BcUdp> { + let (buf, magic) = verify(le_u32, |x| { + matches!( + *x, + MAGIC_HEADER_UDP_NEGO | MAGIC_HEADER_UDP_ACK | MAGIC_HEADER_UDP_DATA + ) + })(buf)?; + + match magic { + MAGIC_HEADER_UDP_NEGO => { + let (buf, payload) = udp_disc(buf)?; + Ok((buf, BcUdp::Discovery(payload))) + } + MAGIC_HEADER_UDP_ACK => { + let (buf, payload) = udp_ack(buf)?; + Ok((buf, BcUdp::Ack(payload))) + } + MAGIC_HEADER_UDP_DATA => { + let (buf, payload) = udp_data(buf)?; + Ok((buf, BcUdp::Data(payload))) + } + _ => unreachable!(), + } +} + +fn udp_disc(buf: &[u8]) -> IResult<&[u8], UdpDiscovery> { + let (buf, payload_size) = le_u32(buf)?; + let (buf, _unknown_a) = verify(le_u32, |&x| x == 1)(buf)?; + let (buf, tid) = le_u32(buf)?; + let (buf, checksum) = le_u32(buf)?; + let (buf, enc_data_slice) = take!(buf, payload_size)?; + + let actual_checksum = calc_crc(enc_data_slice); + assert_eq!(checksum, actual_checksum); + + let decrypted_payload = decrypt(tid, enc_data_slice); + let payload = UdpXml::try_parse(decrypted_payload.as_slice()) + .map_err(|_| Err::Error(make_error(buf, ErrorKind::MapRes)))?; + + let data = UdpDiscovery { tid, payload }; + Ok((buf, data)) +} + +fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { + let (buf, connection_id) = le_u32(buf)?; + let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, _unknown_b) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, packet_id) = le_u32(buf)?; + let (buf, _unknown_c) = le_u32(buf)?; + let (buf, _unknown_d) = verify(le_u32, |&x| x == 0)(buf)?; + + let data = UdpAck { + connection_id, + packet_id, + }; + Ok((buf, data)) +} + +fn udp_data(buf: &[u8]) -> IResult<&[u8], UdpData> { + let (buf, connection_id) = le_u32(buf)?; + let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, packet_id) = le_u32(buf)?; + let (buf, payload_size) = le_u32(buf)?; + let (buf, payload) = take!(buf, payload_size)?; + + let data = UdpData { + connection_id, + packet_id, + payload: payload.to_vec(), + }; + Ok((buf, data)) +} + +#[cfg(test)] +mod tests { + use super::Error; + use crate::bc_protocol::FileSubscriber; + use crate::bcudp::model::*; + use crate::bcudp::xml::*; + use assert_matches::assert_matches; + use env_logger::Env; + use log::*; + use std::io::ErrorKind; + use std::path::PathBuf; + + fn init() { + let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) + .is_test(true) + .try_init(); + } + + fn sample(name: &str) -> PathBuf { + let dir = std::env::current_dir().unwrap(); // This is crate root during cargo test + dir.join("src").join("bcudp").join("samples").join(name) + } + + #[test] + // Tests the decoding of a UdpDiscovery with a discovery xml + fn test_nego_disconnect() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_disc.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 96, + payload: UdpXml { + disconnect: Some(Disconnect { + cid: 82000, + did: 80, + }), + .. + }, + })) + ); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera Transmission xml + fn test_nego_cam_transmission() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_camt.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 113, + payload: UdpXml { + camera_transmission: Some(CameraTransmission { + sid: 62098713, + conn: conn_str, + cid: 82001, + did: 96, + }), + .. + }, + })) if &conn_str == "local" + ); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Client Transmission xml + fn test_nego_client_transmission() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_clientt.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 1101, + payload: UdpXml { + client_transmission: Some(ClientTransmission { + sid: 62098713, + conn: conn_str, + cid: 82001, + mtu: 1350, + }), + .. + }, + })) if &conn_str == "local" + ); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera CFM xml + fn test_nego_cfm() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_negotiate_camcfm.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Discovery(UdpDiscovery { + tid: 1101, + payload: UdpXml { + camera_cfm: Some(CameraCfm { + sid: 62098713, + conn: conn_str, + rsp: 0, + cid: 82001, + did: 96, + time_r: 0, + }), + .. + }, + })) if &conn_str == "local" + ); + } + + #[test] + // Tests the decoding of an acknoledge packet + fn test_ack() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_ack.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Ack(UdpAck { + connection_id: 80, + packet_id: 2439, + })) + ); + } + + #[test] + // Tests the decoding of an data packet + fn test_data() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![sample("udp_data.bin")]); + + let e = BcUdp::deserialize(&mut subsciber); + assert_matches!( + e, + Ok(BcUdp::Data(UdpData { + connection_id: 82000, + packet_id: 2439, + payload: payload_data + })) if payload_data.len() == 1176 + ); + } + + #[test] + // Tests the decoding of multiple packets + fn test_multi_packets() { + init(); + + let mut subsciber = FileSubscriber::from_files(vec![ + sample("udp_multi_0.bin"), + sample("udp_multi_1.bin"), + sample("udp_multi_2.bin"), + sample("udp_multi_3.bin"), + sample("udp_multi_4.bin"), + sample("udp_multi_5.bin"), + sample("udp_multi_6.bin"), + sample("udp_multi_7.bin"), + sample("udp_multi_8.bin"), + sample("udp_multi_9.bin"), + ]); + + // Should derealise all of this + loop { + let e = BcUdp::deserialize(&mut subsciber); + match e { + Err(Error::IoError(e)) if e.kind() == ErrorKind::UnexpectedEof => { + // Reach end of files + break; + } + Err(e) => { + error!("{:?}", e); + panic!(); + } + Ok(_) => {} + } + } + } +} diff --git a/crates/core/src/bcudp/mod.rs b/crates/core/src/bcudp/mod.rs new file mode 100644 index 0000000..4c50f65 --- /dev/null +++ b/crates/core/src/bcudp/mod.rs @@ -0,0 +1,32 @@ +//! This module contains the protocol for dealing with UDP. +//! +//! There are three types of packets +//! +//! - Discovery +//! - Ack +//! - Data +//! +//! --- +//! +//! **Discovery**: Deals with setting up the initial connection and including their +//! connection IDs and the MTU +//! +//! --- +//! +//! **Ack**: Is sent after every packet is recieved +//! +//! --- +//! +//! **Data**: Contains a Bc packet payload. This is a stream and one Bc Packet may +//! be split accross multiple UDP Data packets +//! + +mod crc; +mod de; +/// Contains the model describing the top level structures +pub mod model; +mod ser; +/// Contains the udp related xml payloads +pub mod xml; +// Constains routines to de/encrypt udp xml +mod xml_crypto; diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs new file mode 100644 index 0000000..46c4214 --- /dev/null +++ b/crates/core/src/bcudp/model.rs @@ -0,0 +1,69 @@ +//! The BcUdp Model +//! + +use super::xml::*; + +/// Top level udp packet +#[derive(Debug, PartialEq, Eq)] +pub enum BcUdp { + /// Packet from the negotiate stage when connection info is exchanged + Discovery(UdpDiscovery), + /// Packet to acknoledge receipt of a data packet + Ack(UdpAck), + /// Packet containing the data (or part of the data) of a Bc packet + Data(UdpData), +} + +/// Magic for the UDP Discovery packet +pub const MAGIC_HEADER_UDP_NEGO: u32 = 0x2a87cf3a; + +/// The Discovery packet is sent and received to init a connection +#[derive(Debug, PartialEq, Eq)] +pub struct UdpDiscovery { + // 4 Bytes Magic + // 4 Byte payload size + // 4 Bytes unknown always `01000000` + /// The transmission id is unique to a message and used as an encryption key + pub tid: u32, + // The checksum of the payload + // pub checksum: u32, + /// The payload + pub payload: UdpXml, +} + +/// Magic for the UDP Ack packet +pub const MAGIC_HEADER_UDP_ACK: u32 = 0x2a87cf20; + +/// Send to acknoledge a [`UdpData`] packet. If this is not sent then the camera will +/// resend the packet +#[derive(Debug, PartialEq, Eq)] +pub struct UdpAck { + /// The connection ID of the other party + /// + /// This is negotiated during [`UdpDiscovery`] + pub connection_id: u32, + // Unknown 4 bytes always 0 + /// The ID of the last data packet [`UdpData`] + pub packet_id: u32, + // 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` + // 2 Bytes Unknown: Observed values `00000000` +} + +/// Magic for the UDP Data packet +pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10; + +/// Contains the data of a [`crate::bc::model::Bc`] packet +#[derive(Debug, PartialEq, Eq)] +pub struct UdpData { + /// The connection ID of the other party + /// + /// This is negotiated during [`UdpDiscovery`] + pub connection_id: u32, + // Unknown 4 bytes always 0 + /// The ID of the data packet + pub packet_id: u32, + // Unknown 4 bytes always 0 + // 4 Byte payload size + /// The payload + pub payload: Vec, +} diff --git a/crates/core/src/bcudp/samples/udp_ack.bin b/crates/core/src/bcudp/samples/udp_ack.bin new file mode 100644 index 0000000000000000000000000000000000000000..0456b5375bae9406b32032f6e248c755778b6b5b GIT binary patch literal 28 ScmY#5->wzFfB@~B2sQvYcmja{ literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_data.bin b/crates/core/src/bcudp/samples/udp_data.bin new file mode 100644 index 0000000000000000000000000000000000000000..d859d7d36ab7edc0248e81922a29037163fe8a6d GIT binary patch literal 1196 zcmWeQ->wzlz{mgs?VJn@GgufHKHS^G#SG*>00}ZO$e#ewKww~6o^+AnBE$cW2@X>B ze;CC~*J&uau(B{FG~NFGX;F|)eT~wK|GwWpaDF{6EVy;LiqAt!QI9kFg%dURwZ7bI zbH7ZnG+(kPHYul0J#Ss{*2{Zei<2vwiI`59U90CJVxkl>}@q|DZgD zu{vj?!|OLim!m`_=Pqhlfaao zW=dr;?Sps^?(YvEKAOKDGdu?STc-XGqnzoQkTOxeqil)?Cgcckv535%%bdsQKfi0w zce}4zuMXOTw|N$?(&?K&~?^LMJ} zUwPojSmYPp<>$Ljr!0Mr{_gTBvp8piD>ImC3#WSW&SdbJeQ#g<$_a=3S^gw5m)v>O zT`)iTPEp^^Z^HYg{i!K$$eDNe*|hKT7EQ8?yd%5$^sc#%RWJEB=zrM~aXkhc60rDh zU_uKA!<1wXBQuj^kT?+B$PB&34Pi1m&bpygfAtCPMaP>rVozvP?>ur-x2a%CL4Z83 zgvHbawMBcoG%Ps|eO!I~Ku_JQYM$+vbL9 zi85SqT3GPczbDV1ztGESefsj!(&dwT4vV?Haap|8X!ZW(8|Ay@R0HfbtH#f{l9|EI zUYu-l?##)Lxr*U$N~9ig&kTL_PAfZqagxeUQ|2u3H7ji<_^y6_=cZt|b+*8{T|V>I zoTynFUe=n{Q@Sm7!W+)`r*Xw52SKxoys+j$Gpubh~CD>tI_<-GUc)Kx@8$1KewhWJG_5k z>db{qduHqu3jVa`b;+57w_T?&-K$l8lNa&x#YWdPJiFI@b_y5ceZk7$@M}K1Lj6;7 z?H3FaVjtcKZ#G^1A|$m%xA9MRb=&g%DY5z$@|y&o&HX&JHX!C|QH99| w!E@8MyX0lXWLW9)Jhfvm(|Vz{A@@Q1M6r)PJk9l`D!Gc98z)SkdH|ft0GPodBme*a literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_0.bin b/crates/core/src/bcudp/samples/udp_multi_0.bin new file mode 100644 index 0000000000000000000000000000000000000000..040417ce78b1122396a9c1f121b44bf5d7f01167 GIT binary patch literal 120 zcmcCI->#Lyz`(!=#Nj}^?f*B`c{%d_w@L%#CgghL^k@2hd|k)5LH5M|NyfK5_FrBw zyLgV7U`@9mQ_4BVlE}O9aSz{?1ny8hvh+;;9nXzt9v{-~jd!UA>bE=XrOD73ANLHX Xzeo6b({zu$s(Zh^zw16BM_3d9`71Wv literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_1.bin b/crates/core/src/bcudp/samples/udp_multi_1.bin new file mode 100644 index 0000000000000000000000000000000000000000..9fc66d03642593a4459457521df9b953a6ebc53b GIT binary patch literal 122 zcmcCI->#L$z`(!=#4$kpWOKru**Wt5*GmH=r)GKNbY%K|d{@V~f$hZqNgB63_UkR5 zT|CoFu%=CrDdn_dN#w2gxQ8!F0(aOQS$d}Aj^{?hCx^5<;$5nN`pqv#YjU=RIqq9g X?){nT)32`J3#NBMU;WVT0Gkg0A5k}G literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_2.bin b/crates/core/src/bcudp/samples/udp_multi_2.bin new file mode 100644 index 0000000000000000000000000000000000000000..24097da06391c8afacd024670f509b2f06822786 GIT binary patch literal 156 zcmcCI->%icz`(!=#4$h|WdFHpc8+yjM4r_j3!5y59{k!^$B0NKK<$nxnOk1Y0`epwG2%D IxAlVp0EVnXA^-pY literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_3.bin b/crates/core/src/bcudp/samples/udp_multi_3.bin new file mode 100644 index 0000000000000000000000000000000000000000..70cb065e6b9afbfd0ff2a680e15989e68971f814 GIT binary patch literal 1350 zcmWeQ->wzFfB;6U3=ALc?crhs3hA(e#TkX}h@=`B8W|h88CjY;ngWrdxrwobrHP|~ ztBIq9fuWl-gR8T-sj0E6iIKCTiwzF00E3ZijN7(8Kp);02~4UA-4hY literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_5.bin b/crates/core/src/bcudp/samples/udp_multi_5.bin new file mode 100644 index 0000000000000000000000000000000000000000..24097da06391c8afacd024670f509b2f06822786 GIT binary patch literal 156 zcmcCI->%icz`(!=#4$h|WdFHpc8+yjM4r_j3!5y59{k!^$B0NKK<$nxnOk1Y0`epwG2%D IxAlVp0EVnXA^-pY literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_6.bin b/crates/core/src/bcudp/samples/udp_multi_6.bin new file mode 100644 index 0000000000000000000000000000000000000000..24097da06391c8afacd024670f509b2f06822786 GIT binary patch literal 156 zcmcCI->%icz`(!=#4$h|WdFHpc8+yjM4r_j3!5y59{k!^$B0NKK<$nxnOk1Y0`epwG2%D IxAlVp0EVnXA^-pY literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_7.bin b/crates/core/src/bcudp/samples/udp_multi_7.bin new file mode 100644 index 0000000000000000000000000000000000000000..70cb065e6b9afbfd0ff2a680e15989e68971f814 GIT binary patch literal 1350 zcmWeQ->wzFfB;6U3=ALc?crhs3hA(e#TkX}h@=`B8W|h88CjY;ngWrdxrwobrHP|~ ztBIq9fuWl-gR8T-sj0E6iIKCTi%icz`(!=#4$h|WdFHpc8+yjM4r_j3!5y59{k!^$B0NKK<$nxnOk1Y0`epwG2%D IxAlVp0EVnXA^-pY literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_multi_9.bin b/crates/core/src/bcudp/samples/udp_multi_9.bin new file mode 100644 index 0000000000000000000000000000000000000000..24097da06391c8afacd024670f509b2f06822786 GIT binary patch literal 156 zcmcCI->%icz`(!=#4$h|WdFHpc8+yjM4r_j3!5y59{k!^$B0NKK<$nxnOk1Y0`epwG2%D IxAlVp0EVnXA^-pY literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin b/crates/core/src/bcudp/samples/udp_negotiate_camcfm.bin new file mode 100644 index 0000000000000000000000000000000000000000..c3c1b0ace310542d6800171d784db3c3753cf323 GIT binary patch literal 156 zcmV;N0Av3;&xb0A000010000@1ONcYvCJ=|5FbzEiBKM@aY%dNDo=<+ZC2tN%Jh{u z-bS*)>)mAWBoh_p-~%-F40~6^1|7aveNgC2!pxa-l>xoN>)mDRFcTH#-~~RW3MB}a zR!yxNcU!nGz@p4$*hsa`_?CYBekUWY>H$B;Kq&~DNCoQ^dtme%_WFuN)H2+$k-sUD Kd;(AC(^61wXh%^1 literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_negotiate_camt.bin b/crates/core/src/bcudp/samples/udp_negotiate_camt.bin new file mode 100644 index 0000000000000000000000000000000000000000..7d3c4ebe86c8c1e324dc096262503aa07a40ca0b GIT binary patch literal 120 zcmcCI->#Lyz`(!=#Dzedxky*8AxGZ-Kxu$nU#>^a*G%7!U+Wk*RG;`iSLm|Se#_;v zi<`^@YbFXZrCe|#L$z`(!=#J(&H4EN;14VMVW`#jydZFg{(+@uQg3)}JoNmq_I72LYM_4eH}0C8Q-U1# Zg%^8&mj3pu%jt^gon literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/udp_negotiate_disc.bin b/crates/core/src/bcudp/samples/udp_negotiate_disc.bin new file mode 100644 index 0000000000000000000000000000000000000000..34f57897d3060ce3e018d1efef2307fbb3653b6b GIT binary patch literal 87 zcmcCI->&7%z`(!=#0fwg;@adiJxAXEa%q6%%q)+Z&jv<&8r5Rn#~k}NUFDMFey#1Z qi>I0iR<}q8CCwJHh`G$}-?81aW=qZTrZ?^j{W~pxFH-%@qz(Wz8X{}} literal 0 HcmV?d00001 diff --git a/crates/core/src/bcudp/samples/xml_crypto_sample1.bin b/crates/core/src/bcudp/samples/xml_crypto_sample1.bin new file mode 100644 index 0000000000000000000000000000000000000000..db2c08c0198acf5697e05e7058cad22fcedcf887 GIT binary patch literal 100 zcmV-q0Gt1wY#&eBbx + +62097899 +local +82000 +80 + + diff --git a/crates/core/src/bcudp/ser.rs b/crates/core/src/bcudp/ser.rs new file mode 100644 index 0000000..04c7887 --- /dev/null +++ b/crates/core/src/bcudp/ser.rs @@ -0,0 +1,183 @@ +use super::{crc::calc_crc, model::*, xml_crypto::encrypt}; +use cookie_factory::bytes::*; +use cookie_factory::sequence::tuple; +use cookie_factory::{combinator::*, gen}; +use cookie_factory::{GenError, SerializeFn}; +use err_derive::Error; +use log::error; +use std::io::Write; + +/// The error types used during serialisation +#[derive(Debug, Error)] +pub enum Error { + /// A Cookie Factor GenError + #[error(display = "Cookie GenError")] + GenError(#[error(source)] GenError), +} + +impl BcUdp { + pub(crate) fn serialize(&self, buf: W) -> Result { + let (buf, _) = match &self { + BcUdp::Discovery(payload) => { + let xml_payload = encrypt(payload.tid, &payload.payload.serialize(vec![]).unwrap()); + gen(bcudp_disc(payload, &xml_payload), buf)? + } + BcUdp::Ack(payload) => gen(bcudp_ack(payload), buf)?, + BcUdp::Data(payload) => { + let binary_payload = &payload.payload; + gen(bcudp_data(payload, binary_payload), buf)? + } + }; + + Ok(buf) + } +} + +fn bcudp_disc<'a, W: 'a + Write>( + payload: &'a UdpDiscovery, + xml_payload: &'a [u8], +) -> impl SerializeFn + 'a { + let checksum = calc_crc(xml_payload); + tuple(( + le_u32(MAGIC_HEADER_UDP_NEGO), + le_u32(xml_payload.len() as u32), + le_u32(1), + le_u32(payload.tid), + le_u32(checksum), + slice(xml_payload), + )) +} + +fn bcudp_ack<'a, W: 'a + Write>(payload: &'a UdpAck) -> impl SerializeFn + 'a { + tuple(( + le_u32(MAGIC_HEADER_UDP_ACK), + le_u32(payload.connection_id), + le_u32(0), + le_u32(0), + le_u32(payload.packet_id), + le_u32(0), + le_u32(0), + )) +} + +fn bcudp_data<'a, W: 'a + Write>( + payload: &'a UdpData, + binary_payload: &'a [u8], +) -> impl SerializeFn + 'a { + tuple(( + le_u32(MAGIC_HEADER_UDP_DATA), + le_u32(payload.connection_id), + le_u32(0), + le_u32(payload.packet_id), + le_u32(binary_payload.len() as u32), + slice(binary_payload), + )) +} + +#[cfg(test)] +mod tests { + use crate::bcudp::model::*; + use env_logger::Env; + + fn init() { + let _ = env_logger::Builder::from_env(Env::default().default_filter_or("info")) + .is_test(true) + .try_init(); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a discovery xml + fn test_nego_disconnect() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_disc.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera Transmission xml + fn test_nego_cam_transmission() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_camt.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Client Transmission xml + fn test_nego_client_transmission() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_clientt.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of a UdpDiscovery with a Camera CFM xml + fn test_nego_cfm() { + init(); + + let sample = include_bytes!("samples/udp_negotiate_camcfm.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + // Raw samples don't quite match exactly + // because the yaserde for xml puts spaces and new lines in different places + // then the raw data from the camera so we skip this last assert + //assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of an acknoledge packet + fn test_ack() { + init(); + + let sample = include_bytes!("samples/udp_ack.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + assert_eq!(&sample[..], ser_buf.as_slice()); + } + + #[test] + // Tests the decoding of an data packet + fn test_data() { + init(); + + let sample = include_bytes!("samples/udp_data.bin"); + + let msg = BcUdp::deserialize(&sample[..]).unwrap(); + let ser_buf = msg.serialize(vec![]).unwrap(); + let msg2 = BcUdp::deserialize::<&[u8]>(ser_buf.as_ref()).unwrap(); + assert_eq!(msg, msg2); + assert_eq!(&sample[..], ser_buf.as_slice()); + } +} diff --git a/crates/core/src/bcudp/xml.rs b/crates/core/src/bcudp/xml.rs new file mode 100644 index 0000000..f99d7ca --- /dev/null +++ b/crates/core/src/bcudp/xml.rs @@ -0,0 +1,138 @@ +// YaSerde currently macro-expands names like __type__value from type_ + +use std::io::{Read, Write}; +// YaSerde is currently naming the traits and the derive macros identically +use yaserde::{ser::Config, YaDeserialize, YaSerialize}; +use yaserde_derive::{YaDeserialize, YaSerialize}; + +/// The top level of the UDP xml is P2P +#[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)] +#[yaserde(rename = "P2P")] +pub struct UdpXml { + /// C2D_S xml + #[yaserde(rename = "C2D_S")] + pub start: Option, + /// C2D_S xml + #[yaserde(rename = "C2D_C")] + pub start_with: Option, + /// D2C_T xml + #[yaserde(rename = "D2C_T")] + pub camera_transmission: Option, + /// C2D_T xml + #[yaserde(rename = "C2D_T")] + pub client_transmission: Option, + /// D2C_CFM xml + #[yaserde(rename = "D2C_CFM")] + pub camera_cfm: Option, + /// C2D_DISC xml + #[yaserde(rename = "C2D_DISC")] + pub disconnect: Option, +} + +impl UdpXml { + pub(crate) fn try_parse(s: impl Read) -> Result { + yaserde::de::from_reader(s) + } + pub(crate) fn serialize(&self, w: W) -> Result { + yaserde::ser::serialize_with_writer(self, w, &Config::default()) + } +} + +/// C2D_S xml +/// +/// The camera will send binary data to port 3000 +/// to whoever it gets this message from +/// +/// It should be broadcasted to port 2015 +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct DiscoveryStartAny { + /// The destination to reply to + pub to: StartTo, +} + +/// to xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct StartTo { + /// Port to open udp connections with + pub port: u32, +} + +/// C2D_C xml +/// +/// This will start a connection with any camera that has this UID +/// It should be broadcasted to port 2018 +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct DiscoveryStartWith { + /// UID of the camera the client wants to connect with + pub uid: String, + /// Cli contains the udp port to communicate on + pub cli: StartCli, + /// The cid is the client ID + pub cid: u32, + /// Maximum transmission size, + pub mtu: u32, + /// Debug mode. Purpose unknown + pub debug: bool, + /// Os of the machine known values are `"MAC"` + #[yaserde(rename = "p")] + pub os: String, +} + +/// C2D_C xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct StartCli { + /// Port to start udp communication with + pub port: u32, +} + +/// C2D_DISC xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct Disconnect { + /// The client connection ID + pub cid: u32, + /// The camera connection ID + pub did: u32, +} + +/// D2C_T xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct CameraTransmission { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// The client connection ID + pub cid: u32, + /// The camera connection ID + pub did: u32, +} + +/// C2D_T xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct ClientTransmission { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// The client connection ID + pub cid: u32, + /// Maximum size in bytes of a transmission + pub mtu: u32, +} + +/// D2C_CFM xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct CameraCfm { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// Unknown known values are `0` + pub rsp: u32, + /// The client connection ID + pub cid: u32, + /// The camera connection ID + pub did: u32, + /// The time but only value that has been observed is `0 + pub time_r: u32, +} diff --git a/crates/core/src/bcudp/xml_crypto.rs b/crates/core/src/bcudp/xml_crypto.rs new file mode 100644 index 0000000..147f575 --- /dev/null +++ b/crates/core/src/bcudp/xml_crypto.rs @@ -0,0 +1,34 @@ +const XML_KEY: [u32; 8] = [ + 0x1f2d3c4b, 0x5a6c7f8d, 0x38172e4b, 0x8271635a, 0x863f1a2b, 0xa5c6f7d8, 0x8371e1b4, 0x17f2d3a5, +]; + +pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { + let key = XML_KEY + .iter() + .map(|i| (i + offset).to_le_bytes()) + .flatten() + .cycle(); + buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() +} + +pub(crate) fn encrypt(offset: u32, buf: &[u8]) -> Vec { + decrypt(offset, buf) +} + +#[test] +fn test_udp_xml_crypto() { + let sample = include_bytes!("samples/xml_crypto_sample1.bin"); + let should_be = include_bytes!("samples/xml_crypto_sample1_plaintext.bin"); + + let decrypted = decrypt(87, &sample[..]); + assert_eq!(decrypted, &should_be[..]); +} + +#[test] +fn test_udp_xml_crypto_roundtrip() { + let zeros: [u8; 256] = [0; 256]; + + let decrypted = encrypt(0, &zeros[..]); + let encrypted = decrypt(0, &decrypted[..]); + assert_eq!(encrypted, &zeros[..]); +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 4b6076a..c2e5a4d 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -30,6 +30,8 @@ pub mod bc; pub mod bc_protocol; /// Contains low level structures and formats for the media substream pub mod bcmedia; +/// Contains low level structures and formats for the udpstream +pub mod bcudp; #[derive(Debug)] /// Certain method just as `start_video` will block forever or return an error diff --git a/dissector/udp.md b/dissector/udp.md new file mode 100644 index 0000000..2e788d2 --- /dev/null +++ b/dissector/udp.md @@ -0,0 +1,283 @@ +# BcUDP + +This document describes the UDP protocol. UDP, unlike TCP, is lossy, there +is no guarantee that all packets sent will be received or that they are received +in the same order. As such the protocol involves sending meta data back and forth +where the camera and client acknowledge packets they have received. + +Additionally the UDP max data size is smaller so packets will be split more +perhaps even several UDP packets per BC message, whereas in TCP the Bc messages were +always in one TCP packet. + +# Packets Types + +There are three types of UDP packets with their own header + +- UDP Discovery: These packets have the magic `3acf872a` and contain encrypted + xml about the connection that will be used +- UDP Ack: These packets have the magic `20cf872a` they are header only and + contain acknowledgement of packets +- UDP Data: These packets contain part of a BC messagse with a special UDP + header that describes the udp message number, to help reassemble + the packets. They have the magic: `10cf872a` + +# UDP Discovery + +These messages are sent as part of the initial connection discovery. +It is a sequence of messages with different xmls. + +If there is no reply is received within 500ms the last message is resent. + +## Header 20 Bytes + +- 4 Bytes magic: `3acf872a` +- 4 Bytes data size: Size in bytes of payload +- 4 Bytes unknown: Always `01000000` for for UDP Discovery +- 4 Bytes Transmission ID: The unique ID of the transmission, every successful + round trip of Discovery it is incremented. + The number is the same for the same transmission + and may be used to identify repeated messages. + It is also used for the encryption. +- 4 Bytes Checksum: The checksum of the payload encrypted payload + +The checksum can be calculated with this rust code: + +```rust +const TABLE: [u32; 1024] = [0x0, 0x0, 0x0, 0x0, 0x96, 0x30, 0x7, 0x77, 0x2C, 0x61, 0xE, 0xEE, 0xBA, 0x51, 0x9, 0x99, 0x19, 0xC4, 0x6D, 0x7, 0x8F, 0xF4, 0x6A, 0x70, 0x35, 0xA5, 0x63, 0xE9, 0xA3, 0x95, 0x64, 0x9E, 0x32, 0x88, 0xDB, 0xE, 0xA4, 0xB8, 0xDC, 0x79, 0x1E, 0xE9, 0xD5, 0xE0, 0x88, 0xD9, 0xD2, 0x97, 0x2B, 0x4C, 0xB6, 0x9, 0xBD, 0x7C, 0xB1, 0x7E, 0x7, 0x2D, 0xB8, 0xE7, 0x91, 0x1D, 0xBF, 0x90, 0x64, 0x10, 0xB7, 0x1D, 0xF2, 0x20, 0xB0, 0x6A, 0x48, 0x71, 0xB9, 0xF3, 0xDE, 0x41, 0xBE, 0x84, 0x7D, 0xD4, 0xDA, 0x1A, 0xEB, 0xE4, 0xDD, 0x6D, 0x51, 0xB5, 0xD4, 0xF4, 0xC7, 0x85, 0xD3, 0x83, 0x56, 0x98, 0x6C, 0x13, 0xC0, 0xA8, 0x6B, 0x64, 0x7A, 0xF9, 0x62, 0xFD, 0xEC, 0xC9, 0x65, 0x8A, 0x4F, 0x5C, 0x1, 0x14, 0xD9, 0x6C, 0x6, 0x63, 0x63, 0x3D, 0xF, 0xFA, 0xF5, 0xD, 0x8, 0x8D, 0xC8, 0x20, 0x6E, 0x3B, 0x5E, 0x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A, 0x8, 0x88, 0x70, 0x6A, 0xF, 0xFF, 0xCA, 0x3B, 0x6, 0x66, 0x5C, 0xB, 0x1, 0x11, 0xFF, 0x9E, 0x65, 0x8F, 0x69, 0xAE, 0x62, 0xF8, 0xD3, 0xFF, 0x6B, 0x61, 0x45, 0xCF, 0x6C, 0x16, 0x78, 0xE2, 0xA, 0xA0, 0xEE, 0xD2, 0xD, 0xD7, 0x54, 0x83, 0x4, 0x4E, 0xC2, 0xB3, 0x3, 0x39, 0x61, 0x26, 0x67, 0xA7, 0xF7, 0x16, 0x60, 0xD0, 0x4D, 0x47, 0x69, 0x49, 0xDB, 0x77, 0x6E, 0x3E, 0x4A, 0x6A, 0xD1, 0xAE, 0xDC, 0x5A, 0xD6, 0xD9, 0x66, 0xB, 0xDF, 0x40, 0xF0, 0x3B, 0xD8, 0x37, 0x53, 0xAE, 0xBC, 0xA9, 0xC5, 0x9E, 0xBB, 0xDE, 0x7F, 0xCF, 0xB2, 0x47, 0xE9, 0xFF, 0xB5, 0x30, 0x1C, 0xF2, 0xBD, 0xBD, 0x8A, 0xC2, 0xBA, 0xCA, 0x30, 0x93, 0xB3, 0x53, 0xA6, 0xA3, 0xB4, 0x24, 0x5, 0x36, 0xD0, 0xBA, 0x93, 0x6, 0xD7, 0xCD, 0x29, 0x57, 0xDE, 0x54, 0xBF, 0x67, 0xD9, 0x23, 0x2E, 0x7A, 0x66, 0xB3, 0xB8, 0x4A, 0x61, 0xC4, 0x2, 0x1B, 0x68, 0x5D, 0x94, 0x2B, 0x6F, 0x2A, 0x37, 0xBE, 0xB, 0xB4, 0xA1, 0x8E, 0xC, 0xC3, 0x1B, 0xDF, 0x5, 0x5A, 0x8D, 0xEF, 0x02, 0x2D,]; + +pub(crate) fn calc_crc(payload: &[u8]) -> u32 { + let mut r: u32 = 0; + for &val in payload.iter() { + let offset = (((val as u32 ^ r) & 0xFF) << 2) as usize; + let val: u32 = TABLE[offset + 3] << 24 + | TABLE[offset + 2] << 16 + | TABLE[offset + 1] << 8 + | TABLE[offset]; + r = val ^ (r >> 8); + } + r +} +``` + + +## Payload + +- Payload can be encrypted and decrypted with this rust code + +```rust +const XML_KEY: [u32; 8] = [ + 0x1f2d3c4b, 0x5a6c7f8d, 0x38172e4b, 0x8271635a, 0x863f1a2b, 0xa5c6f7d8, 0x8371e1b4, 0x17f2d3a5, +]; + +pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { + let key = XML_KEY + .iter() + .map(|i| (i + offset).to_le_bytes()) + .flatten() + .cycle(); + buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() +} +``` + +## Start Discovery payload + +Client send this packet as a broadcast on 255.255.255.255 on port 2015 +to init a connection + +```xml + + + + 57268 + + + +``` + +--- + +**Camera Replies with Binary** + +Camera replies with binary data to port 3000 + +This data seems to include the +- Camera name +- ip address +- TCP port +- Camera UID + + +**Tcp camera** + +If the camera supports tcp the client will use this binary data to open a +standard tcp bc connection + +**Udp Camera** + +If the camera supports UDP the client will send this xml packet +as a broadcast on 255.255.255.255 on port 2018 + +```xml + + + 95270000YGAKNWKJ + + 24862 + + 849013 + 1350 + 0 +

MAC

+ + +``` + +**Both** + +A camera can do both of the above. In this case it will try to login +to both udp and tcp. Then the udp will disconnect. + +--- + +## T Payload Camera + +Camera replies with this payload on the port specified in `C2D_C` + +```xml + + + 62097899 + local + 82000 + 80 + + +``` + +- **sid**: ID of the camera +- **conn**: Type of connection only observed `local` value +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera + + +Camera also sends this + +```xml + + + + 3000 + 10000 + 60000 + + 0 + 849013 + 192 + + +``` + + +## T Payload Client + +Client then replies with this. + +```xml + + + 62097899 + local + 82000 + 1350 + + +``` + +- **sid**: ID of the camera +- **conn**: Type of connection only observed `local` value +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera +- **mtu**: The maximum transmission unit of the connection. Which is the + largest packet size in bytes + +**Login** + +The client can now login over UDP + + +## Dissconnect + +After a message ID 02 (logout) the client send this + +```xml + + + 82000 + 80 + + +``` + +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera + +## Other + +Some cameras seem to also send this before login + +```xml + + + 62097899 + local + 0 + 82000 + 80 + 0 + + +``` + +- **sid**: ID of the camera +- **conn**: Type of connection only observed `local` value +- **rsp**: Unknown always 0 +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera +- **time_r**: Should be the time but it is always 0 + +# UDP Ack + +These messages are sent to acknowledge receipt of message. They are header only. + +## Header 28 Bytes + +- 4 Bytes magic: `20cf872a` +- 4 Bytes Connection ID: This is the connection ID negotiated during UDP Discovery +- 4 Bytes unknown: Always `00000000` for for UDP Ack +- 4 Bytes unknown: Always `00000000` for for UDP Ack +- 4 Bytes Last Packet ID: Last received packet id +- 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` **NEEDS INFO** +- 4 Bytes Unknown: Observed values `00000000` + +**To Investigate:** + - Why does the unknown byte change. It starts at zero and remains that way for a long + time. Then seems to change and remain at the new value for a long time + +# UDP Data + +UDP data packets contain the BC packets with an extra header. + +Whenever a packet is received a UDP Ack is sent. If the sender of the packet +does not get the Ack within 1000ms it resends the packet + +## Header 20 Bytes + +- 4 Bytes magic: `10cf872a` +- 4 Bytes Connection ID: This is the connection ID negotiated during UDP Discovery +- 4 Bytes unknown: Always `00000000` for for UDP Data +- 4 Bytes Packet ID: The ID of the packet mono-atomically increases for each new packet +- 4 Bytes Payload Size: Size of UDP payload in bytes + +## Payload + +The payload is a standard Bc Packet From b70a88451dc075db9225a3dc0fd5606ada3f9c3c Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 15 Aug 2021 10:55:33 +0700 Subject: [PATCH 18/56] Added UDP based connection --- Cargo.lock | 90 ++- crates/core/Cargo.toml | 2 + crates/core/src/bc/de.rs | 15 +- crates/core/src/bc_protocol.rs | 46 +- .../{connection.rs => connection/bcconn.rs} | 122 ++-- .../src/bc_protocol/connection/bcsource.rs | 172 ++++++ .../core/src/bc_protocol/connection/bcsub.rs | 29 + .../bc_protocol/{ => connection}/binarysub.rs | 5 +- .../bc_protocol/{ => connection}/filesub.rs | 0 crates/core/src/bc_protocol/connection/mod.rs | 70 +++ .../src/bc_protocol/connection/tcpconn.rs | 69 +++ .../src/bc_protocol/connection/udpconn.rs | 519 ++++++++++++++++++ crates/core/src/bc_protocol/resolution.rs | 187 +++++++ crates/core/src/bcudp/de.rs | 10 +- crates/core/src/bcudp/mod.rs | 6 +- crates/core/src/bcudp/model.rs | 14 +- crates/core/src/bcudp/xml.rs | 74 ++- crates/core/src/lib.rs | 2 + dissector/udp.md | 38 +- 19 files changed, 1291 insertions(+), 179 deletions(-) rename crates/core/src/bc_protocol/{connection.rs => connection/bcconn.rs} (67%) create mode 100644 crates/core/src/bc_protocol/connection/bcsource.rs create mode 100644 crates/core/src/bc_protocol/connection/bcsub.rs rename crates/core/src/bc_protocol/{ => connection}/binarysub.rs (97%) rename crates/core/src/bc_protocol/{ => connection}/filesub.rs (100%) create mode 100644 crates/core/src/bc_protocol/connection/mod.rs create mode 100644 crates/core/src/bc_protocol/connection/tcpconn.rs create mode 100644 crates/core/src/bc_protocol/connection/udpconn.rs create mode 100644 crates/core/src/bc_protocol/resolution.rs diff --git a/Cargo.lock b/Cargo.lock index 73f3d64..2b413d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,9 +35,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "0.7.15" +version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" dependencies = [ "memchr", ] @@ -63,6 +63,12 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" +[[package]] +name = "assert_matches" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" + [[package]] name = "atty" version = "0.2.14" @@ -377,6 +383,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "wasi", +] + [[package]] name = "gio" version = "0.14.0" @@ -808,9 +825,9 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" [[package]] name = "memchr" -version = "2.3.4" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" +checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc" [[package]] name = "memoffset" @@ -866,6 +883,7 @@ name = "neolink_core" version = "0.4.0" dependencies = [ "aes", + "assert_matches", "cfb-mode", "cookie-factory", "env_logger", @@ -874,6 +892,8 @@ dependencies = [ "log", "md5", "nom", + "rand", + "regex", "socket2", "time", "xml-rs", @@ -883,9 +903,9 @@ dependencies = [ [[package]] name = "nom" -version = "6.2.1" +version = "6.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c5c51b9083a3c620fa67a2a635d1ce7d95b897e957d6b28ff9a5da960a103a6" +checksum = "e7413f999671bd4745a7b624bd370a569fb6bc574b23c83a3c5ed2e453f3d5e2" dependencies = [ "bitvec", "funty", @@ -966,6 +986,12 @@ version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" +[[package]] +name = "ppv-lite86" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" + [[package]] name = "pretty-hex" version = "0.2.1" @@ -1037,10 +1063,50 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "941ba9d78d8e2f7ce474c015eea4d9c6d25b6a3327f9832ee29a4de27f91bbb8" [[package]] -name = "regex" -version = "1.4.6" +name = "rand" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a26af418b574bd56588335b3a3659a65725d4e636eb1016c2f9e3b38c7cc759" +checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", + "rand_hc", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_hc" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" dependencies = [ "aho-corasick", "memchr", @@ -1522,6 +1588,12 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + [[package]] name = "wasm-bindgen" version = "0.2.74" diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index d6a782c..c304ec4 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -18,6 +18,8 @@ time = "0.2" yaserde = "0.3.16" yaserde_derive = "0.3.16" xml-rs = "0.8" +rand = "0.8.4" +regex = "1.5.4" [dev-dependencies] assert_matches = "1.5.0" diff --git a/crates/core/src/bc/de.rs b/crates/core/src/bc/de.rs index 6ce7d6f..8f0d896 100644 --- a/crates/core/src/bc/de.rs +++ b/crates/core/src/bc/de.rs @@ -1,10 +1,12 @@ use super::model::*; use super::xml::{BcPayloads, BcXml}; use super::xml_crypto; +use crate::RX_TIMEOUT; use err_derive::Error; use nom::IResult; use nom::{bytes::streaming::take, combinator::*, number::streaming::*, sequence::*}; use std::io::Read; +use time::OffsetDateTime; /// The error types used during deserialisation #[derive(Debug, Error)] @@ -48,17 +50,20 @@ where Err(e) => return Err(e.into()), }; + let start_time = OffsetDateTime::now_utc(); loop { match (&mut rdr) .take(to_read.get() as u64) .read_to_end(&mut input) { Ok(0) => { - return Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "Read returned 0 bytes", - ) - .into()); + if (OffsetDateTime::now_utc() - start_time) > RX_TIMEOUT { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } } Ok(_) => break, Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index c6dda1c..fffe0bb 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -1,36 +1,32 @@ -use self::connection::BcConnection; use crate::{bc, bcmedia}; use log::*; use std::convert::TryInto; -use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicU16, Ordering}; -use std::time::Duration; use Md5Trunc::*; -mod binarysub; mod connection; mod errors; -pub(crate) mod filesub; mod ledstate; mod login; mod logout; mod ping; mod reboot; +mod resolution; mod stream; mod talk; mod time; mod version; -pub use binarysub::BinarySubscriber; +use super::RX_TIMEOUT; +pub(crate) use connection::*; pub use errors::Error; pub use ledstate::LightState; +pub use resolution::*; pub use stream::{StreamOutput, StreamOutputError}; type Result = std::result::Result; -const RX_TIMEOUT: Duration = Duration::from_secs(5); - impl<'a> From for Error { fn from(k: std::sync::mpsc::RecvTimeoutError) -> Self { match k { @@ -77,8 +73,7 @@ impl BcCamera { /// /// # Parameters /// - /// * `host` - The address of the camera either ip address or hostname string is ok but - /// [`std::net::SocketAddr`] is fine too + /// * `host` - The address of the camera either ip address, hostname string, or uid is ok /// /// * `channel_id` - The channel ID this is usually zero unless using a NVR /// @@ -86,15 +81,24 @@ impl BcCamera { /// /// returns either an error or the camera /// - pub fn new_with_addr(host: T, channel_id: u8) -> Result { - let addr_iter = match host.to_socket_addrs() { + pub fn new_with_addr(host: T, channel_id: u8) -> Result { + let addr_iter = match host.to_socket_addrs_or_uid() { Ok(iter) => iter, Err(_) => return Err(Error::AddrResolutionError), }; for addr in addr_iter { - debug!("Trying {}", addr); - let conn = match BcConnection::new(addr, RX_TIMEOUT) { + let source = match addr { + SocketAddrOrUid::SocketAddr(addr) => { + debug!("Trying address {}", addr); + BcSource::new_tcp(addr, RX_TIMEOUT)? + } + SocketAddrOrUid::Uid(uid) => { + debug!("Trying uid {}", uid); + BcSource::new_udp(&uid, RX_TIMEOUT)? + } + }; + let conn = match BcConnection::new(source) { Ok(conn) => conn, Err(err) => match err { connection::Error::Communication(ref err) => { @@ -105,7 +109,7 @@ impl BcCamera { }, }; - debug!("Success: {}", addr); + debug!("Success"); return Ok(Self { connection: Some(conn), message_num: AtomicU16::new(0), @@ -126,13 +130,11 @@ impl BcCamera { /// This will drop the connection. It will try to send the logout request to the camera /// first pub fn disconnect(&mut self) { - // Stop polling now. We don't need it for a disconnect - // and if we don't then another we might get a deserialise - // error from another thread that polls and needs the login. - // - // It will also ensure that when we drop the connection we don't - // get an error for read retrun zero bytes. if let Some(connection) = &self.connection { + // Stop polling now. We don't need it for a disconnect + // + // It will also ensure that when we drop the connection we don't + // get an error for read return zero bytes from the polling thread; connection.stop_polling(); if let Err(err) = self.logout() { warn!("Could not log out, ignoring: {}", err); @@ -178,7 +180,7 @@ fn md5_string(input: &str, trunc: Md5Trunc) -> String { } /// This is a convience function to make an AES key from the login password and the NONCE -/// negociated during login +/// negotiated during login pub fn make_aes_key(nonce: &str, passwd: &str) -> [u8; 16] { let key_phrase = format!("{}-{}", nonce, passwd); let key_phrase_hash = format!("{:X}\0", md5::compute(&key_phrase)) diff --git a/crates/core/src/bc_protocol/connection.rs b/crates/core/src/bc_protocol/connection/bcconn.rs similarity index 67% rename from crates/core/src/bc_protocol/connection.rs rename to crates/core/src/bc_protocol/connection/bcconn.rs index a4a822e..f1c787c 100644 --- a/crates/core/src/bc_protocol/connection.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -1,12 +1,13 @@ +use super::{BcSource, BcSubscription, Error, Result, TcpSource}; use crate::bc; use crate::bc::model::*; -use err_derive::Error; use log::*; use socket2::{Domain, Socket, Type}; use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::error::Error as StdErr; // Just need the traits -use std::net::{Shutdown, SocketAddr, TcpStream}; +use std::io::{Error as IoError, Read, Write}; +use std::net::{SocketAddr, TcpStream}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; use std::thread::JoinHandle; @@ -18,7 +19,7 @@ use std::time::Duration; /// /// There can be only one subscriber per kind of message at a time. pub struct BcConnection { - connection: Arc>, + sink: Arc>, subscribers: Arc>>>, rx_thread: Option>, // Arc> because it is shared between context @@ -27,46 +28,22 @@ pub struct BcConnection { poll_abort: Arc, } -pub struct BcSubscription<'a> { - pub rx: Receiver, - msg_id: u32, - conn: &'a BcConnection, -} - -type Result = std::result::Result; - -#[derive(Debug, Error)] -pub enum Error { - #[error(display = "Communication error")] - Communication(#[error(source)] std::io::Error), - - #[error(display = "Deserialization error")] - Deserialization(#[error(source)] bc::de::Error), - - #[error(display = "Serialization error")] - Serialization(#[error(source)] bc::ser::Error), - - #[error(display = "Simultaneous subscription")] - SimultaneousSubscription { msg_id: u32 }, -} - impl BcConnection { - pub fn new(addr: SocketAddr, timeout: Duration) -> Result { - let tcp_conn = connect_to(addr, timeout)?; + pub fn new(source: BcSource) -> Result { let subscribers: Arc>>> = Default::default(); let mut subs = subscribers.clone(); - let conn = tcp_conn.try_clone()?; let encryption_protocol = Arc::new(Mutex::new(EncryptionProtocol::Unencrypted)); let connections_encryption_protocol = encryption_protocol.clone(); let poll_abort = Arc::new(AtomicBool::new(false)); let poll_abort_rx = poll_abort.clone(); + let conn = source.try_clone()?; let rx_thread = std::thread::spawn(move || { let mut context = BcContext::new(connections_encryption_protocol); let mut result; loop { - result = BcConnection::poll(&mut context, &conn, &mut subs); + result = Self::poll(&mut context, &conn, &mut subs); if poll_abort_rx.load(Ordering::Relaxed) { break; // Poll has been aborted by request usally during disconnect } @@ -83,7 +60,7 @@ impl BcConnection { }); Ok(BcConnection { - connection: Arc::new(Mutex::new(tcp_conn)), + sink: Arc::new(Mutex::new(source)), subscribers, rx_thread: Some(rx_thread), encryption_protocol, @@ -91,27 +68,45 @@ impl BcConnection { }) } + pub fn stop_polling(&self) { + self.poll_abort.store(true, Ordering::Relaxed); + } + + pub(super) fn send(&self, bc: Bc) -> Result<()> { + bc.serialize(&*self.sink.lock().unwrap(), &self.get_encrypted())?; + let _ = self.sink.lock().unwrap().flush(); + Ok(()) + } + pub fn subscribe(&self, msg_id: u32) -> Result { let (tx, rx) = channel(); match self.subscribers.lock().unwrap().entry(msg_id) { Entry::Vacant(vac_entry) => vac_entry.insert(tx), Entry::Occupied(_) => return Err(Error::SimultaneousSubscription { msg_id }), }; - Ok(BcSubscription { - rx, - conn: self, - msg_id, - }) + Ok(BcSubscription::new(rx, msg_id, self)) + } + + pub fn unsubscribe(&self, msg_id: u32) -> Result<()> { + self.subscribers.lock().unwrap().remove(&msg_id); + Ok(()) + } + + pub fn set_encrypted(&self, value: EncryptionProtocol) { + *(self.encryption_protocol.lock().unwrap()) = value; + } + + pub fn get_encrypted(&self) -> EncryptionProtocol { + (*self.encryption_protocol.lock().unwrap()).clone() } fn poll( context: &mut BcContext, - connection: &TcpStream, + connection: &BcSource, subscribers: &mut Arc>>>, ) -> Result<()> { // Don't hold the lock during deserialization so we don't poison the subscribers mutex if // something goes wrong - let response = Bc::deserialize(context, connection).map_err(|err| { // If the connection hangs up, hang up on all subscribers subscribers.lock().unwrap().clear(); @@ -136,24 +131,11 @@ impl BcConnection { Ok(()) } - - pub fn stop_polling(&self) { - self.poll_abort.store(true, Ordering::Relaxed); - } - - pub fn set_encrypted(&self, value: EncryptionProtocol) { - *(self.encryption_protocol.lock().unwrap()) = value; - } - - pub fn get_encrypted(&self) -> EncryptionProtocol { - (*self.encryption_protocol.lock().unwrap()).clone() - } } impl Drop for BcConnection { fn drop(&mut self) { debug!("Shutting down BcConnection..."); - let _ = self.connection.lock().unwrap().shutdown(Shutdown::Both); match self .rx_thread .take() @@ -169,41 +151,3 @@ impl Drop for BcConnection { } } } - -impl<'a> BcSubscription<'a> { - pub fn send(&self, bc: Bc) -> Result<()> { - assert!(bc.meta.msg_id == self.msg_id); - - bc.serialize( - &*self.conn.connection.lock().unwrap(), - &self.conn.get_encrypted(), - )?; - Ok(()) - } -} - -/// Makes it difficult to avoid unsubscribing when you're finished -impl<'a> Drop for BcSubscription<'a> { - fn drop(&mut self) { - self.conn.subscribers.lock().unwrap().remove(&self.msg_id); - } -} - -/// Helper to create a TcpStream with a connect timeout -fn connect_to(addr: SocketAddr, timeout: Duration) -> Result { - let socket = match addr { - SocketAddr::V4(_) => Socket::new(Domain::ipv4(), Type::stream(), None)?, - SocketAddr::V6(_) => { - let s = Socket::new(Domain::ipv6(), Type::stream(), None)?; - s.set_only_v6(false)?; - s - } - }; - - socket.set_keepalive(Some(timeout))?; - socket.set_read_timeout(Some(timeout))?; - socket.set_write_timeout(Some(timeout))?; - socket.connect_timeout(&addr.into(), timeout)?; - - Ok(socket.into_tcp_stream()) -} diff --git a/crates/core/src/bc_protocol/connection/bcsource.rs b/crates/core/src/bc_protocol/connection/bcsource.rs new file mode 100644 index 0000000..1628e58 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/bcsource.rs @@ -0,0 +1,172 @@ +use super::{Result, TcpSource, UdpSource}; +use std::io::{Error as IoError, ErrorKind, Read, Write}; +use std::net::SocketAddr; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +type IoResult = std::result::Result; + +pub enum BcSource { + Tcp(Mutex), + Udp(Mutex), +} + +impl BcSource { + pub fn new_tcp(addr: SocketAddr, timeout: Duration) -> Result { + let source = TcpSource::new(addr, timeout)?; + Ok(BcSource::Tcp(Mutex::new(source))) + } + + pub fn new_udp(uid: &str, timeout: Duration) -> Result { + let source = UdpSource::new(uid, timeout)?; + Ok(BcSource::Udp(Mutex::new(source))) + } + + pub fn try_clone(&self) -> IoResult { + match self { + BcSource::Tcp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(BcSource::Tcp(Mutex::new(locked.try_clone()?))), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for clone", + )), + }, + + BcSource::Udp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(BcSource::Udp(Mutex::new(locked.try_clone()?))), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock udp for clone", + )), + }, + } + } +} + +impl Read for BcSource { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + match self { + BcSource::Tcp(source) => match &mut source.get_mut() { + Ok(locked) => Ok(locked.read(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for read", + )), + }, + + BcSource::Udp(source) => match &mut source.get_mut() { + Ok(locked) => Ok(locked.read(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock udp for read", + )), + }, + } + } +} + +impl Read for &BcSource { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + match self { + BcSource::Tcp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(locked.read(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for &read", + )), + }, + + BcSource::Udp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(locked.read(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock udp for &read", + )), + }, + } + } +} + +impl Write for BcSource { + fn write(&mut self, buf: &[u8]) -> IoResult { + match self { + BcSource::Tcp(source) => match &mut source.get_mut() { + Ok(locked) => Ok(locked.write(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for write", + )), + }, + + BcSource::Udp(source) => match &mut source.get_mut() { + Ok(locked) => Ok(locked.write(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock udp for write", + )), + }, + } + } + + fn flush(&mut self) -> IoResult<()> { + match self { + BcSource::Tcp(source) => match &mut source.get_mut() { + Ok(locked) => Ok(locked.flush()?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for flush", + )), + }, + + BcSource::Udp(source) => match &mut source.get_mut() { + Ok(locked) => Ok(locked.flush()?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp udp for flush", + )), + }, + } + } +} + +impl Write for &BcSource { + fn write(&mut self, buf: &[u8]) -> IoResult { + match self { + BcSource::Tcp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(locked.write(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for write", + )), + }, + + BcSource::Udp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(locked.write(buf)?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock udp for write", + )), + }, + } + } + + fn flush(&mut self) -> IoResult<()> { + match self { + BcSource::Tcp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(locked.flush()?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock tcp for &flush", + )), + }, + + BcSource::Udp(source) => match &mut source.try_lock() { + Ok(locked) => Ok(locked.flush()?), + Err(_) => Err(IoError::new( + ErrorKind::WouldBlock, + "Unable to lock udp for &flush", + )), + }, + } + } +} diff --git a/crates/core/src/bc_protocol/connection/bcsub.rs b/crates/core/src/bc_protocol/connection/bcsub.rs new file mode 100644 index 0000000..d84fd39 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/bcsub.rs @@ -0,0 +1,29 @@ +use super::{BcConnection, Result}; +use crate::bc::model::*; +use std::sync::mpsc::Receiver; + +pub struct BcSubscription<'a> { + pub rx: Receiver, + msg_id: u32, + conn: &'a BcConnection, +} + +impl<'a> BcSubscription<'a> { + pub fn new(rx: Receiver, msg_id: u32, conn: &'a BcConnection) -> BcSubscription<'a> { + BcSubscription { rx, msg_id, conn } + } + + pub fn send(&self, bc: Bc) -> Result<()> { + assert!(bc.meta.msg_id == self.msg_id); + self.conn.send(bc)?; + Ok(()) + } +} + +/// Makes it difficult to avoid unsubscribing when you're finished +impl<'a> Drop for BcSubscription<'a> { + fn drop(&mut self) { + // It's fine if we can't unsubscribe as that means we already have + let _ = self.conn.unsubscribe(self.msg_id); + } +} diff --git a/crates/core/src/bc_protocol/binarysub.rs b/crates/core/src/bc_protocol/connection/binarysub.rs similarity index 97% rename from crates/core/src/bc_protocol/binarysub.rs rename to crates/core/src/bc_protocol/connection/binarysub.rs index bc4618f..e09552c 100644 --- a/crates/core/src/bc_protocol/binarysub.rs +++ b/crates/core/src/bc_protocol/connection/binarysub.rs @@ -1,4 +1,7 @@ -use super::{connection::BcSubscription, RX_TIMEOUT}; +use super::{ + super::{connection::BcSubscription, RX_TIMEOUT}, + BcConnection, +}; use crate::bc::model::*; use std::{ io::{BufRead, Error, ErrorKind, Read}, diff --git a/crates/core/src/bc_protocol/filesub.rs b/crates/core/src/bc_protocol/connection/filesub.rs similarity index 100% rename from crates/core/src/bc_protocol/filesub.rs rename to crates/core/src/bc_protocol/connection/filesub.rs diff --git a/crates/core/src/bc_protocol/connection/mod.rs b/crates/core/src/bc_protocol/connection/mod.rs new file mode 100644 index 0000000..004cada --- /dev/null +++ b/crates/core/src/bc_protocol/connection/mod.rs @@ -0,0 +1,70 @@ +#![allow(unused_imports)] +//! This module handles connections and subscribers +//! +//! This includes a tcp and udp connections. As well +//! as subscribers to binary streams that are encoded +//! in the bc packets. +//! +use crate::bc; +use crate::bc::model::*; +use crate::bcudp; +use err_derive::Error; +use log::*; +use socket2::{Domain, Socket, Type}; +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::error::Error as StdErr; // Just need the traits +use std::net::{SocketAddr, TcpStream}; +use std::sync::mpsc::{channel, Receiver, RecvError, Sender}; +use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; + +use std::thread::JoinHandle; +use std::time::Duration; + +mod bcconn; +mod bcsource; +mod bcsub; +mod binarysub; +mod filesub; +mod tcpconn; +mod udpconn; + +pub(crate) use self::{ + bcconn::BcConnection, bcsource::BcSource, bcsub::BcSubscription, binarysub::BinarySubscriber, + filesub::FileSubscriber, tcpconn::TcpSource, udpconn::UdpSource, +}; + +#[derive(Debug, Error)] +pub enum Error { + #[error(display = "Communication error")] + Communication(#[error(source)] std::io::Error), + + #[error(display = "Communication Reciever error")] + RecvCommunication(#[error(source)] RecvError), + + #[error(display = "Deserialization error")] + Deserialization(#[error(source)] bc::de::Error), + + #[error(display = "Serialization error")] + Serialization(#[error(source)] bc::ser::Error), + + #[error(display = "UDP Deserialization error")] + UdpDeserialization(#[error(source)] bcudp::de::Error), + + #[error(display = "UDP Serialization error")] + UdpSerialization(#[error(source)] bcudp::ser::Error), + + #[error(display = "Simultaneous subscription")] + SimultaneousSubscription { msg_id: u32 }, + + #[error(display = "Timeout")] + Timeout, + + #[error(display = "This connection type in unsupported")] + UnsupportedConnection, + + #[error(display = "Camera Unconnected")] + ConnectionUnavaliable, +} + +type Result = std::result::Result; diff --git a/crates/core/src/bc_protocol/connection/tcpconn.rs b/crates/core/src/bc_protocol/connection/tcpconn.rs new file mode 100644 index 0000000..0f0e4b7 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/tcpconn.rs @@ -0,0 +1,69 @@ +use super::{BcSubscription, Error, Result}; +use crate::bc; +use crate::bc::model::*; +use log::*; +use socket2::{Domain, Socket, Type}; +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::error::Error as StdErr; // Just need the traits +use std::io::{Error as IoError, Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::Duration; + +type IoResult = std::result::Result; + +pub struct TcpSource { + stream: TcpStream, +} + +impl TcpSource { + pub fn new(addr: SocketAddr, timeout: Duration) -> Result { + let tcp_conn = connect_to(addr, timeout)?; + + Ok(Self { stream: tcp_conn }) + } + + pub fn try_clone(&self) -> IoResult { + Ok(Self { + stream: self.stream.try_clone()?, + }) + } +} + +impl Read for TcpSource { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + self.stream.read(buf) + } +} + +impl Write for TcpSource { + fn write(&mut self, buf: &[u8]) -> IoResult { + self.stream.write(buf) + } + + fn flush(&mut self) -> IoResult<()> { + self.stream.flush() + } +} + +/// Helper to create a TcpStream with a connect timeout +fn connect_to(addr: SocketAddr, timeout: Duration) -> Result { + let socket = match addr { + SocketAddr::V4(_) => Socket::new(Domain::ipv4(), Type::stream(), None)?, + SocketAddr::V6(_) => { + let s = Socket::new(Domain::ipv6(), Type::stream(), None)?; + s.set_only_v6(false)?; + s + } + }; + + socket.set_keepalive(Some(timeout))?; + socket.set_read_timeout(Some(timeout))?; + socket.set_write_timeout(Some(timeout))?; + socket.connect_timeout(&addr.into(), timeout)?; + + Ok(socket.into_tcp_stream()) +} diff --git a/crates/core/src/bc_protocol/connection/udpconn.rs b/crates/core/src/bc_protocol/connection/udpconn.rs new file mode 100644 index 0000000..95cf7b9 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/udpconn.rs @@ -0,0 +1,519 @@ +use super::{BcSubscription, Error, Result}; +use crate::bc; +use crate::bc::model::*; +use crate::bcudp; +use crate::bcudp::{model::*, xml::*}; +use log::*; +use rand::{seq::SliceRandom, thread_rng, Rng}; +use socket2::{Domain, Socket, Type}; +use std::collections::btree_map::Entry; +use std::collections::BTreeMap; +use std::collections::HashMap; +use std::error::Error as StdErr; // Just need the traits +use std::io::{BufRead, Error as IoError, Read, Write}; +use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; +use std::sync::{ + atomic::{AtomicBool, AtomicU32, Ordering}, + mpsc::{channel, Receiver, Sender}, + Arc, Mutex, +}; +use std::thread::JoinHandle; +use std::time::Duration; +use time::OffsetDateTime; + +type IoResult = std::result::Result; + +const WAIT_TIME: Duration = Duration::from_millis(500); + +pub struct UdpSource { + socket: UdpSocket, + address: SocketAddr, + client_id: u32, + camera_id: u32, + mtu: u32, + outgoing: Arc>>, + incoming: Arc>>, + aborter: AbortHandle, + next_to_consume: Arc, + next_send_message: Arc, + // Buffered because a single read might not read a whole packet + read_buffer: Buffered, + write_buffer: Buffered, +} + +#[derive(Default, Clone)] +struct Buffered { + buffer: Vec, + consumed: usize, +} + +#[derive(Debug)] +struct QueuedMessage { + buf: Vec, + time_last_tried: Option, +} + +struct DiscoveryResult { + socket: UdpSocket, + address: SocketAddr, + client_id: u32, + camera_id: u32, + mtu: u32, +} + +#[derive(Clone)] +struct AbortHandle { + aborted: Arc, +} + +impl AbortHandle { + fn new() -> Self { + Self { + aborted: Arc::new(AtomicBool::new(false)), + } + } + + fn abort(&self) { + self.aborted.store(true, Ordering::Relaxed); + } + + fn is_aborted(&self) -> bool { + self.aborted.load(Ordering::Relaxed) + } +} + +impl UdpSource { + fn get_socket(timeout: Duration) -> Result { + // Select a random port to bind to + let mut ports: Vec = (53500..54000).into_iter().collect(); + let mut rng = thread_rng(); + ports.shuffle(&mut rng); + + let addrs: Vec<_> = ports + .iter() + .map(|&port| SocketAddr::from(([0, 0, 0, 0], port))) + .collect(); + let socket = UdpSocket::bind(&addrs[..])?; + socket.set_read_timeout(Some(timeout))?; + socket.set_write_timeout(Some(timeout))?; + socket.set_broadcast(true)?; + Ok(socket) + } + + fn retrying_send_to( + socket: &UdpSocket, + buf: &[u8], + addr: T, + ) -> IoResult<(usize, AbortHandle)> { + let addr: SocketAddr = addr.to_socket_addrs()?.next().unwrap(); + let handle = AbortHandle::new(); + let bytes_send = socket.send_to(&buf, &addr)?; + + let thread_buffer = buf.to_vec(); + let thread_handle = handle.clone(); + let thread_socket = socket.try_clone()?; + let thread_addr = addr; + + std::thread::spawn(move || { + std::thread::sleep(WAIT_TIME); + while !thread_handle.is_aborted() { + let _ = thread_socket.send_to(&thread_buffer[..], &thread_addr); + std::thread::sleep(WAIT_TIME); + } + }); + + Ok((bytes_send, handle)) + } + + fn discover_from_uuid(uid: &str, timeout: Duration) -> Result { + let start_time = OffsetDateTime::now_utc(); + + let socket = Self::get_socket(timeout)?; + + let mut rng = thread_rng(); + // If tid is too large it will overflow during encrypt so we just use a random u8 + let tid: u32 = (rng.gen::()) as u32; + let client_id: u32 = rng.gen(); + let local_addr = socket.local_addr()?; + let port = local_addr.port(); + + // TODO: Path MTU discovery + let mtu = 1350; + + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_c: Some(C2dC { + uid: uid.to_string(), + cli: ClientList { port: port as u32 }, + cid: client_id, + mtu, + debug: false, + os: "MAC".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = + Self::retrying_send_to(&socket, &buf[..], "255.255.255.255:2018")?; + assert_eq!(amount_sent, buf.len()); + + let camera_address; + let camera_id; + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, socket_addr)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_c_r: Some(D2cCr { did, cid, .. }), + .. + }, + })) if cid == client_id => { + abort.abort(); + camera_address = socket_addr; + camera_id = did; + break; + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + return Err(Error::Timeout); + } + } + + // Ensure we didn't forget to abort the sending + abort.abort(); + // Actual connection time! + socket.connect(camera_address)?; + + Ok(DiscoveryResult { + socket, + address: camera_address, + client_id, + camera_id, + mtu, + }) + } + + pub fn new(uid: &str, timeout: Duration) -> Result { + let discovery_result = Self::discover_from_uuid(uid, timeout)?; + info!("UID {:?} found at {:?}", uid, discovery_result.address); + + let me = UdpSource { + socket: discovery_result.socket, + address: discovery_result.address, + client_id: discovery_result.client_id, + camera_id: discovery_result.camera_id, + mtu: discovery_result.mtu, + incoming: Default::default(), + outgoing: Default::default(), + aborter: AbortHandle::new(), + next_to_consume: Arc::new(AtomicU32::new(0)), + next_send_message: Arc::new(AtomicU32::new(0)), + read_buffer: Default::default(), + write_buffer: Default::default(), + }; + + me.start_polling()?; + + Ok(me) + } + + pub fn try_clone(&self) -> IoResult { + Ok(Self { + socket: self.socket.try_clone()?, + address: self.address, + client_id: self.client_id, + camera_id: self.camera_id, + mtu: self.mtu, + incoming: self.incoming.clone(), + outgoing: self.outgoing.clone(), + aborter: self.aborter.clone(), + next_to_consume: self.next_to_consume.clone(), + next_send_message: self.next_send_message.clone(), + // These are not shared mutable so they don't pollute each other buffer + read_buffer: self.read_buffer.clone(), + write_buffer: self.write_buffer.clone(), + }) + } + + fn start_polling(&self) -> IoResult<()> { + self.start_polling_recv()?; + self.start_polling_send()?; + Ok(()) + } + + fn handle_ack( + next_to_consume: u32, + camera_id: u32, + incoming: &mut HashMap, + socket: &UdpSocket, + ) { + // Send an acknoledge. + // we want the next packet that's missing after the + // last consumed packet. + let mut next_packet = next_to_consume; + loop { + if incoming.get(&next_packet).is_none() { + break; + } else { + next_packet += 1; + } + } + if next_packet > 0 { + let last_received_contigous_packet = next_packet - 1; + let ack_msg = BcUdp::Ack(UdpAck { + connection_id: camera_id, + packet_id: last_received_contigous_packet, + }); + debug!("Re ack packet: {}", last_received_contigous_packet); + let mut ack_buf = vec![]; + if ack_msg.serialize(&mut ack_buf).is_ok() { + if let Ok(amount_sent) = socket.send(&ack_buf[..]) { + assert_eq!(amount_sent, ack_buf.len()); + } else { + error!("Unable to send acknoledgement"); + } + } else { + error!("Unable to serialize acknoledgement"); + } + } + } + + fn start_polling_recv(&self) -> IoResult<()> { + let thread_aborter = self.aborter.clone(); + let thread_incoming = self.incoming.clone(); + let thread_outgoing = self.outgoing.clone(); + let thread_socket = self.socket.try_clone()?; + let thread_mtu = self.mtu; + let thread_client_id = self.client_id; + let thread_camera_id = self.camera_id; + let thread_next_consumed = self.next_to_consume.clone(); + + std::thread::spawn(move || { + while !thread_aborter.is_aborted() { + debug!("Poll UDP Read"); + // Reciving + let mut read_buf = vec![0_u8; thread_mtu as usize]; + if let Ok(bytes_read) = thread_socket.recv(&mut read_buf[..]) { + match BcUdp::deserialize(&read_buf[0..bytes_read]) { + Ok(BcUdp::Discovery(packet)) => { + warn!("Got unexpected discovery packet: {:?}", packet) + } + Ok(BcUdp::Ack(UdpAck { + connection_id: cid, + packet_id, + })) if cid == thread_client_id => { + // Camera got our message remove older ones from the send queue + debug!("Got acknoledgment of {}", packet_id); + thread_outgoing + .lock() + .unwrap() + .retain(|&k, _| k > packet_id); + // Queue for resend now + thread_outgoing + .lock() + .unwrap() + .iter_mut() + .for_each(|(_, v)| v.time_last_tried = None); + + Self::handle_ack( + thread_next_consumed.load(Ordering::Relaxed), + thread_camera_id, + &mut *thread_incoming.lock().unwrap(), + &thread_socket, + ); + } + Ok(BcUdp::Data(UdpData { + connection_id: cid, + packet_id, + payload, + })) if cid == thread_client_id => { + // Got some data add it to our buffer + let consumed_packet = thread_next_consumed.load(Ordering::Relaxed); + if packet_id >= consumed_packet { + debug!("Reciving UDP data packet with ID: {}", packet_id); + thread_incoming.lock().unwrap().insert( + packet_id, + QueuedMessage { + buf: payload, + time_last_tried: None, + }, + ); + + Self::handle_ack( + thread_next_consumed.load(Ordering::Relaxed), + thread_camera_id, + &mut *thread_incoming.lock().unwrap(), + &thread_socket, + ); + } + } + Ok(bcudp) => warn!("Unexpected bcudp received {:?}", bcudp), + Err(e) => error!("Unable to poll from udp socket {:?}", e), + } + } + } + }); + + Ok(()) + } + + fn start_polling_send(&self) -> IoResult<()> { + let thread_aborter = self.aborter.clone(); + let thread_outgoing = self.outgoing.clone(); + let thread_socket = self.socket.try_clone()?; + + std::thread::spawn(move || { + while !thread_aborter.is_aborted() { + // debug!("Poll UDP Send"); + let now = OffsetDateTime::now_utc(); + for (packet_id, message) in thread_outgoing.lock().unwrap().iter_mut() { + let mut should_send = false; + if let Some(&time_last_tried) = message.time_last_tried.as_ref() { + if (now - time_last_tried) >= WAIT_TIME { + should_send = true; + } + } else { + should_send = true; + } + if should_send { + debug!( + "Sending message ID {} with payload len {}", + packet_id, + message.buf.len() + ); + message.time_last_tried = Some(now); + if thread_socket.send(&message.buf[..]).is_err() { + warn!("Failed to send message on udp"); + } + } + } + } + }); + + Ok(()) + } + + fn stop_polling(&self) { + self.aborter.abort(); + } +} + +// Ensuring polling stops +impl Drop for UdpSource { + fn drop(&mut self) { + self.stop_polling(); + } +} + +impl Read for UdpSource { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + let buffer = self.fill_buf()?; + let amt = std::cmp::min(buf.len(), buffer.len()); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if amt == 1 { + buf[0] = buffer[0]; + } else { + buf[..amt].copy_from_slice(&buffer[..amt]); + } + + self.consume(amt); + + Ok(amt) + } +} + +impl BufRead for UdpSource { + fn fill_buf(&mut self) -> IoResult<&[u8]> { + const CLEAR_CONSUMED_AT: usize = 1024; + // This is a trade off between caching too much dead memory + // and calling the drain method too often + if self.read_buffer.consumed > CLEAR_CONSUMED_AT { + let _ = self + .read_buffer + .buffer + .drain(0..self.read_buffer.consumed) + .collect::>(); + self.read_buffer.consumed = 0; + } + if self.read_buffer.buffer.len() <= self.read_buffer.consumed { + // Get next packet of the read queue + if let Some(msg) = self + .incoming + .lock() + .unwrap() + .remove(&self.next_to_consume.load(Ordering::Relaxed)) + { + self.next_to_consume.fetch_add(1, Ordering::Relaxed); + self.read_buffer.buffer.extend(msg.buf); + } + } + + Ok(&self.read_buffer.buffer.as_slice()[self.read_buffer.consumed..]) + } + + fn consume(&mut self, amt: usize) { + assert!(self.read_buffer.consumed + amt <= self.read_buffer.buffer.len()); + self.read_buffer.consumed += amt; + } +} + +const UDPDATA_HEADER_SIZE: usize = 20; +impl Write for UdpSource { + fn write(&mut self, buf: &[u8]) -> IoResult { + self.write_buffer.buffer.extend(buf.to_vec()); + if self.write_buffer.buffer.len() > self.mtu as usize - UDPDATA_HEADER_SIZE { + let _ = self.flush(); + } + Ok(buf.len()) + } + + fn flush(&mut self) -> IoResult<()> { + for chunk in self + .write_buffer + .buffer + .chunks(self.mtu as usize - UDPDATA_HEADER_SIZE) + { + let packet_id = self.next_send_message.fetch_add(1, Ordering::Relaxed); + let msg = BcUdp::Data(UdpData { + connection_id: self.camera_id, + packet_id, + payload: chunk.to_vec(), + }); + let mut buf = vec![]; + // If this errors it is unrecoverable + // + // It really shouldn't be able to Err though + msg.serialize(&mut buf) + .expect("Failed to serialize UDP Data"); + debug!("Writing"); + self.outgoing.lock().unwrap().insert( + packet_id, + QueuedMessage { + time_last_tried: None, + buf, + }, + ); + } + self.write_buffer.buffer.clear(); + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/resolution.rs b/crates/core/src/bc_protocol/resolution.rs new file mode 100644 index 0000000..b89d701 --- /dev/null +++ b/crates/core/src/bc_protocol/resolution.rs @@ -0,0 +1,187 @@ +//! This is a helper module to resolve either to a UID or a SockerAddr + +use log::*; +use std::{ + io::Error, + net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}, +}; + +/// Used to return either the SocketAddr or the UID +pub enum SocketAddrOrUid { + /// When the result is a addr it will be this + SocketAddr(SocketAddr), + /// When the result is a UID + Uid(String), +} + +/// An extension of ToSocketAddrs that will also resolve to a camera UID +pub trait ToSocketAddrsOrUid: ToSocketAddrs { + /// The return type of the function + type UidIter: Iterator; + + /// This handles the actual resolution. It should first check the + /// normal [.to_socket_addrs()] and if that fails it should check + /// if it looks like a uid + fn to_socket_addrs_or_uid(&self) -> Result; +} + +impl ToSocketAddrsOrUid for SocketAddr { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for str { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + match self.to_socket_addrs() { + Ok(addrs) => Ok(addrs + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()), + Err(e) => { + debug!("Trying as uid"); + let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap(); + if re.is_match(self) { + Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter()) + } else { + debug!("Regex fails {:?} => {:?} ", re, self); + Err(e) + } + } + } + } +} + +impl ToSocketAddrsOrUid for String { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + match self.to_socket_addrs() { + Ok(addrs) => Ok(addrs + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()), + Err(e) => { + debug!("Trying as uid"); + let re = regex::Regex::new(r"^[0-9A-Za-z]+$").unwrap(); + if re.is_match(self) { + Ok(vec![SocketAddrOrUid::Uid(self.to_string())].into_iter()) + } else { + debug!("Regex fails {:?} => {:?} ", re, self); + Err(e) + } + } + } + } +} + +impl ToSocketAddrsOrUid for (&str, u16) { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for (IpAddr, u16) { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for (String, u16) { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for (Ipv4Addr, u16) { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for (Ipv6Addr, u16) { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for SocketAddrV4 { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for SocketAddrV6 { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl<'a> ToSocketAddrsOrUid for &'a [SocketAddr] { + type UidIter = std::vec::IntoIter; + + fn to_socket_addrs_or_uid(&self) -> Result { + Ok(self + .to_socket_addrs()? + .map(SocketAddrOrUid::SocketAddr) + .collect::>() + .into_iter()) + } +} + +impl ToSocketAddrsOrUid for &T { + type UidIter = T::UidIter; + fn to_socket_addrs_or_uid(&self) -> Result { + (&**self).to_socket_addrs_or_uid() + } +} diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index 1b3d6e8..a8cc9ff 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -5,7 +5,7 @@ use nom::{ combinator::*, error::{make_error, ErrorKind}, number::streaming::*, - take, take_str, Err, + take, Err, }; use std::io::Read; @@ -180,7 +180,7 @@ mod tests { Ok(BcUdp::Discovery(UdpDiscovery { tid: 96, payload: UdpXml { - disconnect: Some(Disconnect { + c2d_disc: Some(C2dDisc { cid: 82000, did: 80, }), @@ -203,7 +203,7 @@ mod tests { Ok(BcUdp::Discovery(UdpDiscovery { tid: 113, payload: UdpXml { - camera_transmission: Some(CameraTransmission { + d2c_t: Some(D2cT { sid: 62098713, conn: conn_str, cid: 82001, @@ -228,7 +228,7 @@ mod tests { Ok(BcUdp::Discovery(UdpDiscovery { tid: 1101, payload: UdpXml { - client_transmission: Some(ClientTransmission { + c2d_t: Some(C2dT { sid: 62098713, conn: conn_str, cid: 82001, @@ -253,7 +253,7 @@ mod tests { Ok(BcUdp::Discovery(UdpDiscovery { tid: 1101, payload: UdpXml { - camera_cfm: Some(CameraCfm { + d2c_cfm: Some(D2cCfm { sid: 62098713, conn: conn_str, rsp: 0, diff --git a/crates/core/src/bcudp/mod.rs b/crates/core/src/bcudp/mod.rs index 4c50f65..21e5ed7 100644 --- a/crates/core/src/bcudp/mod.rs +++ b/crates/core/src/bcudp/mod.rs @@ -22,10 +22,12 @@ //! mod crc; -mod de; +/// Functions to deserialize udp packets +pub mod de; /// Contains the model describing the top level structures pub mod model; -mod ser; +/// Functions to serialize udp packets +pub mod ser; /// Contains the udp related xml payloads pub mod xml; // Constains routines to de/encrypt udp xml diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index 46c4214..c83348e 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -38,9 +38,13 @@ pub const MAGIC_HEADER_UDP_ACK: u32 = 0x2a87cf20; /// resend the packet #[derive(Debug, PartialEq, Eq)] pub struct UdpAck { - /// The connection ID of the other party + /// The connection ID /// - /// This is negotiated during [`UdpDiscovery`] + /// This is negotiated during [`UdpDiscovery`] as cid for the client and did for the camera + /// + /// When receiving from the camera it will be cid + /// + /// When sending to the camera it should be did pub connection_id: u32, // Unknown 4 bytes always 0 /// The ID of the last data packet [`UdpData`] @@ -57,7 +61,11 @@ pub const MAGIC_HEADER_UDP_DATA: u32 = 0x2a87cf10; pub struct UdpData { /// The connection ID of the other party /// - /// This is negotiated during [`UdpDiscovery`] + /// This is negotiated during [`UdpDiscovery`] as cid for the client and did for the camera + /// + /// When receiving from the camera it will be cid + /// + /// When sending to the camera it should be did pub connection_id: u32, // Unknown 4 bytes always 0 /// The ID of the data packet diff --git a/crates/core/src/bcudp/xml.rs b/crates/core/src/bcudp/xml.rs index f99d7ca..798fb2a 100644 --- a/crates/core/src/bcudp/xml.rs +++ b/crates/core/src/bcudp/xml.rs @@ -6,27 +6,30 @@ use yaserde::{ser::Config, YaDeserialize, YaSerialize}; use yaserde_derive::{YaDeserialize, YaSerialize}; /// The top level of the UDP xml is P2P -#[derive(PartialEq, Eq, Debug, YaDeserialize, YaSerialize)] +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] #[yaserde(rename = "P2P")] pub struct UdpXml { - /// C2D_S xml + /// C2D_S xml Discovery of any client #[yaserde(rename = "C2D_S")] - pub start: Option, - /// C2D_S xml + pub c2d_s: Option, + /// C2D_S xml Discovery of client with a UID #[yaserde(rename = "C2D_C")] - pub start_with: Option, + pub c2d_c: Option, + /// D2C_C_C xml Reply from discovery + #[yaserde(rename = "D2C_C_R")] + pub d2c_c_r: Option, /// D2C_T xml #[yaserde(rename = "D2C_T")] - pub camera_transmission: Option, + pub d2c_t: Option, /// C2D_T xml #[yaserde(rename = "C2D_T")] - pub client_transmission: Option, + pub c2d_t: Option, /// D2C_CFM xml #[yaserde(rename = "D2C_CFM")] - pub camera_cfm: Option, - /// C2D_DISC xml + pub d2c_cfm: Option, + /// C2D_DISC xml Disconnect #[yaserde(rename = "C2D_DISC")] - pub disconnect: Option, + pub c2d_disc: Option, } impl UdpXml { @@ -45,14 +48,14 @@ impl UdpXml { /// /// It should be broadcasted to port 2015 #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct DiscoveryStartAny { +pub struct C2dS { /// The destination to reply to - pub to: StartTo, + pub to: PortList, } -/// to xml +/// Port list xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct StartTo { +pub struct PortList { /// Port to open udp connections with pub port: u32, } @@ -62,11 +65,11 @@ pub struct StartTo { /// This will start a connection with any camera that has this UID /// It should be broadcasted to port 2018 #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct DiscoveryStartWith { +pub struct C2dC { /// UID of the camera the client wants to connect with pub uid: String, /// Cli contains the udp port to communicate on - pub cli: StartCli, + pub cli: ClientList, /// The cid is the client ID pub cid: u32, /// Maximum transmission size, @@ -78,16 +81,43 @@ pub struct DiscoveryStartWith { pub os: String, } -/// C2D_C xml +/// Client List xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct StartCli { +pub struct ClientList { /// Port to start udp communication with pub port: u32, } +/// D2C_C_R xml +/// +/// This will start a connection with any camera that has this UID +/// It should be broadcasted to port 2018 +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct D2cCr { + /// Called timer but not sure what it is a timer of + pub timer: Timer, + /// Unknown + pub rsp: u32, + /// Client ID + pub cid: u32, + /// Camera ID + pub did: u32, +} + +/// Timer provided by D2C_C_R +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct Timer { + /// Unknown + def: u32, + /// Unknown + hb: u32, + /// Unknown + hbt: u32, +} + /// C2D_DISC xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct Disconnect { +pub struct C2dDisc { /// The client connection ID pub cid: u32, /// The camera connection ID @@ -96,7 +126,7 @@ pub struct Disconnect { /// D2C_T xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct CameraTransmission { +pub struct D2cT { /// The camera SID pub sid: u32, /// Type of connection observed values are `"local"` @@ -109,7 +139,7 @@ pub struct CameraTransmission { /// C2D_T xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct ClientTransmission { +pub struct C2dT { /// The camera SID pub sid: u32, /// Type of connection observed values are `"local"` @@ -122,7 +152,7 @@ pub struct ClientTransmission { /// D2C_CFM xml #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] -pub struct CameraCfm { +pub struct D2cCfm { /// The camera SID pub sid: u32, /// Type of connection observed values are `"local"` diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c2e5a4d..cbeca6c 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -42,3 +42,5 @@ pub enum Never {} /// /// Most commands will either return their `Ok(result)` or this `Err(Error)` pub use bc_protocol::Error; + +pub(crate) const RX_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); diff --git a/dissector/udp.md b/dissector/udp.md index 2e788d2..77edf3e 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -117,6 +117,10 @@ standard tcp bc connection If the camera supports UDP the client will send this xml packet as a broadcast on 255.255.255.255 on port 2018 +**Known UID** + +If the UID is already known you can skip to this step. + ```xml @@ -139,33 +143,14 @@ to both udp and tcp. Then the udp will disconnect. --- -## T Payload Camera +## D2C_C_R Payload Camera Camera replies with this payload on the port specified in `C2D_C` -```xml - - - 62097899 - local - 82000 - 80 - - -``` - -- **sid**: ID of the camera -- **conn**: Type of connection only observed `local` value -- **cid**: The connection ID of the client -- **did**: The connection ID of the camera - - -Camera also sends this - ```xml - + 3000 10000 60000 @@ -177,6 +162,12 @@ Camera also sends this ``` +- **timer** Unknown timer of some sort` +- **rsp**: Unknown +- **cid**: The connection ID of the client +- **did**: The connection ID of the camera + + ## T Payload Client @@ -200,6 +191,11 @@ Client then replies with this. - **mtu**: The maximum transmission unit of the connection. Which is the largest packet size in bytes + +## T Payload Camera + +Camera replies with this payload on the port specified in `C2D_C` + **Login** The client can now login over UDP From c0e1a817d2b81e2ebf6ddd45ee20f56613d9af2e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 15 Aug 2021 14:17:06 +0700 Subject: [PATCH 19/56] Removed redundant field in udp dissector --- dissector/baichuan.lua | 3 --- 1 file changed, 3 deletions(-) diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index aa543f6..86992a2 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -22,7 +22,6 @@ password = ProtoField.string("baichuan.password", "password", base.ASCII) -- UDP Related content udp_magic = ProtoField.int32("baichuan.udp_magic", "udp_magic", base.DEC) -udp_type = ProtoField.int8("baichuan.udp_type", "udp_type", base.DEC) udp_message_id = ProtoField.int8("baichuan.udp_message_id", "udp_message_id", base.DEC) udp_connection_id = ProtoField.int32("baichuan.udp_connection_id", "udp_connection_id", base.DEC) udp_unknown = ProtoField.int32("baichuan.udp_unknown", "udp_unknown", base.DEC) @@ -49,7 +48,6 @@ bc_protocol.fields = { username, password, udp_magic, - udp_type, udp_message_id, udp_connection_id, udp_unknown, @@ -463,7 +461,6 @@ function process_udp_header(buffer, headers_tree) local header = headers_tree:add(bc_protocol, buffer(0, header_data.length), "Baichuan UDP Header, length: " .. header_data.length .. ", type " .. header_data.class) header:add_le(udp_magic, buffer(0,4)) - header:add_le(udp_type, buffer(0,1)) if header_data.class == 0x3a then header:add_le(udp_size, buffer(4, 4)) header:add_le(udp_unknown,buffer(8, 4)) From 8aee6e8e8dc5a9b570b21bc1cf92c5929b342e2d Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 15 Aug 2021 16:51:15 +0700 Subject: [PATCH 20/56] Add a better timeout handling to UDP and Media --- .../src/bc_protocol/connection/udpconn.rs | 21 ++++++----- crates/core/src/bcmedia/de.rs | 35 ++++++++++++++----- crates/core/src/bcudp/de.rs | 35 ++++++++++++++----- 3 files changed, 65 insertions(+), 26 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpconn.rs b/crates/core/src/bc_protocol/connection/udpconn.rs index 95cf7b9..c97eb2d 100644 --- a/crates/core/src/bc_protocol/connection/udpconn.rs +++ b/crates/core/src/bc_protocol/connection/udpconn.rs @@ -3,6 +3,7 @@ use crate::bc; use crate::bc::model::*; use crate::bcudp; use crate::bcudp::{model::*, xml::*}; +use crate::RX_TIMEOUT; use log::*; use rand::{seq::SliceRandom, thread_rng, Rng}; use socket2::{Domain, Socket, Type}; @@ -456,14 +457,18 @@ impl BufRead for UdpSource { } if self.read_buffer.buffer.len() <= self.read_buffer.consumed { // Get next packet of the read queue - if let Some(msg) = self - .incoming - .lock() - .unwrap() - .remove(&self.next_to_consume.load(Ordering::Relaxed)) - { - self.next_to_consume.fetch_add(1, Ordering::Relaxed); - self.read_buffer.buffer.extend(msg.buf); + let start_time = OffsetDateTime::now_utc(); + while (start_time - OffsetDateTime::now_utc()) < RX_TIMEOUT { + if let Some(msg) = self + .incoming + .lock() + .unwrap() + .remove(&self.next_to_consume.load(Ordering::Relaxed)) + { + self.next_to_consume.fetch_add(1, Ordering::Relaxed); + self.read_buffer.buffer.extend(msg.buf); + break; + } } } diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index 1fd7e1b..04aacb8 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -1,9 +1,11 @@ use super::model::BcMediaIframe; use super::model::*; +use crate::RX_TIMEOUT; use err_derive::Error; use nom::IResult; use nom::{combinator::*, named, number::streaming::*, take, take_str}; use std::io::Read; +use time::OffsetDateTime; // PAD_SIZE: Media packets use 8 byte padding const PAD_SIZE: u32 = 8; @@ -50,15 +52,30 @@ where Err(e) => return Err(e.into()), }; - if 0 == (&mut rdr) - .take(to_read.get() as u64) - .read_to_end(&mut input)? - { - return Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "Read returned 0 bytes", - ) - .into()); + let start_time = OffsetDateTime::now_utc(); + loop { + match (&mut rdr) + .take(to_read.get() as u64) + .read_to_end(&mut input) + { + Ok(0) => { + if (OffsetDateTime::now_utc() - start_time) > RX_TIMEOUT { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } + } + Ok(_) => break, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + // This is a temporaily unavaliable resource + // We should just wait and try again + } + Err(e) => { + return Err(e.into()); + } + } } } } diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index a8cc9ff..1115905 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -1,4 +1,5 @@ use super::{crc::calc_crc, model::*, xml::*, xml_crypto::decrypt}; +use crate::RX_TIMEOUT; use err_derive::Error; use nom::IResult; use nom::{ @@ -8,6 +9,7 @@ use nom::{ take, Err, }; use std::io::Read; +use time::OffsetDateTime; /// The error types used during deserialisation #[derive(Debug, Error)] @@ -51,15 +53,30 @@ where Err(e) => return Err(e.into()), }; - if 0 == (&mut rdr) - .take(to_read.get() as u64) - .read_to_end(&mut input)? - { - return Err(std::io::Error::new( - std::io::ErrorKind::UnexpectedEof, - "Read returned 0 bytes", - ) - .into()); + let start_time = OffsetDateTime::now_utc(); + loop { + match (&mut rdr) + .take(to_read.get() as u64) + .read_to_end(&mut input) + { + Ok(0) => { + if (OffsetDateTime::now_utc() - start_time) > RX_TIMEOUT { + return Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "Read returned 0 bytes", + ) + .into()); + } + } + Ok(_) => break, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + // This is a temporaily unavaliable resource + // We should just wait and try again + } + Err(e) => { + return Err(e.into()); + } + } } } } From 643953845a9cc136f14f0ca7fec3af0d9100ebf2 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 16 Aug 2021 11:28:30 +0700 Subject: [PATCH 21/56] Doc update to include battery cameras and doc fixes --- README.md | 11 +++++++++++ docs/unix_setup.md | 1 - sample_config.toml | 10 ++++++++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8c93ce9..552a7bb 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,14 @@ docker run \ The Docker image is "best effort" and intended for advanced users; questions about running Docker are outside the scope of Neolink. +If you use a UDP only camera, such as a battery camera you will need to either +use `--net=host` or setup a [macvlan](https://docs.docker.com/network/macvlan/) +for the docker image that supports UDP broadcast. +This is because UDP requires that udp broadcast messages are transmitted across +the docker network interface, however this is [not possible in the default +bridging mode](https://github.com/docker/for-linux/issues/637) + + ## Configuration **Note**: for a more comprehensive setup tutorial, refer to the @@ -120,6 +128,9 @@ about running Docker are outside the scope of Neolink. Copy and modify the `sample_config.toml` to specify the address, username, and password for each camera (if there is no password, you can omit that line). +The address can be a camera UID, in this case your network must support UDP +broadcasts. Battery cameras exclusively use this UDP mode so you must always +use a UID in the address field. Each `[[cameras]]` block creates a new camera; the `name` determines the RTSP path you should connect your client to. diff --git a/docs/unix_setup.md b/docs/unix_setup.md index 40886ef..cb4ee02 100644 --- a/docs/unix_setup.md +++ b/docs/unix_setup.md @@ -42,7 +42,6 @@ Here are some examples for commands of package managers libgstrtspserver-1.0-0 \ libgstreamer1.0-0 \ libgstreamer-plugins-bad1.0-0 \ - libgstreamer-plugins-good1.0-0 \ gstreamer1.0-plugins-good \ gstreamer1.0-plugins-bad ``` diff --git a/sample_config.toml b/sample_config.toml index cbe4fa2..74228df 100644 --- a/sample_config.toml +++ b/sample_config.toml @@ -14,7 +14,7 @@ bind = "0.0.0.0" # Choose if the client is required to provide a certificate signed by the server's CA. # none|requested|required - default none -# tls_client_auth = "required" +# tls_client_auth = "required" # You can password protect the rtsp server mount points by adding users # like the following me and someone. If you do not add [[users]] @@ -50,7 +50,13 @@ name = "storage shed" username = "admin" password = "987654321" address = "192.168.1.245:9000" +# The address could instead be set to a camera UID like this +# address = "ABCD01234567890EFG" +# If you use an NVR that relays several camera connections you can choose which +# camera to connect to with by setting the `channel_id` +# # By default channel_id = 0. Eg the first connected camera on the device -# Note this counts from 0. An 8 channel NVR would have channels 0 through 7 +# **Note**: that unlike in the offical client the numbering starts from 0 not 1. +# An 8 channel NVR would have channels 0 through 7 # channel_id = 1 From 7a5def551d17950ec9480f114ccec167ec88fe51 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 18 Aug 2021 11:11:55 +0700 Subject: [PATCH 22/56] Use ports 2015 and 2018 for UDP discovery Also add remote discovery but it is disabled for now --- crates/core/Cargo.toml | 1 + crates/core/src/bc_protocol/connection/mod.rs | 2 +- .../src/bc_protocol/connection/udpconn.rs | 436 +++++++++++++++++- crates/core/src/bcudp/de.rs | 4 +- crates/core/src/bcudp/model.rs | 12 +- crates/core/src/bcudp/ser.rs | 4 +- crates/core/src/bcudp/xml.rs | 146 +++++- src/talk/gst.rs | 2 +- 8 files changed, 565 insertions(+), 42 deletions(-) diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index c304ec4..83db767 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -10,6 +10,7 @@ aes = "0.6" cfb-mode = "0.6" cookie-factory = "0.3" err-derive = "0.2" +lazy_static = "1.4" log = { version = "0.4" } md5 = "0.7" nom = "6.1.2" diff --git a/crates/core/src/bc_protocol/connection/mod.rs b/crates/core/src/bc_protocol/connection/mod.rs index 004cada..4d6a235 100644 --- a/crates/core/src/bc_protocol/connection/mod.rs +++ b/crates/core/src/bc_protocol/connection/mod.rs @@ -63,7 +63,7 @@ pub enum Error { #[error(display = "This connection type in unsupported")] UnsupportedConnection, - #[error(display = "Camera Unconnected")] + #[error(display = "Camera Not Findable")] ConnectionUnavaliable, } diff --git a/crates/core/src/bc_protocol/connection/udpconn.rs b/crates/core/src/bc_protocol/connection/udpconn.rs index c97eb2d..28ef9ae 100644 --- a/crates/core/src/bc_protocol/connection/udpconn.rs +++ b/crates/core/src/bc_protocol/connection/udpconn.rs @@ -4,6 +4,7 @@ use crate::bc::model::*; use crate::bcudp; use crate::bcudp::{model::*, xml::*}; use crate::RX_TIMEOUT; +use lazy_static::lazy_static; use log::*; use rand::{seq::SliceRandom, thread_rng, Rng}; use socket2::{Domain, Socket, Type}; @@ -12,7 +13,7 @@ use std::collections::BTreeMap; use std::collections::HashMap; use std::error::Error as StdErr; // Just need the traits use std::io::{BufRead, Error as IoError, Read, Write}; -use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; +use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket}; use std::sync::{ atomic::{AtomicBool, AtomicU32, Ordering}, mpsc::{channel, Receiver, Sender}, @@ -26,11 +27,29 @@ type IoResult = std::result::Result; const WAIT_TIME: Duration = Duration::from_millis(500); +// TODO: Path MTU discovery +const MTU: u32 = 1350; + +lazy_static! { + static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [ + "p2p.reolink.com", + "p2p1.reolink.com", + "p2p2.reolink.com", + "p2p3.reolink.com", + "p2p14.reolink.com", + "p2p15.reolink.com", + "p2p6.reolink.com", + "p2p7.reolink.com", + "p2p8.reolink.com", + "p2p9.reolink.com", + ]; +} + pub struct UdpSource { socket: UdpSocket, address: SocketAddr, - client_id: u32, - camera_id: u32, + client_id: i32, + camera_id: i32, mtu: u32, outgoing: Arc>>, incoming: Arc>>, @@ -57,8 +76,8 @@ struct QueuedMessage { struct DiscoveryResult { socket: UdpSocket, address: SocketAddr, - client_id: u32, - camera_id: u32, + client_id: i32, + camera_id: i32, mtu: u32, } @@ -106,19 +125,50 @@ impl UdpSource { buf: &[u8], addr: T, ) -> IoResult<(usize, AbortHandle)> { - let addr: SocketAddr = addr.to_socket_addrs()?.next().unwrap(); + let addr = addr.to_socket_addrs()?.next().ok_or_else(|| { + IoError::new(std::io::ErrorKind::NotFound, Error::ConnectionUnavaliable) + })?; + Self::retrying_send_to_multi(socket, buf, &[addr]) + } + + fn retrying_send_to_multi( + socket: &UdpSocket, + buf: &[u8], + addrs: &[T], + ) -> IoResult<(usize, AbortHandle)> { let handle = AbortHandle::new(); - let bytes_send = socket.send_to(&buf, &addr)?; + + let addrs: Vec = addrs + .iter() + .map(|a| { + a.to_socket_addrs() + .ok() + .and_then(|mut a_iter| a_iter.next()) + }) + .flatten() + .collect(); + + let mut bytes_send = 0; + for addr in addrs.iter() { + bytes_send = socket.send_to(buf, &addr)?; + } let thread_buffer = buf.to_vec(); let thread_handle = handle.clone(); let thread_socket = socket.try_clone()?; - let thread_addr = addr; + let thread_addr: Vec = addrs; + + const MAX_RETRIES: usize = 10; std::thread::spawn(move || { std::thread::sleep(WAIT_TIME); - while !thread_handle.is_aborted() { - let _ = thread_socket.send_to(&thread_buffer[..], &thread_addr); + for _ in 0..MAX_RETRIES { + if thread_handle.is_aborted() { + break; + } + for addr in thread_addr.iter() { + let _ = thread_socket.send_to(&thread_buffer[..], &addr); + } std::thread::sleep(WAIT_TIME); } }); @@ -126,20 +176,19 @@ impl UdpSource { Ok((bytes_send, handle)) } - fn discover_from_uuid(uid: &str, timeout: Duration) -> Result { - let start_time = OffsetDateTime::now_utc(); - - let socket = Self::get_socket(timeout)?; - + fn discover_from_uuid_local( + uid: &str, + socket: &UdpSocket, + timeout: Duration, + ) -> Result { let mut rng = thread_rng(); // If tid is too large it will overflow during encrypt so we just use a random u8 let tid: u32 = (rng.gen::()) as u32; - let client_id: u32 = rng.gen(); + let client_id: i32 = rng.gen(); let local_addr = socket.local_addr()?; let port = local_addr.port(); - // TODO: Path MTU discovery - let mtu = 1350; + let mtu = MTU; let msg = BcUdp::Discovery(UdpDiscovery { tid, @@ -159,10 +208,14 @@ impl UdpSource { let mut buf = vec![]; msg.serialize(&mut buf)?; - let (amount_sent, abort) = - Self::retrying_send_to(&socket, &buf[..], "255.255.255.255:2018")?; + let (amount_sent, abort) = Self::retrying_send_to_multi( + socket, + &buf[..], + &["255.255.255.255:2015", "255.255.255.255:2018"], + )?; assert_eq!(amount_sent, buf.len()); + let start_time = OffsetDateTime::now_utc(); let camera_address; let camera_id; loop { @@ -202,7 +255,7 @@ impl UdpSource { socket.connect(camera_address)?; Ok(DiscoveryResult { - socket, + socket: socket.try_clone()?, address: camera_address, client_id, camera_id, @@ -210,8 +263,345 @@ impl UdpSource { }) } + fn get_register( + uid: &str, + socket: &UdpSocket, + timeout: Duration, + tid: u32, + // client_id: u32, + ) -> Result { + // let local_addr = socket.local_addr()?; + // let local_port = local_addr.port(); + + let mtu = MTU; + + for p2p_relay in P2P_RELAY_HOSTNAMES.iter() { + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2m_q: Some(C2mQ { + uid: uid.to_string(), + os: "MAC".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = + Self::retrying_send_to(socket, &buf[..], format!("{}:9999", p2p_relay))?; + assert_eq!(amount_sent, buf.len()); + + let start_time = OffsetDateTime::now_utc(); + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + m2c_q_r: Some(m2c_q_r), + .. + }, + })) => { + abort.abort(); + return Ok(m2c_q_r); + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + // This p2p server didn't have the data we need try another + continue; + } + } + } + Err(Error::ConnectionUnavaliable) + } + + fn discover_from_uuid_remote( + uid: &str, + socket: &UdpSocket, + timeout: Duration, + ) -> Result { + let local_addr = socket.local_addr()?; + let local_port = local_addr.port(); + + let mut rng = thread_rng(); + // If tid is too large it will overflow during encrypt so we just use a random u8 + let tid: u32 = (rng.gen::()) as u32; + let mtu = MTU; + let client_id: i32 = rng.gen(); + + let m2c_q_r = Self::get_register(uid, socket, timeout, tid)?; + + let register_address = m2c_q_r.reg; + let relay_address = m2c_q_r.relay; + let log_address = m2c_q_r.log; + let device_address = m2c_q_r.t; + + debug!("Register address found: {:?}", register_address); + debug!("Registering this address: {:?}", local_addr); + + let local_family = if local_addr.ip().is_ipv4() { 4 } else { 6 }; + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2r_c: Some(C2rC { + uid: uid.to_string(), + cli: IpPort { + ip: local_addr.ip().to_string(), + port: local_port, + }, + relay: relay_address, + cid: client_id, + family: local_family, + debug: false, + os: "MAC".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = Self::retrying_send_to( + socket, + &buf[..], + format!("{}:{}", register_address.ip, register_address.port), + )?; + assert_eq!(amount_sent, buf.len()); + + let device_sid; + let dev_loc; + let start_time = OffsetDateTime::now_utc(); + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + // Got camera data from register + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + r2c_t: Some(R2cT { dev, cid, sid, .. }), + .. + }, + })) if cid == client_id => { + abort.abort(); + // Make a local request to the camera with the dev info + device_sid = sid; + dev_loc = dev; + break; + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + return Err(Error::Timeout); + } + } + + debug!("Register revealed address as SID: {:?}", device_sid); + debug!("Register revealed address as IP: {:?}", dev_loc); + + // ensure abort + abort.abort(); + + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_t: Some(C2dT { + sid: device_sid, + cid: client_id, + mtu, + conn: "local".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = + Self::retrying_send_to(socket, &buf[..], format!("{}:{}", dev_loc.ip, dev_loc.port))?; + assert_eq!(amount_sent, buf.len()); + + let device_id; + let start_time = OffsetDateTime::now_utc(); + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + // Got camera data from camera + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_t: Some(D2cT { cid, did, .. }), + .. + }, + })) if cid == client_id => { + device_id = did; + break; + } + // Got camera data from camera CFM + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_cfm: Some(D2cCfm { cid, did, .. }), + .. + }, + })) if cid == client_id => { + device_id = did; + break; + } + // Got camera data from camera disc + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_disc: Some(D2cDisc { cid, did, .. }), + .. + }, + })) if cid == client_id => { + device_id = did; + break; + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + return Err(Error::Timeout); + } + } + + debug!("Got device ID as: {:?}", device_id); + + // Ensure aborted + abort.abort(); + + // Announce to the log that we will connect locally + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2r_cfm: Some(C2rCfm { + sid: device_sid, + cid: client_id, + did: device_id, + conn: "local".to_string(), + rsp: 0, + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + // Just let this retry to max limit as we don't get a reply + let (amount_sent, _) = Self::retrying_send_to( + socket, + &buf[..], + format!("{}:{}", log_address.ip, log_address.port), + )?; + assert_eq!(amount_sent, buf.len()); + + // Announce a map type connection (I think this means we could connect remotely) + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_t: Some(C2dT { + sid: device_sid, + cid: client_id, + mtu, + conn: "map".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + // Just let this retry to max limit as we don't get a reply + let (amount_sent, _) = Self::retrying_send_to( + socket, + &buf[..], + format!("{}:{}", device_address.ip, device_address.port), + )?; + assert_eq!(amount_sent, buf.len()); + + let camera_address: SocketAddr = format!("{}:{}", device_address.ip, device_address.port) + .to_socket_addrs()? + .next() + .ok_or(Error::ConnectionUnavaliable)?; + + Ok(DiscoveryResult { + socket: socket.try_clone()?, + address: camera_address, + client_id, + camera_id: device_id, + mtu, + }) + } + + fn discover_from_uuid( + uid: &str, + timeout: Duration, + allow_remote: bool, + ) -> Result { + let socket = Self::get_socket(timeout)?; + match Self::discover_from_uuid_local(uid, &socket, timeout) { + Err(Error::Timeout) if allow_remote => { + Self::discover_from_uuid_remote(uid, &socket, timeout) + } + Ok(result) => Ok(result), + Err(e) => Err(e), + } + } + + /// It is possible to contact the reolink servers using udp to + /// learn the ip and port of the camera. By default I have turned + /// this feature off with no way to enable it from the usual + /// command line interface or config. + /// + /// However it may prove neccesary one day to use it so it is here in the + /// library and other programs may want to use it. + pub fn new_allow_remote(uid: &str, timeout: Duration) -> Result { + Self::new_with_remote(uid, timeout, true) + } + pub fn new(uid: &str, timeout: Duration) -> Result { - let discovery_result = Self::discover_from_uuid(uid, timeout)?; + Self::new_with_remote(uid, timeout, false) + } + + fn new_with_remote(uid: &str, timeout: Duration, allow_remote: bool) -> Result { + let discovery_result = Self::discover_from_uuid(uid, timeout, allow_remote)?; info!("UID {:?} found at {:?}", uid, discovery_result.address); let me = UdpSource { @@ -260,7 +650,7 @@ impl UdpSource { fn handle_ack( next_to_consume: u32, - camera_id: u32, + camera_id: i32, incoming: &mut HashMap, socket: &UdpSocket, ) { diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index 1115905..d5f3820 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -132,7 +132,7 @@ fn udp_disc(buf: &[u8]) -> IResult<&[u8], UdpDiscovery> { } fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { - let (buf, connection_id) = le_u32(buf)?; + let (buf, connection_id) = le_i32(buf)?; let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; let (buf, _unknown_b) = verify(le_u32, |&x| x == 0)(buf)?; let (buf, packet_id) = le_u32(buf)?; @@ -147,7 +147,7 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { } fn udp_data(buf: &[u8]) -> IResult<&[u8], UdpData> { - let (buf, connection_id) = le_u32(buf)?; + let (buf, connection_id) = le_i32(buf)?; let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; let (buf, packet_id) = le_u32(buf)?; let (buf, payload_size) = le_u32(buf)?; diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index c83348e..80e11c4 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -45,7 +45,11 @@ pub struct UdpAck { /// When receiving from the camera it will be cid /// /// When sending to the camera it should be did - pub connection_id: u32, + /// + /// We use i32 because when we send the connection id to the reolink + /// register and then download the same connection id from the register_address + /// it comes back in an xml that is encoded as i32 (i.e. can be negative string) + pub connection_id: i32, // Unknown 4 bytes always 0 /// The ID of the last data packet [`UdpData`] pub packet_id: u32, @@ -66,7 +70,11 @@ pub struct UdpData { /// When receiving from the camera it will be cid /// /// When sending to the camera it should be did - pub connection_id: u32, + /// + /// We use i32 because when we send the connection id to the reolink + /// register and then download the same connection id from the register_address + /// it comes back in an xml that is encoded as i32 (i.e. can be negative string) + pub connection_id: i32, // Unknown 4 bytes always 0 /// The ID of the data packet pub packet_id: u32, diff --git a/crates/core/src/bcudp/ser.rs b/crates/core/src/bcudp/ser.rs index 04c7887..b64d2fe 100644 --- a/crates/core/src/bcudp/ser.rs +++ b/crates/core/src/bcudp/ser.rs @@ -51,7 +51,7 @@ fn bcudp_disc<'a, W: 'a + Write>( fn bcudp_ack<'a, W: 'a + Write>(payload: &'a UdpAck) -> impl SerializeFn + 'a { tuple(( le_u32(MAGIC_HEADER_UDP_ACK), - le_u32(payload.connection_id), + le_i32(payload.connection_id), le_u32(0), le_u32(0), le_u32(payload.packet_id), @@ -66,7 +66,7 @@ fn bcudp_data<'a, W: 'a + Write>( ) -> impl SerializeFn + 'a { tuple(( le_u32(MAGIC_HEADER_UDP_DATA), - le_u32(payload.connection_id), + le_i32(payload.connection_id), le_u32(0), le_u32(payload.packet_id), le_u32(binary_payload.len() as u32), diff --git a/crates/core/src/bcudp/xml.rs b/crates/core/src/bcudp/xml.rs index 798fb2a..093c3d0 100644 --- a/crates/core/src/bcudp/xml.rs +++ b/crates/core/src/bcudp/xml.rs @@ -30,6 +30,24 @@ pub struct UdpXml { /// C2D_DISC xml Disconnect #[yaserde(rename = "C2D_DISC")] pub c2d_disc: Option, + /// D2C_DISC xml Disconnect + #[yaserde(rename = "D2C_DISC")] + pub d2c_disc: Option, + /// C2M_Q xml client to middle man query + #[yaserde(rename = "C2M_Q")] + pub c2m_q: Option, + /// M2C_Q_R xml middle man to client query reply + #[yaserde(rename = "M2C_Q_R")] + pub m2c_q_r: Option, + /// C2R_C xml client to register connect + #[yaserde(rename = "C2R_C")] + pub c2r_c: Option, + /// R2C_T xml register to clinet with device ID etc + #[yaserde(rename = "R2C_T")] + pub r2c_t: Option, + /// C2R_CFM xml client to register CFM + #[yaserde(rename = "C2R_CFM")] + pub c2r_cfm: Option, } impl UdpXml { @@ -71,12 +89,12 @@ pub struct C2dC { /// Cli contains the udp port to communicate on pub cli: ClientList, /// The cid is the client ID - pub cid: u32, + pub cid: i32, /// Maximum transmission size, pub mtu: u32, /// Debug mode. Purpose unknown pub debug: bool, - /// Os of the machine known values are `"MAC"` + /// Os of the machine known values are `"MAC"`, `"WIN"` #[yaserde(rename = "p")] pub os: String, } @@ -99,9 +117,9 @@ pub struct D2cCr { /// Unknown pub rsp: u32, /// Client ID - pub cid: u32, + pub cid: i32, /// Camera ID - pub did: u32, + pub did: i32, } /// Timer provided by D2C_C_R @@ -119,9 +137,18 @@ pub struct Timer { #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct C2dDisc { /// The client connection ID - pub cid: u32, + pub cid: i32, /// The camera connection ID - pub did: u32, + pub did: i32, +} + +/// D2C_DISC xml +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct D2cDisc { + /// The client connection ID + pub cid: i32, + /// The camera connection ID + pub did: i32, } /// D2C_T xml @@ -132,9 +159,9 @@ pub struct D2cT { /// Type of connection observed values are `"local"` pub conn: String, /// The client connection ID - pub cid: u32, + pub cid: i32, /// The camera connection ID - pub did: u32, + pub did: i32, } /// C2D_T xml @@ -145,12 +172,92 @@ pub struct C2dT { /// Type of connection observed values are `"local"` pub conn: String, /// The client connection ID - pub cid: u32, + pub cid: i32, /// Maximum size in bytes of a transmission pub mtu: u32, } +/// C2M_Q xml +/// +/// This is from client to a reolink middle man server +/// +/// It should be sent to a reolink p2p sever on port 9999 +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct C2mQ { + /// UID to look up + pub uid: String, + /// Os of the machine known values are `"MAC"`, `"WIN"` + #[yaserde(rename = "p")] + pub os: String, +} + +/// M2C_Q_R xml +/// +/// This is from middle man reolink server to client +/// +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct M2cQr { + /// The register server location + pub reg: IpPort, + /// The relay server location + pub relay: IpPort, + /// The log server location + pub log: IpPort, + /// The camera location + pub t: IpPort, +} + +/// Used as part of M2C_Q_R to provide the host and port +/// +/// of the register, relay and log servers +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct IpPort { + /// Ip of the service + pub ip: String, + /// Port of the service + pub port: u16, +} + +/// C2R_C xml +/// +/// This is from client to the register reolink server +/// +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct C2rC { + /// The UID to register connecition request with + pub uid: String, + /// The location of the client + pub cli: IpPort, + /// The location of the relay server + pub relay: IpPort, + /// The client id + pub cid: i32, + /// Debug setting. Unknown purpose observed values are `0` + pub debug: bool, + /// Inet family. Observed values `4` + pub family: u8, + /// Os of the machine known values are `"MAC"`, `"WIN"` + #[yaserde(rename = "p")] + pub os: String, +} + +/// R2C_T xml +/// +/// This is from register reolink server to clinet with device ip and did etc +/// +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct R2cT { + /// The location of the camera + pub dev: IpPort, + /// The client id + pub cid: i32, + /// The camera SID + pub sid: u32, +} + /// D2C_CFM xml +/// +/// Device to client, with connection started from middle man server #[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] pub struct D2cCfm { /// The camera SID @@ -160,9 +267,26 @@ pub struct D2cCfm { /// Unknown known values are `0` pub rsp: u32, /// The client connection ID - pub cid: u32, + pub cid: i32, /// The camera connection ID - pub did: u32, + pub did: i32, /// The time but only value that has been observed is `0 pub time_r: u32, } + +/// C2R_CFM xml +/// +/// Client to register +#[derive(PartialEq, Eq, Default, Debug, YaDeserialize, YaSerialize)] +pub struct C2rCfm { + /// The camera SID + pub sid: u32, + /// Type of connection observed values are `"local"` + pub conn: String, + /// Unknown known values are `0` + pub rsp: u32, + /// The client connection ID + pub cid: i32, + /// The camera connection ID + pub did: i32, +} diff --git a/src/talk/gst.rs b/src/talk/gst.rs index b0e44b7..2aef77d 100644 --- a/src/talk/gst.rs +++ b/src/talk/gst.rs @@ -106,7 +106,7 @@ fn set_data_channel(appsink: &AppSink, tx: SyncSender>) { // We know what format the data in the memory region has, since we requested // it by setting the appsink's caps. So what we do here is interpret the - // memory region we mapped as an array of signed 16 bit integers. + // memory region we mapped as an array of signed 8 bit integers. let samples = map.as_slice_of::().map_err(|_| { element_error!( appsink, From 884b7c600dfff492244219447e6562006ecd9d41 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 18 Aug 2021 15:09:50 +0700 Subject: [PATCH 23/56] Handle camera hang up on udp --- .../src/bc_protocol/connection/udpconn.rs | 33 +++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpconn.rs b/crates/core/src/bc_protocol/connection/udpconn.rs index 28ef9ae..736ad9e 100644 --- a/crates/core/src/bc_protocol/connection/udpconn.rs +++ b/crates/core/src/bc_protocol/connection/udpconn.rs @@ -702,6 +702,17 @@ impl UdpSource { let mut read_buf = vec![0_u8; thread_mtu as usize]; if let Ok(bytes_read) = thread_socket.recv(&mut read_buf[..]) { match BcUdp::deserialize(&read_buf[0..bytes_read]) { + Ok(BcUdp::Discovery(UdpDiscovery { + payload: + UdpXml { + d2c_disc: Some(D2cDisc { cid, did }), + .. + }, + .. + })) if cid == thread_client_id && did == thread_camera_id => { + thread_aborter.abort(); + debug!("Client requested disconnect") + } Ok(BcUdp::Discovery(packet)) => { warn!("Got unexpected discovery packet: {:?}", packet) } @@ -789,8 +800,8 @@ impl UdpSource { message.buf.len() ); message.time_last_tried = Some(now); - if thread_socket.send(&message.buf[..]).is_err() { - warn!("Failed to send message on udp"); + if let Err(e) = thread_socket.send(&message.buf[..]) { + error!("Failed to send message on udp: {:?}", e); } } } @@ -814,6 +825,12 @@ impl Drop for UdpSource { impl Read for UdpSource { fn read(&mut self, buf: &mut [u8]) -> IoResult { + if self.aborter.is_aborted() { + return Err(IoError::new( + std::io::ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } let buffer = self.fill_buf()?; let amt = std::cmp::min(buf.len(), buffer.len()); @@ -874,6 +891,12 @@ impl BufRead for UdpSource { const UDPDATA_HEADER_SIZE: usize = 20; impl Write for UdpSource { fn write(&mut self, buf: &[u8]) -> IoResult { + if self.aborter.is_aborted() { + return Err(IoError::new( + std::io::ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } self.write_buffer.buffer.extend(buf.to_vec()); if self.write_buffer.buffer.len() > self.mtu as usize - UDPDATA_HEADER_SIZE { let _ = self.flush(); @@ -882,6 +905,12 @@ impl Write for UdpSource { } fn flush(&mut self) -> IoResult<()> { + if self.aborter.is_aborted() { + return Err(IoError::new( + std::io::ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } for chunk in self .write_buffer .buffer From d432f7862d8ea8646fe967bafb2351f76c966524 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Fri, 20 Aug 2021 17:45:36 +0700 Subject: [PATCH 24/56] Update to the udp dissector --- dissector/baichuan.lua | 80 +++++++++++++++++++++++++++++++++--------- 1 file changed, 64 insertions(+), 16 deletions(-) diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 86992a2..65b1a3f 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -15,13 +15,13 @@ unknown = ProtoField.int8("baichuan.unknown", "unknown", base.DEC) msg_handle = ProtoField.int8("baichuan.message_handle", "messageHandle", base.DEC) status_code = ProtoField.int16("baichuan.status_code", "status_code", base.DEC) message_class = ProtoField.int32("baichuan.msg_class", "messageClass", base.DEC) -f_payload_offset = ProtoField.int32("baichuan.payload_offset", "binOffset", base.DEC) f_bin_offset = ProtoField.int32("baichuan.bin_offset", "binOffset", base.DEC) username = ProtoField.string("baichuan.username", "username", base.ASCII) password = ProtoField.string("baichuan.password", "password", base.ASCII) -- UDP Related content udp_magic = ProtoField.int32("baichuan.udp_magic", "udp_magic", base.DEC) +udp_type = ProtoField.int8("baichuan.udp_type", "udp_type", base.DEC) udp_message_id = ProtoField.int8("baichuan.udp_message_id", "udp_message_id", base.DEC) udp_connection_id = ProtoField.int32("baichuan.udp_connection_id", "udp_connection_id", base.DEC) udp_unknown = ProtoField.int32("baichuan.udp_unknown", "udp_unknown", base.DEC) @@ -43,11 +43,11 @@ bc_protocol.fields = { encrypt_xml, status_code, message_class, - f_payload_offset, f_bin_offset, username, password, udp_magic, + udp_type, udp_message_id, udp_connection_id, udp_unknown, @@ -187,12 +187,7 @@ end function get_header_len(buffer) local magic = buffer(0, 4):le_uint() - if magic == 0x0abcdef0 then - -- Client <-> BC - elseif magic == 0x0fedcba0 then - -- BC <-> BC - else - -- Unknown magic + if magic ~= 0x0abcdef0 then return -1 -- No header found end local header_len = header_lengths[buffer(18, 2):le_uint()] @@ -396,6 +391,8 @@ function get_udp_header_len(buffer) udptype = buffer(0, 1):le_uint() if udptype == 0x3a then return 20 + elseif udptype == 0x31 then + return 20 elseif udptype == 0x20 then return 28 elseif udptype == 0x10 then @@ -426,6 +423,11 @@ function get_udp_header(buffer) udp_unknown1 = buffer(8, 4):le_uint() udp_tid = buffer(12, 4):le_uint() udp_checksum = buffer(16, 4):le_uint() + elseif udp_class == 0x31 then + udp_size = buffer(4, 4):le_uint() + udp_unknown1 = buffer(8, 4):le_uint() + udp_tid = buffer(12, 4):le_uint() + udp_checksum = buffer(16, 4):le_uint() elseif udp_class == 0x20 then udp_connection_id = buffer(4, 4):le_uint() udp_unknown1 = buffer(8, 4):le_uint() @@ -461,11 +463,17 @@ function process_udp_header(buffer, headers_tree) local header = headers_tree:add(bc_protocol, buffer(0, header_data.length), "Baichuan UDP Header, length: " .. header_data.length .. ", type " .. header_data.class) header:add_le(udp_magic, buffer(0,4)) + header:add_le(udp_type, buffer(0,1)) if header_data.class == 0x3a then header:add_le(udp_size, buffer(4, 4)) header:add_le(udp_unknown,buffer(8, 4)) header:add_le(udp_tid, buffer(12, 4)) header:add_le(udp_checksum, buffer(16, 4)) + elseif header_data.class == 0x31 then + header:add_le(udp_size, buffer(4, 4)) + header:add_le(udp_unknown,buffer(8, 4)) + header:add_le(udp_tid, buffer(12, 4)) + header:add_le(udp_checksum, buffer(16, 4)) elseif header_data.class == 0x20 then header:add_le(udp_connection_id, buffer(4, 4)) header:add_le(udp_unknown, buffer(8, 4)) @@ -674,6 +682,9 @@ function bc_protocol.dissector(buffer, pinfo, tree) local subtree = tree:add(bc_protocol, decryped_tvb, "UDP Message Data") Dissector.get("xml"):call(decryped_tvb, pinfo, subtree) pinfo.cols.protocol = bc_protocol.name .. " UDP Heartbeat" + elseif udp_header.class == 0x31 then + pinfo.cols.protocol = bc_protocol.name .. " UDP Relay" + elseif udp_header.class == 0x20 then pinfo.cols.protocol = bc_protocol.name .. " UDP ACK" else @@ -713,12 +724,49 @@ function bc_protocol.dissector(buffer, pinfo, tree) end end -DissectorTable.get("tcp.port"):add(9000, bc_protocol) -DissectorTable.get("tcp.port"):add(52941, bc_protocol) -- change to your own custom port +local function heuristic_checker_udp(buffer, pinfo, tree) + -- guard for length + print("UDP Heur") + length = buffer:len() + if length < 4 then return false end + print("LEN GOOD") + local potential_magic = buffer(0,4):le_uint() + print("MAGIC??? " .. string.format("%x", potential_magic)) + + if potential_magic ~= 0x2a87cf3a and + potential_magic ~= 0x2a87cf20 and + potential_magic ~= 0x2a87cf10 and + potential_magic ~= 0x2a87cf31 then + + return false + end + + print("YEP") + bc_protocol.dissector(buffer, pinfo, tree) + return true +end + +local function heuristic_checker_tcp(buffer, pinfo, tree) + -- guard for length + length = buffer:len() + if length < 4 then return false end + + local potential_magic = buffer(0,4):le_uint() + if potential_magic ~= 0xabcdef0 then return false end + + bc_protocol.dissector(buffer, pinfo, tree) + return true +end + +bc_protocol:register_heuristic("udp", heuristic_checker_udp) +bc_protocol:register_heuristic("tcp", heuristic_checker_tcp) + +-- DissectorTable.get("tcp.port"):add(9000, bc_protocol) +-- DissectorTable.get("tcp.port"):add(53959, bc_protocol) -- change to your own custom port + +-- DissectorTable.get("udp.port"):add(2000, bc_protocol) +-- DissectorTable.get("udp.port"):add(2015, bc_protocol) +-- DissectorTable.get("udp.port"):add(2018, bc_protocol) +-- DissectorTable.get("udp.port"):add(2000, bc_protocol) +-- DissectorTable.get("udp.port"):add(9999, bc_protocol) -DissectorTable.get("udp.port"):add(23534, bc_protocol) -- change to your own custom port -DissectorTable.get("udp.port"):add(29237, bc_protocol) -DissectorTable.get("udp.port"):add(39654, bc_protocol) -DissectorTable.get("udp.port"):add(28100, bc_protocol) -DissectorTable.get("udp.port"):add(13154, bc_protocol) -DissectorTable.get("udp.port"):add(2015, bc_protocol) From 33a227420a980fca545d48a716a86e39ce63b3c6 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 21 Aug 2021 09:47:25 +0700 Subject: [PATCH 25/56] Udp Layer rewrite Using a keep alive message Restructed udp into modules Using all interfaces broadcast address (ipv4) Using remote discovery if local fails --- crates/core/Cargo.toml | 2 + crates/core/src/bc/model.rs | 2 + crates/core/src/bc_protocol.rs | 27 +- .../connection/{udpconn.rs => _udpconn.rs} | 463 ++++++++-------- .../core/src/bc_protocol/connection/bcconn.rs | 25 +- .../connection/udpconn/aborthandle.rs | 25 + .../connection/udpconn/discover.rs | 520 ++++++++++++++++++ .../src/bc_protocol/connection/udpconn/mod.rs | 326 +++++++++++ .../connection/udpconn/transmit.rs | 222 ++++++++ crates/core/src/bc_protocol/ping.rs | 38 +- crates/core/src/bcmedia/de.rs | 5 +- crates/core/src/bcudp/de.rs | 12 +- crates/core/src/bcudp/model.rs | 4 +- dissector/baichuan.lua | 11 +- dissector/udp.md | 41 +- 15 files changed, 1467 insertions(+), 256 deletions(-) rename crates/core/src/bc_protocol/connection/{udpconn.rs => _udpconn.rs} (69%) create mode 100644 crates/core/src/bc_protocol/connection/udpconn/aborthandle.rs create mode 100644 crates/core/src/bc_protocol/connection/udpconn/discover.rs create mode 100644 crates/core/src/bc_protocol/connection/udpconn/mod.rs create mode 100644 crates/core/src/bc_protocol/connection/udpconn/transmit.rs diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 83db767..5c70db6 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -21,6 +21,8 @@ yaserde_derive = "0.3.16" xml-rs = "0.8" rand = "0.8.4" regex = "1.5.4" +crossbeam-channel = "0.5.1" +get_if_addrs = "0.5.3" [dev-dependencies] assert_matches = "1.5.0" diff --git a/crates/core/src/bc/model.rs b/crates/core/src/bc/model.rs index e4f1215..b71bd3b 100644 --- a/crates/core/src/bc/model.rs +++ b/crates/core/src/bc/model.rs @@ -32,6 +32,8 @@ pub const MSG_ID_TALK: u32 = 202; pub const MSG_ID_GET_LED_STATUS: u32 = 208; /// Setting the LED status is done with this ID pub const MSG_ID_SET_LED_STATUS: u32 = 209; +/// UDP Keep alive +pub const MSG_ID_UDP_KEEP_ALIVE: u32 = 234; /// An empty password in legacy format pub const EMPTY_LEGACY_PASSWORD: &str = diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index fffe0bb..dfdc604 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -19,6 +19,7 @@ mod time; mod version; use super::RX_TIMEOUT; +use bc::model::*; pub(crate) use connection::*; pub use errors::Error; pub use ledstate::LightState; @@ -63,6 +64,7 @@ impl Credentials { impl Drop for BcCamera { fn drop(&mut self) { + debug!("Dropping camera"); self.disconnect(); } } @@ -98,6 +100,7 @@ impl BcCamera { BcSource::new_udp(&uid, RX_TIMEOUT)? } }; + let conn = match BcConnection::new(source) { Ok(conn) => conn, Err(err) => match err { @@ -110,13 +113,33 @@ impl BcCamera { }; debug!("Success"); - return Ok(Self { + let me = Self { connection: Some(conn), message_num: AtomicU16::new(0), channel_id, logged_in: false, credentials: None, - }); + }; + + if let Some(conn) = &me.connection { + let keep_alive_msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_UDP_KEEP_ALIVE, + channel_id: me.channel_id, + msg_num: me.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + conn.set_keep_alive_msg(keep_alive_msg); + } + + return Ok(me); } Err(Error::Timeout) diff --git a/crates/core/src/bc_protocol/connection/udpconn.rs b/crates/core/src/bc_protocol/connection/_udpconn.rs similarity index 69% rename from crates/core/src/bc_protocol/connection/udpconn.rs rename to crates/core/src/bc_protocol/connection/_udpconn.rs index 736ad9e..8f3db4e 100644 --- a/crates/core/src/bc_protocol/connection/udpconn.rs +++ b/crates/core/src/bc_protocol/connection/_udpconn.rs @@ -4,6 +4,9 @@ use crate::bc::model::*; use crate::bcudp; use crate::bcudp::{model::*, xml::*}; use crate::RX_TIMEOUT; +use crossbeam_channel::{ + unbounded, Receiver, RecvError, RecvTimeoutError, SendError, SendTimeoutError, Sender, +}; use lazy_static::lazy_static; use log::*; use rand::{seq::SliceRandom, thread_rng, Rng}; @@ -16,7 +19,6 @@ use std::io::{BufRead, Error as IoError, Read, Write}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket}; use std::sync::{ atomic::{AtomicBool, AtomicU32, Ordering}, - mpsc::{channel, Receiver, Sender}, Arc, Mutex, }; use std::thread::JoinHandle; @@ -51,11 +53,12 @@ pub struct UdpSource { client_id: i32, camera_id: i32, mtu: u32, - outgoing: Arc>>, - incoming: Arc>>, + + camera_acknowledged: Arc, + client_sent: Arc, + client_wants: Arc, + unacknowledged: Arc>>>, aborter: AbortHandle, - next_to_consume: Arc, - next_send_message: Arc, // Buffered because a single read might not read a whole packet read_buffer: Buffered, write_buffer: Buffered, @@ -67,12 +70,6 @@ struct Buffered { consumed: usize, } -#[derive(Debug)] -struct QueuedMessage { - buf: Vec, - time_last_tried: Option, -} - struct DiscoveryResult { socket: UdpSocket, address: SocketAddr, @@ -103,7 +100,7 @@ impl AbortHandle { } impl UdpSource { - fn get_socket(timeout: Duration) -> Result { + fn get_socket(_timeout: Duration) -> Result { // Select a random port to bind to let mut ports: Vec = (53500..54000).into_iter().collect(); let mut rng = thread_rng(); @@ -116,6 +113,7 @@ impl UdpSource { let socket = UdpSocket::bind(&addrs[..])?; socket.set_read_timeout(Some(timeout))?; socket.set_write_timeout(Some(timeout))?; + // socket.set_nonblocking(true)?; socket.set_broadcast(true)?; Ok(socket) } @@ -276,6 +274,7 @@ impl UdpSource { let mtu = MTU; for p2p_relay in P2P_RELAY_HOSTNAMES.iter() { + debug!("Trying register: {}", p2p_relay); let msg = BcUdp::Discovery(UdpDiscovery { tid, payload: UdpXml { @@ -300,6 +299,18 @@ impl UdpSource { let mut buf = vec![0; mtu as usize]; if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { match BcUdp::deserialize(&buf[0..bytes_read]) { + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + m2c_q_r: Some(m2c_q_r), + .. + }, + })) if m2c_q_r.reg.port == 0 || m2c_q_r.reg.ip.is_empty() => { + // This register is empty + abort.abort(); + break; + } Ok(BcUdp::Discovery(UdpDiscovery { tid: _, payload: @@ -321,10 +332,11 @@ impl UdpSource { } else { abort.abort(); // This p2p server didn't have the data we need try another - continue; + break; } } } + debug!("All registers tried"); Err(Error::ConnectionUnavaliable) } @@ -344,10 +356,12 @@ impl UdpSource { let m2c_q_r = Self::get_register(uid, socket, timeout, tid)?; + debug!("Got this information from the register: {:?}", m2c_q_r); + let register_address = m2c_q_r.reg; let relay_address = m2c_q_r.relay; let log_address = m2c_q_r.log; - let device_address = m2c_q_r.t; + // let device_address = m2c_q_r.t; debug!("Register address found: {:?}", register_address); debug!("Registering this address: {:?}", local_addr); @@ -549,18 +563,17 @@ impl UdpSource { msg.serialize(&mut buf)?; // Just let this retry to max limit as we don't get a reply - let (amount_sent, _) = Self::retrying_send_to( - socket, - &buf[..], - format!("{}:{}", device_address.ip, device_address.port), - )?; + let (amount_sent, _) = + Self::retrying_send_to(socket, &buf[..], format!("{}:{}", dev_loc.ip, dev_loc.port))?; assert_eq!(amount_sent, buf.len()); - let camera_address: SocketAddr = format!("{}:{}", device_address.ip, device_address.port) + let camera_address: SocketAddr = format!("{}:{}", dev_loc.ip, dev_loc.port) .to_socket_addrs()? .next() .ok_or(Error::ConnectionUnavaliable)?; + socket.connect(camera_address)?; + Ok(DiscoveryResult { socket: socket.try_clone()?, address: camera_address, @@ -597,29 +610,33 @@ impl UdpSource { } pub fn new(uid: &str, timeout: Duration) -> Result { - Self::new_with_remote(uid, timeout, false) + Self::new_with_remote(uid, timeout, true) } fn new_with_remote(uid: &str, timeout: Duration, allow_remote: bool) -> Result { let discovery_result = Self::discover_from_uuid(uid, timeout, allow_remote)?; info!("UID {:?} found at {:?}", uid, discovery_result.address); + let (to_outgoing, outgoing) = unbounded(); + let (incoming, from_incoming) = unbounded(); let me = UdpSource { socket: discovery_result.socket, address: discovery_result.address, client_id: discovery_result.client_id, camera_id: discovery_result.camera_id, mtu: discovery_result.mtu, - incoming: Default::default(), - outgoing: Default::default(), + incoming: from_incoming, + outgoing: to_outgoing, + camera_acknowledged: Default::default(), + unacknowledged: Default::default(), + client_sent: Default::default(), + client_wants: Default::default(), aborter: AbortHandle::new(), - next_to_consume: Arc::new(AtomicU32::new(0)), - next_send_message: Arc::new(AtomicU32::new(0)), read_buffer: Default::default(), write_buffer: Default::default(), }; - me.start_polling()?; + me.start_polling(outgoing, incoming)?; Ok(me) } @@ -634,174 +651,141 @@ impl UdpSource { incoming: self.incoming.clone(), outgoing: self.outgoing.clone(), aborter: self.aborter.clone(), - next_to_consume: self.next_to_consume.clone(), - next_send_message: self.next_send_message.clone(), + camera_acknowledged: self.camera_acknowledged.clone(), + unacknowledged: self.unacknowledged.clone(), + client_sent: self.client_sent.clone(), + client_wants: self.client_wants.clone(), // These are not shared mutable so they don't pollute each other buffer - read_buffer: self.read_buffer.clone(), - write_buffer: self.write_buffer.clone(), + read_buffer: Default::default(), + write_buffer: Default::default(), }) } - fn start_polling(&self) -> IoResult<()> { - self.start_polling_recv()?; - self.start_polling_send()?; + fn start_polling( + &self, + outgoing: Receiver>, + incoming: Sender>, + ) -> IoResult<()> { Ok(()) } - fn handle_ack( - next_to_consume: u32, - camera_id: i32, - incoming: &mut HashMap, - socket: &UdpSocket, - ) { - // Send an acknoledge. - // we want the next packet that's missing after the - // last consumed packet. - let mut next_packet = next_to_consume; - loop { - if incoming.get(&next_packet).is_none() { - break; - } else { - next_packet += 1; - } - } - if next_packet > 0 { - let last_received_contigous_packet = next_packet - 1; - let ack_msg = BcUdp::Ack(UdpAck { - connection_id: camera_id, - packet_id: last_received_contigous_packet, - }); - debug!("Re ack packet: {}", last_received_contigous_packet); - let mut ack_buf = vec![]; - if ack_msg.serialize(&mut ack_buf).is_ok() { - if let Ok(amount_sent) = socket.send(&ack_buf[..]) { - assert_eq!(amount_sent, ack_buf.len()); - } else { - error!("Unable to send acknoledgement"); - } - } else { - error!("Unable to serialize acknoledgement"); - } - } - } - - fn start_polling_recv(&self) -> IoResult<()> { - let thread_aborter = self.aborter.clone(); - let thread_incoming = self.incoming.clone(); - let thread_outgoing = self.outgoing.clone(); + fn start_polling_outgoing(&self, outgoing: Receiver>) -> IoResult<()> { let thread_socket = self.socket.try_clone()?; - let thread_mtu = self.mtu; - let thread_client_id = self.client_id; + let thread_aborter = self.aborter.clone(); let thread_camera_id = self.camera_id; - let thread_next_consumed = self.next_to_consume.clone(); + let thread_client_sent = self.client_sent.clone(); std::thread::spawn(move || { while !thread_aborter.is_aborted() { - debug!("Poll UDP Read"); - // Reciving - let mut read_buf = vec![0_u8; thread_mtu as usize]; - if let Ok(bytes_read) = thread_socket.recv(&mut read_buf[..]) { - match BcUdp::deserialize(&read_buf[0..bytes_read]) { - Ok(BcUdp::Discovery(UdpDiscovery { - payload: - UdpXml { - d2c_disc: Some(D2cDisc { cid, did }), - .. - }, - .. - })) if cid == thread_client_id && did == thread_camera_id => { + match outgoing.recv_timeout(RX_TIMEOUT) { + Ok(msg) => { + let packet_id = thread_client_sent.fetch_add(1, Ordering::Relaxed); + let bcudp_msg = BcUdp::Data(UdpData { + connection_id: thread_camera_id, + packet_id, + payload: msg, + }); + + let mut buf = vec![]; + if let Err(e) = bcudp_msg.serialize(&mut buf) { + error!("Failed to serialize bcudp: {:?}, Err: {:?}", bcudp_msg, e); thread_aborter.abort(); - debug!("Client requested disconnect") + break; } - Ok(BcUdp::Discovery(packet)) => { - warn!("Got unexpected discovery packet: {:?}", packet) - } - Ok(BcUdp::Ack(UdpAck { - connection_id: cid, - packet_id, - })) if cid == thread_client_id => { - // Camera got our message remove older ones from the send queue - debug!("Got acknoledgment of {}", packet_id); - thread_outgoing - .lock() - .unwrap() - .retain(|&k, _| k > packet_id); - // Queue for resend now - thread_outgoing - .lock() - .unwrap() - .iter_mut() - .for_each(|(_, v)| v.time_last_tried = None); - Self::handle_ack( - thread_next_consumed.load(Ordering::Relaxed), - thread_camera_id, - &mut *thread_incoming.lock().unwrap(), - &thread_socket, - ); + if let Err(e) = thread_socket.send(&buf) { + error!("Failed to send udp data: {:?}, Err: {:?}", bcudp_msg, e); + thread_aborter.abort(); + break; } - Ok(BcUdp::Data(UdpData { - connection_id: cid, - packet_id, - payload, - })) if cid == thread_client_id => { - // Got some data add it to our buffer - let consumed_packet = thread_next_consumed.load(Ordering::Relaxed); - if packet_id >= consumed_packet { - debug!("Reciving UDP data packet with ID: {}", packet_id); - thread_incoming.lock().unwrap().insert( - packet_id, - QueuedMessage { - buf: payload, - time_last_tried: None, - }, - ); - - Self::handle_ack( - thread_next_consumed.load(Ordering::Relaxed), - thread_camera_id, - &mut *thread_incoming.lock().unwrap(), - &thread_socket, - ); - } - } - Ok(bcudp) => warn!("Unexpected bcudp received {:?}", bcudp), - Err(e) => error!("Unable to poll from udp socket {:?}", e), + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => { + break; } } } }); - Ok(()) } - fn start_polling_send(&self) -> IoResult<()> { - let thread_aborter = self.aborter.clone(); - let thread_outgoing = self.outgoing.clone(); + fn start_polling_ack(&self) -> IoResult<()> { let thread_socket = self.socket.try_clone()?; + let thread_aborter = self.aborter.clone(); + let thread_unacknowledged = self.unacknowledged.clone(); + std::thread::spawn(move || while !thread_aborter.is_aborted() {}); + Ok(()) + } + + fn start_polling_incoming(&self, incoming: Sender>) -> IoResult<()> { + let mut thread_socket = self.socket.try_clone()?; + let thread_aborter = self.aborter.clone(); + let thread_mtu = self.mtu; + let thread_camera_acknowledged = self.camera_acknowledged.clone(); + let thread_client_wants = self.client_wants.clone(); + let thread_client_id = self.client_id; + let thread_camera_id = self.camera_id; std::thread::spawn(move || { while !thread_aborter.is_aborted() { - // debug!("Poll UDP Send"); - let now = OffsetDateTime::now_utc(); - for (packet_id, message) in thread_outgoing.lock().unwrap().iter_mut() { - let mut should_send = false; - if let Some(&time_last_tried) = message.time_last_tried.as_ref() { - if (now - time_last_tried) >= WAIT_TIME { - should_send = true; + let mut buf = vec![0; thread_mtu as usize]; + if let Ok(new_size) = thread_socket.recv(&mut buf) { + match BcUdp::deserialize(&buf[0..new_size]) { + Ok(bcudp_msg) => { + match bcudp_msg { + BcUdp::Discovery(UdpDiscovery { + payload: + UdpXml { + d2c_disc: Some(D2cDisc { cid, did }), + .. + }, + .. + }) if cid == thread_client_id && did == thread_camera_id => { + thread_aborter.abort(); + debug!("Client requested disconnect") + } + BcUdp::Discovery(packet) => { + debug!("Got unexpected discovery packet: {:?}", packet) + } + BcUdp::Ack(UdpAck { + connection_id, + packet_id, + }) if connection_id == thread_client_id => { + thread_camera_acknowledged + .fetch_max(packet_id, Ordering::Acquire); + } + BcUdp::Data(UdpData { + connection_id: cid, + packet_id, + payload, + }) if cid == thread_client_id => { + if let Ok(_) = thread_client_wants.fetch_update( + Ordering::SeqCst, + Ordering::SeqCst, + |v| { + if v == packet_id { + Some(v + 1) + } else { + None + } + }, + ) { + match incoming.send(payload) { + Ok(msg) => {} + Err(_) => { + error!("Failed to get payload from UDP"); + thread_aborter.abort(); + break; + } + } + } + } + }; } - } else { - should_send = true; - } - if should_send { - debug!( - "Sending message ID {} with payload len {}", - packet_id, - message.buf.len() - ); - message.time_last_tried = Some(now); - if let Err(e) = thread_socket.send(&message.buf[..]) { - error!("Failed to send message on udp: {:?}", e); + Err(e) => { + error!("Cannot deser UDP msg: {:?}", e); + thread_aborter.abort(); + break; } } } @@ -851,35 +835,34 @@ impl Read for UdpSource { impl BufRead for UdpSource { fn fill_buf(&mut self) -> IoResult<&[u8]> { - const CLEAR_CONSUMED_AT: usize = 1024; - // This is a trade off between caching too much dead memory - // and calling the drain method too often - if self.read_buffer.consumed > CLEAR_CONSUMED_AT { - let _ = self - .read_buffer - .buffer - .drain(0..self.read_buffer.consumed) - .collect::>(); - self.read_buffer.consumed = 0; - } - if self.read_buffer.buffer.len() <= self.read_buffer.consumed { - // Get next packet of the read queue - let start_time = OffsetDateTime::now_utc(); - while (start_time - OffsetDateTime::now_utc()) < RX_TIMEOUT { - if let Some(msg) = self - .incoming - .lock() - .unwrap() - .remove(&self.next_to_consume.load(Ordering::Relaxed)) - { - self.next_to_consume.fetch_add(1, Ordering::Relaxed); - self.read_buffer.buffer.extend(msg.buf); - break; - } - } - } - - Ok(&self.read_buffer.buffer.as_slice()[self.read_buffer.consumed..]) + // const CLEAR_CONSUMED_AT: usize = 1024; + // // This is a trade off between caching too much dead memory + // // and calling the drain method too often + // if self.read_buffer.consumed > CLEAR_CONSUMED_AT { + // let _ = self + // .read_buffer + // .buffer + // .drain(0..self.read_buffer.consumed) + // .collect::>(); + // self.read_buffer.consumed = 0; + // } + // if self.read_buffer.buffer.len() <= self.read_buffer.consumed { + // // Get next packet of the read queue + // let start_time = OffsetDateTime::now_utc(); + // while (start_time - OffsetDateTime::now_utc()) < RX_TIMEOUT { + // let mut lock = self.incoming.lock().unwrap(); + // if (*lock).contains_key(&self.next_to_consume.load(Ordering::Relaxed)) { + // let next = self.next_to_consume.fetch_add(1, Ordering::Relaxed); + // debug!("Removing: {}", next); + // if let Some(msg) = lock.remove(&next) { + // self.read_buffer.buffer.extend(msg.buf); + // break; + // } + // } + // } + // } + // + // Ok(&self.read_buffer.buffer.as_slice()[self.read_buffer.consumed..]) } fn consume(&mut self, amt: usize) { @@ -891,53 +874,53 @@ impl BufRead for UdpSource { const UDPDATA_HEADER_SIZE: usize = 20; impl Write for UdpSource { fn write(&mut self, buf: &[u8]) -> IoResult { - if self.aborter.is_aborted() { - return Err(IoError::new( - std::io::ErrorKind::ConnectionAborted, - "Connection dropped", - )); - } - self.write_buffer.buffer.extend(buf.to_vec()); - if self.write_buffer.buffer.len() > self.mtu as usize - UDPDATA_HEADER_SIZE { - let _ = self.flush(); - } - Ok(buf.len()) + // if self.aborter.is_aborted() { + // return Err(IoError::new( + // std::io::ErrorKind::ConnectionAborted, + // "Connection dropped", + // )); + // } + // self.write_buffer.buffer.extend(buf.to_vec()); + // if self.write_buffer.buffer.len() > self.mtu as usize - UDPDATA_HEADER_SIZE { + // let _ = self.flush(); + // } + // Ok(buf.len()) } fn flush(&mut self) -> IoResult<()> { - if self.aborter.is_aborted() { - return Err(IoError::new( - std::io::ErrorKind::ConnectionAborted, - "Connection dropped", - )); - } - for chunk in self - .write_buffer - .buffer - .chunks(self.mtu as usize - UDPDATA_HEADER_SIZE) - { - let packet_id = self.next_send_message.fetch_add(1, Ordering::Relaxed); - let msg = BcUdp::Data(UdpData { - connection_id: self.camera_id, - packet_id, - payload: chunk.to_vec(), - }); - let mut buf = vec![]; - // If this errors it is unrecoverable - // - // It really shouldn't be able to Err though - msg.serialize(&mut buf) - .expect("Failed to serialize UDP Data"); - debug!("Writing"); - self.outgoing.lock().unwrap().insert( - packet_id, - QueuedMessage { - time_last_tried: None, - buf, - }, - ); - } - self.write_buffer.buffer.clear(); - Ok(()) + // if self.aborter.is_aborted() { + // return Err(IoError::new( + // std::io::ErrorKind::ConnectionAborted, + // "Connection dropped", + // )); + // } + // for chunk in self + // .write_buffer + // .buffer + // .chunks(self.mtu as usize - UDPDATA_HEADER_SIZE) + // { + // let packet_id = self.next_send_message.fetch_add(1, Ordering::Relaxed); + // let msg = BcUdp::Data(UdpData { + // connection_id: self.camera_id, + // packet_id, + // payload: chunk.to_vec(), + // }); + // let mut buf = vec![]; + // // If this errors it is unrecoverable + // // + // // It really shouldn't be able to Err though + // msg.serialize(&mut buf) + // .expect("Failed to serialize UDP Data"); + // debug!("Writing"); + // self.outgoing.lock().unwrap().insert( + // packet_id, + // QueuedMessage { + // time_last_tried: None, + // buf, + // }, + // ); + // } + // self.write_buffer.buffer.clear(); + // Ok(()) } } diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index f1c787c..4f606f2 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -26,6 +26,7 @@ pub struct BcConnection { // and connection for deserialisation and serialistion respectivly encryption_protocol: Arc>, poll_abort: Arc, + keep_alive_msg: Arc>>, } impl BcConnection { @@ -38,8 +39,11 @@ impl BcConnection { let connections_encryption_protocol = encryption_protocol.clone(); let poll_abort = Arc::new(AtomicBool::new(false)); let poll_abort_rx = poll_abort.clone(); - let conn = source.try_clone()?; + let mut conn = source.try_clone()?; + let keep_alive_msg: Arc>> = Arc::new(Mutex::new(None)); + let connections_keep_alive_msg = keep_alive_msg.clone(); let rx_thread = std::thread::spawn(move || { + let keep_alive_encryption_protocol = connections_encryption_protocol.clone(); let mut context = BcContext::new(connections_encryption_protocol); let mut result; loop { @@ -56,6 +60,14 @@ impl BcConnection { } break; } + // Send a udp keep alive if set + if let Ok(lock) = connections_keep_alive_msg.try_lock() { + if let Some(keep_alive_msg) = lock.as_ref() { + let _ = keep_alive_msg + .serialize(&conn, &keep_alive_encryption_protocol.lock().unwrap()); + let _ = conn.flush(); + } + } } }); @@ -65,6 +77,7 @@ impl BcConnection { rx_thread: Some(rx_thread), encryption_protocol, poll_abort, + keep_alive_msg, }) } @@ -92,6 +105,10 @@ impl BcConnection { Ok(()) } + pub fn set_keep_alive_msg(&self, msg: Bc) { + *self.keep_alive_msg.lock().unwrap() = Some(msg); + } + pub fn set_encrypted(&self, value: EncryptionProtocol) { *(self.encryption_protocol.lock().unwrap()) = value; } @@ -124,8 +141,10 @@ impl BcConnection { } } Entry::Vacant(_) => { - debug!("Ignoring uninteresting message ID {}", msg_id); - trace!("Contents: {:?}", response); + if msg_id != MSG_ID_UDP_KEEP_ALIVE { + debug!("Ignoring uninteresting message ID {}", msg_id); + trace!("Contents: {:?}", response); + } } } diff --git a/crates/core/src/bc_protocol/connection/udpconn/aborthandle.rs b/crates/core/src/bc_protocol/connection/udpconn/aborthandle.rs new file mode 100644 index 0000000..989405e --- /dev/null +++ b/crates/core/src/bc_protocol/connection/udpconn/aborthandle.rs @@ -0,0 +1,25 @@ +use std::sync::{ + atomic::{AtomicBool, Ordering}, + Arc, +}; + +#[derive(Clone)] +pub struct AbortHandle { + aborted: Arc, +} + +impl AbortHandle { + pub fn new() -> Self { + Self { + aborted: Arc::new(AtomicBool::new(false)), + } + } + + pub fn abort(&self) { + self.aborted.store(true, Ordering::Relaxed); + } + + pub fn is_aborted(&self) -> bool { + self.aborted.load(Ordering::Relaxed) + } +} diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs new file mode 100644 index 0000000..8e259a4 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -0,0 +1,520 @@ +use super::{aborthandle::AbortHandle, Error, Result, MTU, P2P_RELAY_HOSTNAMES, WAIT_TIME}; +use crate::bcudp::{model::*, xml::*}; +use log::*; +use rand::{seq::SliceRandom, thread_rng, Rng}; +use std::io::{Error as IoError, ErrorKind, Result as IoResult}; +use std::net::{Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket}; +use std::time::Duration; +use time::OffsetDateTime; + +pub struct UdpDiscover { + pub client_id: i32, + pub camera_id: i32, + pub mtu: u32, + pub address: SocketAddr, +} + +impl UdpDiscover { + fn retrying_send_to( + socket: &UdpSocket, + buf: &[u8], + addr: T, + ) -> IoResult<(usize, AbortHandle)> { + let addr = addr + .to_socket_addrs()? + .next() + .ok_or_else(|| IoError::new(ErrorKind::NotFound, Error::ConnectionUnavaliable))?; + Self::retrying_send_to_multi(socket, buf, &[addr]) + } + + fn retrying_send_to_multi( + socket: &UdpSocket, + buf: &[u8], + addrs: &[T], + ) -> IoResult<(usize, AbortHandle)> { + let handle = AbortHandle::new(); + + let addrs: Vec = addrs + .iter() + .map(|a| { + a.to_socket_addrs() + .ok() + .and_then(|mut a_iter| a_iter.next()) + }) + .flatten() + .collect(); + + let mut bytes_send = 0; + for addr in addrs.iter() { + bytes_send = socket.send_to(buf, &addr)?; + } + + let thread_buffer = buf.to_vec(); + let thread_handle = handle.clone(); + let thread_socket = socket.try_clone()?; + let thread_addr: Vec = addrs; + + const MAX_RETRIES: usize = 10; + + std::thread::spawn(move || { + std::thread::sleep(WAIT_TIME); + for _ in 0..MAX_RETRIES { + if thread_handle.is_aborted() { + break; + } + for addr in thread_addr.iter() { + let _ = thread_socket.send_to(&thread_buffer[..], &addr); + } + std::thread::sleep(WAIT_TIME); + } + }); + + Ok((bytes_send, handle)) + } + + fn discover_from_uuid_local(socket: &UdpSocket, uid: &str, timeout: Duration) -> Result { + let mut rng = thread_rng(); + // If tid is too large it will overflow during encrypt so we just use a random u8 + let tid: u32 = (rng.gen::()) as u32; + let client_id: i32 = rng.gen(); + let local_addr = socket.local_addr()?; + let port = local_addr.port(); + + let mtu = MTU; + + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_c: Some(C2dC { + uid: uid.to_string(), + cli: ClientList { port: port as u32 }, + cid: client_id, + mtu, + debug: false, + os: "MAC".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let mut broadcasts = vec![Ipv4Addr::BROADCAST]; + for iface in get_if_addrs::get_if_addrs()?.iter() { + if let get_if_addrs::IfAddr::V4(ifacev4) = &iface.addr { + if let Some(broadcast) = ifacev4.broadcast.as_ref() { + broadcasts.push(*broadcast); + } + } + } + let ports: [u16; 2] = [2015, 2018]; + let destinations: Vec<(Ipv4Addr, u16)> = broadcasts + .iter() + .map(|&addr| { + ports + .iter() + .map(|&port| (addr, port)) + .collect::>() + }) + .flatten() + .collect(); + debug!("Broadcasting to: {:?}", destinations); + + let (amount_sent, abort) = Self::retrying_send_to_multi(socket, &buf[..], &destinations)?; + assert_eq!(amount_sent, buf.len()); + + let start_time = OffsetDateTime::now_utc(); + let camera_address; + let camera_id; + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, socket_addr)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_c_r: Some(D2cCr { did, cid, .. }), + .. + }, + })) if cid == client_id => { + abort.abort(); + camera_address = socket_addr; + camera_id = did; + break; + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + return Err(Error::Timeout); + } + } + + // Ensure we didn't forget to abort the sending + abort.abort(); + // Actual connection time! + socket.connect(camera_address)?; + + Ok(UdpDiscover { + address: camera_address, + client_id, + camera_id, + mtu, + }) + } + + fn get_register( + uid: &str, + socket: &UdpSocket, + timeout: Duration, + tid: u32, + // client_id: u32, + ) -> Result { + // let local_addr = socket.local_addr()?; + // let local_port = local_addr.port(); + + let mtu = MTU; + + for p2p_relay in P2P_RELAY_HOSTNAMES.iter() { + debug!("Trying register: {}", p2p_relay); + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2m_q: Some(C2mQ { + uid: uid.to_string(), + os: "MAC".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = + Self::retrying_send_to(socket, &buf[..], format!("{}:9999", p2p_relay))?; + assert_eq!(amount_sent, buf.len()); + + let start_time = OffsetDateTime::now_utc(); + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + m2c_q_r: Some(m2c_q_r), + .. + }, + })) if m2c_q_r.reg.port == 0 || m2c_q_r.reg.ip.is_empty() => { + // This register is empty + abort.abort(); + break; + } + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + m2c_q_r: Some(m2c_q_r), + .. + }, + })) => { + abort.abort(); + return Ok(m2c_q_r); + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + // This p2p server didn't have the data we need try another + break; + } + } + } + debug!("All registers tried"); + Err(Error::ConnectionUnavaliable) + } + + fn discover_from_uuid_remote( + socket: &UdpSocket, + uid: &str, + timeout: Duration, + ) -> Result { + let local_addr = socket.local_addr()?; + let local_port = local_addr.port(); + + let mut rng = thread_rng(); + // If tid is too large it will overflow during encrypt so we just use a random u8 + let tid: u32 = (rng.gen::()) as u32; + let mtu = MTU; + let client_id: i32 = rng.gen(); + + let m2c_q_r = Self::get_register(uid, socket, timeout, tid)?; + + debug!("Got this information from the register: {:?}", m2c_q_r); + + let register_address = m2c_q_r.reg; + let relay_address = m2c_q_r.relay; + let log_address = m2c_q_r.log; + // let device_address = m2c_q_r.t; + + debug!("Register address found: {:?}", register_address); + debug!("Registering this address: {:?}", local_addr); + + let local_family = if local_addr.ip().is_ipv4() { 4 } else { 6 }; + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2r_c: Some(C2rC { + uid: uid.to_string(), + cli: IpPort { + ip: "10.251.254.10".to_string(), + port: local_port, + }, + relay: relay_address, + cid: client_id, + family: local_family, + debug: false, + os: "MAC".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = Self::retrying_send_to( + socket, + &buf[..], + format!("{}:{}", register_address.ip, register_address.port), + )?; + assert_eq!(amount_sent, buf.len()); + + let device_sid; + let dev_loc; + let start_time = OffsetDateTime::now_utc(); + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + // Got camera data from register + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + r2c_t: Some(R2cT { dev, cid, sid, .. }), + .. + }, + })) if cid == client_id && !dev.ip.is_empty() && dev.port > 0 => { + abort.abort(); + // Make a local request to the camera with the dev info + device_sid = sid; + dev_loc = dev; + break; + } + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + r2c_t: Some(R2cT { cid, .. }), + .. + }, + })) if cid == client_id => { + // Got a reply but the ip/port was empty please wait + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + return Err(Error::Timeout); + } + } + + debug!("Register revealed address as SID: {:?}", device_sid); + debug!("Register revealed address as IP: {:?}", dev_loc); + + // ensure abort + abort.abort(); + + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_t: Some(C2dT { + sid: device_sid, + cid: client_id, + mtu, + conn: "local".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + let (amount_sent, abort) = + Self::retrying_send_to(socket, &buf[..], format!("{}:{}", dev_loc.ip, dev_loc.port))?; + assert_eq!(amount_sent, buf.len()); + + let device_id; + let start_time = OffsetDateTime::now_utc(); + loop { + if (OffsetDateTime::now_utc() - start_time) <= timeout { + let mut buf = vec![0; mtu as usize]; + if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { + match BcUdp::deserialize(&buf[0..bytes_read]) { + // Got camera data from camera + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_t: Some(D2cT { cid, did, .. }), + .. + }, + })) if cid == client_id => { + device_id = did; + break; + } + // Got camera data from camera CFM + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_cfm: Some(D2cCfm { cid, did, .. }), + .. + }, + })) if cid == client_id => { + device_id = did; + break; + } + // Got camera data from camera disc + Ok(BcUdp::Discovery(UdpDiscovery { + tid: _, + payload: + UdpXml { + d2c_disc: Some(D2cDisc { cid, did, .. }), + .. + }, + })) if cid == client_id => { + device_id = did; + break; + } + Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), + Err(_) => debug!( + "Udp Discovery got this unexpected binary: {:?}", + &buf[0..bytes_read] + ), + } + } + } else { + abort.abort(); + return Err(Error::Timeout); + } + } + + debug!("Got device ID as: {:?}", device_id); + + // Ensure aborted + abort.abort(); + + // Announce to the log that we will connect locally + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2r_cfm: Some(C2rCfm { + sid: device_sid, + cid: client_id, + did: device_id, + conn: "local".to_string(), + rsp: 0, + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + // Just let this retry to max limit as we don't get a reply + let (amount_sent, _) = Self::retrying_send_to( + socket, + &buf[..], + format!("{}:{}", log_address.ip, log_address.port), + )?; + assert_eq!(amount_sent, buf.len()); + + // Announce a map type connection (I think this means we could connect remotely) + let msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_t: Some(C2dT { + sid: device_sid, + cid: client_id, + mtu, + conn: "map".to_string(), + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + msg.serialize(&mut buf)?; + + // Just let this retry to max limit as we don't get a reply + let (amount_sent, _) = + Self::retrying_send_to(socket, &buf[..], format!("{}:{}", dev_loc.ip, dev_loc.port))?; + assert_eq!(amount_sent, buf.len()); + + let camera_address: SocketAddr = format!("{}:{}", dev_loc.ip, dev_loc.port) + .to_socket_addrs()? + .next() + .ok_or(Error::ConnectionUnavaliable)?; + + socket.connect(camera_address)?; + + Ok(UdpDiscover { + address: camera_address, + client_id, + camera_id: device_id, + mtu, + }) + } + + pub fn discover_from_uuid( + socket: &UdpSocket, + uid: &str, + timeout: Duration, + allow_remote: bool, + ) -> Result { + match Self::discover_from_uuid_local(socket, uid, timeout) { + Err(Error::Timeout) if allow_remote => { + info!("Trying remote discovery against reolink servers"); + Self::discover_from_uuid_remote(socket, uid, timeout) + } + Ok(result) => Ok(result), + Err(e) => Err(e), + } + } +} diff --git a/crates/core/src/bc_protocol/connection/udpconn/mod.rs b/crates/core/src/bc_protocol/connection/udpconn/mod.rs new file mode 100644 index 0000000..f781cd7 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/udpconn/mod.rs @@ -0,0 +1,326 @@ +/// The module will handle a udp connection +/// +/// Because of the complexity it is seperated into modules +/// +/// discover module handles the initial handshake which discovers +/// the ip from the uid and reconnects +/// +/// transmit handles the sending and recieving of data through the socket +/// this includes the BcUdp wrapping and the acknoledgements +/// +use super::{Error, Result}; +use crossbeam_channel::{unbounded, Receiver, RecvTimeoutError, Sender}; +use lazy_static::lazy_static; +use log::*; +use rand::{seq::SliceRandom, thread_rng, Rng}; +use std::{ + io::{BufRead, Error as IoError, ErrorKind, Read, Result as IoResult, Write}, + net::{SocketAddr, UdpSocket}, + sync::Arc, + time::Duration, +}; +use time::OffsetDateTime; + +mod aborthandle; +mod discover; +mod transmit; + +use aborthandle::*; +use discover::*; +use transmit::*; + +// How long to set the socket wait +// This is kept short so as to not block the read and write parts +const SOCKET_WAIT_TIME: Duration = Duration::from_millis(50); +// How long to wait between retransmits when no reply is recieved +const WAIT_TIME: Duration = Duration::from_millis(500); +// The maximum data size including header +// +// TODO: Maybe use path mtu discovery (although reolinks seems to just use this constant) +const MTU: u32 = 1030; + +lazy_static! { + static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [ + "p2p.reolink.com", + "p2p1.reolink.com", + "p2p2.reolink.com", + "p2p3.reolink.com", + "p2p6.reolink.com", + "p2p7.reolink.com", + "p2p8.reolink.com", + "p2p9.reolink.com", + "p2p14.reolink.com", + "p2p15.reolink.com", + ]; +} + +pub struct UdpSource { + outgoing: Sender>, + incoming: Receiver>, + aborter: AbortHandle, + timeout: Duration, + mtu: u32, + + read_buffer: Buffered, + write_buffer: Buffered, +} + +impl UdpSource { + pub fn new(uid: &str, timeout: Duration) -> Result { + let (outgoing, from_outgoing) = unbounded(); + let (to_incoming, incoming) = unbounded(); + let aborter = AbortHandle::new(); + + Self::start_polling(uid, timeout, &aborter, to_incoming, from_outgoing)?; + + Ok(Self { + outgoing, + incoming, + aborter, + timeout, + mtu: MTU, + + read_buffer: Default::default(), + write_buffer: Default::default(), + }) + } + + fn start_polling( + uid: &str, + timeout: Duration, + aborter: &AbortHandle, + to_incoming: Sender>, + from_outgoing: Receiver>, + ) -> Result<()> { + let socket = Self::get_socket(SOCKET_WAIT_TIME)?; + let allow_remote = true; + let discovery_result = Arc::new(UdpDiscover::discover_from_uuid( + &socket, + uid, + timeout, + allow_remote, + )?); + socket.connect(discovery_result.address)?; + let transmit = Arc::new(UdpTransmit::new()); + + let thread_aborter = aborter.clone(); + let thread_transmit = transmit.clone(); + let thread_socket = socket.try_clone()?; + let thread_discovery_result = discovery_result.clone(); + + // Poll Read + std::thread::spawn(move || { + while !thread_aborter.is_aborted() { + if let Err(err) = thread_transmit.poll_read( + &thread_socket, + &(*thread_discovery_result), + &to_incoming, + ) { + if !thread_aborter.is_aborted() { + match err { + TransmitError::Disc => { + error!("Camera requested disconnect"); + thread_aborter.abort(); + } + e => { + error!("Error during Udp Transmit: {:?}", e); + thread_aborter.abort(); + } + } + } + } + } + error!("Udp read poll aborted"); + }); + + let thread_aborter = aborter.clone(); + let thread_socket = socket.try_clone()?; + let thread_transmit = transmit; + let thread_discovery_result = discovery_result; + + // Poll Write + std::thread::spawn(move || { + let mut outgoing_history = Default::default(); + while !thread_aborter.is_aborted() { + if let Err(err) = thread_transmit.poll_write( + &thread_socket, + &(*thread_discovery_result), + &from_outgoing, + &mut outgoing_history, + ) { + if !thread_aborter.is_aborted() { + match err { + TransmitError::Disc => { + error!("Camera requested disconnect"); + thread_aborter.abort(); + } + e => { + error!("Error during Udp Transmit: {:?}", e); + thread_aborter.abort(); + } + } + } + } + } + error!("Udp write poll aborted"); + }); + + Ok(()) + } + + pub fn try_clone(&self) -> IoResult { + Ok(Self { + outgoing: self.outgoing.clone(), + incoming: self.incoming.clone(), + aborter: self.aborter.clone(), + timeout: self.timeout, + mtu: self.mtu, + + // New buffer so they don't pollute each other + read_buffer: Default::default(), + write_buffer: Default::default(), + }) + } + + fn stop_polling(&self) { + self.aborter.abort(); + } + + fn get_socket(timeout: Duration) -> Result { + // Select a random port to bind to + let mut ports: Vec = (53500..54000).into_iter().collect(); + let mut rng = thread_rng(); + ports.shuffle(&mut rng); + + let addrs: Vec<_> = ports + .iter() + .map(|&port| SocketAddr::from(([0, 0, 0, 0], port))) + .collect(); + let socket = UdpSocket::bind(&addrs[..])?; + socket.set_read_timeout(Some(timeout))?; + socket.set_write_timeout(Some(timeout))?; + socket.set_nonblocking(false)?; + socket.set_broadcast(true)?; + Ok(socket) + } +} + +// Ensuring polling stops +impl Drop for UdpSource { + fn drop(&mut self) { + self.stop_polling(); + } +} + +#[derive(Default)] +struct Buffered { + buffer: Vec, + consumed: usize, +} + +impl Read for UdpSource { + fn read(&mut self, buf: &mut [u8]) -> IoResult { + if self.aborter.is_aborted() { + return Err(IoError::new( + ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } + let buffer = self.fill_buf()?; + let amt = std::cmp::min(buf.len(), buffer.len()); + + // First check if the amount of bytes we want to read is small: + // `copy_from_slice` will generally expand to a call to `memcpy`, and + // for a single byte the overhead is significant. + if amt == 1 { + buf[0] = buffer[0]; + } else { + buf[..amt].copy_from_slice(&buffer[..amt]); + } + + self.consume(amt); + + Ok(amt) + } +} + +impl BufRead for UdpSource { + fn fill_buf(&mut self) -> IoResult<&[u8]> { + const CLEAR_CONSUMED_AT: usize = 1024; + // This is a trade off between caching too much dead memory + // and calling the drain method too often + if self.read_buffer.consumed > CLEAR_CONSUMED_AT { + let _ = self + .read_buffer + .buffer + .drain(0..self.read_buffer.consumed) + .collect::>(); + self.read_buffer.consumed = 0; + } + if self.read_buffer.buffer.len() <= self.read_buffer.consumed { + // Get next packet of the read queue + match self.incoming.recv_timeout(self.timeout) { + Ok(buf) => self.read_buffer.buffer.extend(buf), + Err(RecvTimeoutError::Timeout) => { + return Err(IoError::new( + ErrorKind::UnexpectedEof, + "Connection timedout when reading from udp channel", + )); + } + Err(RecvTimeoutError::Disconnected) => { + return Err(IoError::new( + ErrorKind::UnexpectedEof, + "Connection dropped when reading from udp channel", + )); + } + } + } + + Ok(&self.read_buffer.buffer.as_slice()[self.read_buffer.consumed..]) + } + + fn consume(&mut self, amt: usize) { + assert!(self.read_buffer.consumed + amt <= self.read_buffer.buffer.len()); + self.read_buffer.consumed += amt; + } +} + +const UDPDATA_HEADER_SIZE: usize = 20; +impl Write for UdpSource { + fn write(&mut self, buf: &[u8]) -> IoResult { + if self.aborter.is_aborted() { + return Err(IoError::new( + std::io::ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } + self.write_buffer.buffer.extend(buf.to_vec()); + if self.write_buffer.buffer.len() > self.mtu as usize - UDPDATA_HEADER_SIZE { + let _ = self.flush(); + } + Ok(buf.len()) + } + + fn flush(&mut self) -> IoResult<()> { + if self.aborter.is_aborted() { + return Err(IoError::new( + std::io::ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } + for chunk in self + .write_buffer + .buffer + .chunks(self.mtu as usize - UDPDATA_HEADER_SIZE) + { + if self.outgoing.send(chunk.to_vec()).is_err() { + return Err(IoError::new( + std::io::ErrorKind::ConnectionAborted, + "Connection dropped", + )); + } + } + self.write_buffer.buffer.clear(); + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs new file mode 100644 index 0000000..a925e71 --- /dev/null +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -0,0 +1,222 @@ +/// This module handles the data from Bc->BcUdp->UdpSocket +/// +/// - It recieves Bc as Vec (after serialize) +/// - It wraps it in BcUdp packet +/// - It retransmits when camera dosen't acknoledge +/// - It sends UdpAck to acknoledge recieved packets +/// +use super::{aborthandle::AbortHandle, discover::UdpDiscover, SOCKET_WAIT_TIME, WAIT_TIME}; +use crate::bcudp::{model::*, xml::*}; +use crossbeam_channel::{Receiver, SendError, Sender, TryRecvError}; +use err_derive::Error; +use log::*; +use std::collections::HashMap; +use std::io::{Error as IoError, ErrorKind}; +use std::net::UdpSocket; +use std::sync::atomic::{AtomicU32, Ordering}; +use time::OffsetDateTime; + +#[derive(Debug, Error)] +pub enum TransmitError { + /// Error raised when IO fails such as when the connection is lost + #[error(display = "Io error")] + Io(#[error(source)] IoError), + + /// Error raised when socket recv IO fails such as when the connection is lost + #[error(display = "Socket Recv error")] + SocketRecv { err: std::io::Error }, + + /// Error raised when socker IO fails such as when the connection is lost + #[error(display = "Socket Send error")] + SocketSend { err: std::io::Error }, + + /// Error raised when camera sends a disconnect request + #[error(display = "Camera Requested Disconnected")] + Disc, + + /// Error raised during deserlization + #[error(display = "BcUdp Deserialization error")] + BcUdpDeserialization(#[error(source)] crate::bcudp::de::Error), + + /// Error raised during serlization + #[error(display = "BcUdp Serialization error")] + BcUdpSerialization(#[error(source)] crate::bcudp::ser::Error), + + /// Error raised during send + #[error(display = "BcUdp Send to Channel Failed")] + BcUdpSend(#[error(source)] SendError>), + + /// Error raised during recv + #[error(display = "BcUdp Recv from Channel Failed")] + BcUdpRecv(#[error(source)] TryRecvError), +} + +type Result = std::result::Result; + +pub struct UdpTransmit { + client_wants: AtomicU32, + camera_acknowledged: AtomicU32, + client_sent: AtomicU32, +} + +impl UdpTransmit { + pub fn new() -> Self { + Self { + client_wants: Default::default(), + camera_acknowledged: Default::default(), + client_sent: Default::default(), + } + } + + pub fn poll_read( + &self, + socket: &UdpSocket, + discovery_result: &UdpDiscover, + send_to_incoming: &Sender>, + ) -> Result<()> { + // Handle recv from `socket` and send to `send_to_incoming` + let mut buf = vec![0; discovery_result.mtu as usize]; + match socket.recv(&mut buf) { + Ok(amount_recv) => { + let bcudp_msg = BcUdp::deserialize(&buf[0..amount_recv])?; + match bcudp_msg { + BcUdp::Discovery(UdpDiscovery { + tid, + payload: + UdpXml { + d2c_disc: Some(D2cDisc { cid, did }), + .. + }, + .. + }) if cid == discovery_result.client_id + && did == discovery_result.camera_id => + { + // Reply with out C2D_Disc and end + let bcudp_msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_disc: Some(C2dDisc { + cid: discovery_result.client_id, + did: discovery_result.camera_id, + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + bcudp_msg.serialize(&mut buf)?; + socket + .send(&buf) + .map_err(|e| TransmitError::SocketSend { err: e })?; + return Err(TransmitError::Disc); + } + BcUdp::Discovery(packet) => { + debug!("Got unexpected discovery packet: {:?}", packet) + } + BcUdp::Ack(UdpAck { + connection_id, + packet_id, + .. + }) if connection_id == discovery_result.client_id => { + self.camera_acknowledged + .fetch_max(packet_id, Ordering::Acquire); + } + BcUdp::Ack(UdpAck { .. }) => { + debug!("Got a UdpAck for another client id"); + } + BcUdp::Data(UdpData { + connection_id: cid, + packet_id, + payload, + }) if cid == discovery_result.client_id => { + // Seperated as let/if due to clippy recommend + trace!("Recieving UdpData packet {}", packet_id); + let updated = self + .client_wants + .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| { + if v == packet_id { + Some(v + 1) + } else { + None + } + }) + .is_ok(); + if updated { + send_to_incoming.send(payload)?; + } + } + BcUdp::Data(UdpData { .. }) => { + debug!("Got UdpData for another client id"); + } + } + } + Err(e) if e.kind() == ErrorKind::WouldBlock || e.kind() == ErrorKind::TimedOut => { + // Just a timeout + } + Err(e) => { + // Should stop + return Err(TransmitError::SocketRecv { err: e }); + } + } + Ok(()) + } + + pub fn poll_write( + &self, + socket: &UdpSocket, + discovery_result: &UdpDiscover, + get_from_outgoing: &Receiver>, + outgoing_history: &mut HashMap>, + ) -> Result<()> { + // Handle Retransmit + let camera_has = self.camera_acknowledged.load(Ordering::Relaxed); + let client_sent = self.client_sent.load(Ordering::Relaxed); + if camera_has < client_sent { + for packet_id in camera_has..(client_sent + 1) { + if let Some(payload) = &outgoing_history.get(&packet_id) { + socket + .send(payload) + .map_err(|e| TransmitError::SocketSend { err: e })?; + } + std::thread::sleep(SOCKET_WAIT_TIME); + } + } + + // Handle recv from `send_to_incoming` and send to `socket` + match get_from_outgoing.try_recv() { + Ok(payload) => { + let packet_id = self.client_sent.fetch_add(1, Ordering::Relaxed); + let bcudp_msg = BcUdp::Data(UdpData { + connection_id: discovery_result.camera_id, + packet_id, + payload, + }); + + let mut buf = vec![]; + bcudp_msg.serialize(&mut buf)?; + socket + .send(&buf) + .map_err(|e| TransmitError::SocketSend { err: e })?; + outgoing_history.insert(packet_id, buf); + } + Err(TryRecvError::Empty) => {} + Err(e) => return Err(e.into()), + } + + // Handle acknoledgment + let client_wants = self.client_wants.load(Ordering::Relaxed); + if client_wants > 0 { + let bcack_msg = BcUdp::Ack(UdpAck { + connection_id: discovery_result.camera_id, + packet_id: client_wants - 1, + }); + + let mut buf = vec![]; + bcack_msg.serialize(&mut buf)?; + socket + .send(&buf) + .map_err(|e| TransmitError::SocketSend { err: e })?; + } + Ok(()) + } +} diff --git a/crates/core/src/bc_protocol/ping.rs b/crates/core/src/bc_protocol/ping.rs index 0c63b0e..0ef9331 100644 --- a/crates/core/src/bc_protocol/ping.rs +++ b/crates/core/src/bc_protocol/ping.rs @@ -1,4 +1,4 @@ -use super::{BcCamera, Result, RX_TIMEOUT}; +use super::{BcCamera, Error, Result, RX_TIMEOUT}; use crate::bc::model::*; impl BcCamera { @@ -28,4 +28,40 @@ impl BcCamera { Ok(()) } + + /// Send a ping repeatedly + pub fn ping_every(&self, milis: u64) -> Result<()> { + let wait = std::time::Duration::from_millis(milis); + + let connection = self.connection.as_ref().expect("Must be connected to ping"); + let sub_ping = connection.subscribe(MSG_ID_PING)?; + + loop { + let ping = Bc { + meta: BcMeta { + msg_id: MSG_ID_PING, + channel_id: self.channel_id, + msg_num: self.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + sub_ping.send(ping)?; + + let reply = sub_ping.rx.recv_timeout(RX_TIMEOUT)?; + + if reply.meta.response_code != 200 { + return Err(Error::UnintelligibleReply { + reply, + why: "Camera responded with an error status code to the ping", + }); + } + std::thread::sleep(wait); + } + } } diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index 04aacb8..42ffce8 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -68,7 +68,10 @@ where } } Ok(_) => break, - Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + Err(e) + if e.kind() == std::io::ErrorKind::WouldBlock + || e.kind() == std::io::ErrorKind::TimedOut => + { // This is a temporaily unavaliable resource // We should just wait and try again } diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index d5f3820..9a52c08 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -135,9 +135,15 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { let (buf, connection_id) = le_i32(buf)?; let (buf, _unknown_a) = verify(le_u32, |&x| x == 0)(buf)?; let (buf, _unknown_b) = verify(le_u32, |&x| x == 0)(buf)?; - let (buf, packet_id) = le_u32(buf)?; - let (buf, _unknown_c) = le_u32(buf)?; - let (buf, _unknown_d) = verify(le_u32, |&x| x == 0)(buf)?; + let (buf, packet_id) = le_u32(buf)?; // This is the point at which the camera has contigious + // packets to + let (buf, _unknown) = le_u32(buf)?; + let (buf, payload_size) = le_u32(buf)?; + let (buf, _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 + // since last contigious packet_id up + // to the last packet we sent and it recieved let data = UdpAck { connection_id, diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index 80e11c4..39de3be 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -54,7 +54,9 @@ pub struct UdpAck { /// The ID of the last data packet [`UdpData`] pub packet_id: u32, // 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` - // 2 Bytes Unknown: Observed values `00000000` + // Unknown but seems to change randomly every second + // 2 Bytes size of a payload + // Payload of `00 01 01 01 01` where `01` is added after every repeat } /// Magic for the UDP Data packet diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 65b1a3f..a5f08a6 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -29,6 +29,7 @@ udp_tid = ProtoField.int32("baichuan.udp_tid", "udp_tid", base.DEC) udp_checksum = ProtoField.int32("baichuan.udp_checksum", "udp_checksum", base.DEC) udp_packet_count = ProtoField.int32("baichuan.udp_packet_count", "udp_packet_count", base.DEC) udp_last_ack_packet = ProtoField.int32("baichuan.udp_last_ack_packet", "udp_last_ack_packet", base.DEC) +udp_ack_payload_size = ProtoField.int32("baichuan.udp_ack_payload_size", "ack_payload_size", base.DEC) udp_size = ProtoField.int32("baichuan.udp_size", "udp_size", base.DEC) bc_protocol.fields = { @@ -55,6 +56,7 @@ bc_protocol.fields = { udp_checksum, udp_packet_count, udp_last_ack_packet, + udp_ack_payload_size, udp_size, } @@ -416,6 +418,7 @@ function get_udp_header(buffer) local udp_unknown3 = nil local udp_unknown4 = nil local udp_last_ack_packet = nil + local udp_ack_payload_size = nil local udp_connection_id = nil local udp_packet_count = nil if udp_class == 0x3a then @@ -434,7 +437,7 @@ function get_udp_header(buffer) udp_unknown2 = buffer(12, 4):le_uint() udp_last_ack_packet = buffer(16, 4):le_uint() udp_unknown3 = buffer(20, 4):le_uint() - udp_unknown4 = buffer(24, 4):le_uint() + udp_ack_payload_size = buffer(24, 4):le_uint() elseif udp_class == 0x10 then udp_connection_id = buffer(4, 4):le_uint() udp_unknown1 = buffer(8, 4):le_uint() @@ -455,6 +458,7 @@ function get_udp_header(buffer) connection_id = udp_connection_id, packet_count = udp_packet_count, last_ack_packet = udp_last_ack_packet, + ack_payload_size = udp_ack_payload_size } end @@ -480,7 +484,7 @@ function process_udp_header(buffer, headers_tree) header:add_le(udp_unknown, buffer(12, 4)) header:add_le(udp_last_ack_packet, buffer(16, 4)) header:add_le(udp_unknown, buffer(20, 4)) - header:add_le(udp_unknown, buffer(24, 4)) + header:add_le(udp_ack_payload_size, buffer(24, 4)) elseif header_data.class == 0x10 then header:add_le(udp_connection_id, buffer(4, 4)) header:add_le(udp_unknown, buffer(8, 4)) @@ -687,6 +691,9 @@ function bc_protocol.dissector(buffer, pinfo, tree) elseif udp_header.class == 0x20 then pinfo.cols.protocol = bc_protocol.name .. " UDP ACK" + if udp_header.ack_payload_size > 0 then + tree:add(bc_protocol, buffer(25,udp_header.ack_payload_size), "BcUdp Ack Payload") + end else subbuffer = buffer(udp_header_len, nil) end diff --git a/dissector/udp.md b/dissector/udp.md index 77edf3e..ad263c1 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -253,11 +253,46 @@ These messages are sent to acknowledge receipt of message. They are header only. - 4 Bytes unknown: Always `00000000` for for UDP Ack - 4 Bytes Last Packet ID: Last received packet id - 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` **NEEDS INFO** -- 4 Bytes Unknown: Observed values `00000000` +- Payload Size: **NEEDS INFO** +- Paload **NEEDS INFO** **To Investigate:** - - Why does the unknown byte change. It starts at zero and remains that way for a long - time. Then seems to change and remain at the new value for a long time + - Why does the unknown byte change. It starts at zero and remains that way for a second + time. Then seems to change and remain at the new value for another second + - Payload is usually 0 but occasionally it is non zero + - When this happens the payload becomes `00 01 01 01 01 01` always the first + byte `00` then just `01`/`00` bytes + - This payload then increases in size by `01` each ackpacket until a new + udpdata packet arrives. At which point the `Last received packet id` jumps + +Here's an example of a UDP Ack payload (size 203 bytes) + +```hex +0000 00 01 01 01 01 01 01 01 01 01 01 01 00 01 01 01 +0010 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +0020 01 01 01 01 00 01 01 01 01 01 01 01 01 01 01 01 +0030 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +0040 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +0050 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +0060 01 01 01 01 01 01 00 01 01 01 01 01 01 01 01 01 +0070 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +0080 01 01 01 01 01 01 01 01 01 01 00 01 01 01 01 01 +0090 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +00a0 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +00b0 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 +00c0 01 01 01 01 01 01 01 01 01 01 01 01 +``` + +I believe this is a truth table of false/true for missing packets + +In this example the last packet sent was number 221 but the camera only +acknowledged number 14 and sent this binary too and the unknown +value was `f8010000` (504). + +If this payload is allowed to grow to ~ 205 bytes the camera sends a +disconnect request and drops the connection + + # UDP Data From 73204acf525593b2f84d973de9f783215ff61c71 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 21 Aug 2021 09:48:02 +0700 Subject: [PATCH 26/56] Added payload to udpack in dissector --- dissector/baichuan.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index a5f08a6..a68363f 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -692,7 +692,7 @@ function bc_protocol.dissector(buffer, pinfo, tree) elseif udp_header.class == 0x20 then pinfo.cols.protocol = bc_protocol.name .. " UDP ACK" if udp_header.ack_payload_size > 0 then - tree:add(bc_protocol, buffer(25,udp_header.ack_payload_size), "BcUdp Ack Payload") + tree:add(bc_protocol, buffer(28,udp_header.ack_payload_size), "BcUdp Ack Payload") end else subbuffer = buffer(udp_header_len, nil) From ea4de74e8d0dba54fb12d02fee0bc4498f1b8db2 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 21 Aug 2021 11:19:58 +0700 Subject: [PATCH 27/56] Readded Bc<->Bc messages to dissector Also added them to the heurestic check --- dissector/baichuan.lua | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index a68363f..e345695 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -189,7 +189,12 @@ end function get_header_len(buffer) local magic = buffer(0, 4):le_uint() - if magic ~= 0x0abcdef0 then + if magic == 0x0abcdef0 then + -- Client <-> BC + elseif magic == 0x0fedcba0 then + -- BC <-> BC + else + -- Unknown magic return -1 -- No header found end local header_len = header_lengths[buffer(18, 2):le_uint()] @@ -400,7 +405,6 @@ function get_udp_header_len(buffer) elseif udptype == 0x10 then return 20 else - print("Unknown udp type") return -1 end end @@ -668,7 +672,6 @@ function process_bc_message(buffer, pinfo, tree) end function bc_protocol.init () - -- print ("(re-)initialise") fragments = {} end @@ -733,22 +736,18 @@ end local function heuristic_checker_udp(buffer, pinfo, tree) -- guard for length - print("UDP Heur") length = buffer:len() if length < 4 then return false end - print("LEN GOOD") local potential_magic = buffer(0,4):le_uint() - print("MAGIC??? " .. string.format("%x", potential_magic)) - if potential_magic ~= 0x2a87cf3a and + if potential_magic ~= 0x2a87cf3a and potential_magic ~= 0x2a87cf20 and potential_magic ~= 0x2a87cf10 and potential_magic ~= 0x2a87cf31 then return false end - - print("YEP") + bc_protocol.dissector(buffer, pinfo, tree) return true end @@ -759,8 +758,11 @@ local function heuristic_checker_tcp(buffer, pinfo, tree) if length < 4 then return false end local potential_magic = buffer(0,4):le_uint() - if potential_magic ~= 0xabcdef0 then return false end - + if potential_magic ~= 0xabcdef0 and + potential_magic ~= 0x0fedcba0 then + return false + end + bc_protocol.dissector(buffer, pinfo, tree) return true end @@ -776,4 +778,3 @@ bc_protocol:register_heuristic("tcp", heuristic_checker_tcp) -- DissectorTable.get("udp.port"):add(2018, bc_protocol) -- DissectorTable.get("udp.port"):add(2000, bc_protocol) -- DissectorTable.get("udp.port"):add(9999, bc_protocol) - From 4b8d16d028011429785c9b9508d7d2823f1bc002 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 21 Aug 2021 13:45:10 +0700 Subject: [PATCH 28/56] Add luacheck and make dissector compilent --- .github/workflows/style_checks.yml | 10 + dissector/baichuan.lua | 464 ++++++++++++++--------------- 2 files changed, 237 insertions(+), 237 deletions(-) diff --git a/.github/workflows/style_checks.yml b/.github/workflows/style_checks.yml index 27757f6..2d02681 100644 --- a/.github/workflows/style_checks.yml +++ b/.github/workflows/style_checks.yml @@ -41,3 +41,13 @@ jobs: - name: rustfmt run: | cargo +nightly fmt --all -- --check + + check_lua: + name: Luacheck + runs-on: ubuntu-latest + steps: + - name: Run luacheck + uses: nebularg/actions-luacheck@v1 + with: + files: 'dissector/baichuan.lua' + args: --globals Dissector,Proto,ProtoField,base,ByteArray,DESEGMENT_ONE_MORE_SEGMENT,DissectorTable diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index e345695..06cd55d 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -2,35 +2,35 @@ -- Copy/symlink it into ~/.local/lib/wireshark/plugins/ and restart Wireshark; it should -- automatically attempt to decode TCP connections on port 9000. -bc_protocol = Proto("Baichuan", "Baichuan/Reolink IP Camera Protocol") +local bc_protocol = Proto("Baichuan", "Baichuan/Reolink IP Camera Protocol") -magic_bytes = ProtoField.int32("baichuan.magic", "magic", base.DEC) -message_id = ProtoField.int32("baichuan.msg_id", "messageId", base.DEC) -message_len = ProtoField.int32("baichuan.msg_len", "messageLen", base.DEC) -xml_enc_offset = ProtoField.int8("baichuan.xml_encryption_offset", "xmlEncryptionOffset", base.DEC) -encrypt_xml = ProtoField.bool("baichuan.encrypt_xml", "encrypt_xml", base.NONE) -channel_id = ProtoField.int8("baichuan.channel_id", "channel_id", base.DEC) -stream_id = ProtoField.int8("baichuan.stream_id", "streamID", base.DEC) -unknown = ProtoField.int8("baichuan.unknown", "unknown", base.DEC) -msg_handle = ProtoField.int8("baichuan.message_handle", "messageHandle", base.DEC) -status_code = ProtoField.int16("baichuan.status_code", "status_code", base.DEC) -message_class = ProtoField.int32("baichuan.msg_class", "messageClass", base.DEC) -f_bin_offset = ProtoField.int32("baichuan.bin_offset", "binOffset", base.DEC) -username = ProtoField.string("baichuan.username", "username", base.ASCII) -password = ProtoField.string("baichuan.password", "password", base.ASCII) +local magic_bytes = ProtoField.int32("baichuan.magic", "magic", base.DEC) +local message_id = ProtoField.int32("baichuan.msg_id", "messageId", base.DEC) +local message_len = ProtoField.int32("baichuan.msg_len", "messageLen", base.DEC) +local xml_enc_offset = ProtoField.int8("baichuan.xml_encryption_offset", "xmlEncryptionOffset", base.DEC) +local encrypt_xml = ProtoField.bool("baichuan.encrypt_xml", "encrypt_xml", base.NONE) +local channel_id = ProtoField.int8("baichuan.channel_id", "channel_id", base.DEC) +local stream_id = ProtoField.int8("baichuan.stream_id", "streamID", base.DEC) +local unknown = ProtoField.int8("baichuan.unknown", "unknown", base.DEC) +local msg_handle = ProtoField.int8("baichuan.message_handle", "messageHandle", base.DEC) +local status_code = ProtoField.int16("baichuan.status_code", "status_code", base.DEC) +local message_class = ProtoField.int32("baichuan.msg_class", "messageClass", base.DEC) +local f_bin_offset = ProtoField.int32("baichuan.bin_offset", "binOffset", base.DEC) +local username = ProtoField.string("baichuan.username", "username", base.ASCII) +local password = ProtoField.string("baichuan.password", "password", base.ASCII) -- UDP Related content -udp_magic = ProtoField.int32("baichuan.udp_magic", "udp_magic", base.DEC) -udp_type = ProtoField.int8("baichuan.udp_type", "udp_type", base.DEC) -udp_message_id = ProtoField.int8("baichuan.udp_message_id", "udp_message_id", base.DEC) -udp_connection_id = ProtoField.int32("baichuan.udp_connection_id", "udp_connection_id", base.DEC) -udp_unknown = ProtoField.int32("baichuan.udp_unknown", "udp_unknown", base.DEC) -udp_tid = ProtoField.int32("baichuan.udp_tid", "udp_tid", base.DEC) -udp_checksum = ProtoField.int32("baichuan.udp_checksum", "udp_checksum", base.DEC) -udp_packet_count = ProtoField.int32("baichuan.udp_packet_count", "udp_packet_count", base.DEC) -udp_last_ack_packet = ProtoField.int32("baichuan.udp_last_ack_packet", "udp_last_ack_packet", base.DEC) -udp_ack_payload_size = ProtoField.int32("baichuan.udp_ack_payload_size", "ack_payload_size", base.DEC) -udp_size = ProtoField.int32("baichuan.udp_size", "udp_size", base.DEC) +local udp_magic = ProtoField.int32("baichuan.udp_magic", "udp_magic", base.DEC) +local udp_type = ProtoField.int8("baichuan.udp_type", "udp_type", base.DEC) +local udp_message_id = ProtoField.int8("baichuan.udp_message_id", "udp_message_id", base.DEC) +local udp_connection_id = ProtoField.int32("baichuan.udp_connection_id", "udp_connection_id", base.DEC) +local udp_unknown = ProtoField.int32("baichuan.udp_unknown", "udp_unknown", base.DEC) +local udp_tid = ProtoField.int32("baichuan.udp_tid", "udp_tid", base.DEC) +local udp_checksum = ProtoField.int32("baichuan.udp_checksum", "udp_checksum", base.DEC) +local udp_packet_count = ProtoField.int32("baichuan.udp_packet_count", "udp_packet_count", base.DEC) +local udp_last_ack_packet = ProtoField.int32("baichuan.udp_last_ack_packet", "udp_last_ack_packet", base.DEC) +local udp_ack_payload_size = ProtoField.int32("baichuan.udp_ack_payload_size", "ack_payload_size", base.DEC) +local udp_size = ProtoField.int32("baichuan.udp_size", "udp_size", base.DEC) bc_protocol.fields = { magic_bytes, @@ -60,7 +60,7 @@ bc_protocol.fields = { udp_size, } -message_types = { +local message_types = { [1]="login", -- / / [2]="logout", [3]=" (video)", @@ -163,21 +163,21 @@ message_types = { [274]="", } -message_classes = { +local message_classes = { [0x6514]="legacy", [0x6614]="modern", [0x6414]="modern", [0x0000]="modern", } -header_lengths = { +local header_lengths = { [0x6514]=20, [0x6614]=20, [0x6414]=24, [0x0000]=24, } -function xml_encrypt(ba, offset) +local function xml_decrypt(ba, offset) local key = "\031\045\060\075\090\105\120\255" -- 1f, 2d, 3c, 4b, 5a, 69, 78 ,ff local e = ByteArray.new() e:set_size(ba:len()) @@ -187,13 +187,9 @@ function xml_encrypt(ba, offset) return e end -function get_header_len(buffer) +local function get_header_len(buffer) local magic = buffer(0, 4):le_uint() - if magic == 0x0abcdef0 then - -- Client <-> BC - elseif magic == 0x0fedcba0 then - -- BC <-> BC - else + if magic ~= 0x0abcdef0 and magic ~= 0x0fedcba0 then -- Unknown magic return -1 -- No header found end @@ -201,19 +197,18 @@ function get_header_len(buffer) return header_len end -function get_header(buffer) +local function get_header(buffer) -- bin_offset is either nil (no binary data) or nonzero -- TODO: bin_offset is actually stateful! local bin_offset = nil - local status_code = nil - local encrypt_xml = nil + local return_code = nil + local encr_xml = nil local header_len = header_lengths[buffer(18, 2):le_uint()] - local msg_type = buffer(4, 4):le_uint() if header_len == 24 then bin_offset = buffer(20, 4):le_uint() -- if NHD-805/806 legacy protocol 30 30 30 30 aka "0000" - status_code = buffer(16, 2):le_uint() + return_code = buffer(16, 2):le_uint() else - encrypt_xml = buffer(16, 1):le_uint() + encr_xml = buffer(16, 1):le_uint() end local msg_type = buffer(4, 4):le_uint() local stream_text = "HD (Clear)" @@ -225,23 +220,23 @@ function get_header(buffer) msg_type = buffer(4, 4):le_uint(), msg_type_str = message_types[msg_type] or "unknown", msg_len = buffer(8, 4):le_uint(), - encrypt_xml = encrypt_xml, + encrypt_xml = encr_xml, channel_id = buffer(12, 1):le_uint(), enc_offset = buffer(12, 1):le_uint(), stream_type = stream_text, unknown = buffer(14, 1):le_uint(), msg_handle = buffer(15, 1):le_uint(), msg_cls = buffer(18, 2):le_uint(), - status_code = status_code, + status_code = return_code, class = message_classes[buffer(18, 2):le_uint()], header_len = header_lengths[buffer(18, 2):le_uint()], bin_offset = bin_offset, } end -function process_header(buffer, headers_tree) +local function process_header(buffer, headers_tree) local header_data = get_header(buffer) - local header = headers_tree:add(bc_protocol, buffer(0, header_len), + local header = headers_tree:add(bc_protocol, buffer(0, header_data.header_len), "Baichuan Message Header, length: " .. header_data.header_len .. ", type " .. header_data.msg_type) local stream_text = " HD (Clear)" if buffer(13, 1):le_uint() == 1 then @@ -269,10 +264,10 @@ function process_header(buffer, headers_tree) else header:add_le(encrypt_xml, buffer(16, 1)) end - return header_len + return header_data.header_len end -function process_body(header, body_buffer, bc_subtree, pinfo) +local function process_body(header, body_buffer, bc_subtree, pinfo) if header.msg_len == 0 then return end @@ -295,9 +290,9 @@ function process_body(header, body_buffer, bc_subtree, pinfo) local body_tvb = xml_buffer:tvb("Meta Payload") body:add(body_tvb(), "Meta Payload") if xml_len >= 4 then - if xml_encrypt(xml_buffer(0,5):bytes(), header.enc_offset):raw() == " 0 then local binary_buffer = body_buffer(header.bin_offset, bin_len) -- Don't extend beyond msg size - body_tvb = binary_buffer:tvb("Main Payload"); + local body_tvb = binary_buffer:tvb("Main Payload"); body:add(body_tvb(), "Main Payload") if bin_len > 4 then - if xml_encrypt(binary_buffer(0,5):bytes(), header.enc_offset):raw() == "= target_len then - start_fragment.result = "DONE" - process_bc_message(reassembled:tvb("Reassembled UDP"), pinfo, tree) - end - end - end -end ---- END UDP CONTENT - -function is_complete_bc_message(buffer) - length = buffer:len() - if length == 0 then - return "DONE" - end - - local sub_buffer = buffer - local table_msg_type_str = {} - local table_msg_type = {} - - local continue_loop = true - while ( continue_loop ) - do - - -- Get min bytes for a magic and header len - if sub_buffer:len() < 20 then - -- Need more bytes but we don't have a header to learn how many bytes - return "+1" - end - header_len = get_header_len(sub_buffer(0, nil)) - - if header_len >= 0 then - -- Valid magic and header found - - -- Ensure min bytes for full header - if sub_buffer:len() < header_len then - -- Need more bytes - return header_len - sub_buffer:len() - end - - - local header = get_header(sub_buffer(0, nil)) - - -- Get full header and body - local full_body_len = header.msg_len + header.header_len - if sub_buffer:len() < full_body_len then - return full_body_len - sub_buffer:len() - end - - local remaining = sub_buffer:len() - header.header_len - if header.header_len < sub_buffer:len() then - local body_buffer = sub_buffer(header.header_len, nil) - remaining = body_buffer:len() - header.msg_len - end - - -- Remaning bytes? - if remaining == 0 then - continue_loop = false - else - sub_buffer = sub_buffer(full_body_len, sub_buffer:len() - full_body_len) - end - else - return "NOMAGIC" - end - end - return "DONE" -end - -function process_bc_message(buffer, pinfo, tree) - length = buffer:len() - +local function process_bc_message(buffer, pinfo, tree) pinfo.cols.protocol = bc_protocol.name local sub_buffer = buffer @@ -631,7 +494,7 @@ function process_bc_message(buffer, pinfo, tree) local continue_loop = true while ( continue_loop ) do - header_len = get_header_len(sub_buffer(0, nil)) + local header_len = get_header_len(sub_buffer(0, nil)) if header_len >= 0 then -- Valid magic and header found @@ -671,8 +534,127 @@ function process_bc_message(buffer, pinfo, tree) return end +local function is_complete_bc_message(buffer) + local length = buffer:len() + if length == 0 then + return "DONE" + end + + local sub_buffer = buffer + + local continue_loop = true + while ( continue_loop ) + do + + -- Get min bytes for a magic and header len + if sub_buffer:len() < 20 then + -- Need more bytes but we don't have a header to learn how many bytes + return "+1" + end + local header_len = get_header_len(sub_buffer(0, nil)) + + if header_len >= 0 then + -- Valid magic and header found + + -- Ensure min bytes for full header + if sub_buffer:len() < header_len then + -- Need more bytes + return header_len - sub_buffer:len() + end + + + local header = get_header(sub_buffer(0, nil)) + + -- Get full header and body + local full_body_len = header.msg_len + header.header_len + if sub_buffer:len() < full_body_len then + return full_body_len - sub_buffer:len() + end + + local remaining = sub_buffer:len() - header.header_len + if header.header_len < sub_buffer:len() then + local body_buffer = sub_buffer(header.header_len, nil) + remaining = body_buffer:len() - header.msg_len + end + + -- Remaning bytes? + if remaining == 0 then + continue_loop = false + else + sub_buffer = sub_buffer(full_body_len, sub_buffer:len() - full_body_len) + end + else + return "NOMAGIC" + end + end + return "DONE" +end + +local function udp_reassemple(udp_header, subbuffer, more, pinfo, tree) + -- Cache udp message for later lookup + local con_id = udp_header.connection_id + if udp_fragments[con_id] == nil then + udp_fragments[con_id] = {} + end + local mess_id = udp_header.packet_count + if udp_fragments[con_id][mess_id] == nil then + udp_fragments[con_id][mess_id] = {} + end + udp_fragments[con_id][mess_id]['result'] = more + udp_fragments[con_id][mess_id]['message_id'] = mess_id + udp_fragments[con_id][mess_id]['buffer'] = subbuffer:bytes() + + -- Go backwards from current ID until: + -- I hit a result that is not NOMAGIC + -- Can be myself + local start_idx = mess_id + local start_fragment = udp_fragments[con_id][start_idx] + while start_fragment.result == "NOMAGIC" do + start_idx = start_idx -1 + start_fragment = udp_fragments[con_id][start_idx] + if start_fragment == nil then + break + end + end + + if start_fragment ~= nil then -- Found a starting fragment + local needed = start_fragment.result + if needed == "DONE" then + if start_fragment.message_id == udp_header.packet_count then + process_bc_message(start_fragment.buffer:tvb(), pinfo, tree) + end + elseif needed == "+1" then + -- Cannot handle in UDP... + -- Only happens in off chance not enough data for + -- even the header + -- Never observed to date + return + else + -- pinfo.cols['info'] = "SEARCHING" + local next_id = start_fragment.message_id + 1 + local reassembled = ByteArray.new() + local total_packet = 1 + reassembled = reassembled .. start_fragment.buffer + local target_len = reassembled:len() + start_fragment.result + while reassembled:len() < target_len do + local next_fragment = udp_fragments[con_id][next_id] + if next_fragment ~= nil then + reassembled = reassembled .. next_fragment.buffer + total_packet = total_packet + 1 + else + break + end + end + if reassembled:len() >= target_len then + start_fragment.result = "DONE" + process_bc_message(reassembled:tvb("Reassembled UDP"), pinfo, tree) + end + end + end +end + function bc_protocol.init () - fragments = {} + udp_fragments = {} end function bc_protocol.dissector(buffer, pinfo, tree) @@ -684,8 +666,8 @@ function bc_protocol.dissector(buffer, pinfo, tree) udp_header = get_udp_header(buffer(0, udp_header_len)) process_udp_header(buffer(0, udp_header_len), tree) if udp_header.class == 0x3a then - decrypted_bytes = udp_decrypt(buffer(udp_header_len, nil):bytes(), udp_header.tid) - decryped_tvb = decrypted_bytes:tvb("UDP Decrypted Message") + local decrypted_bytes = udp_decrypt(buffer(udp_header_len, nil):bytes(), udp_header.tid) + local decryped_tvb = decrypted_bytes:tvb("UDP Decrypted Message") local subtree = tree:add(bc_protocol, decryped_tvb, "UDP Message Data") Dissector.get("xml"):call(decryped_tvb, pinfo, subtree) pinfo.cols.protocol = bc_protocol.name .. " UDP Heartbeat" @@ -708,7 +690,6 @@ function bc_protocol.dissector(buffer, pinfo, tree) end if subbuffer ~= nil then local more = is_complete_bc_message(subbuffer) - if pinfo.can_desegment == 1 then -- TCP can use the desegment method if more == "DONE" then process_bc_message(subbuffer, pinfo, tree) @@ -733,10 +714,11 @@ function bc_protocol.dissector(buffer, pinfo, tree) end end end +--- END UDP CONTENT local function heuristic_checker_udp(buffer, pinfo, tree) -- guard for length - length = buffer:len() + local length = buffer:len() if length < 4 then return false end local potential_magic = buffer(0,4):le_uint() @@ -752,25 +734,33 @@ local function heuristic_checker_udp(buffer, pinfo, tree) return true end +local added_tcp_ports = {} + local function heuristic_checker_tcp(buffer, pinfo, tree) -- guard for length - length = buffer:len() + local length = buffer:len() if length < 4 then return false end - local potential_magic = buffer(0,4):le_uint() - if potential_magic ~= 0xabcdef0 and + if potential_magic ~= 0x0abcdef0 and potential_magic ~= 0x0fedcba0 then return false end + if added_tcp_ports[pinfo.dst_port] == nil then + table.insert(added_tcp_ports, pinfo.dst_port) + DissectorTable.get("tcp.port"):add(pinfo.dst_port, bc_protocol) + end + if added_tcp_ports[pinfo.src_port] == nil then + table.insert(added_tcp_ports, pinfo.src_port) + DissectorTable.get("tcp.port"):add(pinfo.src_port, bc_protocol) + end + bc_protocol.dissector(buffer, pinfo, tree) return true end bc_protocol:register_heuristic("udp", heuristic_checker_udp) bc_protocol:register_heuristic("tcp", heuristic_checker_tcp) - --- DissectorTable.get("tcp.port"):add(9000, bc_protocol) -- DissectorTable.get("tcp.port"):add(53959, bc_protocol) -- change to your own custom port -- DissectorTable.get("udp.port"):add(2000, bc_protocol) From b8cab8f68d2bef7ba72be229e0373030f4234142 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sat, 21 Aug 2021 14:06:46 +0700 Subject: [PATCH 29/56] Make dissector add the ports table upon detection for udp too --- .github/workflows/style_checks.yml | 3 ++- dissector/baichuan.lua | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/.github/workflows/style_checks.yml b/.github/workflows/style_checks.yml index 2d02681..d1b8bf5 100644 --- a/.github/workflows/style_checks.yml +++ b/.github/workflows/style_checks.yml @@ -46,8 +46,9 @@ jobs: name: Luacheck runs-on: ubuntu-latest steps: + - uses: actions/checkout@v1 - name: Run luacheck uses: nebularg/actions-luacheck@v1 with: files: 'dissector/baichuan.lua' - args: --globals Dissector,Proto,ProtoField,base,ByteArray,DESEGMENT_ONE_MORE_SEGMENT,DissectorTable + args: --globals Dissector Proto ProtoField base ByteArray DESEGMENT_ONE_MORE_SEGMENT DissectorTable diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 06cd55d..819d2e1 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -716,6 +716,7 @@ function bc_protocol.dissector(buffer, pinfo, tree) end --- END UDP CONTENT +local added_udp_ports = {} local function heuristic_checker_udp(buffer, pinfo, tree) -- guard for length local length = buffer:len() @@ -730,6 +731,15 @@ local function heuristic_checker_udp(buffer, pinfo, tree) return false end + if added_udp_ports[pinfo.dst_port] == nil then + table.insert(added_udp_ports, pinfo.dst_port) + DissectorTable.get("udp.port"):add(pinfo.dst_port, bc_protocol) + end + if added_udp_ports[pinfo.src_port] == nil then + table.insert(added_udp_ports, pinfo.src_port) + DissectorTable.get("udp.port"):add(pinfo.src_port, bc_protocol) + end + bc_protocol.dissector(buffer, pinfo, tree) return true end From dae1fd3761a01260db95e61f14b9c1c304503160 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 22 Aug 2021 16:02:52 +0700 Subject: [PATCH 30/56] Update udp doc --- dissector/udp.md | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/dissector/udp.md b/dissector/udp.md index ad263c1..e2dc814 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -94,6 +94,12 @@ to init a connection ``` +It also sends this binary on port 2000 as a broadcast + +``` +aaaa0000 +``` + --- **Camera Replies with Binary** @@ -115,7 +121,7 @@ standard tcp bc connection **Udp Camera** If the camera supports UDP the client will send this xml packet -as a broadcast on 255.255.255.255 on port 2018 +as a broadcast on 255.255.255.255 on port 2018/2015 **Known UID** @@ -217,6 +223,8 @@ After a message ID 02 (logout) the client send this - **cid**: The connection ID of the client - **did**: The connection ID of the camera +The camera also send it but with a `D2C_DISC` tag + ## Other Some cameras seem to also send this before login @@ -257,12 +265,12 @@ These messages are sent to acknowledge receipt of message. They are header only. - Paload **NEEDS INFO** **To Investigate:** - - Why does the unknown byte change. It starts at zero and remains that way for a second - time. Then seems to change and remain at the new value for another second - - Payload is usually 0 but occasionally it is non zero + - 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 + - Payload size is usually 0 but occasionally it is non zero - When this happens the payload becomes `00 01 01 01 01 01` always the first byte `00` then just `01`/`00` bytes - - This payload then increases in size by `01` each ackpacket until a new + - This payload then increases in size by `01` each ack packet until a new udpdata packet arrives. At which point the `Last received packet id` jumps Here's an example of a UDP Ack payload (size 203 bytes) @@ -292,6 +300,10 @@ value was `f8010000` (504). If this payload is allowed to grow to ~ 205 bytes the camera sends a disconnect request and drops the connection +I believe that the `Bytes Last Packet ID` in the header is the number of +contiguous packets then the payload represents a table of non contiguous +packets it wants + # UDP Data From f2a63492039697b2e357152e1fcc1d627de20df8 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Sun, 22 Aug 2021 17:20:36 +0700 Subject: [PATCH 31/56] Adjust how neoliknk handles udp resend --- crates/core/src/bc_protocol/connection/udpconn/transmit.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs index a925e71..d11665f 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -172,8 +172,10 @@ impl UdpTransmit { let camera_has = self.camera_acknowledged.load(Ordering::Relaxed); let client_sent = self.client_sent.load(Ordering::Relaxed); if camera_has < client_sent { - for packet_id in camera_has..(client_sent + 1) { + debug!("Resending {:?}", (camera_has + 1)..(client_sent + 1)); + for packet_id in (camera_has + 1)..(client_sent + 1) { if let Some(payload) = &outgoing_history.get(&packet_id) { + debug!(" - Sending {}", packet_id); socket .send(payload) .map_err(|e| TransmitError::SocketSend { err: e })?; @@ -208,7 +210,7 @@ impl UdpTransmit { if client_wants > 0 { let bcack_msg = BcUdp::Ack(UdpAck { connection_id: discovery_result.camera_id, - packet_id: client_wants - 1, + packet_id: client_wants, }); let mut buf = vec![]; From 1d841714c132feb05930a81681c85f0b7d0e561b Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 23 Aug 2021 07:47:29 +0700 Subject: [PATCH 32/56] Use correct body size on dissector --- dissector/baichuan.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dissector/baichuan.lua b/dissector/baichuan.lua index 819d2e1..a911283 100644 --- a/dissector/baichuan.lua +++ b/dissector/baichuan.lua @@ -507,7 +507,7 @@ local function process_bc_message(buffer, pinfo, tree) local remaining = sub_buffer:len() - header.header_len - local bc_subtree = tree:add(bc_protocol, sub_buffer(0, header.msg_len), + local bc_subtree = tree:add(bc_protocol, sub_buffer(0, header.full_body_len), "Baichuan IP Camera Protocol, " .. header.msg_type_str .. ":" .. header.msg_type .. " message") process_header(sub_buffer, bc_subtree) if header.header_len < sub_buffer:len() then From 0fbde1f5f927f84ffe907ea20d7e48f827ef5d3e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 24 Aug 2021 07:56:32 +0700 Subject: [PATCH 33/56] Attempt to handle more complex udp acknoledgements --- .../src/bc_protocol/connection/udpconn/mod.rs | 2 - .../connection/udpconn/transmit.rs | 212 ++++++++++++++---- crates/core/src/bcudp/de.rs | 17 +- crates/core/src/bcudp/model.rs | 6 +- crates/core/src/bcudp/ser.rs | 13 +- 5 files changed, 199 insertions(+), 51 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpconn/mod.rs b/crates/core/src/bc_protocol/connection/udpconn/mod.rs index f781cd7..b3f33b6 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/mod.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/mod.rs @@ -140,13 +140,11 @@ impl UdpSource { // Poll Write std::thread::spawn(move || { - let mut outgoing_history = Default::default(); while !thread_aborter.is_aborted() { if let Err(err) = thread_transmit.poll_write( &thread_socket, &(*thread_discovery_result), &from_outgoing, - &mut outgoing_history, ) { if !thread_aborter.is_aborted() { match err { diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs index d11665f..f3e49a4 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -13,7 +13,10 @@ use log::*; use std::collections::HashMap; use std::io::{Error as IoError, ErrorKind}; use std::net::UdpSocket; -use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{ + atomic::{AtomicU32, Ordering}, + Mutex, +}; use time::OffsetDateTime; #[derive(Debug, Error)] @@ -54,16 +57,159 @@ pub enum TransmitError { type Result = std::result::Result; pub struct UdpTransmit { - client_wants: AtomicU32, - camera_acknowledged: AtomicU32, - client_sent: AtomicU32, + client_recieved: ClientRecieved, + client_sent: ClientSent, +} + +#[derive(Default)] +struct ClientSent { + buffer: Mutex>>, + last_sent: Mutex>, +} + +impl ClientSent { + fn get_next_packet_id(&self) -> u32 { + let mut lock = self.last_sent.lock().unwrap(); + if let Some(current) = lock.as_ref() { + *lock = Some(current + 1); + } else { + *lock = Some(0); + } + lock.unwrap() + } + + fn register_payload(&self, packet_id: u32, payload: Vec) { + self.buffer + .lock() + .unwrap() + .entry(packet_id) + .or_insert(payload); + } + + // fn acknoledge_to(&self, packet_id: u32) { + // self.buffer.lock().unwrap().retain(|&k, _| k > packet_id); + // } + // + // fn acknoledge_these(&self, packet_ids: Vec) { + // let locked = self.buffer.lock().unwrap(); + // for packet_id in packet_ids { + // let _ = locked.remove(&packet_id); + // } + // } + + fn acknoledge_from_ack_data(&self, start: u32, payload: Vec) { + let mut locked = self.buffer.lock().unwrap(); + locked.retain(|&k, _| k > start); + + for (idx, &value) in payload.iter().enumerate() { + let packet_id = start + idx as u32; + if value > 0 { + locked.remove(&packet_id); + } + } + } + + fn lock(&self) -> ClientSentLocked { + ClientSentLocked::new(self) + } +} + +struct ClientSentLocked<'a> { + locked: std::sync::MutexGuard<'a, HashMap>>, +} + +impl<'a> ClientSentLocked<'a> { + fn new(source: &'a ClientSent) -> Self { + let locked = source.buffer.lock().unwrap(); + Self { locked } + } + + fn needs_resend(&self) -> ResendIter { + ResendIter { + iter: self.locked.iter(), + } + } +} + +struct ResendIter<'a> { + iter: std::collections::hash_map::Iter<'a, u32, Vec>, +} + +impl<'a> std::iter::Iterator for ResendIter<'a> { + type Item = (u32, &'a Vec); + + fn next(&mut self) -> Option { + let (k, v) = self.iter.next()?; + Some((*k, v)) + } +} + +#[derive(Default)] +struct ClientRecieved { + buffer: Mutex>>, + consumed: Mutex>, +} + +impl ClientRecieved { + // Consume all contigious packets + fn consume(&self) -> Vec> { + let mut locked = self.buffer.lock().unwrap(); + let mut results = vec![]; + if locked.keys().max().is_some() { + // Just check there is some data + let mut packet_id_loc = self.consumed.lock().unwrap(); + let mut next_packet_id = packet_id_loc.map(|v| v + 1).unwrap_or(0); + while let Some(payload) = locked.remove(&next_packet_id) { + *packet_id_loc = Some(next_packet_id); + results.push(payload); + next_packet_id = packet_id_loc.unwrap() + 1; + } + } + results + } + + // Revieve a new packet only update if entry is new + fn receive(&self, packet_id: u32, payload: Vec) { + let mut locked = self.buffer.lock().unwrap(); + let _ = locked.entry(packet_id).or_insert(payload); + } + + fn get_needed_packets(&self) -> Option<(u32, Vec)> { + let locked = self.buffer.lock().unwrap(); + let packet_id_loc = self.consumed.lock().unwrap(); + + // If this is none we have recieved no packets so we cannot + // ack anything anyways. Just return None + let mut start = packet_id_loc.as_ref().copied()?; + + // Find the last contigous packet + while locked.contains_key(&(start + 1)) { + start += 1; + } + + // Find last packet in buffer + let vec = if let Some(end) = locked.keys().max() { + let mut vec = vec![]; + for i in (start + 1)..(end + 1) { + if locked.contains_key(&i) { + vec.push(0) + } else { + vec.push(1) + } + } + vec + } else { + vec![] + }; + + Some((start, vec)) + } } impl UdpTransmit { pub fn new() -> Self { Self { - client_wants: Default::default(), - camera_acknowledged: Default::default(), + client_recieved: Default::default(), client_sent: Default::default(), } } @@ -91,7 +237,7 @@ impl UdpTransmit { }) if cid == discovery_result.client_id && did == discovery_result.camera_id => { - // Reply with out C2D_Disc and end + // Reply with C2D_Disc and end let bcudp_msg = BcUdp::Discovery(UdpDiscovery { tid, payload: UdpXml { @@ -116,10 +262,10 @@ impl UdpTransmit { BcUdp::Ack(UdpAck { connection_id, packet_id, - .. + payload, }) if connection_id == discovery_result.client_id => { - self.camera_acknowledged - .fetch_max(packet_id, Ordering::Acquire); + self.client_sent + .acknoledge_from_ack_data(packet_id, payload); } BcUdp::Ack(UdpAck { .. }) => { debug!("Got a UdpAck for another client id"); @@ -131,18 +277,10 @@ impl UdpTransmit { }) if cid == discovery_result.client_id => { // Seperated as let/if due to clippy recommend trace!("Recieving UdpData packet {}", packet_id); - let updated = self - .client_wants - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| { - if v == packet_id { - Some(v + 1) - } else { - None - } - }) - .is_ok(); - if updated { - send_to_incoming.send(payload)?; + self.client_recieved.receive(packet_id, payload); + + for next_payload in self.client_recieved.consume().drain(..) { + send_to_incoming.send(next_payload)?; } } BcUdp::Data(UdpData { .. }) => { @@ -166,28 +304,19 @@ impl UdpTransmit { socket: &UdpSocket, discovery_result: &UdpDiscover, get_from_outgoing: &Receiver>, - outgoing_history: &mut HashMap>, ) -> Result<()> { // Handle Retransmit - let camera_has = self.camera_acknowledged.load(Ordering::Relaxed); - let client_sent = self.client_sent.load(Ordering::Relaxed); - if camera_has < client_sent { - debug!("Resending {:?}", (camera_has + 1)..(client_sent + 1)); - for packet_id in (camera_has + 1)..(client_sent + 1) { - if let Some(payload) = &outgoing_history.get(&packet_id) { - debug!(" - Sending {}", packet_id); - socket - .send(payload) - .map_err(|e| TransmitError::SocketSend { err: e })?; - } - std::thread::sleep(SOCKET_WAIT_TIME); - } + for (_, payload) in self.client_sent.lock().needs_resend() { + socket + .send(payload) + .map_err(|e| TransmitError::SocketSend { err: e })?; + std::thread::sleep(SOCKET_WAIT_TIME); } // Handle recv from `send_to_incoming` and send to `socket` match get_from_outgoing.try_recv() { Ok(payload) => { - let packet_id = self.client_sent.fetch_add(1, Ordering::Relaxed); + let packet_id = self.client_sent.get_next_packet_id(); let bcudp_msg = BcUdp::Data(UdpData { connection_id: discovery_result.camera_id, packet_id, @@ -199,18 +328,19 @@ impl UdpTransmit { socket .send(&buf) .map_err(|e| TransmitError::SocketSend { err: e })?; - outgoing_history.insert(packet_id, buf); + self.client_sent.register_payload(packet_id, buf); } Err(TryRecvError::Empty) => {} Err(e) => return Err(e.into()), } // Handle acknoledgment - let client_wants = self.client_wants.load(Ordering::Relaxed); - if client_wants > 0 { + let client_wants = self.client_recieved.get_needed_packets(); + if let Some((client_wants, also_wants)) = client_wants { let bcack_msg = BcUdp::Ack(UdpAck { connection_id: discovery_result.camera_id, packet_id: client_wants, + payload: also_wants, }); let mut buf = vec![]; @@ -219,6 +349,8 @@ impl UdpTransmit { .send(&buf) .map_err(|e| TransmitError::SocketSend { err: e })?; } + + std::thread::sleep(SOCKET_WAIT_TIME); Ok(()) } } diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index 9a52c08..d4c2802 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -139,15 +139,21 @@ fn udp_ack(buf: &[u8]) -> IResult<&[u8], UdpAck> { // packets to let (buf, _unknown) = le_u32(buf)?; let (buf, payload_size) = le_u32(buf)?; - let (buf, _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 - // since last contigious packet_id up - // to the last packet we sent and it recieved + 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 + // since last contigious packet_id up + // to the last packet we sent and it recieved + (buf, t_payload.to_vec()) + } else { + (buf, vec![]) + }; let data = UdpAck { connection_id, packet_id, + payload, }; Ok((buf, data)) } @@ -303,6 +309,7 @@ mod tests { Ok(BcUdp::Ack(UdpAck { connection_id: 80, packet_id: 2439, + .. })) ); } diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index 39de3be..712475a 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -56,7 +56,11 @@ pub struct UdpAck { // 2 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` // Unknown but seems to change randomly every second // 2 Bytes size of a payload - // Payload of `00 01 01 01 01` where `01` is added after every repeat + // + /// Payload of `00 01 01 01 01` where `01` is added after every repeat + /// + /// This is a truth table of packets after `packet_id` that have not been recieved + pub payload: Vec, } /// Magic for the UDP Data packet diff --git a/crates/core/src/bcudp/ser.rs b/crates/core/src/bcudp/ser.rs index b64d2fe..e9071f7 100644 --- a/crates/core/src/bcudp/ser.rs +++ b/crates/core/src/bcudp/ser.rs @@ -22,7 +22,10 @@ impl BcUdp { let xml_payload = encrypt(payload.tid, &payload.payload.serialize(vec![]).unwrap()); gen(bcudp_disc(payload, &xml_payload), buf)? } - BcUdp::Ack(payload) => gen(bcudp_ack(payload), buf)?, + BcUdp::Ack(payload) => { + let binary_payload = &payload.payload; + gen(bcudp_ack(payload, binary_payload), buf)? + } BcUdp::Data(payload) => { let binary_payload = &payload.payload; gen(bcudp_data(payload, binary_payload), buf)? @@ -48,7 +51,10 @@ fn bcudp_disc<'a, W: 'a + Write>( )) } -fn bcudp_ack<'a, W: 'a + Write>(payload: &'a UdpAck) -> impl SerializeFn + 'a { +fn bcudp_ack<'a, W: 'a + Write>( + payload: &'a UdpAck, + binary_payload: &'a [u8], +) -> impl SerializeFn + 'a { tuple(( le_u32(MAGIC_HEADER_UDP_ACK), le_i32(payload.connection_id), @@ -56,7 +62,8 @@ fn bcudp_ack<'a, W: 'a + Write>(payload: &'a UdpAck) -> impl SerializeFn + 'a le_u32(0), le_u32(payload.packet_id), le_u32(0), - le_u32(0), + le_u32(binary_payload.len() as u32), + slice(binary_payload), )) } From 08d174a89dba667dbf4c2bb3851480212c44a0f3 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 24 Aug 2021 09:36:11 +0700 Subject: [PATCH 34/56] Fix to the more complex udp ack --- .../connection/udpconn/transmit.rs | 6 +++--- dissector/udp.md | 21 +++++-------------- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs index f3e49a4..2b3d19e 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -102,7 +102,7 @@ impl ClientSent { locked.retain(|&k, _| k > start); for (idx, &value) in payload.iter().enumerate() { - let packet_id = start + idx as u32; + let packet_id = (start + 1) + idx as u32; if value > 0 { locked.remove(&packet_id); } @@ -192,9 +192,9 @@ impl ClientRecieved { let mut vec = vec![]; for i in (start + 1)..(end + 1) { if locked.contains_key(&i) { - vec.push(0) - } else { vec.push(1) + } else { + vec.push(0) } } vec diff --git a/dissector/udp.md b/dissector/udp.md index e2dc814..ce0ca93 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -261,17 +261,12 @@ These messages are sent to acknowledge receipt of message. They are header only. - 4 Bytes unknown: Always `00000000` for for UDP Ack - 4 Bytes Last Packet ID: Last received packet id - 4 Bytes Unknown: Observed values `00000000`, `d6010000`, `d7160000` `09e00000` **NEEDS INFO** -- Payload Size: **NEEDS INFO** -- Paload **NEEDS INFO** +- Payload Size +- Paload **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 - - Payload size is usually 0 but occasionally it is non zero - - When this happens the payload becomes `00 01 01 01 01 01` always the first - byte `00` then just `01`/`00` bytes - - This payload then increases in size by `01` each ack packet until a new - udpdata packet arrives. At which point the `Last received packet id` jumps Here's an example of a UDP Ack payload (size 203 bytes) @@ -291,19 +286,13 @@ Here's an example of a UDP Ack payload (size 203 bytes) 00c0 01 01 01 01 01 01 01 01 01 01 01 01 ``` -I believe this is a truth table of false/true for missing packets - -In this example the last packet sent was number 221 but the camera only -acknowledged number 14 and sent this binary too and the unknown -value was `f8010000` (504). +The payload is a truth table. If the packet ID in header is 50 +then the first byte corresponds to packet id 51, the second 52 +etc etc. If the byte if `00` then the camera will resend that packet If this payload is allowed to grow to ~ 205 bytes the camera sends a disconnect request and drops the connection -I believe that the `Bytes Last Packet ID` in the header is the number of -contiguous packets then the payload represents a table of non contiguous -packets it wants - # UDP Data From af1e52b850af0e9221a0fb06428c38a6d8abb764 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 24 Aug 2021 10:04:25 +0700 Subject: [PATCH 35/56] Send UDP disconnect when UDP is finished --- .../connection/udpconn/discover.rs | 23 +++++++++++++++++++ .../src/bc_protocol/connection/udpconn/mod.rs | 2 ++ .../connection/udpconn/transmit.rs | 18 +-------------- dissector/udp.md | 2 +- 4 files changed, 27 insertions(+), 18 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs index 8e259a4..8a57951 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/discover.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -517,4 +517,27 @@ impl UdpDiscover { Err(e) => Err(e), } } + + pub fn send_client_disconnect(&self, socket: &UdpSocket) { + if let Ok(addr) = socket.peer_addr() { + let mut rng = thread_rng(); + let tid: u32 = (rng.gen::()) as u32; + let bcudp_msg = BcUdp::Discovery(UdpDiscovery { + tid, + payload: UdpXml { + c2d_disc: Some(C2dDisc { + cid: self.client_id, + did: self.camera_id, + }), + ..Default::default() + }, + }); + + let mut buf = vec![]; + let buf = bcudp_msg + .serialize(&mut buf) + .expect("Unable to serliaze udp disconnect"); + let _ = Self::retrying_send_to(socket, buf, addr); + } + } } diff --git a/crates/core/src/bc_protocol/connection/udpconn/mod.rs b/crates/core/src/bc_protocol/connection/udpconn/mod.rs index b3f33b6..6de04fd 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/mod.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/mod.rs @@ -131,6 +131,8 @@ impl UdpSource { } } error!("Udp read poll aborted"); + // We send client disconnect here + thread_discovery_result.send_client_disconnect(&thread_socket); }); let thread_aborter = aborter.clone(); diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs index 2b3d19e..7aa801a 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -227,7 +227,6 @@ impl UdpTransmit { let bcudp_msg = BcUdp::deserialize(&buf[0..amount_recv])?; match bcudp_msg { BcUdp::Discovery(UdpDiscovery { - tid, payload: UdpXml { d2c_disc: Some(D2cDisc { cid, did }), @@ -238,22 +237,7 @@ impl UdpTransmit { && did == discovery_result.camera_id => { // Reply with C2D_Disc and end - let bcudp_msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2d_disc: Some(C2dDisc { - cid: discovery_result.client_id, - did: discovery_result.camera_id, - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - bcudp_msg.serialize(&mut buf)?; - socket - .send(&buf) - .map_err(|e| TransmitError::SocketSend { err: e })?; + discovery_result.send_client_disconnect(socket); return Err(TransmitError::Disc); } BcUdp::Discovery(packet) => { diff --git a/dissector/udp.md b/dissector/udp.md index ce0ca93..519aef1 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -120,7 +120,7 @@ standard tcp bc connection **Udp Camera** -If the camera supports UDP the client will send this xml packet +If the camera supports UDP the client will send the following xml packet as a broadcast on 255.255.255.255 on port 2018/2015 **Known UID** From 7ab46e4273d51c88ef2dce57987dabfa9b4af7d8 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 31 Aug 2021 20:55:12 +0700 Subject: [PATCH 36/56] Clean up files --- Cargo.lock | 87 +- .../src/bc_protocol/connection/_udpconn.rs | 926 ------------------ 2 files changed, 75 insertions(+), 938 deletions(-) delete mode 100644 crates/core/src/bc_protocol/connection/_udpconn.rs diff --git a/Cargo.lock b/Cargo.lock index 2b413d8..1933e7b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -48,7 +48,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" dependencies = [ - "winapi", + "winapi 0.3.9", ] [[package]] @@ -77,7 +77,7 @@ checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi", "libc", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -122,6 +122,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c1bf4a04a88c54f589125563643d773f3254b5c38571395e2b591c693bbc81" +[[package]] +name = "c_linked_list" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4964518bd3b4a8190e832886cdc0da9794f12e8e6c1613a9e90ff331c4c8724b" + [[package]] name = "cfb-mode" version = "0.6.0" @@ -195,11 +201,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" dependencies = [ "cfg-if 0.1.10", - "crossbeam-channel", + "crossbeam-channel 0.4.4", "crossbeam-deque", "crossbeam-epoch", "crossbeam-queue", - "crossbeam-utils", + "crossbeam-utils 0.7.2", ] [[package]] @@ -208,10 +214,20 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" dependencies = [ - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-utils 0.8.5", +] + [[package]] name = "crossbeam-deque" version = "0.7.4" @@ -219,7 +235,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" dependencies = [ "crossbeam-epoch", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -231,7 +247,7 @@ checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" dependencies = [ "autocfg", "cfg-if 0.1.10", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "lazy_static", "maybe-uninit", "memoffset", @@ -245,7 +261,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" dependencies = [ "cfg-if 0.1.10", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -260,6 +276,16 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" +dependencies = [ + "cfg-if 1.0.0", + "lazy_static", +] + [[package]] name = "discard" version = "1.0.4" @@ -373,6 +399,12 @@ dependencies = [ "slab", ] +[[package]] +name = "gcc" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" + [[package]] name = "generic-array" version = "0.14.4" @@ -383,6 +415,28 @@ dependencies = [ "version_check", ] +[[package]] +name = "get_if_addrs" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abddb55a898d32925f3148bd281174a68eeb68bbfd9a5938a57b18f506ee4ef7" +dependencies = [ + "c_linked_list", + "get_if_addrs-sys", + "libc", + "winapi 0.2.8", +] + +[[package]] +name = "get_if_addrs-sys" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d04f9fb746cf36b191c00f3ede8bde9c8e64f9f4b05ae2694a9ccf5e3f5ab48" +dependencies = [ + "gcc", + "libc", +] + [[package]] name = "getrandom" version = "0.2.3" @@ -421,7 +475,7 @@ dependencies = [ "gobject-sys", "libc", "system-deps", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -886,9 +940,12 @@ dependencies = [ "assert_matches", "cfb-mode", "cookie-factory", + "crossbeam-channel 0.5.1", "env_logger", "err-derive", + "get_if_addrs", "indoc", + "lazy_static", "log", "md5", "nom", @@ -1218,7 +1275,7 @@ checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" dependencies = [ "cfg-if 1.0.0", "libc", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -1430,7 +1487,7 @@ dependencies = [ "stdweb", "time-macros", "version_check", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -1648,6 +1705,12 @@ version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + [[package]] name = "winapi" version = "0.3.9" @@ -1670,7 +1733,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ - "winapi", + "winapi 0.3.9", ] [[package]] diff --git a/crates/core/src/bc_protocol/connection/_udpconn.rs b/crates/core/src/bc_protocol/connection/_udpconn.rs deleted file mode 100644 index 8f3db4e..0000000 --- a/crates/core/src/bc_protocol/connection/_udpconn.rs +++ /dev/null @@ -1,926 +0,0 @@ -use super::{BcSubscription, Error, Result}; -use crate::bc; -use crate::bc::model::*; -use crate::bcudp; -use crate::bcudp::{model::*, xml::*}; -use crate::RX_TIMEOUT; -use crossbeam_channel::{ - unbounded, Receiver, RecvError, RecvTimeoutError, SendError, SendTimeoutError, Sender, -}; -use lazy_static::lazy_static; -use log::*; -use rand::{seq::SliceRandom, thread_rng, Rng}; -use socket2::{Domain, Socket, Type}; -use std::collections::btree_map::Entry; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::error::Error as StdErr; // Just need the traits -use std::io::{BufRead, Error as IoError, Read, Write}; -use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket}; -use std::sync::{ - atomic::{AtomicBool, AtomicU32, Ordering}, - Arc, Mutex, -}; -use std::thread::JoinHandle; -use std::time::Duration; -use time::OffsetDateTime; - -type IoResult = std::result::Result; - -const WAIT_TIME: Duration = Duration::from_millis(500); - -// TODO: Path MTU discovery -const MTU: u32 = 1350; - -lazy_static! { - static ref P2P_RELAY_HOSTNAMES: [&'static str; 10] = [ - "p2p.reolink.com", - "p2p1.reolink.com", - "p2p2.reolink.com", - "p2p3.reolink.com", - "p2p14.reolink.com", - "p2p15.reolink.com", - "p2p6.reolink.com", - "p2p7.reolink.com", - "p2p8.reolink.com", - "p2p9.reolink.com", - ]; -} - -pub struct UdpSource { - socket: UdpSocket, - address: SocketAddr, - client_id: i32, - camera_id: i32, - mtu: u32, - - camera_acknowledged: Arc, - client_sent: Arc, - client_wants: Arc, - unacknowledged: Arc>>>, - aborter: AbortHandle, - // Buffered because a single read might not read a whole packet - read_buffer: Buffered, - write_buffer: Buffered, -} - -#[derive(Default, Clone)] -struct Buffered { - buffer: Vec, - consumed: usize, -} - -struct DiscoveryResult { - socket: UdpSocket, - address: SocketAddr, - client_id: i32, - camera_id: i32, - mtu: u32, -} - -#[derive(Clone)] -struct AbortHandle { - aborted: Arc, -} - -impl AbortHandle { - fn new() -> Self { - Self { - aborted: Arc::new(AtomicBool::new(false)), - } - } - - fn abort(&self) { - self.aborted.store(true, Ordering::Relaxed); - } - - fn is_aborted(&self) -> bool { - self.aborted.load(Ordering::Relaxed) - } -} - -impl UdpSource { - fn get_socket(_timeout: Duration) -> Result { - // Select a random port to bind to - let mut ports: Vec = (53500..54000).into_iter().collect(); - let mut rng = thread_rng(); - ports.shuffle(&mut rng); - - let addrs: Vec<_> = ports - .iter() - .map(|&port| SocketAddr::from(([0, 0, 0, 0], port))) - .collect(); - let socket = UdpSocket::bind(&addrs[..])?; - socket.set_read_timeout(Some(timeout))?; - socket.set_write_timeout(Some(timeout))?; - // socket.set_nonblocking(true)?; - socket.set_broadcast(true)?; - Ok(socket) - } - - fn retrying_send_to( - socket: &UdpSocket, - buf: &[u8], - addr: T, - ) -> IoResult<(usize, AbortHandle)> { - let addr = addr.to_socket_addrs()?.next().ok_or_else(|| { - IoError::new(std::io::ErrorKind::NotFound, Error::ConnectionUnavaliable) - })?; - Self::retrying_send_to_multi(socket, buf, &[addr]) - } - - fn retrying_send_to_multi( - socket: &UdpSocket, - buf: &[u8], - addrs: &[T], - ) -> IoResult<(usize, AbortHandle)> { - let handle = AbortHandle::new(); - - let addrs: Vec = addrs - .iter() - .map(|a| { - a.to_socket_addrs() - .ok() - .and_then(|mut a_iter| a_iter.next()) - }) - .flatten() - .collect(); - - let mut bytes_send = 0; - for addr in addrs.iter() { - bytes_send = socket.send_to(buf, &addr)?; - } - - let thread_buffer = buf.to_vec(); - let thread_handle = handle.clone(); - let thread_socket = socket.try_clone()?; - let thread_addr: Vec = addrs; - - const MAX_RETRIES: usize = 10; - - std::thread::spawn(move || { - std::thread::sleep(WAIT_TIME); - for _ in 0..MAX_RETRIES { - if thread_handle.is_aborted() { - break; - } - for addr in thread_addr.iter() { - let _ = thread_socket.send_to(&thread_buffer[..], &addr); - } - std::thread::sleep(WAIT_TIME); - } - }); - - Ok((bytes_send, handle)) - } - - fn discover_from_uuid_local( - uid: &str, - socket: &UdpSocket, - timeout: Duration, - ) -> Result { - let mut rng = thread_rng(); - // If tid is too large it will overflow during encrypt so we just use a random u8 - let tid: u32 = (rng.gen::()) as u32; - let client_id: i32 = rng.gen(); - let local_addr = socket.local_addr()?; - let port = local_addr.port(); - - let mtu = MTU; - - let msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2d_c: Some(C2dC { - uid: uid.to_string(), - cli: ClientList { port: port as u32 }, - cid: client_id, - mtu, - debug: false, - os: "MAC".to_string(), - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - msg.serialize(&mut buf)?; - - let (amount_sent, abort) = Self::retrying_send_to_multi( - socket, - &buf[..], - &["255.255.255.255:2015", "255.255.255.255:2018"], - )?; - assert_eq!(amount_sent, buf.len()); - - let start_time = OffsetDateTime::now_utc(); - let camera_address; - let camera_id; - loop { - if (OffsetDateTime::now_utc() - start_time) <= timeout { - let mut buf = vec![0; mtu as usize]; - if let Ok((bytes_read, socket_addr)) = socket.recv_from(&mut buf) { - match BcUdp::deserialize(&buf[0..bytes_read]) { - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - d2c_c_r: Some(D2cCr { did, cid, .. }), - .. - }, - })) if cid == client_id => { - abort.abort(); - camera_address = socket_addr; - camera_id = did; - break; - } - Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), - Err(_) => debug!( - "Udp Discovery got this unexpected binary: {:?}", - &buf[0..bytes_read] - ), - } - } - } else { - abort.abort(); - return Err(Error::Timeout); - } - } - - // Ensure we didn't forget to abort the sending - abort.abort(); - // Actual connection time! - socket.connect(camera_address)?; - - Ok(DiscoveryResult { - socket: socket.try_clone()?, - address: camera_address, - client_id, - camera_id, - mtu, - }) - } - - fn get_register( - uid: &str, - socket: &UdpSocket, - timeout: Duration, - tid: u32, - // client_id: u32, - ) -> Result { - // let local_addr = socket.local_addr()?; - // let local_port = local_addr.port(); - - let mtu = MTU; - - for p2p_relay in P2P_RELAY_HOSTNAMES.iter() { - debug!("Trying register: {}", p2p_relay); - let msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2m_q: Some(C2mQ { - uid: uid.to_string(), - os: "MAC".to_string(), - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - msg.serialize(&mut buf)?; - - let (amount_sent, abort) = - Self::retrying_send_to(socket, &buf[..], format!("{}:9999", p2p_relay))?; - assert_eq!(amount_sent, buf.len()); - - let start_time = OffsetDateTime::now_utc(); - loop { - if (OffsetDateTime::now_utc() - start_time) <= timeout { - let mut buf = vec![0; mtu as usize]; - if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { - match BcUdp::deserialize(&buf[0..bytes_read]) { - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - m2c_q_r: Some(m2c_q_r), - .. - }, - })) if m2c_q_r.reg.port == 0 || m2c_q_r.reg.ip.is_empty() => { - // This register is empty - abort.abort(); - break; - } - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - m2c_q_r: Some(m2c_q_r), - .. - }, - })) => { - abort.abort(); - return Ok(m2c_q_r); - } - Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), - Err(_) => debug!( - "Udp Discovery got this unexpected binary: {:?}", - &buf[0..bytes_read] - ), - } - } - } else { - abort.abort(); - // This p2p server didn't have the data we need try another - break; - } - } - } - debug!("All registers tried"); - Err(Error::ConnectionUnavaliable) - } - - fn discover_from_uuid_remote( - uid: &str, - socket: &UdpSocket, - timeout: Duration, - ) -> Result { - let local_addr = socket.local_addr()?; - let local_port = local_addr.port(); - - let mut rng = thread_rng(); - // If tid is too large it will overflow during encrypt so we just use a random u8 - let tid: u32 = (rng.gen::()) as u32; - let mtu = MTU; - let client_id: i32 = rng.gen(); - - let m2c_q_r = Self::get_register(uid, socket, timeout, tid)?; - - debug!("Got this information from the register: {:?}", m2c_q_r); - - let register_address = m2c_q_r.reg; - let relay_address = m2c_q_r.relay; - let log_address = m2c_q_r.log; - // let device_address = m2c_q_r.t; - - debug!("Register address found: {:?}", register_address); - debug!("Registering this address: {:?}", local_addr); - - let local_family = if local_addr.ip().is_ipv4() { 4 } else { 6 }; - let msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2r_c: Some(C2rC { - uid: uid.to_string(), - cli: IpPort { - ip: local_addr.ip().to_string(), - port: local_port, - }, - relay: relay_address, - cid: client_id, - family: local_family, - debug: false, - os: "MAC".to_string(), - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - msg.serialize(&mut buf)?; - - let (amount_sent, abort) = Self::retrying_send_to( - socket, - &buf[..], - format!("{}:{}", register_address.ip, register_address.port), - )?; - assert_eq!(amount_sent, buf.len()); - - let device_sid; - let dev_loc; - let start_time = OffsetDateTime::now_utc(); - loop { - if (OffsetDateTime::now_utc() - start_time) <= timeout { - let mut buf = vec![0; mtu as usize]; - if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { - match BcUdp::deserialize(&buf[0..bytes_read]) { - // Got camera data from register - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - r2c_t: Some(R2cT { dev, cid, sid, .. }), - .. - }, - })) if cid == client_id => { - abort.abort(); - // Make a local request to the camera with the dev info - device_sid = sid; - dev_loc = dev; - break; - } - Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), - Err(_) => debug!( - "Udp Discovery got this unexpected binary: {:?}", - &buf[0..bytes_read] - ), - } - } - } else { - abort.abort(); - return Err(Error::Timeout); - } - } - - debug!("Register revealed address as SID: {:?}", device_sid); - debug!("Register revealed address as IP: {:?}", dev_loc); - - // ensure abort - abort.abort(); - - let msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2d_t: Some(C2dT { - sid: device_sid, - cid: client_id, - mtu, - conn: "local".to_string(), - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - msg.serialize(&mut buf)?; - - let (amount_sent, abort) = - Self::retrying_send_to(socket, &buf[..], format!("{}:{}", dev_loc.ip, dev_loc.port))?; - assert_eq!(amount_sent, buf.len()); - - let device_id; - let start_time = OffsetDateTime::now_utc(); - loop { - if (OffsetDateTime::now_utc() - start_time) <= timeout { - let mut buf = vec![0; mtu as usize]; - if let Ok((bytes_read, _)) = socket.recv_from(&mut buf) { - match BcUdp::deserialize(&buf[0..bytes_read]) { - // Got camera data from camera - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - d2c_t: Some(D2cT { cid, did, .. }), - .. - }, - })) if cid == client_id => { - device_id = did; - break; - } - // Got camera data from camera CFM - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - d2c_cfm: Some(D2cCfm { cid, did, .. }), - .. - }, - })) if cid == client_id => { - device_id = did; - break; - } - // Got camera data from camera disc - Ok(BcUdp::Discovery(UdpDiscovery { - tid: _, - payload: - UdpXml { - d2c_disc: Some(D2cDisc { cid, did, .. }), - .. - }, - })) if cid == client_id => { - device_id = did; - break; - } - Ok(smt) => debug!("Udp Discovery got this unexpected BcUdp {:?}", smt), - Err(_) => debug!( - "Udp Discovery got this unexpected binary: {:?}", - &buf[0..bytes_read] - ), - } - } - } else { - abort.abort(); - return Err(Error::Timeout); - } - } - - debug!("Got device ID as: {:?}", device_id); - - // Ensure aborted - abort.abort(); - - // Announce to the log that we will connect locally - let msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2r_cfm: Some(C2rCfm { - sid: device_sid, - cid: client_id, - did: device_id, - conn: "local".to_string(), - rsp: 0, - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - msg.serialize(&mut buf)?; - - // Just let this retry to max limit as we don't get a reply - let (amount_sent, _) = Self::retrying_send_to( - socket, - &buf[..], - format!("{}:{}", log_address.ip, log_address.port), - )?; - assert_eq!(amount_sent, buf.len()); - - // Announce a map type connection (I think this means we could connect remotely) - let msg = BcUdp::Discovery(UdpDiscovery { - tid, - payload: UdpXml { - c2d_t: Some(C2dT { - sid: device_sid, - cid: client_id, - mtu, - conn: "map".to_string(), - }), - ..Default::default() - }, - }); - - let mut buf = vec![]; - msg.serialize(&mut buf)?; - - // Just let this retry to max limit as we don't get a reply - let (amount_sent, _) = - Self::retrying_send_to(socket, &buf[..], format!("{}:{}", dev_loc.ip, dev_loc.port))?; - assert_eq!(amount_sent, buf.len()); - - let camera_address: SocketAddr = format!("{}:{}", dev_loc.ip, dev_loc.port) - .to_socket_addrs()? - .next() - .ok_or(Error::ConnectionUnavaliable)?; - - socket.connect(camera_address)?; - - Ok(DiscoveryResult { - socket: socket.try_clone()?, - address: camera_address, - client_id, - camera_id: device_id, - mtu, - }) - } - - fn discover_from_uuid( - uid: &str, - timeout: Duration, - allow_remote: bool, - ) -> Result { - let socket = Self::get_socket(timeout)?; - match Self::discover_from_uuid_local(uid, &socket, timeout) { - Err(Error::Timeout) if allow_remote => { - Self::discover_from_uuid_remote(uid, &socket, timeout) - } - Ok(result) => Ok(result), - Err(e) => Err(e), - } - } - - /// It is possible to contact the reolink servers using udp to - /// learn the ip and port of the camera. By default I have turned - /// this feature off with no way to enable it from the usual - /// command line interface or config. - /// - /// However it may prove neccesary one day to use it so it is here in the - /// library and other programs may want to use it. - pub fn new_allow_remote(uid: &str, timeout: Duration) -> Result { - Self::new_with_remote(uid, timeout, true) - } - - pub fn new(uid: &str, timeout: Duration) -> Result { - Self::new_with_remote(uid, timeout, true) - } - - fn new_with_remote(uid: &str, timeout: Duration, allow_remote: bool) -> Result { - let discovery_result = Self::discover_from_uuid(uid, timeout, allow_remote)?; - info!("UID {:?} found at {:?}", uid, discovery_result.address); - - let (to_outgoing, outgoing) = unbounded(); - let (incoming, from_incoming) = unbounded(); - let me = UdpSource { - socket: discovery_result.socket, - address: discovery_result.address, - client_id: discovery_result.client_id, - camera_id: discovery_result.camera_id, - mtu: discovery_result.mtu, - incoming: from_incoming, - outgoing: to_outgoing, - camera_acknowledged: Default::default(), - unacknowledged: Default::default(), - client_sent: Default::default(), - client_wants: Default::default(), - aborter: AbortHandle::new(), - read_buffer: Default::default(), - write_buffer: Default::default(), - }; - - me.start_polling(outgoing, incoming)?; - - Ok(me) - } - - pub fn try_clone(&self) -> IoResult { - Ok(Self { - socket: self.socket.try_clone()?, - address: self.address, - client_id: self.client_id, - camera_id: self.camera_id, - mtu: self.mtu, - incoming: self.incoming.clone(), - outgoing: self.outgoing.clone(), - aborter: self.aborter.clone(), - camera_acknowledged: self.camera_acknowledged.clone(), - unacknowledged: self.unacknowledged.clone(), - client_sent: self.client_sent.clone(), - client_wants: self.client_wants.clone(), - // These are not shared mutable so they don't pollute each other buffer - read_buffer: Default::default(), - write_buffer: Default::default(), - }) - } - - fn start_polling( - &self, - outgoing: Receiver>, - incoming: Sender>, - ) -> IoResult<()> { - Ok(()) - } - - fn start_polling_outgoing(&self, outgoing: Receiver>) -> IoResult<()> { - let thread_socket = self.socket.try_clone()?; - let thread_aborter = self.aborter.clone(); - let thread_camera_id = self.camera_id; - let thread_client_sent = self.client_sent.clone(); - - std::thread::spawn(move || { - while !thread_aborter.is_aborted() { - match outgoing.recv_timeout(RX_TIMEOUT) { - Ok(msg) => { - let packet_id = thread_client_sent.fetch_add(1, Ordering::Relaxed); - let bcudp_msg = BcUdp::Data(UdpData { - connection_id: thread_camera_id, - packet_id, - payload: msg, - }); - - let mut buf = vec![]; - if let Err(e) = bcudp_msg.serialize(&mut buf) { - error!("Failed to serialize bcudp: {:?}, Err: {:?}", bcudp_msg, e); - thread_aborter.abort(); - break; - } - - if let Err(e) = thread_socket.send(&buf) { - error!("Failed to send udp data: {:?}, Err: {:?}", bcudp_msg, e); - thread_aborter.abort(); - break; - } - } - Err(RecvTimeoutError::Timeout) => {} - Err(RecvTimeoutError::Disconnected) => { - break; - } - } - } - }); - Ok(()) - } - - fn start_polling_ack(&self) -> IoResult<()> { - let thread_socket = self.socket.try_clone()?; - let thread_aborter = self.aborter.clone(); - let thread_unacknowledged = self.unacknowledged.clone(); - std::thread::spawn(move || while !thread_aborter.is_aborted() {}); - Ok(()) - } - - fn start_polling_incoming(&self, incoming: Sender>) -> IoResult<()> { - let mut thread_socket = self.socket.try_clone()?; - let thread_aborter = self.aborter.clone(); - let thread_mtu = self.mtu; - let thread_camera_acknowledged = self.camera_acknowledged.clone(); - let thread_client_wants = self.client_wants.clone(); - let thread_client_id = self.client_id; - let thread_camera_id = self.camera_id; - - std::thread::spawn(move || { - while !thread_aborter.is_aborted() { - let mut buf = vec![0; thread_mtu as usize]; - if let Ok(new_size) = thread_socket.recv(&mut buf) { - match BcUdp::deserialize(&buf[0..new_size]) { - Ok(bcudp_msg) => { - match bcudp_msg { - BcUdp::Discovery(UdpDiscovery { - payload: - UdpXml { - d2c_disc: Some(D2cDisc { cid, did }), - .. - }, - .. - }) if cid == thread_client_id && did == thread_camera_id => { - thread_aborter.abort(); - debug!("Client requested disconnect") - } - BcUdp::Discovery(packet) => { - debug!("Got unexpected discovery packet: {:?}", packet) - } - BcUdp::Ack(UdpAck { - connection_id, - packet_id, - }) if connection_id == thread_client_id => { - thread_camera_acknowledged - .fetch_max(packet_id, Ordering::Acquire); - } - BcUdp::Data(UdpData { - connection_id: cid, - packet_id, - payload, - }) if cid == thread_client_id => { - if let Ok(_) = thread_client_wants.fetch_update( - Ordering::SeqCst, - Ordering::SeqCst, - |v| { - if v == packet_id { - Some(v + 1) - } else { - None - } - }, - ) { - match incoming.send(payload) { - Ok(msg) => {} - Err(_) => { - error!("Failed to get payload from UDP"); - thread_aborter.abort(); - break; - } - } - } - } - }; - } - Err(e) => { - error!("Cannot deser UDP msg: {:?}", e); - thread_aborter.abort(); - break; - } - } - } - } - }); - - Ok(()) - } - - fn stop_polling(&self) { - self.aborter.abort(); - } -} - -// Ensuring polling stops -impl Drop for UdpSource { - fn drop(&mut self) { - self.stop_polling(); - } -} - -impl Read for UdpSource { - fn read(&mut self, buf: &mut [u8]) -> IoResult { - if self.aborter.is_aborted() { - return Err(IoError::new( - std::io::ErrorKind::ConnectionAborted, - "Connection dropped", - )); - } - let buffer = self.fill_buf()?; - let amt = std::cmp::min(buf.len(), buffer.len()); - - // First check if the amount of bytes we want to read is small: - // `copy_from_slice` will generally expand to a call to `memcpy`, and - // for a single byte the overhead is significant. - if amt == 1 { - buf[0] = buffer[0]; - } else { - buf[..amt].copy_from_slice(&buffer[..amt]); - } - - self.consume(amt); - - Ok(amt) - } -} - -impl BufRead for UdpSource { - fn fill_buf(&mut self) -> IoResult<&[u8]> { - // const CLEAR_CONSUMED_AT: usize = 1024; - // // This is a trade off between caching too much dead memory - // // and calling the drain method too often - // if self.read_buffer.consumed > CLEAR_CONSUMED_AT { - // let _ = self - // .read_buffer - // .buffer - // .drain(0..self.read_buffer.consumed) - // .collect::>(); - // self.read_buffer.consumed = 0; - // } - // if self.read_buffer.buffer.len() <= self.read_buffer.consumed { - // // Get next packet of the read queue - // let start_time = OffsetDateTime::now_utc(); - // while (start_time - OffsetDateTime::now_utc()) < RX_TIMEOUT { - // let mut lock = self.incoming.lock().unwrap(); - // if (*lock).contains_key(&self.next_to_consume.load(Ordering::Relaxed)) { - // let next = self.next_to_consume.fetch_add(1, Ordering::Relaxed); - // debug!("Removing: {}", next); - // if let Some(msg) = lock.remove(&next) { - // self.read_buffer.buffer.extend(msg.buf); - // break; - // } - // } - // } - // } - // - // Ok(&self.read_buffer.buffer.as_slice()[self.read_buffer.consumed..]) - } - - fn consume(&mut self, amt: usize) { - assert!(self.read_buffer.consumed + amt <= self.read_buffer.buffer.len()); - self.read_buffer.consumed += amt; - } -} - -const UDPDATA_HEADER_SIZE: usize = 20; -impl Write for UdpSource { - fn write(&mut self, buf: &[u8]) -> IoResult { - // if self.aborter.is_aborted() { - // return Err(IoError::new( - // std::io::ErrorKind::ConnectionAborted, - // "Connection dropped", - // )); - // } - // self.write_buffer.buffer.extend(buf.to_vec()); - // if self.write_buffer.buffer.len() > self.mtu as usize - UDPDATA_HEADER_SIZE { - // let _ = self.flush(); - // } - // Ok(buf.len()) - } - - fn flush(&mut self) -> IoResult<()> { - // if self.aborter.is_aborted() { - // return Err(IoError::new( - // std::io::ErrorKind::ConnectionAborted, - // "Connection dropped", - // )); - // } - // for chunk in self - // .write_buffer - // .buffer - // .chunks(self.mtu as usize - UDPDATA_HEADER_SIZE) - // { - // let packet_id = self.next_send_message.fetch_add(1, Ordering::Relaxed); - // let msg = BcUdp::Data(UdpData { - // connection_id: self.camera_id, - // packet_id, - // payload: chunk.to_vec(), - // }); - // let mut buf = vec![]; - // // If this errors it is unrecoverable - // // - // // It really shouldn't be able to Err though - // msg.serialize(&mut buf) - // .expect("Failed to serialize UDP Data"); - // debug!("Writing"); - // self.outgoing.lock().unwrap().insert( - // packet_id, - // QueuedMessage { - // time_last_tried: None, - // buf, - // }, - // ); - // } - // self.write_buffer.buffer.clear(); - // Ok(()) - } -} From 2dcb807b7432d1e272d9e78349bbebcc7539d787 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 31 Aug 2021 20:56:50 +0700 Subject: [PATCH 37/56] Update lock file --- Cargo.lock | 170 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 149 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f984fd5..6d7dc65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -35,9 +35,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "0.7.15" +version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" dependencies = [ "memchr", ] @@ -48,7 +48,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" dependencies = [ - "winapi", + "winapi 0.3.9", ] [[package]] @@ -77,7 +77,7 @@ checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi", "libc", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -122,6 +122,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c1bf4a04a88c54f589125563643d773f3254b5c38571395e2b591c693bbc81" +[[package]] +name = "c_linked_list" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4964518bd3b4a8190e832886cdc0da9794f12e8e6c1613a9e90ff331c4c8724b" + [[package]] name = "cfb-mode" version = "0.6.0" @@ -195,11 +201,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69323bff1fb41c635347b8ead484a5ca6c3f11914d784170b158d8449ab07f8e" dependencies = [ "cfg-if 0.1.10", - "crossbeam-channel", + "crossbeam-channel 0.4.4", "crossbeam-deque", "crossbeam-epoch", "crossbeam-queue", - "crossbeam-utils", + "crossbeam-utils 0.7.2", ] [[package]] @@ -208,10 +214,20 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b153fe7cbef478c567df0f972e02e6d736db11affe43dfc9c56a9374d1adfb87" dependencies = [ - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] +[[package]] +name = "crossbeam-channel" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ed27e177f16d65f0f0c22a213e17c696ace5dd64b14258b52f9417ccb52db4" +dependencies = [ + "cfg-if 1.0.0", + "crossbeam-utils 0.8.5", +] + [[package]] name = "crossbeam-deque" version = "0.7.4" @@ -219,7 +235,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c20ff29ded3204c5106278a81a38f4b482636ed4fa1e6cfbeef193291beb29ed" dependencies = [ "crossbeam-epoch", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -231,7 +247,7 @@ checksum = "058ed274caafc1f60c4997b5fc07bf7dc7cca454af7c6e81edffe5f33f70dace" dependencies = [ "autocfg", "cfg-if 0.1.10", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "lazy_static", "maybe-uninit", "memoffset", @@ -245,7 +261,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "774ba60a54c213d409d5353bda12d49cd68d14e45036a285234c8d6f91f92570" dependencies = [ "cfg-if 0.1.10", - "crossbeam-utils", + "crossbeam-utils 0.7.2", "maybe-uninit", ] @@ -260,6 +276,16 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "crossbeam-utils" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82cfc11ce7f2c3faef78d8a684447b40d503d9681acebed6cb728d45940c4db" +dependencies = [ + "cfg-if 1.0.0", + "lazy_static", +] + [[package]] name = "discard" version = "1.0.4" @@ -373,6 +399,12 @@ dependencies = [ "slab", ] +[[package]] +name = "gcc" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" + [[package]] name = "generic-array" version = "0.14.4" @@ -383,6 +415,39 @@ dependencies = [ "version_check", ] +[[package]] +name = "get_if_addrs" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abddb55a898d32925f3148bd281174a68eeb68bbfd9a5938a57b18f506ee4ef7" +dependencies = [ + "c_linked_list", + "get_if_addrs-sys", + "libc", + "winapi 0.2.8", +] + +[[package]] +name = "get_if_addrs-sys" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d04f9fb746cf36b191c00f3ede8bde9c8e64f9f4b05ae2694a9ccf5e3f5ab48" +dependencies = [ + "gcc", + "libc", +] + +[[package]] +name = "getrandom" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "wasi", +] + [[package]] name = "gio" version = "0.14.0" @@ -410,7 +475,7 @@ dependencies = [ "gobject-sys", "libc", "system-deps", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -814,9 +879,9 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" [[package]] name = "memchr" -version = "2.3.4" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" +checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" [[package]] name = "memoffset" @@ -876,12 +941,17 @@ dependencies = [ "assert_matches", "cfb-mode", "cookie-factory", + "crossbeam-channel 0.5.1", "env_logger", "err-derive", + "get_if_addrs", "indoc", + "lazy_static", "log", "md5", "nom", + "rand", + "regex", "socket2", "time", "xml-rs", @@ -891,9 +961,9 @@ dependencies = [ [[package]] name = "nom" -version = "6.2.1" +version = "6.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c5c51b9083a3c620fa67a2a635d1ce7d95b897e957d6b28ff9a5da960a103a6" +checksum = "e7413f999671bd4745a7b624bd370a569fb6bc574b23c83a3c5ed2e453f3d5e2" dependencies = [ "bitvec", "funty", @@ -974,6 +1044,12 @@ version = "0.3.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" +[[package]] +name = "ppv-lite86" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" + [[package]] name = "pretty-hex" version = "0.2.1" @@ -1045,10 +1121,50 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "941ba9d78d8e2f7ce474c015eea4d9c6d25b6a3327f9832ee29a4de27f91bbb8" [[package]] -name = "regex" -version = "1.4.6" +name = "rand" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a26af418b574bd56588335b3a3659a65725d4e636eb1016c2f9e3b38c7cc759" +checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", + "rand_hc", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rand_hc" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7" +dependencies = [ + "rand_core", +] + +[[package]] +name = "regex" +version = "1.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" dependencies = [ "aho-corasick", "memchr", @@ -1160,7 +1276,7 @@ checksum = "122e570113d28d773067fab24266b66753f6ea915758651696b6e35e49f88d6e" dependencies = [ "cfg-if 1.0.0", "libc", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -1372,7 +1488,7 @@ dependencies = [ "stdweb", "time-macros", "version_check", - "winapi", + "winapi 0.3.9", ] [[package]] @@ -1530,6 +1646,12 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + [[package]] name = "wasm-bindgen" version = "0.2.74" @@ -1584,6 +1706,12 @@ version = "0.2.74" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7cff876b8f18eed75a66cf49b65e7f967cb354a7aa16003fb55dbfd25b44b4f" +[[package]] +name = "winapi" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" + [[package]] name = "winapi" version = "0.3.9" @@ -1606,7 +1734,7 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ - "winapi", + "winapi 0.3.9", ] [[package]] From 1094cdf71301e6324ea0233c32d2cb7d9c0a5581 Mon Sep 17 00:00:00 2001 From: Troy Rollo Date: Wed, 1 Sep 2021 22:30:14 +1000 Subject: [PATCH 38/56] Fix IFrame and PFrame identification for Swann DVRs --- crates/core/src/bcmedia/de.rs | 8 ++++---- crates/core/src/bcmedia/model.rs | 4 ++++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/core/src/bcmedia/de.rs b/crates/core/src/bcmedia/de.rs index 67de1f9..f499bfb 100644 --- a/crates/core/src/bcmedia/de.rs +++ b/crates/core/src/bcmedia/de.rs @@ -76,8 +76,8 @@ fn bcmedia(buf: &[u8]) -> IResult<&[u8], BcMedia> { *x, MAGIC_HEADER_BCMEDIA_INFO_V1 | MAGIC_HEADER_BCMEDIA_INFO_V2 - | MAGIC_HEADER_BCMEDIA_IFRAME - | MAGIC_HEADER_BCMEDIA_PFRAME + | MAGIC_HEADER_BCMEDIA_IFRAME..=MAGIC_HEADER_BCMEDIA_IFRAME_LAST + | MAGIC_HEADER_BCMEDIA_PFRAME..=MAGIC_HEADER_BCMEDIA_PFRAME_LAST | MAGIC_HEADER_BCMEDIA_AAC | MAGIC_HEADER_BCMEDIA_ADPCM ) @@ -92,11 +92,11 @@ fn bcmedia(buf: &[u8]) -> IResult<&[u8], BcMedia> { let (buf, payload) = bcmedia_info_v2(buf)?; Ok((buf, BcMedia::InfoV2(payload))) } - MAGIC_HEADER_BCMEDIA_IFRAME => { + MAGIC_HEADER_BCMEDIA_IFRAME..=MAGIC_HEADER_BCMEDIA_IFRAME_LAST => { let (buf, payload) = bcmedia_iframe(buf)?; Ok((buf, BcMedia::Iframe(payload))) } - MAGIC_HEADER_BCMEDIA_PFRAME => { + MAGIC_HEADER_BCMEDIA_PFRAME..=MAGIC_HEADER_BCMEDIA_PFRAME_LAST => { let (buf, payload) = bcmedia_pframe(buf)?; Ok((buf, BcMedia::Pframe(payload))) } diff --git a/crates/core/src/bcmedia/model.rs b/crates/core/src/bcmedia/model.rs index 3edc8a5..732028d 100644 --- a/crates/core/src/bcmedia/model.rs +++ b/crates/core/src/bcmedia/model.rs @@ -103,7 +103,9 @@ pub struct BcMediaInfoV2 { // unknown: u16 } +// IFrame magics include the channel number in them pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME: u32 = 0x63643030; +pub(super) const MAGIC_HEADER_BCMEDIA_IFRAME_LAST: u32 = 0x63643039; /// Video Types for I/PFrame #[derive(Debug)] @@ -132,7 +134,9 @@ pub struct BcMediaIframe { pub data: Vec, } +// PFrame magics include the channel number in them pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME: u32 = 0x63643130; +pub(super) const MAGIC_HEADER_BCMEDIA_PFRAME_LAST: u32 = 0x63643139; /// This is a BcMedia video PFrame. #[derive(Debug)] From 3516af13bacad7afb147b75e4717e3cbda89ee6c Mon Sep 17 00:00:00 2001 From: Andrew King Date: Sat, 4 Sep 2021 09:19:39 +0700 Subject: [PATCH 39/56] Typo in BcUdp Co-authored-by: George Hilliard --- crates/core/src/bcudp/model.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index 712475a..667ba2c 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -8,7 +8,7 @@ use super::xml::*; pub enum BcUdp { /// Packet from the negotiate stage when connection info is exchanged Discovery(UdpDiscovery), - /// Packet to acknoledge receipt of a data packet + /// Packet to acknowledge receipt of a data packet Ack(UdpAck), /// Packet containing the data (or part of the data) of a Bc packet Data(UdpData), From 162bdf85cc646f7b7dff8ffcb220096948a09624 Mon Sep 17 00:00:00 2001 From: Andrew King Date: Sat, 4 Sep 2021 09:20:07 +0700 Subject: [PATCH 40/56] Update crates/core/src/bcudp/model.rs Co-authored-by: George Hilliard --- crates/core/src/bcudp/model.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/core/src/bcudp/model.rs b/crates/core/src/bcudp/model.rs index 667ba2c..b82c2d5 100644 --- a/crates/core/src/bcudp/model.rs +++ b/crates/core/src/bcudp/model.rs @@ -20,6 +20,7 @@ pub const MAGIC_HEADER_UDP_NEGO: u32 = 0x2a87cf3a; /// The Discovery packet is sent and received to init a connection #[derive(Debug, PartialEq, Eq)] pub struct UdpDiscovery { + // The packet also contains these header fields not deserialized into this struct: // 4 Bytes Magic // 4 Byte payload size // 4 Bytes unknown always `01000000` From f07d3ce318bd2eb2a2ae08b25c0d20cb7e70b2b7 Mon Sep 17 00:00:00 2001 From: Andrew King Date: Sat, 4 Sep 2021 09:23:34 +0700 Subject: [PATCH 41/56] Update sample_config.toml Co-authored-by: George Hilliard --- sample_config.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sample_config.toml b/sample_config.toml index 74228df..aca5815 100644 --- a/sample_config.toml +++ b/sample_config.toml @@ -59,4 +59,4 @@ address = "192.168.1.245:9000" # By default channel_id = 0. Eg the first connected camera on the device # **Note**: that unlike in the offical client the numbering starts from 0 not 1. # An 8 channel NVR would have channels 0 through 7 -# channel_id = 1 +# channel_id = 0 From 6c69acf0cbeb76c0aeca061735ae07d70cfede3a Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 6 Sep 2021 18:31:40 +0700 Subject: [PATCH 42/56] Use fastcrc crate for udp crc --- Cargo.lock | 26 ++++++++++++ crates/core/Cargo.toml | 15 +++---- crates/core/src/bcudp/crc.rs | 80 ++---------------------------------- 3 files changed, 38 insertions(+), 83 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6d7dc65..92aab45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -194,6 +194,30 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "396de984970346b0d9e93d1415082923c679e5ae5c3ee3dcbd104f5610af126b" +[[package]] +name = "crc" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10c2722795460108a7872e1cd933a85d6ec38abc4baecad51028f702da28889f" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccaeedb56da03b09f598226e25e80088cb4cd25f316e6e4df7d695f0feeb1403" + +[[package]] +name = "crc32fast" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81156fece84ab6a9f2afdb109ce3ae577e42b1228441eded99bd77f627953b1a" +dependencies = [ + "cfg-if 1.0.0", +] + [[package]] name = "crossbeam" version = "0.7.3" @@ -941,6 +965,8 @@ dependencies = [ "assert_matches", "cfb-mode", "cookie-factory", + "crc", + "crc32fast", "crossbeam-channel 0.5.1", "env_logger", "err-derive", diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 5c70db6..8410ad6 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -9,20 +9,21 @@ edition = "2018" aes = "0.6" cfb-mode = "0.6" cookie-factory = "0.3" +crc32fast = "1.2.1" +crossbeam-channel = "0.5.1" err-derive = "0.2" +get_if_addrs = "0.5.3" lazy_static = "1.4" log = { version = "0.4" } md5 = "0.7" nom = "6.1.2" -socket2 = "0.3" -time = "0.2" -yaserde = "0.3.16" -yaserde_derive = "0.3.16" -xml-rs = "0.8" rand = "0.8.4" regex = "1.5.4" -crossbeam-channel = "0.5.1" -get_if_addrs = "0.5.3" +socket2 = "0.3" +time = "0.2" +xml-rs = "0.8" +yaserde = "0.3.16" +yaserde_derive = "0.3.16" [dev-dependencies] assert_matches = "1.5.0" diff --git a/crates/core/src/bcudp/crc.rs b/crates/core/src/bcudp/crc.rs index 150a0e7..760df61 100644 --- a/crates/core/src/bcudp/crc.rs +++ b/crates/core/src/bcudp/crc.rs @@ -1,79 +1,7 @@ -const TABLE: [u32; 1024] = [ - 0x0, 0x0, 0x0, 0x0, 0x96, 0x30, 0x7, 0x77, 0x2C, 0x61, 0xE, 0xEE, 0xBA, 0x51, 0x9, 0x99, 0x19, - 0xC4, 0x6D, 0x7, 0x8F, 0xF4, 0x6A, 0x70, 0x35, 0xA5, 0x63, 0xE9, 0xA3, 0x95, 0x64, 0x9E, 0x32, - 0x88, 0xDB, 0xE, 0xA4, 0xB8, 0xDC, 0x79, 0x1E, 0xE9, 0xD5, 0xE0, 0x88, 0xD9, 0xD2, 0x97, 0x2B, - 0x4C, 0xB6, 0x9, 0xBD, 0x7C, 0xB1, 0x7E, 0x7, 0x2D, 0xB8, 0xE7, 0x91, 0x1D, 0xBF, 0x90, 0x64, - 0x10, 0xB7, 0x1D, 0xF2, 0x20, 0xB0, 0x6A, 0x48, 0x71, 0xB9, 0xF3, 0xDE, 0x41, 0xBE, 0x84, 0x7D, - 0xD4, 0xDA, 0x1A, 0xEB, 0xE4, 0xDD, 0x6D, 0x51, 0xB5, 0xD4, 0xF4, 0xC7, 0x85, 0xD3, 0x83, 0x56, - 0x98, 0x6C, 0x13, 0xC0, 0xA8, 0x6B, 0x64, 0x7A, 0xF9, 0x62, 0xFD, 0xEC, 0xC9, 0x65, 0x8A, 0x4F, - 0x5C, 0x1, 0x14, 0xD9, 0x6C, 0x6, 0x63, 0x63, 0x3D, 0xF, 0xFA, 0xF5, 0xD, 0x8, 0x8D, 0xC8, - 0x20, 0x6E, 0x3B, 0x5E, 0x10, 0x69, 0x4C, 0xE4, 0x41, 0x60, 0xD5, 0x72, 0x71, 0x67, 0xA2, 0xD1, - 0xE4, 0x3, 0x3C, 0x47, 0xD4, 0x4, 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 0x66, 0x5C, 0xB, 0x1, 0x11, 0xFF, 0x9E, 0x65, - 0x8F, 0x69, 0xAE, 0x62, 0xF8, 0xD3, 0xFF, 0x6B, 0x61, 0x45, 0xCF, 0x6C, 0x16, 0x78, 0xE2, 0xA, - 0xA0, 0xEE, 0xD2, 0xD, 0xD7, 0x54, 0x83, 0x4, 0x4E, 0xC2, 0xB3, 0x3, 0x39, 0x61, 0x26, 0x67, - 0xA7, 0xF7, 0x16, 0x60, 0xD0, 0x4D, 0x47, 0x69, 0x49, 0xDB, 0x77, 0x6E, 0x3E, 0x4A, 0x6A, 0xD1, - 0xAE, 0xDC, 0x5A, 0xD6, 0xD9, 0x66, 0xB, 0xDF, 0x40, 0xF0, 0x3B, 0xD8, 0x37, 0x53, 0xAE, 0xBC, - 0xA9, 0xC5, 0x9E, 0xBB, 0xDE, 0x7F, 0xCF, 0xB2, 0x47, 0xE9, 0xFF, 0xB5, 0x30, 0x1C, 0xF2, 0xBD, - 0xBD, 0x8A, 0xC2, 0xBA, 0xCA, 0x30, 0x93, 0xB3, 0x53, 0xA6, 0xA3, 0xB4, 0x24, 0x5, 0x36, 0xD0, - 0xBA, 0x93, 0x6, 0xD7, 0xCD, 0x29, 0x57, 0xDE, 0x54, 0xBF, 0x67, 0xD9, 0x23, 0x2E, 0x7A, 0x66, - 0xB3, 0xB8, 0x4A, 0x61, 0xC4, 0x2, 0x1B, 0x68, 0x5D, 0x94, 0x2B, 0x6F, 0x2A, 0x37, 0xBE, 0xB, - 0xB4, 0xA1, 0x8E, 0xC, 0xC3, 0x1B, 0xDF, 0x5, 0x5A, 0x8D, 0xEF, 0x02, 0x2D, -]; +use crc32fast::Hasher; pub(crate) fn calc_crc(payload: &[u8]) -> u32 { - let mut r: u32 = 0; - for &val in payload.iter() { - let offset = (((val as u32 ^ r) & 0xFF) << 2) as usize; - let val: u32 = TABLE[offset + 3] << 24 - | TABLE[offset + 2] << 16 - | TABLE[offset + 1] << 8 - | TABLE[offset]; - r = val ^ (r >> 8); - } - r + let mut hasher = Hasher::new_with_initial(0xffffffff); + hasher.update(payload); + hasher.finalize() ^ 0xffffffff_u32 } From 8b85042fe8ebaed53f77a02a3629c5a2fe27036e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 6 Sep 2021 20:26:01 +0700 Subject: [PATCH 43/56] Removed unneeded code in the udp description --- dissector/udp.md | 38 ++++---------------------------------- 1 file changed, 4 insertions(+), 34 deletions(-) diff --git a/dissector/udp.md b/dissector/udp.md index 519aef1..a3d879a 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -40,44 +40,14 @@ If there is no reply is received within 500ms the last message is resent. It is also used for the encryption. - 4 Bytes Checksum: The checksum of the payload encrypted payload -The checksum can be calculated with this rust code: - -```rust -const TABLE: [u32; 1024] = [0x0, 0x0, 0x0, 0x0, 0x96, 0x30, 0x7, 0x77, 0x2C, 0x61, 0xE, 0xEE, 0xBA, 0x51, 0x9, 0x99, 0x19, 0xC4, 0x6D, 0x7, 0x8F, 0xF4, 0x6A, 0x70, 0x35, 0xA5, 0x63, 0xE9, 0xA3, 0x95, 0x64, 0x9E, 0x32, 0x88, 0xDB, 0xE, 0xA4, 0xB8, 0xDC, 0x79, 0x1E, 0xE9, 0xD5, 0xE0, 0x88, 0xD9, 0xD2, 0x97, 0x2B, 0x4C, 0xB6, 0x9, 0xBD, 0x7C, 0xB1, 0x7E, 0x7, 0x2D, 0xB8, 0xE7, 0x91, 0x1D, 0xBF, 0x90, 0x64, 0x10, 0xB7, 0x1D, 0xF2, 0x20, 0xB0, 0x6A, 0x48, 0x71, 0xB9, 0xF3, 0xDE, 0x41, 0xBE, 0x84, 0x7D, 0xD4, 0xDA, 0x1A, 0xEB, 0xE4, 0xDD, 0x6D, 0x51, 0xB5, 0xD4, 0xF4, 0xC7, 0x85, 0xD3, 0x83, 0x56, 0x98, 0x6C, 0x13, 0xC0, 0xA8, 0x6B, 0x64, 0x7A, 0xF9, 0x62, 0xFD, 0xEC, 0xC9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pub(crate) fn calc_crc(payload: &[u8]) -> u32 { - let mut r: u32 = 0; - for &val in payload.iter() { - let offset = (((val as u32 ^ r) & 0xFF) << 2) as usize; - let val: u32 = TABLE[offset + 3] << 24 - | TABLE[offset + 2] << 16 - | TABLE[offset + 1] << 8 - | TABLE[offset]; - r = val ^ (r >> 8); - } - r -} -``` +The checksum can be calculated with a polynomial of `0x04c11db7`, an init value +of `0x00000000` and an xorout of `0x00000000`. ## Payload -- Payload can be encrypted and decrypted with this rust code - -```rust -const XML_KEY: [u32; 8] = [ - 0x1f2d3c4b, 0x5a6c7f8d, 0x38172e4b, 0x8271635a, 0x863f1a2b, 0xa5c6f7d8, 0x8371e1b4, 0x17f2d3a5, -]; - -pub(crate) fn decrypt(offset: u32, buf: &[u8]) -> Vec { - let key = XML_KEY - .iter() - .map(|i| (i + offset).to_le_bytes()) - .flatten() - .cycle(); - buf.iter().zip(key).map(|(byte, key)| key ^ byte).collect() -} -``` +- The XML payloads and encrypted with a simple xor algorithm. See the full + source in neolink for details. ## Start Discovery payload From 7d95663d908e7a5e47f81935be9dfe0647badbf4 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 6 Sep 2021 20:30:52 +0700 Subject: [PATCH 44/56] Remove ping every --- Cargo.lock | 16 ------------ crates/core/src/bc_protocol/ping.rs | 38 +---------------------------- 2 files changed, 1 insertion(+), 53 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 92aab45..4a1db80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -194,21 +194,6 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "396de984970346b0d9e93d1415082923c679e5ae5c3ee3dcbd104f5610af126b" -[[package]] -name = "crc" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10c2722795460108a7872e1cd933a85d6ec38abc4baecad51028f702da28889f" -dependencies = [ - "crc-catalog", -] - -[[package]] -name = "crc-catalog" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccaeedb56da03b09f598226e25e80088cb4cd25f316e6e4df7d695f0feeb1403" - [[package]] name = "crc32fast" version = "1.2.1" @@ -965,7 +950,6 @@ dependencies = [ "assert_matches", "cfb-mode", "cookie-factory", - "crc", "crc32fast", "crossbeam-channel 0.5.1", "env_logger", diff --git a/crates/core/src/bc_protocol/ping.rs b/crates/core/src/bc_protocol/ping.rs index 0ef9331..0c63b0e 100644 --- a/crates/core/src/bc_protocol/ping.rs +++ b/crates/core/src/bc_protocol/ping.rs @@ -1,4 +1,4 @@ -use super::{BcCamera, Error, Result, RX_TIMEOUT}; +use super::{BcCamera, Result, RX_TIMEOUT}; use crate::bc::model::*; impl BcCamera { @@ -28,40 +28,4 @@ impl BcCamera { Ok(()) } - - /// Send a ping repeatedly - pub fn ping_every(&self, milis: u64) -> Result<()> { - let wait = std::time::Duration::from_millis(milis); - - let connection = self.connection.as_ref().expect("Must be connected to ping"); - let sub_ping = connection.subscribe(MSG_ID_PING)?; - - loop { - let ping = Bc { - meta: BcMeta { - msg_id: MSG_ID_PING, - channel_id: self.channel_id, - msg_num: self.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - sub_ping.send(ping)?; - - let reply = sub_ping.rx.recv_timeout(RX_TIMEOUT)?; - - if reply.meta.response_code != 200 { - return Err(Error::UnintelligibleReply { - reply, - why: "Camera responded with an error status code to the ping", - }); - } - std::thread::sleep(wait); - } - } } From 8327a8348b63e59df2e86c55dd0d31b10864a35e Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Mon, 6 Sep 2021 20:31:55 +0700 Subject: [PATCH 45/56] Reference battery before udp in the readme --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index acc3c12..86d2856 100644 --- a/README.md +++ b/README.md @@ -80,9 +80,9 @@ Builds are provided for the following platforms: 1. [Install Gstreamer][gstreamer] from the most recent MSI installer on Windows, or your package manager on Linux. - + On Ubuntu/Debian machines gstreamer can be installed with: - + ```bash sudo apt install \ libgstrtspserver-1.0-0 \ @@ -105,12 +105,12 @@ or your package manager on Linux. 3. Download and unpack Neolink from the links above. 1. Note: you can also click on [this link][ci-download] to see all historical builds. You will need to be logged in to GitHub to download directly from the builds page (wget doesn't work) - + Raspberry Pi OS x64 example: - + ```bash unzip release-arm64-buster.zip - sudo cp neolink /usr/local/bin/ + sudo cp neolink /usr/local/bin/ sudo chmod +x /usr/local/bin/neolink ``` 4. Write a configuration file for your cameras. See the section below. @@ -175,7 +175,7 @@ services: The Docker image is "best effort" and intended for advanced users; questions about running Docker are outside the scope of Neolink. -If you use a UDP only camera, such as a battery camera you will need to either +If you use a battery-powered camera (or other UDP-only camera) you will need to either use `--net=host` or setup a [macvlan](https://docs.docker.com/network/macvlan/) for the docker image that supports UDP broadcast. This is because UDP requires that udp broadcast messages are transmitted across From 9b23d8dbfc1f78e0de28b30f02d8b59782f53e79 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 8 Sep 2021 11:45:37 +0700 Subject: [PATCH 46/56] Add Uid as a seperate field into the config --- crates/core/src/bc_protocol.rs | 167 ++++++++++++++++++++++----------- src/main.rs | 1 + src/reboot/config.rs | 20 +++- src/reboot/mod.rs | 22 +++-- src/rtsp/config.rs | 18 +++- src/rtsp/mod.rs | 9 +- src/statusled/config.rs | 20 +++- src/statusled/mod.rs | 23 +++-- src/talk/config.rs | 20 +++- src/talk/mod.rs | 23 +++-- src/utils.rs | 39 ++++++++ 11 files changed, 269 insertions(+), 93 deletions(-) create mode 100644 src/utils.rs diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 9c81700..b058622 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -1,6 +1,7 @@ use crate::{bc, bcmedia}; use log::*; use std::convert::TryInto; +use std::net::ToSocketAddrs; use std::sync::atomic::{AtomicU16, Ordering}; use Md5Trunc::*; @@ -75,7 +76,7 @@ impl BcCamera { /// /// # Parameters /// - /// * `host` - The address of the camera either ip address, hostname string, or uid is ok + /// * `host` - The address of the camera either ip address, hostname string /// /// * `channel_id` - The channel ID this is usually zero unless using a NVR /// @@ -83,68 +84,128 @@ impl BcCamera { /// /// returns either an error or the camera /// - pub fn new_with_addr(host: T, channel_id: u8) -> Result { + pub fn new_with_addr(host: T, channel_id: u8) -> Result { + let addr_iter = match host.to_socket_addrs() { + Ok(iter) => iter, + Err(_) => return Err(Error::AddrResolutionError), + }; + for addr in addr_iter { + if let Ok(cam) = Self::new(SocketAddrOrUid::SocketAddr(addr), channel_id) { + return Ok(cam); + } + } + + Err(Error::Timeout) + } + + /// + /// Create a new camera interface with this uid and channel ID + /// + /// # Parameters + /// + /// * `uid` - The uid of the camera + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new_with_uid(uid: &str, channel_id: u8) -> Result { + Self::new(SocketAddrOrUid::Uid(uid.to_string()), channel_id) + } + + /// + /// Create a new camera interface with this address/uid and channel ID + /// + /// This method will first perform hostname resolution on the address + /// then fallback to uid if that resolution fails. + /// + /// Be aware that it is possible (although unlikely) that there is + /// a dns entry with the same address as the uid. If uncertain use + /// one of the other methods. + /// + /// # Parameters + /// + /// * `host` - The address of the camera either ip address, hostname string, or uid + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new_with_addr_or_uid(host: T, channel_id: u8) -> Result { let addr_iter = match host.to_socket_addrs_or_uid() { Ok(iter) => iter, Err(_) => return Err(Error::AddrResolutionError), }; - - for addr in addr_iter { - let source = match addr { - SocketAddrOrUid::SocketAddr(addr) => { - debug!("Trying address {}", addr); - BcSource::new_tcp(addr, RX_TIMEOUT)? - } - SocketAddrOrUid::Uid(uid) => { - debug!("Trying uid {}", uid); - BcSource::new_udp(&uid, RX_TIMEOUT)? - } - }; - - let conn = match BcConnection::new(source) { - Ok(conn) => conn, - Err(err) => match err { - connection::Error::Communication(ref err) => { - debug!("Assuming timeout from {}", err); - continue; - } - err => return Err(err.into()), - }, - }; - - debug!("Success"); - let me = Self { - connection: Some(conn), - message_num: AtomicU16::new(0), - channel_id, - logged_in: false, - credentials: None, - }; - - if let Some(conn) = &me.connection { - let keep_alive_msg = Bc { - meta: BcMeta { - msg_id: MSG_ID_UDP_KEEP_ALIVE, - channel_id: me.channel_id, - msg_num: me.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; - - conn.set_keep_alive_msg(keep_alive_msg); + for addr_or_uid in addr_iter { + if let Ok(cam) = Self::new(addr_or_uid, channel_id) { + return Ok(cam); } - - return Ok(me); } Err(Error::Timeout) } + /// + /// Create a new camera interface with this address/uid and channel ID + /// + /// # Parameters + /// + /// * `addr` - An enum of [`SocketAddrOrUid`] that contains the address + /// + /// * `channel_id` - The channel ID this is usually zero unless using a NVR + /// + /// # Returns + /// + /// returns either an error or the camera + /// + pub fn new(addr: SocketAddrOrUid, channel_id: u8) -> Result { + let source = match addr { + SocketAddrOrUid::SocketAddr(addr) => { + debug!("Trying address {}", addr); + BcSource::new_tcp(addr, RX_TIMEOUT)? + } + SocketAddrOrUid::Uid(uid) => { + debug!("Trying uid {}", uid); + BcSource::new_udp(&uid, RX_TIMEOUT)? + } + }; + + let conn = BcConnection::new(source)?; + + debug!("Success"); + let me = Self { + connection: Some(conn), + message_num: AtomicU16::new(0), + channel_id, + logged_in: false, + credentials: None, + }; + + if let Some(conn) = &me.connection { + let keep_alive_msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_UDP_KEEP_ALIVE, + channel_id: me.channel_id, + msg_num: me.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; + + conn.set_keep_alive_msg(keep_alive_msg); + } + + Ok(me) + } + /// This method will get a new message number and increment the message count atomically pub fn new_message_num(&self) -> u16 { self.message_num.fetch_add(1, Ordering::Relaxed) diff --git a/src/main.rs b/src/main.rs index 64f1f63..4bfcfe9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,7 @@ mod reboot; mod rtsp; mod statusled; mod talk; +mod utils; use cmdline::{Command, Opt}; diff --git a/src/reboot/config.rs b/src/reboot/config.rs index de60ef2..3000f65 100644 --- a/src/reboot/config.rs +++ b/src/reboot/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::clone::Clone; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; #[derive(Debug, Deserialize, Validate, Clone)] @@ -10,11 +10,15 @@ pub(crate) struct Config { } #[derive(Debug, Deserialize, Validate, Clone)] +#[validate(schema(function = "validate_camera_config"))] pub(crate) struct CameraConfig { pub(crate) name: String, #[serde(rename = "address")] - pub(crate) camera_addr: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -27,3 +31,15 @@ pub(crate) struct CameraConfig { fn default_channel_id() -> u8 { 0 } + +fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { + match (&camera_config.camera_addr, &camera_config.camera_uid) { + (None, None) => Err(ValidationError::new( + "Either camera address or uid must be given", + )), + (Some(_), Some(_)) => Err(ValidationError::new( + "Must provide either camera address or uid not both", + )), + _ => Ok(()), + } +} diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index 9219e45..d7187c0 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -13,13 +13,13 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use neolink_core::bc_protocol::BcCamera; use std::fs; use validator::Validate; mod cmdline; mod config; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::Config; @@ -41,19 +41,21 @@ pub fn main(opt: Opt) -> Result<()> { for camera_config in &config.cameras { if opt.camera == camera_config.name { cam_found = true; + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); info!( "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr + camera_config.name, camera_addr ); - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id - ) - })?; + let mut camera = camera_addr + .connect_camera(camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); camera diff --git a/src/rtsp/config.rs b/src/rtsp/config.rs index fb2ead6..013c3de 100644 --- a/src/rtsp/config.rs +++ b/src/rtsp/config.rs @@ -41,11 +41,15 @@ pub(crate) struct Config { } #[derive(Debug, Deserialize, Validate, Clone)] +#[validate(schema(function = "validate_camera_config"))] pub(crate) struct CameraConfig { pub(crate) name: String, #[serde(rename = "address")] - pub(crate) camera_addr: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -115,3 +119,15 @@ fn validate_username(name: &str) -> Result<(), ValidationError> { } Ok(()) } + +fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { + match (&camera_config.camera_addr, &camera_config.camera_uid) { + (None, None) => Err(ValidationError::new( + "Either camera address or uid must be given", + )), + (Some(_), Some(_)) => Err(ValidationError::new( + "Must provide either camera address or uid not both", + )), + _ => Ok(()), + } +} diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index 0c45298..d055f14 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -45,6 +45,7 @@ mod config; /// The errors this subcommand can raise mod gst; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::{CameraConfig, Config, UserConfig}; use gst::{GstOutputs, RtspServer, TlsAuthenticationMode}; @@ -225,12 +226,14 @@ fn camera_main( let mut connected = false; let mut login_fail = false; (|| { + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) + camera_addr.connect_camera(camera_config.channel_id) .with_context(|| { format!( "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id + camera_config.name, camera_addr, camera_config.channel_id ) })?; @@ -241,7 +244,7 @@ fn camera_main( info!( "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr + camera_config.name, camera_addr ); info!("{}: Logging in", camera_config.name); diff --git a/src/statusled/config.rs b/src/statusled/config.rs index de60ef2..3000f65 100644 --- a/src/statusled/config.rs +++ b/src/statusled/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::clone::Clone; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; #[derive(Debug, Deserialize, Validate, Clone)] @@ -10,11 +10,15 @@ pub(crate) struct Config { } #[derive(Debug, Deserialize, Validate, Clone)] +#[validate(schema(function = "validate_camera_config"))] pub(crate) struct CameraConfig { pub(crate) name: String, #[serde(rename = "address")] - pub(crate) camera_addr: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -27,3 +31,15 @@ pub(crate) struct CameraConfig { fn default_channel_id() -> u8 { 0 } + +fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { + match (&camera_config.camera_addr, &camera_config.camera_uid) { + (None, None) => Err(ValidationError::new( + "Either camera address or uid must be given", + )), + (Some(_), Some(_)) => Err(ValidationError::new( + "Must provide either camera address or uid not both", + )), + _ => Ok(()), + } +} diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index 6f32b2a..5f3769f 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -17,13 +17,13 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use neolink_core::bc_protocol::BcCamera; use std::fs; use validator::Validate; mod cmdline; mod config; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::Config; @@ -45,19 +45,22 @@ pub fn main(opt: Opt) -> Result<()> { for camera_config in &config.cameras { if opt.camera == camera_config.name { cam_found = true; + + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); info!( "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr + camera_config.name, camera_addr ); - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id - ) - })?; + let mut camera = camera_addr + .connect_camera(camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); camera diff --git a/src/talk/config.rs b/src/talk/config.rs index de60ef2..3000f65 100644 --- a/src/talk/config.rs +++ b/src/talk/config.rs @@ -1,6 +1,6 @@ use serde::Deserialize; use std::clone::Clone; -use validator::Validate; +use validator::{Validate, ValidationError}; use validator_derive::Validate; #[derive(Debug, Deserialize, Validate, Clone)] @@ -10,11 +10,15 @@ pub(crate) struct Config { } #[derive(Debug, Deserialize, Validate, Clone)] +#[validate(schema(function = "validate_camera_config"))] pub(crate) struct CameraConfig { pub(crate) name: String, #[serde(rename = "address")] - pub(crate) camera_addr: String, + pub(crate) camera_addr: Option, + + #[serde(rename = "uid")] + pub(crate) camera_uid: Option, pub(crate) username: String, pub(crate) password: Option, @@ -27,3 +31,15 @@ pub(crate) struct CameraConfig { fn default_channel_id() -> u8 { 0 } + +fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { + match (&camera_config.camera_addr, &camera_config.camera_uid) { + (None, None) => Err(ValidationError::new( + "Either camera address or uid must be given", + )), + (Some(_), Some(_)) => Err(ValidationError::new( + "Must provide either camera address or uid not both", + )), + _ => Ok(()), + } +} diff --git a/src/talk/mod.rs b/src/talk/mod.rs index a2a032a..c9a569f 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -13,7 +13,7 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use neolink_core::{bc::xml::TalkConfig, bc_protocol::BcCamera}; +use neolink_core::bc::xml::TalkConfig; use std::fs; use validator::Validate; @@ -21,6 +21,7 @@ mod cmdline; mod config; mod gst; +use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; use config::Config; @@ -42,19 +43,21 @@ pub fn main(opt: Opt) -> Result<()> { for camera_config in &config.cameras { if opt.camera == camera_config.name { cam_found = true; + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_addr).unwrap(); info!( "{}: Connecting to camera at {}", - camera_config.name, camera_config.camera_addr + camera_config.name, camera_addr ); - let mut camera = - BcCamera::new_with_addr(&camera_config.camera_addr, camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_config.camera_addr, camera_config.channel_id - ) - })?; + let mut camera = camera_addr + .connect_camera(camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; info!("{}: Logging in", camera_config.name); camera diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..7f1f8e5 --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,39 @@ +//! Contains code that is not specific to any of the subcommands +//! +use anyhow::{anyhow, Error}; +use neolink_core::bc_protocol::BcCamera; +use std::fmt::{Display, Error as FmtError, Formatter}; + +pub(crate) enum AddressOrUid { + Address(String), + Uid(String), +} + +impl Display for AddressOrUid { + fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> { + match self { + AddressOrUid::Address(host) => write!(f, "Address: {}", host), + AddressOrUid::Uid(host) => write!(f, "UID: {}", host), + } + } +} + +impl AddressOrUid { + // Created by translating the config fields directly + pub(crate) fn new(address: &Option, uid: &Option) -> Result { + 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(host), None) => Ok(AddressOrUid::Address(host.clone())), + (None, Some(host)) => Ok(AddressOrUid::Uid(host.clone())), + } + } + + // Convience method to get the BcCamera with the appropiate method + pub(crate) fn connect_camera(&self, channel_id: u8) -> Result { + match self { + AddressOrUid::Address(host) => Ok(BcCamera::new_with_addr(host, channel_id)?), + AddressOrUid::Uid(host) => Ok(BcCamera::new_with_uid(host, channel_id)?), + } + } +} From ad0b79eec5db37fd7b751f7d8878c80020cc3042 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 8 Sep 2021 11:50:53 +0700 Subject: [PATCH 47/56] Add comments to the udp crc --- crates/core/src/bcudp/crc.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/core/src/bcudp/crc.rs b/crates/core/src/bcudp/crc.rs index 760df61..e50e5a1 100644 --- a/crates/core/src/bcudp/crc.rs +++ b/crates/core/src/bcudp/crc.rs @@ -1,7 +1,20 @@ use crc32fast::Hasher; pub(crate) fn calc_crc(payload: &[u8]) -> u32 { + // Bc uses a non standard crc. + // + // It uses the polynomial 0x04c11db7 + // It uses the inital value or 0x00000000 + // It uses the xorout of 0x00000000 + // + // The crc32fast has an odd behavior were it bitwise negates + // the initial value before the loop. In order to have + // an effective initial value of 0x00000000 we need to provide + // the value 0xffffffff let mut hasher = Hasher::new_with_initial(0xffffffff); hasher.update(payload); + // crc32fast uses the algorithm CRC-32/ISO-HDLC + // This has an xorout of 0xffffffff + // we must undo this xorout hasher.finalize() ^ 0xffffffff_u32 } From 79e012647ad7e753bcb5897a8241802bfabd6b09 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 8 Sep 2021 15:19:42 +0700 Subject: [PATCH 48/56] Read me updates --- README.md | 37 ++++++++++++++++++++++++++----------- sample_config.toml | 8 ++++++-- 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 86d2856..1eed5d1 100644 --- a/README.md +++ b/README.md @@ -106,13 +106,14 @@ or your package manager on Linux. 1. Note: you can also click on [this link][ci-download] to see all historical builds. You will need to be logged in to GitHub to download directly from the builds page (wget doesn't work) - Raspberry Pi OS x64 example: + Ubuntu/Debian/Raspberry Pi OS example: ```bash unzip release-arm64-buster.zip sudo cp neolink /usr/local/bin/ sudo chmod +x /usr/local/bin/neolink ``` + 4. Write a configuration file for your cameras. See the section below. 5. Launch Neolink from a shell, passing your configuration file: @@ -189,18 +190,29 @@ bridging mode](https://github.com/docker/for-linux/issues/637) [Blue Iris setup walkthrough in `docs/`][blue-iris-setup] (which is probably also helpful even with other NVR software). +**Note**: more comprehensive setup details for linux based devices is provided in +[docs/unix_setup.md][unix-setup] + +**Note**: instructions for also setting up a (systemd based) service for linux +based devices is provided in [docs/unix_service.md][unix-service] + [blue-iris-setup]: docs/Setting%20Up%20Neolink%20For%20Use%20With%20Blue%20Iris.md +[unix-setup]: docs/unix_setup.md +[unix-service]: docs/unix_service.md Copy and modify the `sample_config.toml` to specify the address, username, and password for each camera (if there is no password, you can omit that line). -The address can be a camera UID, in this case your network must support UDP -broadcasts. Battery cameras exclusively use this UDP mode so you must always -use a UID in the address field. +The default credentials for some cameras is username `admin` password `123456`. + +- For a non battery powered camera you need to provide the address field with the +ip and port (default 9000). + +- For a battery powered camera you need to provide the uid field with the +camera's UID. In this case your network must support UDP. +Battery cameras exclusively use this UDP mode so you must always use a UID. Each `[[cameras]]` block creates a new camera; the `name` determines the RTSP path you should connect your client to. -Currently Neolink cannot auto-detect cameras like the official clients do; you -must specify their IP addresses directly. By default, the HD stream is available at the RTSP path `/name` or `/name/mainStream`, and the SD stream is available at `/name/subStream`. @@ -215,16 +227,16 @@ You can modify this by changing the `bind` and the `bind_port` parameter. You only need one `bind`/`bind_port` setting at the top of the config file. You can enable `rtsps` (TLS) by adding a `certificate = "/path/to/pem"` to the -top section of the config file. This PEM should contain by the certificate +top section of the config file. This PEM should contain 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 +`rtsps`. You can also use 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. TLS is disabled by default. You can password-protect the Neolink server by adding `[[users]]` sections to -the configuration file: +the configuration file, but this is not secure without also using TLS: ``` [[users]] @@ -257,11 +269,13 @@ 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`: +- On sh: + ```sh set RUST_LOG=debug ``` -On Linux: +- On Bash: ```bash export RUST_LOG=debug @@ -317,7 +331,7 @@ been upgraded several times. The modern variant uses obfuscated XML commands and sends ordinary H.265 or H.264 video streams encapsulated in a custom header. -More details about the on-the-wire protocol will come later. +More details of the on-the-wire protocol are provided in [`dissector/`](dissector/). ### Baichuan dissector @@ -326,6 +340,7 @@ directory. It dissects the BC header and also allows viewing the deobfuscated XML in command messages. +(It cannot deobfuscate newer messages that use AES encryption.) To use it, copy or symlink it into your Wireshark plugin directory; typically this is `~/.local/lib/wireshark/plugins/` under Linux. diff --git a/sample_config.toml b/sample_config.toml index aca5815..14a572d 100644 --- a/sample_config.toml +++ b/sample_config.toml @@ -35,6 +35,9 @@ name = "driveway" username = "admin" password = "12345678" address = "192.168.1.187:9000" +# If you use a battery camera: **Instead** of an `address` supply the uid +# as follows +# uid = "ABCD01234567890EFG" # By default any of the users can connect (or anyone at all if no users are specfied) # You can uncomment the following to permit only specfic users @@ -50,8 +53,9 @@ name = "storage shed" username = "admin" password = "987654321" address = "192.168.1.245:9000" -# The address could instead be set to a camera UID like this -# address = "ABCD01234567890EFG" +# If you use a battery camera: **Instead** of an `address` supply the uid +# as follows +# uid = "ABCD01234567890EFG" # If you use an NVR that relays several camera connections you can choose which # camera to connect to with by setting the `channel_id` From a301944298f9e63f1d45ea2cf6c842b98933fa95 Mon Sep 17 00:00:00 2001 From: Andrew King Date: Wed, 8 Sep 2021 16:29:03 +0700 Subject: [PATCH 49/56] Apply suggestions from code review --- crates/core/src/bc_protocol.rs | 2 +- .../connection/udpconn/discover.rs | 27 +++++++++++++++++++ .../connection/udpconn/transmit.rs | 7 ++++- crates/core/src/bcudp/de.rs | 2 +- dissector/udp.md | 18 ++++++++++--- src/utils.rs | 2 +- 6 files changed, 51 insertions(+), 7 deletions(-) diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index b058622..50375f4 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -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 /// diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs index 8a57951..44dee46 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/discover.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -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( 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( 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 { 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, diff --git a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs index 7aa801a..0125b86 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/transmit.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/transmit.rs @@ -97,6 +97,7 @@ impl ClientSent { // } // } + // This function translates the `UdpAck` payload directly fn acknoledge_from_ack_data(&self, start: u32, payload: Vec) { 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)> { 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); diff --git a/crates/core/src/bcudp/de.rs b/crates/core/src/bcudp/de.rs index d4c2802..ab4479c 100644 --- a/crates/core/src/bcudp/de.rs +++ b/crates/core/src/bcudp/de.rs @@ -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()) diff --git a/dissector/udp.md b/dissector/udp.md index a3d879a..e3e3cd6 100644 --- a/dissector/udp.md +++ b/dissector/udp.md @@ -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 + + +62097899 +local +82000 +528 + + +``` **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) diff --git a/src/utils.rs b/src/utils.rs index 7f1f8e5..8039f9f 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -23,7 +23,7 @@ impl AddressOrUid { pub(crate) fn new(address: &Option, uid: &Option) -> Result { 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())), } From f70a93ac569695f681fd08890c29492465417e70 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 8 Sep 2021 17:02:19 +0700 Subject: [PATCH 50/56] Register the default ip address during the remote discovery --- Cargo.lock | 69 +++++++++++++++++++ crates/core/Cargo.toml | 1 + .../connection/udpconn/discover.rs | 8 ++- 3 files changed, 75 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4a1db80..e828ff0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -122,6 +122,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c1bf4a04a88c54f589125563643d773f3254b5c38571395e2b591c693bbc81" +[[package]] +name = "byteorder" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" + [[package]] name = "c_linked_list" version = "1.1.1" @@ -182,6 +188,12 @@ dependencies = [ "vec_map", ] +[[package]] +name = "const-sha1" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb58b6451e8c2a812ad979ed1d83378caa5e927eef2622017a45f251457c2c9d" + [[package]] name = "const_fn" version = "0.4.8" @@ -859,6 +871,19 @@ version = "0.2.98" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320cfe77175da3a483efed4bc0adc1968ca050b098ce4f2f1c13a56626128790" +[[package]] +name = "local-ip-address" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b143c6ef86e36328caa40a7578e95d1544aca8a1740235fd2b416a69441a5c7" +dependencies = [ + "libc", + "memalloc", + "neli", + "thiserror", + "windows", +] + [[package]] name = "log" version = "0.4.14" @@ -886,6 +911,12 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" +[[package]] +name = "memalloc" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df39d232f5c40b0891c10216992c2f250c054105cb1e56f0fc9032db6203ecc1" + [[package]] name = "memchr" version = "2.4.1" @@ -907,6 +938,16 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5136edda114182728ccdedb9f5eda882781f35fa6e80cc360af12a8932507f3" +[[package]] +name = "neli" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9053554eb5dcb7e10d9cdab1206965bde870eed5d0d341532ca035e3ba221508" +dependencies = [ + "byteorder", + "libc", +] + [[package]] name = "neolink" version = "0.4.0" @@ -957,6 +998,7 @@ dependencies = [ "get_if_addrs", "indoc", "lazy_static", + "local-ip-address", "log", "md5", "nom", @@ -1753,6 +1795,33 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68088239696c06152844eadc03d262f088932cce50c67e4ace86e19d95e976fe" +dependencies = [ + "const-sha1", + "windows_gen", + "windows_macros", +] + +[[package]] +name = "windows_gen" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf583322dc423ee021035b358e535015f7fd163058a31e2d37b99a939141121d" + +[[package]] +name = "windows_macros" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58acfb8832e9f707f8997bd161e537a1c1f603e60a5bd9c3cf53484fdcc998f3" +dependencies = [ + "syn", + "windows_gen", +] + [[package]] name = "wyz" version = "0.2.0" diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 8410ad6..37b4465 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -14,6 +14,7 @@ crossbeam-channel = "0.5.1" err-derive = "0.2" get_if_addrs = "0.5.3" lazy_static = "1.4" +local-ip-address = "0.4.4" log = { version = "0.4" } md5 = "0.7" nom = "6.1.2" diff --git a/crates/core/src/bc_protocol/connection/udpconn/discover.rs b/crates/core/src/bc_protocol/connection/udpconn/discover.rs index 44dee46..f17c805 100644 --- a/crates/core/src/bc_protocol/connection/udpconn/discover.rs +++ b/crates/core/src/bc_protocol/connection/udpconn/discover.rs @@ -1,5 +1,6 @@ use super::{aborthandle::AbortHandle, Error, Result, MTU, P2P_RELAY_HOSTNAMES, WAIT_TIME}; use crate::bcudp::{model::*, xml::*}; +use local_ip_address::local_ip; use log::*; use rand::{seq::SliceRandom, thread_rng, Rng}; use std::io::{Error as IoError, ErrorKind, Result as IoResult}; @@ -272,7 +273,7 @@ impl UdpDiscover { // 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`) + // tries to connect to us using this data) // - 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 @@ -300,8 +301,9 @@ impl UdpDiscover { let log_address = m2c_q_r.log; // let device_address = m2c_q_r.t; + let default_local_address = local_ip().expect("There to be a local ip"); debug!("Register address found: {:?}", register_address); - debug!("Registering this address: {:?}", local_addr); + debug!("Registering this address: {:?}", default_local_address); let local_family = if local_addr.ip().is_ipv4() { 4 } else { 6 }; let msg = BcUdp::Discovery(UdpDiscovery { @@ -310,7 +312,7 @@ impl UdpDiscover { c2r_c: Some(C2rC { uid: uid.to_string(), cli: IpPort { - ip: "10.251.254.10".to_string(), + ip: default_local_address.to_string(), port: local_port, }, relay: relay_address, From de39e7ed2a771c374d24a83d2f5486c9adfa4845 Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 00:25:54 -0500 Subject: [PATCH 51/56] Re-unify configuration files Unfortunately the grammar of the --config parameter is a bit of a football right now; previously you were allowed to specify it anywhere because there wasn't much in the way of a CLI, then when subcommands were added it became required to specify it after the subcommand. This change makes it so that it must be specified *before* the subcommand. Ideally it would just be required *somewhere* in the command line but clap doesn't support "global" for required arguments (and it is indeed required). On the whole, I'm okay with the change - the net win of having a unified config struct makes up for the ergonomics hit in my opinion, and it unlocks some further refactoring I will do next. --- src/cmdline.rs | 2 +- src/{rtsp => }/config.rs | 0 src/main.rs | 43 +++++++++++++++++++++++--------------- src/reboot/cmdline.rs | 4 ---- src/reboot/config.rs | 45 ---------------------------------------- src/reboot/mod.rs | 20 +++--------------- src/rtsp/cmdline.rs | 7 +------ src/rtsp/mod.rs | 17 ++------------- src/statusled/cmdline.rs | 4 ---- src/statusled/config.rs | 45 ---------------------------------------- src/statusled/mod.rs | 20 +++--------------- src/talk/cmdline.rs | 3 --- src/talk/config.rs | 45 ---------------------------------------- src/talk/mod.rs | 22 ++++---------------- 14 files changed, 40 insertions(+), 237 deletions(-) rename src/{rtsp => }/config.rs (100%) delete mode 100644 src/reboot/config.rs delete mode 100644 src/statusled/config.rs delete mode 100644 src/talk/config.rs diff --git a/src/cmdline.rs b/src/cmdline.rs index 6136dce..1b4d3a6 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -6,7 +6,7 @@ use structopt::{clap::AppSettings, StructOpt}; #[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))] pub struct Opt { #[structopt(short, long, parse(from_os_str))] - pub config: Option, + pub config: PathBuf, #[structopt(subcommand)] pub cmd: Option, } diff --git a/src/rtsp/config.rs b/src/config.rs similarity index 100% rename from src/rtsp/config.rs rename to src/config.rs diff --git a/src/main.rs b/src/main.rs index 4bfcfe9..6aa14dc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,12 +7,15 @@ //! It contains sub commands for running an rtsp proxy which can be used on Reolink cameras //! that do not nativly support RTSP. //! -use anyhow::Result; +use anyhow::{Context, Result}; use env_logger::Env; use log::*; +use std::fs; use structopt::StructOpt; +use validator::Validate; mod cmdline; +mod config; mod reboot; mod rtsp; mod statusled; @@ -20,6 +23,7 @@ mod talk; mod utils; use cmdline::{Command, Opt}; +use config::Config; fn main() -> Result<()> { env_logger::Builder::from_env(Env::default().default_filter_or("info")).init(); @@ -32,30 +36,35 @@ fn main() -> Result<()> { let opt = Opt::from_args(); - match (opt.cmd, opt.config) { - (None, None) => { - // Should be caught at the clap validation - unreachable!(); - } - (None, Some(config)) => { + let config: Config = toml::from_str( + &fs::read_to_string(&opt.config) + .with_context(|| format!("Failed to read {:?}", &opt.config))?, + ) + .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + + config + .validate() + .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + + match opt.cmd { + None => { warn!( "Deprecated command line option. Please use: `neolink rtsp --config={:?}`", config ); - rtsp::main(rtsp::Opt { config })?; + rtsp::main(rtsp::Opt {}, config)?; } - (Some(_), Some(_)) => error!("--config should be given after the subcommand"), - (Some(Command::Rtsp(opts)), None) => { - rtsp::main(opts)?; + Some(Command::Rtsp(opts)) => { + rtsp::main(opts, config)?; } - (Some(Command::StatusLight(opts)), None) => { - statusled::main(opts)?; + Some(Command::StatusLight(opts)) => { + statusled::main(opts, config)?; } - (Some(Command::Reboot(opts)), None) => { - reboot::main(opts)?; + Some(Command::Reboot(opts)) => { + reboot::main(opts, config)?; } - (Some(Command::Talk(opts)), None) => { - talk::main(opts)?; + Some(Command::Talk(opts)) => { + talk::main(opts, config)?; } } diff --git a/src/reboot/cmdline.rs b/src/reboot/cmdline.rs index 8c94ee1..1f6cd91 100644 --- a/src/reboot/cmdline.rs +++ b/src/reboot/cmdline.rs @@ -1,12 +1,8 @@ -use std::path::PathBuf; use structopt::StructOpt; /// The reboot command will reboot the camera #[derive(StructOpt, Debug)] pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, /// The name of the camera to change the lights of. Must be a name in the config pub camera: String, } diff --git a/src/reboot/config.rs b/src/reboot/config.rs deleted file mode 100644 index 3000f65..0000000 --- a/src/reboot/config.rs +++ /dev/null @@ -1,45 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -#[validate(schema(function = "validate_camera_config"))] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: Option, - - #[serde(rename = "uid")] - pub(crate) camera_uid: Option, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, -} - -fn default_channel_id() -> u8 { - 0 -} - -fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { - match (&camera_config.camera_addr, &camera_config.camera_uid) { - (None, None) => Err(ValidationError::new( - "Either camera address or uid must be given", - )), - (Some(_), Some(_)) => Err(ValidationError::new( - "Must provide either camera address or uid not both", - )), - _ => Ok(()), - } -} diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index d7187c0..1521bdc 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -13,30 +13,17 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use std::fs; -use validator::Validate; mod cmdline; -mod config; +use super::config::Config; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::Config; /// Entry point for the reboot subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &fs::read_to_string(&opt.config) - .with_context(|| format!("Failed to read {:?}", &opt.config))?, - ) - .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { let mut cam_found = false; for camera_config in &config.cameras { if opt.camera == camera_config.name { @@ -72,9 +59,8 @@ pub fn main(opt: Opt) -> Result<()> { if !cam_found { Err(anyhow!( - "Camera {} was not in the config file {:?}", + "Camera {} not found in the config file", &opt.camera, - &opt.config )) } else { Ok(()) diff --git a/src/rtsp/cmdline.rs b/src/rtsp/cmdline.rs index 2a7092b..baedb75 100644 --- a/src/rtsp/cmdline.rs +++ b/src/rtsp/cmdline.rs @@ -1,10 +1,5 @@ -use std::path::PathBuf; use structopt::StructOpt; /// The rtsp command will serve all cameras in the config over the rtsp protocol #[derive(StructOpt, Debug)] -pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, -} +pub struct Opt {} diff --git a/src/rtsp/mod.rs b/src/rtsp/mod.rs index d055f14..6c11129 100644 --- a/src/rtsp/mod.rs +++ b/src/rtsp/mod.rs @@ -33,37 +33,24 @@ use log::*; use neolink_core::bc_protocol::{BcCamera, Stream}; use neolink_core::Never; use std::collections::HashSet; -use std::fs; use std::sync::Arc; use std::time::Duration; -use validator::Validate; // mod adpcm; /// The command line parameters for this subcommand mod cmdline; -mod config; /// The errors this subcommand can raise mod gst; +use super::config::{CameraConfig, Config, UserConfig}; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::{CameraConfig, Config, UserConfig}; use gst::{GstOutputs, RtspServer, TlsAuthenticationMode}; /// Entry point for the rtsp subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &fs::read_to_string(&opt.config) - .with_context(|| format!("Failed to read {:?}", &opt.config))?, - ) - .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +pub(crate) fn main(_opt: Opt, config: Config) -> Result<()> { let rtsp = &RtspServer::new(); set_up_tls(&config, rtsp); diff --git a/src/statusled/cmdline.rs b/src/statusled/cmdline.rs index e0c448d..1a47514 100644 --- a/src/statusled/cmdline.rs +++ b/src/statusled/cmdline.rs @@ -1,5 +1,4 @@ use anyhow::{anyhow, Result}; -use std::path::PathBuf; use structopt::StructOpt; fn onoff_parse(src: &str) -> Result { @@ -16,9 +15,6 @@ fn onoff_parse(src: &str) -> Result { /// The status-light command will control the blue status light on the camera #[derive(StructOpt, Debug)] pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, /// The name of the camera to change the lights of. Must be a name in the config pub camera: String, /// Whether to turn the light on or off diff --git a/src/statusled/config.rs b/src/statusled/config.rs deleted file mode 100644 index 3000f65..0000000 --- a/src/statusled/config.rs +++ /dev/null @@ -1,45 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -#[validate(schema(function = "validate_camera_config"))] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: Option, - - #[serde(rename = "uid")] - pub(crate) camera_uid: Option, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, -} - -fn default_channel_id() -> u8 { - 0 -} - -fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { - match (&camera_config.camera_addr, &camera_config.camera_uid) { - (None, None) => Err(ValidationError::new( - "Either camera address or uid must be given", - )), - (Some(_), Some(_)) => Err(ValidationError::new( - "Must provide either camera address or uid not both", - )), - _ => Ok(()), - } -} diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index 5f3769f..2ccffe1 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -17,30 +17,17 @@ /// use anyhow::{anyhow, Context, Result}; use log::*; -use std::fs; -use validator::Validate; mod cmdline; -mod config; +use super::config::Config; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::Config; /// Entry point for the ledstatus subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &fs::read_to_string(&opt.config) - .with_context(|| format!("Failed to read {:?}", &opt.config))?, - ) - .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { let mut cam_found = false; for camera_config in &config.cameras { if opt.camera == camera_config.name { @@ -77,9 +64,8 @@ pub fn main(opt: Opt) -> Result<()> { if !cam_found { Err(anyhow!( - "Camera {} was not in the config file {:?}", + "Camera {} not found in the config file", &opt.camera, - &opt.config )) } else { Ok(()) diff --git a/src/talk/cmdline.rs b/src/talk/cmdline.rs index bd16704..675e574 100644 --- a/src/talk/cmdline.rs +++ b/src/talk/cmdline.rs @@ -9,9 +9,6 @@ use structopt::StructOpt; /// `gst-launch` can be used to prepare this data #[derive(StructOpt, Debug)] pub struct Opt { - /// The path to the config file - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, /// The name of the camera to change the lights of. Must be a name in the config pub camera: String, /// The path to the audio file. diff --git a/src/talk/config.rs b/src/talk/config.rs deleted file mode 100644 index 3000f65..0000000 --- a/src/talk/config.rs +++ /dev/null @@ -1,45 +0,0 @@ -use serde::Deserialize; -use std::clone::Clone; -use validator::{Validate, ValidationError}; -use validator_derive::Validate; - -#[derive(Debug, Deserialize, Validate, Clone)] -pub(crate) struct Config { - #[validate] - pub(crate) cameras: Vec, -} - -#[derive(Debug, Deserialize, Validate, Clone)] -#[validate(schema(function = "validate_camera_config"))] -pub(crate) struct CameraConfig { - pub(crate) name: String, - - #[serde(rename = "address")] - pub(crate) camera_addr: Option, - - #[serde(rename = "uid")] - pub(crate) camera_uid: Option, - - pub(crate) username: String, - pub(crate) password: Option, - - #[validate(range(min = 0, max = 31, message = "Invalid channel", code = "channel_id"))] - #[serde(default = "default_channel_id")] - pub(crate) channel_id: u8, -} - -fn default_channel_id() -> u8 { - 0 -} - -fn validate_camera_config(camera_config: &CameraConfig) -> Result<(), ValidationError> { - match (&camera_config.camera_addr, &camera_config.camera_uid) { - (None, None) => Err(ValidationError::new( - "Either camera address or uid must be given", - )), - (Some(_), Some(_)) => Err(ValidationError::new( - "Must provide either camera address or uid not both", - )), - _ => Ok(()), - } -} diff --git a/src/talk/mod.rs b/src/talk/mod.rs index c9a569f..44b823b 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -8,37 +8,24 @@ /// # Usage /// /// ```bash -/// neolink status-light --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName +/// neolink talk --config=config.toml --adpcm-file=data.adpcm --sample-rate=16000 --block-size=512 CameraName /// ``` /// use anyhow::{anyhow, Context, Result}; use log::*; use neolink_core::bc::xml::TalkConfig; -use std::fs; -use validator::Validate; mod cmdline; -mod config; mod gst; +use super::config::Config; use crate::utils::AddressOrUid; pub(crate) use cmdline::Opt; -use config::Config; /// Entry point for the talk subcommand /// /// Opt is the command line options -pub fn main(opt: Opt) -> Result<()> { - let config: Config = toml::from_str( - &fs::read_to_string(&opt.config) - .with_context(|| format!("Failed to read {:?}", &opt.config))?, - ) - .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; - - config - .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; - +pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { let mut cam_found = false; for camera_config in &config.cameras { if opt.camera == camera_config.name { @@ -128,9 +115,8 @@ pub fn main(opt: Opt) -> Result<()> { if !cam_found { Err(anyhow!( - "Camera {} was not in the config file {:?}", + "Camera {} not found in the config file", &opt.camera, - &opt.config )) } else { Ok(()) From fdd50f9dc0f56ddaa629f4f36be76a062e2d13af Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 00:41:15 -0500 Subject: [PATCH 52/56] Refactor: move single-camera boilerplate to utils.rs --- src/main.rs | 2 +- src/reboot/mod.rs | 50 ++------------- src/statusled/mod.rs | 51 ++------------- src/talk/mod.rs | 150 ++++++++++++++++--------------------------- src/utils.rs | 48 +++++++++++++- 5 files changed, 119 insertions(+), 182 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6aa14dc..6f033ad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -40,7 +40,7 @@ fn main() -> Result<()> { &fs::read_to_string(&opt.config) .with_context(|| format!("Failed to read {:?}", &opt.config))?, ) - .with_context(|| format!("Failed to load {:?} as a config file", &opt.config))?; + .with_context(|| format!("Failed to parse the {:?} config file", &opt.config))?; config .validate() diff --git a/src/reboot/mod.rs b/src/reboot/mod.rs index 1521bdc..435cc7f 100644 --- a/src/reboot/mod.rs +++ b/src/reboot/mod.rs @@ -11,58 +11,22 @@ /// neolink reboot --config=config.toml CameraName /// ``` /// -use anyhow::{anyhow, Context, Result}; -use log::*; +use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::utils::AddressOrUid; +use crate::utils::find_and_connect; pub(crate) use cmdline::Opt; /// Entry point for the reboot subcommand /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut cam_found = false; - for camera_config in &config.cameras { - if opt.camera == camera_config.name { - cam_found = true; - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_addr - ); + let camera = find_and_connect(&config, &opt.camera)?; - let mut camera = camera_addr - .connect_camera(camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_addr, camera_config.channel_id - ) - })?; - - info!("{}: Logging in", camera_config.name); - camera - .login(&camera_config.username, camera_config.password.as_deref()) - .with_context(|| format!("Failed to login to {}", camera_config.name))?; - - info!("{}: Connected and logged in", camera_config.name); - - camera - .reboot() - .context("Could not send reboot command to the camera")?; - } - } - - if !cam_found { - Err(anyhow!( - "Camera {} not found in the config file", - &opt.camera, - )) - } else { - Ok(()) - } + camera + .reboot() + .context("Could not send reboot command to the camera")?; + Ok(()) } diff --git a/src/statusled/mod.rs b/src/statusled/mod.rs index 2ccffe1..ed50013 100644 --- a/src/statusled/mod.rs +++ b/src/statusled/mod.rs @@ -15,59 +15,22 @@ /// neolink status-light --config=config.toml CameraName off /// ``` /// -use anyhow::{anyhow, Context, Result}; -use log::*; +use anyhow::{Context, Result}; mod cmdline; use super::config::Config; -use crate::utils::AddressOrUid; +use crate::utils::find_and_connect; pub(crate) use cmdline::Opt; /// Entry point for the ledstatus subcommand /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut cam_found = false; - for camera_config in &config.cameras { - if opt.camera == camera_config.name { - cam_found = true; + let mut camera = find_and_connect(&config, &opt.camera)?; - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_addr - ); - - let mut camera = camera_addr - .connect_camera(camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_addr, camera_config.channel_id - ) - })?; - - info!("{}: Logging in", camera_config.name); - camera - .login(&camera_config.username, camera_config.password.as_deref()) - .with_context(|| format!("Failed to login to {}", camera_config.name))?; - - info!("{}: Connected and logged in", camera_config.name); - - camera - .led_light_set(opt.on) - .context("Unable to set camera light state")?; - } - } - - if !cam_found { - Err(anyhow!( - "Camera {} not found in the config file", - &opt.camera, - )) - } else { - Ok(()) - } + camera + .led_light_set(opt.on) + .context("Unable to set camera light state")?; + Ok(()) } diff --git a/src/talk/mod.rs b/src/talk/mod.rs index 44b823b..d0af688 100644 --- a/src/talk/mod.rs +++ b/src/talk/mod.rs @@ -12,113 +12,77 @@ /// ``` /// use anyhow::{anyhow, Context, Result}; -use log::*; use neolink_core::bc::xml::TalkConfig; mod cmdline; mod gst; use super::config::Config; -use crate::utils::AddressOrUid; +use crate::utils::{connect_and_login, find_camera_by_name}; pub(crate) use cmdline::Opt; /// Entry point for the talk subcommand /// /// Opt is the command line options pub(crate) fn main(opt: Opt, config: Config) -> Result<()> { - let mut cam_found = false; - for camera_config in &config.cameras { - if opt.camera == camera_config.name { - cam_found = true; - let camera_addr = - AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_addr).unwrap(); - info!( - "{}: Connecting to camera at {}", - camera_config.name, camera_addr - ); + let camera_config = find_camera_by_name(&config, &opt.camera)?; + let camera = connect_and_login(camera_config)?; - let mut camera = camera_addr - .connect_camera(camera_config.channel_id) - .with_context(|| { - format!( - "Failed to connect to camera {} at {} on channel {}", - camera_config.name, camera_addr, camera_config.channel_id - ) - })?; - - info!("{}: Logging in", camera_config.name); - camera - .login(&camera_config.username, camera_config.password.as_deref()) - .with_context(|| format!("Failed to login to {}", camera_config.name))?; - - info!("{}: Connected and logged in", camera_config.name); - - let talk_ability = camera - .talk_ability() - .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; - if talk_ability.duplex_list.is_empty() - || talk_ability.audio_stream_mode_list.is_empty() - || talk_ability.audio_config_list.is_empty() - { - return Err(anyhow!( - "Camera {} does not support talk", - camera_config.name - )); - } - - // Just copy that data from the first talk ability in the config have never seen more - // than one ability - let config = 0; - - let talk_config = TalkConfig { - channel_id: camera_config.channel_id, - duplex: talk_ability.duplex_list[config].duplex.clone(), - audio_stream_mode: talk_ability.audio_stream_mode_list[config] - .audio_stream_mode - .clone(), - audio_config: talk_ability.audio_config_list[config].audio_config.clone(), - ..Default::default() - }; - - let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; - let sample_rate = talk_config.audio_config.sample_rate; - if block_size == 0 || sample_rate == 0 { - return Err(anyhow!( - "The camera {} does not support talk with adpcm", - camera_config.name - )); - } - - let rx = match (&opt.file_path, &opt.microphone) { - (Some(path), false) => gst::from_input( - &format!( - "filesrc location={}", - path.to_str().expect("File path not UTF8 complient") - ), - opt.volume, - block_size, - sample_rate, - ) - .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, - (None, true) => { - gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) - .context("Failed to setup gst using the microphone")? - } - _ => unreachable!(), - }; - - camera - .talk_stream(rx, talk_config) - .context("Talk stream ended early")?; - } + let talk_ability = camera + .talk_ability() + .with_context(|| format!("Camera {} does not support talk", camera_config.name))?; + if talk_ability.duplex_list.is_empty() + || talk_ability.audio_stream_mode_list.is_empty() + || talk_ability.audio_config_list.is_empty() + { + return Err(anyhow!( + "Camera {} does not support talk", + camera_config.name + )); } - if !cam_found { - Err(anyhow!( - "Camera {} not found in the config file", - &opt.camera, - )) - } else { - Ok(()) + // Just copy that data from the first talk ability in the config have never seen more + // than one ability + let config = 0; + + let talk_config = TalkConfig { + channel_id: camera_config.channel_id, + duplex: talk_ability.duplex_list[config].duplex.clone(), + audio_stream_mode: talk_ability.audio_stream_mode_list[config] + .audio_stream_mode + .clone(), + audio_config: talk_ability.audio_config_list[config].audio_config.clone(), + ..Default::default() + }; + + let block_size = (talk_config.audio_config.length_per_encoder / 2) + 4; + let sample_rate = talk_config.audio_config.sample_rate; + if block_size == 0 || sample_rate == 0 { + return Err(anyhow!( + "The camera {} does not support talk with adpcm", + camera_config.name + )); } + + let rx = match (&opt.file_path, &opt.microphone) { + (Some(path), false) => gst::from_input( + &format!( + "filesrc location={}", + path.to_str().expect("File path not UTF8 complient") + ), + opt.volume, + block_size, + sample_rate, + ) + .with_context(|| format!("Failed to setup gst with the file: {:?}", path))?, + (None, true) => gst::from_input(&opt.input_src, opt.volume, block_size, sample_rate) + .context("Failed to setup gst using the microphone")?, + _ => unreachable!(), + }; + + camera + .talk_stream(rx, talk_config) + .context("Talk stream ended early")?; + + Ok(()) } diff --git a/src/utils.rs b/src/utils.rs index 8039f9f..cd0e067 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,6 +1,9 @@ //! Contains code that is not specific to any of the subcommands //! -use anyhow::{anyhow, Error}; +use log::*; + +use super::config::{CameraConfig, Config}; +use anyhow::{anyhow, Context, Error, Result}; use neolink_core::bc_protocol::BcCamera; use std::fmt::{Display, Error as FmtError, Formatter}; @@ -37,3 +40,46 @@ impl AddressOrUid { } } } + +pub(crate) fn find_and_connect(config: &Config, name: &str) -> Result { + let camera_config = find_camera_by_name(config, name)?; + connect_and_login(camera_config) +} + +pub(crate) fn connect_and_login(camera_config: &CameraConfig) -> Result { + let camera_addr = + AddressOrUid::new(&camera_config.camera_addr, &camera_config.camera_uid).unwrap(); + info!( + "{}: Connecting to camera at {}", + camera_config.name, camera_addr + ); + + let mut camera = camera_addr + .connect_camera(camera_config.channel_id) + .with_context(|| { + format!( + "Failed to connect to camera {} at {} on channel {}", + camera_config.name, camera_addr, camera_config.channel_id + ) + })?; + + info!("{}: Logging in", camera_config.name); + camera + .login(&camera_config.username, camera_config.password.as_deref()) + .with_context(|| format!("Failed to login to {}", camera_config.name))?; + + info!("{}: Connected and logged in", camera_config.name); + + Ok(camera) +} + +pub(crate) fn find_camera_by_name<'a, 'b>( + config: &'a Config, + name: &'b str, +) -> Result<&'a CameraConfig> { + config + .cameras + .iter() + .find(|c| c.name == name) + .ok_or_else(|| anyhow!("Camera {} not found in the config file", name)) +} From 81b148f6cd9ea65f98392c7094304bd70ce51994 Mon Sep 17 00:00:00 2001 From: George Hilliard Date: Fri, 29 Oct 2021 01:24:02 -0500 Subject: [PATCH 53/56] Allow --config anywhere in CLI Since clap doesn't support required + global, do our own insisting. --- src/cmdline.rs | 10 +++++++--- src/main.rs | 9 +++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/cmdline.rs b/src/cmdline.rs index 1b4d3a6..1fb1f18 100644 --- a/src/cmdline.rs +++ b/src/cmdline.rs @@ -3,10 +3,14 @@ use structopt::{clap::AppSettings, StructOpt}; /// A standards-compliant bridge to Reolink IP cameras #[derive(StructOpt, Debug)] -#[structopt(name = "neolink", setting(AppSettings::ArgRequiredElseHelp))] +#[structopt( + name = "neolink", + setting(AppSettings::ArgRequiredElseHelp), + setting(AppSettings::UnifiedHelpMessage) +)] pub struct Opt { - #[structopt(short, long, parse(from_os_str))] - pub config: PathBuf, + #[structopt(short, long, global(true), parse(from_os_str))] + pub config: Option, #[structopt(subcommand)] pub cmd: Option, } diff --git a/src/main.rs b/src/main.rs index 6f033ad..ff6a0fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,15 +36,16 @@ fn main() -> Result<()> { let opt = Opt::from_args(); + let conf_path = opt.config.context("Must supply --config file")?; let config: Config = toml::from_str( - &fs::read_to_string(&opt.config) - .with_context(|| format!("Failed to read {:?}", &opt.config))?, + &fs::read_to_string(&conf_path) + .with_context(|| format!("Failed to read {:?}", conf_path))?, ) - .with_context(|| format!("Failed to parse the {:?} config file", &opt.config))?; + .with_context(|| format!("Failed to parse the {:?} config file", conf_path))?; config .validate() - .with_context(|| format!("Failed to validate the {:?} config file", &opt.config))?; + .with_context(|| format!("Failed to validate the {:?} config file", conf_path))?; match opt.cmd { None => { From 039edfc18ee675b09573fa774a5c912a1a7a4c0d Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Tue, 2 Nov 2021 13:40:43 +0700 Subject: [PATCH 54/56] Limit sending keep alive packets --- .../core/src/bc_protocol/connection/bcconn.rs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index 4f606f2..ef50b53 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -11,7 +11,7 @@ use std::net::{SocketAddr, TcpStream}; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::{atomic::AtomicBool, atomic::Ordering, Arc, Mutex}; use std::thread::JoinHandle; -use std::time::Duration; +use std::time::{Duration, Instant}; /// A shareable connection to a camera. Handles serialization of messages. To send/receive, call /// .[subscribe()] with a message ID. You can use the BcSubscription to send or receive only @@ -46,6 +46,8 @@ impl BcConnection { let keep_alive_encryption_protocol = connections_encryption_protocol.clone(); let mut context = BcContext::new(connections_encryption_protocol); let mut result; + let mut last_keep_alive = Instant::now(); + let keep_alive_time = Duration::from_millis(500); loop { result = Self::poll(&mut context, &conn, &mut subs); if poll_abort_rx.load(Ordering::Relaxed) { @@ -61,11 +63,14 @@ impl BcConnection { break; } // Send a udp keep alive if set - if let Ok(lock) = connections_keep_alive_msg.try_lock() { - if let Some(keep_alive_msg) = lock.as_ref() { - let _ = keep_alive_msg - .serialize(&conn, &keep_alive_encryption_protocol.lock().unwrap()); - let _ = conn.flush(); + if last_keep_alive.elapsed() > keep_alive_time { + last_keep_alive = Instant::now(); + if let Ok(lock) = connections_keep_alive_msg.try_lock() { + if let Some(keep_alive_msg) = lock.as_ref() { + let _ = keep_alive_msg + .serialize(&conn, &keep_alive_encryption_protocol.lock().unwrap()); + let _ = conn.flush(); + } } } } From 9021acf6d6f1bd59fd654c109f5f8dd0fa98f262 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Wed, 24 Nov 2021 17:12:02 +0700 Subject: [PATCH 55/56] Stop sending keep alive messages if the camera responses with an error code to them --- crates/core/src/bc_protocol/connection/bcconn.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index ef50b53..c693f0c 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -49,7 +49,7 @@ impl BcConnection { let mut last_keep_alive = Instant::now(); let keep_alive_time = Duration::from_millis(500); loop { - result = Self::poll(&mut context, &conn, &mut subs); + result = Self::poll(&mut context, &conn, &mut subs, &connections_keep_alive_msg); if poll_abort_rx.load(Ordering::Relaxed) { break; // Poll has been aborted by request usally during disconnect } @@ -126,6 +126,7 @@ impl BcConnection { context: &mut BcContext, connection: &BcSource, subscribers: &mut Arc>>>, + connections_keep_alive_msg: &Arc>>, ) -> Result<()> { // Don't hold the lock during deserialization so we don't poison the subscribers mutex if // something goes wrong @@ -149,6 +150,14 @@ impl BcConnection { if msg_id != MSG_ID_UDP_KEEP_ALIVE { debug!("Ignoring uninteresting message ID {}", msg_id); trace!("Contents: {:?}", response); + } else { + // This is a keep alive message let see what the camera says about it + if response.meta.response_code != 200 { + // Camera dosen't support the current keep alive message stop sending them + if let Ok(mut lock) = connections_keep_alive_msg.try_lock() { + *lock = None; + } + } } } } From 0145983198a301738396958999757cc246006fd8 Mon Sep 17 00:00:00 2001 From: QuantumEntangledAndy Date: Thu, 25 Nov 2021 10:36:56 +0700 Subject: [PATCH 56/56] Only enable keep alive during UDP connection --- crates/core/src/bc_protocol.rs | 31 ++++++++++--------- .../core/src/bc_protocol/connection/bcconn.rs | 4 +++ .../src/bc_protocol/connection/bcsource.rs | 4 +++ 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/crates/core/src/bc_protocol.rs b/crates/core/src/bc_protocol.rs index 50375f4..24c8fca 100644 --- a/crates/core/src/bc_protocol.rs +++ b/crates/core/src/bc_protocol.rs @@ -186,23 +186,24 @@ impl BcCamera { }; if let Some(conn) = &me.connection { - let keep_alive_msg = Bc { - meta: BcMeta { - msg_id: MSG_ID_UDP_KEEP_ALIVE, - channel_id: me.channel_id, - msg_num: me.new_message_num(), - stream_type: 0, - response_code: 0, - class: 0x6414, - }, - body: BcBody::ModernMsg(ModernMsg { - ..Default::default() - }), - }; + if conn.is_udp() { + let keep_alive_msg = Bc { + meta: BcMeta { + msg_id: MSG_ID_UDP_KEEP_ALIVE, + channel_id: me.channel_id, + msg_num: me.new_message_num(), + stream_type: 0, + response_code: 0, + class: 0x6414, + }, + body: BcBody::ModernMsg(ModernMsg { + ..Default::default() + }), + }; - conn.set_keep_alive_msg(keep_alive_msg); + conn.set_keep_alive_msg(keep_alive_msg); + } } - Ok(me) } diff --git a/crates/core/src/bc_protocol/connection/bcconn.rs b/crates/core/src/bc_protocol/connection/bcconn.rs index c693f0c..e6ee85e 100644 --- a/crates/core/src/bc_protocol/connection/bcconn.rs +++ b/crates/core/src/bc_protocol/connection/bcconn.rs @@ -122,6 +122,10 @@ impl BcConnection { (*self.encryption_protocol.lock().unwrap()).clone() } + pub fn is_udp(&self) -> bool { + self.sink.lock().unwrap().is_udp() + } + fn poll( context: &mut BcContext, connection: &BcSource, diff --git a/crates/core/src/bc_protocol/connection/bcsource.rs b/crates/core/src/bc_protocol/connection/bcsource.rs index 1628e58..be31773 100644 --- a/crates/core/src/bc_protocol/connection/bcsource.rs +++ b/crates/core/src/bc_protocol/connection/bcsource.rs @@ -12,6 +12,10 @@ pub enum BcSource { } impl BcSource { + pub fn is_udp(&self) -> bool { + matches!(self, BcSource::Udp(_)) + } + pub fn new_tcp(addr: SocketAddr, timeout: Duration) -> Result { let source = TcpSource::new(addr, timeout)?; Ok(BcSource::Tcp(Mutex::new(source)))