-
Notifications
You must be signed in to change notification settings - Fork 4
/
packet.rs
2046 lines (1928 loc) · 91.5 KB
/
packet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::type_complexity)]
use std::any::{type_name, Any, TypeId};
use std::cmp::max;
use std::error::Error;
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use bimap::BiMap;
use bytes::Bytes;
use hashbrown::HashMap;
use indexmap::IndexMap;
use log::{debug, error, trace, warn};
use quinn::{Connection, Endpoint, ReadError, RecvStream, SendStream, VarInt, WriteError};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::runtime::Runtime;
use tokio::sync::mpsc::error::TryRecvError;
use tokio::sync::mpsc::Receiver;
use tokio::sync::{mpsc, Mutex, RwLock};
use tokio::task::JoinHandle;
use crate::quinn_helpers::{make_client_endpoint, make_server_endpoint};
use crate::{CloseError, ConnectionError, ErrorType, ReceiveError, SendError};
#[cfg(test)]
#[path = "./packet_tests.rs"]
mod packet_tests;
// Sent at the end of frames
const FRAME_BOUNDARY: &[u8] = b"AAAAAA031320050421";
/// Packet trait that allows a struct to be sent through [`PacketManager`], for serializing
///
/// This is automatically implemented if using the macros [`bincode_packet`](`durian_macros::bincode_packet`),
/// [`BinPacket`](`durian_macros::BinPacket`), or [`UnitPacket`](`durian_macros::UnitPacket`).
pub trait Packet {
/// Return a serialized form of the Packet as [`Bytes`]
fn as_bytes(&self) -> Bytes;
// https://stackoverflow.com/questions/33687447/how-to-get-a-reference-to-a-concrete-type-from-a-trait-object
// fn as_any(self: Self) -> Box<dyn Any>;
}
/// PacketBuilder is the deserializer for [`Packet`] and used when [`PacketManager`] receives bytes
///
/// This is automatically implemented if using the macros [`bincode_packet`](`durian_macros::bincode_packet`),
/// [`BinPacket`](`durian_macros::BinPacket`), or [`UnitPacket`](`durian_macros::UnitPacket`).
pub trait PacketBuilder<T: Packet> {
/// Deserializes [`Bytes`] into the [`Packet`] this PacketBuilder is implemented for
///
/// # Error
/// Returns an error if deserializing fails
fn read(&self, bytes: Bytes) -> Result<T, Box<dyn Error>>;
}
/// The core of `durian` that is the central struct containing all the necessary APIs for initiating and managing
/// connections, creating streams, sending [`Packets`](`Packet`), receiving, broadcasting, etc.
///
/// A `PacketManager` would be created on each client to connect to a
/// single server, and one created on the server to connect to multiple clients. It contains both
/// synchronous and asynchronous APIs, so you can call the functions both from a synchronous
/// context, or within an async runtime (_Note: the synchronous path will create a separate
/// isolated async runtime context per `PacketManager` instance._)
///
/// There are 4 basic steps to using the `PacketManager`, which would be done on both the client
/// and server side:
///
/// 1. Create a `PacketManager` via [`new()`](`PacketManager::new()`) or, if calling from an async context, [`new_for_async()`](`PacketManager::new_for_async()`)
///
/// 2. Register the [`Packets`](`Packet`) and [`PacketBuilders`](`PacketBuilder`) that the `PacketManager` will __receive__
/// and __send__ using [`register_receive_packet()`](`PacketManager::register_receive_packet()`) and [`register_send_packet()`](`PacketManager::register_send_packet()`).
/// The ordering of `Packet` registration matters for the `receive` channel and
/// `send` channel each - the client and server must register the same packets in the same order,
/// for the opposite channels.
/// - In other words, the client must register `receive` packets in the
/// same order the server registers the same as `send` packets, and vice versa, the client must
/// register `send` packets in the same order the server registers the same as `receive` packets.
/// This helps to ensure the client and servers are in sync on what Packets to send/receive, almost
/// like ensuring they are on the same "version" so to speak, and is used to properly identify
/// Packets.
///
/// 3. Initiate connection(s) with [`init_client()`](`PacketManager::init_client()`) (or the async variant [`async_init_client()`](`PacketManager::async_init_client()`)
/// if on the client side, else use [`init_server()`](`PacketManager::init_server()`) (or the async variant [`async_init_server)`](`PacketManager::async_init_server()`)
/// if on the server side.
///
/// 4. Send packets using any of [`broadcast()`](`PacketManager::broadcast()`), [`send()`](`PacketManager::send()`), [`send_to()`](`PacketManager::send_to()`)
/// or the respective `async` variants if calling from an async context already. Receive packets
/// using any of [`received_all()`](`PacketManager::received_all()`) , [`received()`](`PacketManager::received()`), or the respective
/// `async` variants.
///
/// # Example
///
/// ```rust
/// use durian::{ClientConfig, PacketManager};
/// use durian_macros::bincode_packet;
///
/// #[bincode_packet]
/// struct Position { x: i32, y: i32 }
/// #[bincode_packet]
/// struct ServerAck;
/// #[bincode_packet]
/// struct ClientAck;
/// #[bincode_packet]
/// struct InputMovement { direction: String }
///
/// fn packet_manager_example() {
/// // Create PacketManager
/// let mut manager = PacketManager::new();
///
/// // Register send and receive packets
/// manager.register_receive_packet::<Position>(PositionPacketBuilder).unwrap();
/// manager.register_receive_packet::<ServerAck>(ServerAckPacketBuilder).unwrap();
/// manager.register_send_packet::<ClientAck>().unwrap();
/// manager.register_send_packet::<InputMovement>().unwrap();
///
/// // Initialize a client
/// let client_config = ClientConfig::new("127.0.0.1:5001", "127.0.0.1:5000", 2, 2);
/// manager.init_client(client_config).unwrap();
///
/// // Send and receive packets
/// manager.broadcast(InputMovement { direction: "North".to_string() }).unwrap();
/// manager.received_all::<Position, PositionPacketBuilder>(false).unwrap();
///
/// // The above PacketManager is for the client. Server side is similar except the packets
/// // are swapped between receive vs send channels:
///
/// // Create PacketManager
/// let mut server_manager = PacketManager::new();
///
/// // Register send and receive packets
/// server_manager.register_receive_packet::<ClientAck>(ClientAckPacketBuilder).unwrap();
/// server_manager.register_receive_packet::<InputMovement>(InputMovementPacketBuilder).unwrap();
/// server_manager.register_send_packet::<Position>().unwrap();
/// server_manager.register_send_packet::<ServerAck>().unwrap();
///
/// // Initialize a client
/// let client_config = ClientConfig::new("127.0.0.1:5001", "127.0.0.1:5000", 2, 2);
/// server_manager.init_client(client_config).unwrap();
///
/// // Send and receive packets
/// server_manager.broadcast(Position { x: 1, y: 3 }).unwrap();
/// server_manager.received_all::<InputMovement, InputMovementPacketBuilder>(false).unwrap();
/// }
/// ```
#[derive(Debug)]
pub struct PacketManager {
/// Packet Id <-> Packet TypeId
receive_packets: BiMap<u32, TypeId>,
/// Packet Id <-> Packet TypeId
send_packets: BiMap<u32, TypeId>,
recv_packet_builders: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
// DenseSlotMap for the below so we can iterate fast, while not degrading insert/remove much
/// Send streams RemoteId -> Packet Id -> SendStream
send_streams: IndexMap<u32, HashMap<u32, RwLock<SendStream>>>,
/// Receive channels, to be filled by separate threads
/// RemoteId -> PacketId -> (Receiver channel, Thread JoinHandle)
rx: IndexMap<u32, HashMap<u32, (RwLock<Receiver<Bytes>>, JoinHandle<()>)>>,
/// Track new send streams to be put into the send_streams IndexMap
/// This is so new send streams can be created after PacketManager initialization
new_send_streams: Arc<RwLock<Vec<(u32, HashMap<u32, RwLock<SendStream>>)>>>,
/// Track new receive streams to be put into the rx IndexMap
/// This is so new receive streams can be created after PacketManager initialization
new_rxs: Arc<RwLock<Vec<(u32, HashMap<u32, (RwLock<Receiver<Bytes>>, JoinHandle<()>)>)>>>,
// Endpoint and Connection structs moved to the struct fields to prevent closing connections
// by dropping.
// This is also used to count the number of clients when broadcasting
/// Remote Id (index in IndexMaps) -> (addr, Connection)
remote_connections: Arc<RwLock<HashMap<u32, (String, Connection)>>>,
// (Socket Address, Endpoint)
source: (String, Option<Arc<Endpoint>>),
/// For tracking receive packet Ids
next_receive_id: u32,
/// For tracking send packet Ids
next_send_id: u32,
// We construct a single Tokio Runtime to be used by each PacketManger instance, so that
// methods can be synchronous. There is also an async version of each API if the user wants
// to use their own runtime.
runtime: Arc<Option<Runtime>>,
}
#[derive(Clone, PartialEq, Eq, Debug)]
/// Client configuration for initiating a connection from a client to a server via [`PacketManager::init_client()`]
pub struct ClientConfig {
/// Socket address of the client (`hostname:port`) (e.g. "127.0.0.1:5001")
pub addr: String,
/// Socket address of the server to connect to (`hostname:port`) (e.g. "127.0.0.1:5000")
pub server_addr: String,
/// Number of `receive` streams to accept from server to client. Must be equal to number of receive packets
/// registered through [`PacketManager::register_receive_packet()`]
pub num_receive_streams: u32,
/// Number of `send` streams to open from client to server. Must be equal to number of send packets registered
/// through [`PacketManager::register_send_packet()`]
pub num_send_streams: u32,
/// Period of inactivity before sending a keep-alive packet
///
/// Keep-alive packets prevent an inactive but otherwise healthy connection from timing out.
///
/// None to disable, which is the default. Only one side of any given connection needs keep-alive enabled for
/// the connection to be preserved. Must be set lower than the idle_timeout of both peers to be effective.
pub keep_alive_interval: Option<Duration>,
/// Maximum duration of inactivity to accept before timing out the connection.
/// The true idle timeout is the minimum of this and the peer's own max idle timeout. Defaults to 60 seconds.
/// None represents an infinite timeout.
///
/// __IMPORTANT: In the case of clients disconnecting abruptly, i.e. your application cannot call
/// [`PacketManager::close_connection()`] or [`PacketManager::finish_connection()`] gracefully, the *true idle timeout* will help to remove
/// disconnected clients from the connection queue, thus allowing them to reconnect after that timeout frame.__
///
/// __WARNING: If a peer or its network path malfunctions or acts maliciously, an infinite idle timeout can result
/// in permanently hung futures!__
pub idle_timeout: Option<Duration>,
/// Protocols to send to server if applicable.
///
/// ## Example:
///
/// ```
/// use durian::ServerConfig;
///
/// let mut config = ServerConfig::new("127.0.0.1:5000", 0, None, 2, 2);
/// config.with_alpn_protocols(&[b"hq-29"]);
/// ```
pub alpn_protocols: Option<Vec<Vec<u8>>>,
}
impl ClientConfig {
/// Construct and return a new [`ClientConfig`]
pub fn new<S: Into<String>>(
addr: S,
server_addr: S,
num_receive_streams: u32,
num_send_streams: u32,
) -> Self {
ClientConfig {
addr: addr.into(),
server_addr: server_addr.into(),
num_receive_streams,
num_send_streams,
keep_alive_interval: None,
idle_timeout: Some(Duration::from_secs(60)),
alpn_protocols: None,
}
}
/// Set the keep alive interval
pub fn with_keep_alive_interval(&mut self, duration: Duration) -> &mut Self {
self.keep_alive_interval = Some(duration);
self
}
/// Set the idle timeout
pub fn with_idle_timeout(&mut self, duration: Duration) -> &mut Self {
self.idle_timeout = Some(duration);
self
}
/// Set the ALPN protocols
pub fn with_alpn_protocols(&mut self, protocols: &[&[u8]]) -> &mut Self {
self.alpn_protocols = Some(protocols.iter().map(|&x| x.into()).collect());
self
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
/// Server configuration for spinning up a server on a socket address via [`PacketManager::init_server()`]
pub struct ServerConfig {
/// Socket address of the server (`hostname:port`) (e.g. "127.0.0.1:5001")
pub addr: String,
/// Number of clients to block waiting for incoming connections
pub wait_for_clients: u32,
/// [Optional] Total number of clients the server expects to connect with. The server will spin up a thread that
/// waits for incoming client connections until `total_expected_clients` is reached. Set to `None` to allow any
/// number of clients connections. If `wait_for_clients > total_expected_clients`, the server will still wait
/// for `wait_for_clients` number of client connections.
pub total_expected_clients: Option<u32>,
/// Set the max number of concurrent connection accepts to process at any given time.
///
/// A thread will be spawned for each, allowing `max_concurrent_accepts` connections to come in at the same time.
/// Default to `wait_for_clients + total_expected_clients(if set)`, else number of cores available.
pub max_concurrent_accepts: u32,
/// Number of `receive` streams to accept from server to client. Must be equal to number of receive packets
/// registered through [`PacketManager::register_receive_packet()`]
pub num_receive_streams: u32,
/// Number of `send` streams to open from client to server. Must be equal to number of send packets registered
/// through [`PacketManager::register_send_packet()`]
pub num_send_streams: u32,
/// Period of inactivity before sending a keep-alive packet
///
/// Keep-alive packets prevent an inactive but otherwise healthy connection from timing out.
///
/// None to disable, which is the default. Only one side of any given connection needs keep-alive enabled for
/// the connection to be preserved. Must be set lower than the idle_timeout of both peers to be effective.
pub keep_alive_interval: Option<Duration>,
/// Maximum duration of inactivity to accept before timing out the connection.
/// The true idle timeout is the minimum of this and the peer's own max idle timeout. Defaults to 60 seconds.
/// None represents an infinite timeout.
///
/// __IMPORTANT: In the case of clients disconnecting abruptly, i.e. your application cannot call
/// [`PacketManager::close_connection()`] or [`PacketManager::finish_connection()`] gracefully, the *true idle timeout* will help to remove
/// disconnected clients from the connection queue, thus allowing them to reconnect after that timeout frame.__
///
/// __WARNING: If a peer or its network path malfunctions or acts maliciously, an infinite idle timeout can result
/// in permanently hung futures!__
pub idle_timeout: Option<Duration>,
/// Protocols to send to server if applicable.
///
/// ## Example:
///
/// ```
/// use durian::ServerConfig;
///
/// let mut config = ServerConfig::new("127.0.0.1:5000", 0, None, 2, 2);
/// config.with_alpn_protocols(&[b"hq-29"]);
/// ```
pub alpn_protocols: Option<Vec<Vec<u8>>>,
}
impl ServerConfig {
/// Construct and return a new [`ServerConfig`]
pub fn new<S: Into<String>>(
addr: S,
wait_for_clients: u32,
total_expected_clients: Option<u32>,
num_receive_streams: u32,
num_send_streams: u32,
) -> Self {
// If total_expected_clients is erroneously set to lower than wait_for_clients, just set it to 0
let mut expected_clients =
if let Some(expected) = total_expected_clients { expected } else { 0 };
expected_clients = if expected_clients > wait_for_clients {
expected_clients - wait_for_clients
} else {
0
};
ServerConfig {
addr: addr.into(),
wait_for_clients,
total_expected_clients,
max_concurrent_accepts: max(num_cpus::get() as u32, expected_clients),
num_receive_streams,
num_send_streams,
keep_alive_interval: None,
idle_timeout: Some(Duration::from_secs(60)),
alpn_protocols: None,
}
}
/// Construct and return a new [`ServerConfig`] that only allows up to `wait_for_clients` number of client connections
pub fn new_with_max_clients<S: Into<String>>(
addr: S,
wait_for_clients: u32,
num_receive_streams: u32,
num_send_streams: u32,
) -> Self {
ServerConfig {
addr: addr.into(),
wait_for_clients,
total_expected_clients: Some(wait_for_clients),
max_concurrent_accepts: num_cpus::get() as u32,
num_receive_streams,
num_send_streams,
keep_alive_interval: None,
idle_timeout: Some(Duration::from_secs(60)),
alpn_protocols: None,
}
}
/// Construct and return a new [`ServerConfig`], with [`total_expected_clients`](`ServerConfig::total_expected_clients`) set to `None` so the server
/// continuously accepts new client connections
pub fn new_listening<S: Into<String>>(
addr: S,
wait_for_clients: u32,
num_receive_streams: u32,
num_send_streams: u32,
) -> Self {
ServerConfig {
addr: addr.into(),
wait_for_clients,
total_expected_clients: None,
max_concurrent_accepts: num_cpus::get() as u32,
num_receive_streams,
num_send_streams,
keep_alive_interval: None,
idle_timeout: Some(Duration::from_secs(60)),
alpn_protocols: None,
}
}
/// Set the keep alive interval
pub fn with_keep_alive_interval(&mut self, duration: Duration) -> &mut Self {
self.keep_alive_interval = Some(duration);
self
}
/// Set the max idle timeout
pub fn with_idle_timeout(&mut self, duration: Option<Duration>) -> &mut Self {
self.idle_timeout = duration;
self
}
/// Set the ALPN protocols
pub fn with_alpn_protocols(&mut self, protocols: &[&[u8]]) -> &mut Self {
self.alpn_protocols = Some(protocols.iter().map(|&x| x.into()).collect());
self
}
/// Set the max concurrent accept connections
pub fn with_max_concurrent_accepts(&mut self, max_concurrent_accepts: u32) -> &mut Self {
self.max_concurrent_accepts = max_concurrent_accepts;
self
}
}
// TODO: Allow closing Endpoint directly, along with its threads
impl PacketManager {
/// Create a new `PacketManager`
///
/// If calling from an asynchronous context/runtime, use the [`new_for_async()`](`PacketManager::new_for_async()`) variant.
/// This constructs a [`tokio Runtime`](`Runtime`) for the `PacketManager` instance.
///
/// # Panic
/// If the [`Runtime`] could not be created. Usually happens if you call `new()` from an existing async runtime.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build();
match runtime {
Ok(runtime) => PacketManager {
receive_packets: BiMap::new(),
send_packets: BiMap::new(),
recv_packet_builders: HashMap::new(),
send_streams: IndexMap::new(),
rx: IndexMap::new(),
new_send_streams: Arc::new(RwLock::new(vec![])),
new_rxs: Arc::new(RwLock::new(Vec::new())),
remote_connections: Arc::new(RwLock::new(HashMap::new())),
source: ("".to_string(), None),
next_receive_id: 0,
next_send_id: 0,
runtime: Arc::new(Some(runtime)),
},
Err(e) => {
panic!("Could not create a Tokio runtime for PacketManager. If you are calling new() from code that already has an async runtime available, use PacketManager.new_async(), and respective async_*() versions of APIs. -- {}", e);
}
}
}
/// Create a new `PacketManager`
///
/// If calling from a synchronous context, use [`new()`](`PacketManager::new()`)
pub fn new_for_async() -> Self {
PacketManager {
receive_packets: BiMap::new(),
send_packets: BiMap::new(),
recv_packet_builders: HashMap::new(),
send_streams: IndexMap::new(),
rx: IndexMap::new(),
new_send_streams: Arc::new(RwLock::new(vec![])),
new_rxs: Arc::new(Default::default()),
remote_connections: Arc::new(RwLock::new(HashMap::new())),
source: ("".to_string(), None),
next_receive_id: 0,
next_send_id: 0,
runtime: Arc::new(None),
}
}
/// Initialize a client side `PacketManager`
///
/// # Arguments
///
/// * `client_config` - Client configuration
///
/// # Returns
/// A [`Result`] containing `()` if successful, else a [`ConnectionError`] on error
///
/// # Panics
/// When the `PacketManager` does not have a runtime instance associated with it, which can happen if you created
/// the `PacketManager` using [`new_for_async()`](`PacketManager::new_for_async()`) instead of [`new()`](`PacketManager::new()`).
pub fn init_client(&mut self, client_config: ClientConfig) -> Result<(), ConnectionError> {
match self.runtime.as_ref() {
None => {
panic!("PacketManager does not have a runtime instance associated with it. Did you mean to call async_init_client()?");
}
Some(runtime) => {
self.validate_connection_prereqs(
client_config.num_receive_streams,
client_config.num_send_streams,
)?;
self.source.0 = client_config.addr.clone();
runtime.block_on(PacketManager::init_client_helper(
client_config,
&self.runtime,
&self.new_rxs,
&self.new_send_streams,
&self.remote_connections,
&mut self.source.1,
))
}
}
}
/// Initialize a client side `PacketManager`, to be used if calling from an async context
///
/// # Arguments
///
/// * `client_config` - Client configuration
///
/// # Returns
/// A `Future` that returns a [`Result`] containing `()` if successful, else a [`ConnectionError`] on error
///
/// # Panics
/// When the `PacketManager` has a runtime instance associated with it, which can happen if you created
/// the `PacketManager` using [`new()`](`PacketManager::new()`) instead of [`new_for_async()`](`PacketManager::new_for_async()`).
pub async fn async_init_client(
&mut self,
client_config: ClientConfig,
) -> Result<(), ConnectionError> {
if self.runtime.is_some() {
panic!("PacketManager has a runtime instance associated with it. If you are using async_init_client(), make sure you create the PacketManager using new_for_async(), not new()");
}
self.validate_connection_prereqs(
client_config.num_receive_streams,
client_config.num_send_streams,
)?;
self.source.0 = client_config.addr.clone();
PacketManager::init_client_helper(
client_config,
&self.runtime,
&self.new_rxs,
&self.new_send_streams,
&self.remote_connections,
&mut self.source.1,
)
.await
}
/// Initialize a server side `PacketManager`
///
/// # Arguments
///
/// * `server_config` - Server configuration
///
/// # Returns
/// A [`Result`] containing `()` if successful, else a [`ConnectionError`] on error
///
/// # Panics
/// When the `PacketManager` does not have a runtime instance associated with it, which can happen if you created
/// the `PacketManager` using [`new_for_async()`](`PacketManager::new_for_async()`) instead of [`new()`](`PacketManager::new()`).
pub fn init_server(&mut self, server_config: ServerConfig) -> Result<(), ConnectionError> {
match self.runtime.as_ref() {
None => {
panic!("PacketManager does not have a runtime instance associated with it. Did you mean to call async_init_server()?");
}
Some(runtime) => {
self.validate_connection_prereqs(
server_config.num_receive_streams,
server_config.num_send_streams,
)?;
self.source.0 = server_config.addr.clone();
runtime.block_on(PacketManager::init_server_helper(
server_config,
&self.runtime,
&self.new_rxs,
&self.new_send_streams,
&self.remote_connections,
&mut self.source.1,
))
}
}
}
/// Initialize a server side `PacketManager`, to be used if calling from an async context
///
/// # Arguments
///
/// * `server_config` - Server configuration
///
/// # Returns
/// A `Future` that returns a [`Result`] containing `()` if successful, else a [`ConnectionError`] on error
///
/// # Panics
/// When the `PacketManager` has a runtime instance associated with it, which can happen if you created
/// the `PacketManager` using [`new()`](`PacketManager::new()`) instead of [`new_for_async()`](`PacketManager::new_for_async()`).
pub async fn async_init_server(
&mut self,
server_config: ServerConfig,
) -> Result<(), ConnectionError> {
if self.runtime.is_some() {
panic!("PacketManager has a runtime instance associated with it. If you are using async_init_server(), make sure you create the PacketManager using new_for_async(), not new()");
}
self.validate_connection_prereqs(
server_config.num_receive_streams,
server_config.num_send_streams,
)?;
self.source.0 = server_config.addr.clone();
PacketManager::init_server_helper(
server_config,
&self.runtime,
&self.new_rxs,
&self.new_send_streams,
&self.remote_connections,
&mut self.source.1,
)
.await
}
fn validate_connection_prereqs(
&self,
num_incoming_streams: u32,
num_outgoing_streams: u32,
) -> Result<(), ConnectionError> {
let num_receive_packets = self.receive_packets.len() as u32;
if num_receive_packets != num_incoming_streams {
return Err(ConnectionError::new(format!("num_incoming_streams={} does not match number of registered receive packets={}. Did you forget to call register_receive_packet()?", num_incoming_streams, num_receive_packets)));
}
let num_send_packets = self.send_packets.len() as u32;
if num_send_packets != num_outgoing_streams {
return Err(ConnectionError::new(format!("num_outgoing_streams={} does not match number of registered send packets={}. Did you forget to call register_send_packet()?", num_incoming_streams, num_send_packets)));
}
Ok(())
}
async fn init_server_helper(
server_config: ServerConfig,
runtime: &Arc<Option<Runtime>>,
new_rxs: &Arc<RwLock<Vec<(u32, HashMap<u32, (RwLock<Receiver<Bytes>>, JoinHandle<()>)>)>>>,
new_send_streams: &Arc<RwLock<Vec<(u32, HashMap<u32, RwLock<SendStream>>)>>>,
client_connections: &Arc<RwLock<HashMap<u32, (String, Connection)>>>,
source_endpoint: &mut Option<Arc<Endpoint>>,
) -> Result<(), ConnectionError> {
debug!("Initiating server with {:?}", server_config);
let (endpoint, server_cert) = make_server_endpoint(
server_config.addr.parse()?,
server_config.keep_alive_interval,
server_config.idle_timeout,
server_config.alpn_protocols,
)?;
let endpoint = Arc::new(endpoint);
let _ = source_endpoint.insert(Arc::clone(&endpoint));
let num_receive_streams = server_config.num_receive_streams;
let num_send_streams = server_config.num_send_streams;
// TODO: use synchronous blocks during read and write of client_connections
// Single connection
for i in 0..server_config.wait_for_clients {
let incoming_conn = endpoint.accept().await.unwrap();
let conn = incoming_conn.await?;
let addr = conn.remote_address();
if client_connections.read().await.contains_key(&i) {
panic!(
"[server] Client with addr={} was already connected as remote_id={}",
addr, i
);
}
println!(
"[server] connection accepted: addr={}, remote_id={}",
conn.remote_address(),
i
);
let (server_send_streams, recv_streams) = PacketManager::open_streams_for_connection(
i,
&conn,
num_receive_streams,
num_send_streams,
)
.await?;
let res = PacketManager::spawn_receive_thread(i, recv_streams, runtime.as_ref())?;
new_rxs.write().await.push((i, res));
new_send_streams.write().await.push((i, server_send_streams));
client_connections.write().await.insert(i, (addr.to_string(), conn));
}
if server_config.total_expected_clients.is_none()
|| server_config.total_expected_clients.unwrap() > server_config.wait_for_clients
{
let remote_id = Arc::new(Mutex::new(server_config.wait_for_clients));
// TODO: save this value
for i in 0..server_config.max_concurrent_accepts {
debug!("Spinning up client connection accept thread #{}", i);
let client_connections = client_connections.clone();
let arc_send_streams = new_send_streams.clone();
let arc_rx = new_rxs.clone();
let arc_runtime = Arc::clone(runtime);
let endpoint = Arc::clone(&endpoint);
let remote_id_clone = Arc::clone(&remote_id);
// TODO: refactor
let accept_client_task = async move {
match server_config.total_expected_clients {
None => loop {
debug!("[server] Waiting for more clients...");
let incoming_conn = endpoint.accept().await.unwrap();
let conn = incoming_conn.await?;
let addr = conn.remote_address();
let mut id = remote_id_clone.lock().await;
if client_connections.read().await.contains_key(&*id) {
panic!("[server] Client with addr={} was already connected as remote_id={}", addr, id);
}
debug!("[server] connection accepted: addr={}", conn.remote_address());
let (send_streams, recv_streams) =
PacketManager::open_streams_for_connection(
*id,
&conn,
num_receive_streams,
num_send_streams,
)
.await?;
let res = PacketManager::spawn_receive_thread(
*id,
recv_streams,
arc_runtime.as_ref(),
)?;
arc_rx.write().await.push((*id, res));
arc_send_streams.write().await.push((*id, send_streams));
client_connections.write().await.insert(*id, (addr.to_string(), conn));
*id += 1;
},
Some(expected_num_clients) => {
for i in 0..(expected_num_clients - server_config.wait_for_clients) {
debug!(
"[server] Waiting for client #{}",
i + server_config.wait_for_clients
);
let incoming_conn = endpoint.accept().await.unwrap();
let conn = incoming_conn.await?;
let addr = conn.remote_address();
let mut id = remote_id_clone.lock().await;
if client_connections.read().await.contains_key(&*id) {
panic!(
"[server] Client with addr={} was already connected as remote_id={}",
addr, id
);
}
debug!(
"[server] connection accepted: addr={}",
conn.remote_address()
);
let (send_streams, recv_streams) =
PacketManager::open_streams_for_connection(
*id,
&conn,
num_receive_streams,
num_send_streams,
)
.await?;
let res = PacketManager::spawn_receive_thread(
*id,
recv_streams,
arc_runtime.as_ref(),
)?;
arc_rx.write().await.push((*id, res));
arc_send_streams.write().await.push((*id, send_streams));
client_connections
.write()
.await
.insert(*id, (addr.to_string(), conn));
*id += 1;
}
}
}
Ok::<(), Box<ConnectionError>>(())
};
let accept_client_thread = match runtime.as_ref() {
None => tokio::spawn(accept_client_task),
Some(runtime) => runtime.spawn(accept_client_task),
};
}
}
Ok(())
}
// TODO: Add support for creating a client PacketManager using an existing endpoint
async fn init_client_helper(
client_config: ClientConfig,
runtime: &Arc<Option<Runtime>>,
new_rxs: &Arc<RwLock<Vec<(u32, HashMap<u32, (RwLock<Receiver<Bytes>>, JoinHandle<()>)>)>>>,
new_send_streams: &Arc<RwLock<Vec<(u32, HashMap<u32, RwLock<SendStream>>)>>>,
// For bookkeeping, but technically the "client_connection" will be the server only
client_connections: &Arc<RwLock<HashMap<u32, (String, Connection)>>>,
source_endpoint: &mut Option<Arc<Endpoint>>,
) -> Result<(), ConnectionError> {
debug!("Initiating client with {:?}", client_config);
// Bind this endpoint to a UDP socket on the given client address.
let endpoint = make_client_endpoint(
client_config.addr.parse()?,
&[],
client_config.keep_alive_interval,
client_config.idle_timeout,
client_config.alpn_protocols,
)?;
let endpoint = Arc::new(endpoint);
let _ = source_endpoint.insert(Arc::clone(&endpoint));
// Connect to the server passing in the server name which is supposed to be in the server certificate.
let conn = endpoint.connect(client_config.server_addr.parse()?, "server")?.await?;
let addr = conn.remote_address();
debug!("[client] connected: addr={}", addr);
let (client_send_streams, recv_streams) = PacketManager::open_streams_for_connection(
0,
&conn,
client_config.num_receive_streams,
client_config.num_send_streams,
)
.await?;
let res = PacketManager::spawn_receive_thread(0, recv_streams, runtime.as_ref())?;
// Client side defaults to only having the 1 server at "remote_id" 0
new_rxs.write().await.push((0, res));
new_send_streams.write().await.push((0, client_send_streams));
client_connections.write().await.insert(0, (addr.to_string(), conn));
Ok(())
}
async fn open_streams_for_connection(
remote_id: u32,
conn: &Connection,
num_incoming_streams: u32,
num_outgoing_streams: u32,
) -> Result<(HashMap<u32, RwLock<SendStream>>, HashMap<u32, RecvStream>), Box<dyn Error>> {
let mut send_streams = HashMap::new();
let mut recv_streams = HashMap::new();
// Note: Packets are not sent immediately upon the write. The thread needs to be kept
// open so that the packets can actually be sent over the wire to the client.
for i in 0..num_outgoing_streams {
trace!("Opening outgoing stream for remote_id={} packet id={}", remote_id, i);
let mut send_stream = conn.open_uni().await?;
trace!("Writing packet to {} for packet id {}", remote_id, i);
send_stream.write_u32(i).await?;
send_streams.insert(i, RwLock::new(send_stream));
}
for i in 0..num_incoming_streams {
trace!("Accepting incoming stream from {} for packet id {}", remote_id, i);
let mut recv = conn.accept_uni().await?;
trace!("Validating incoming packet from {} id {}", remote_id, i);
let id = recv.read_u32().await?;
trace!("Received incoming packet from {} with packet id {}", remote_id, id);
// if id >= self.next_receive_id {
// return Err(Box::new(ConnectionError::new(format!("Received unexpected packet ID {} from server", id))));
// }
recv_streams.insert(i, recv);
}
Ok((send_streams, recv_streams))
}
fn spawn_receive_thread(
remote_id: u32,
recv_streams: HashMap<u32, RecvStream>,
runtime: &Option<Runtime>,
) -> Result<HashMap<u32, (RwLock<Receiver<Bytes>>, JoinHandle<()>)>, Box<dyn Error>> {
let mut rxs = HashMap::new();
trace!(
"Spawning receive thread for remote_id={} for {} ids",
remote_id,
recv_streams.len()
);
for (id, mut recv_stream) in recv_streams.into_iter() {
let (tx, rx) = mpsc::channel(100);
let task = async move {
let mut partial_chunk: Option<Bytes> = None;
loop {
// TODO: relay error message
// TODO: configurable size limit
let chunk = recv_stream.read_chunk(usize::MAX, true).await;
if let Err(e) = &chunk {
match e {
ReadError::Reset(_) => {}
ReadError::ConnectionLost(_) => {
warn!("Receive stream for remote_id={}, packet id={} errored. This may mean the connection was closed prematurely: {:?}", remote_id, id, e);
break;
}
ReadError::UnknownStream => {}
ReadError::IllegalOrderedRead => {}
ReadError::ZeroRttRejected => {}
}
}
match chunk.unwrap() {
None => {
// TODO: Error
debug!(
"Receive stream for remote_id={}, packet id={} is finished, got None when reading chunks",
remote_id, id
);
break;
}
Some(chunk) => {
trace!(
"Received chunked packets for id={}, length={}",
id,
chunk.bytes.len()
);
let bytes;
match partial_chunk.take() {
None => {
bytes = chunk.bytes;
}
Some(part) => {
bytes = Bytes::from([part, chunk.bytes].concat());
trace!(
"Concatenated saved part and chunked packet: {:?}",
bytes
);
}
}
// TODO: Make trace log
trace!("Received bytes: {:?}", bytes);
let boundaries: Vec<usize> = bytes
.windows(FRAME_BOUNDARY.len())
.enumerate()
.filter(|(_, w)| matches!(*w, FRAME_BOUNDARY))
.map(|(i, _)| i)
.collect();
let mut offset = 0;
for i in boundaries.iter() {
// Reached end of bytes
if offset >= bytes.len() {
break;
}
let frame = bytes.slice(offset..*i);
match partial_chunk.take() {
None => {
if matches!(frame.as_ref(), FRAME_BOUNDARY) {
error!("Found a dangling FRAME_BOUNDARY in packet frame. This most likely is a bug in durian")
} else {
trace!(
"Transmitting received bytes of length {}",
frame.len()
);
// Should never have FRAME_BOUNDARY at this point
tx.send(frame).await.unwrap();
}
}
Some(part) => {
let reconstructed_frame =
Bytes::from([part, frame].concat());
if matches!(reconstructed_frame.as_ref(), FRAME_BOUNDARY) {
error!("Found a dangling FRAME_BOUNDARY in packet frame. This most likely is a bug in durian")
} else {
trace!(
"Transmitting reconstructed received bytes of length {}",
reconstructed_frame.len()
);
// Remove boundary if at beginning of reconstructed frame
if reconstructed_frame.starts_with(FRAME_BOUNDARY) {
tx.send(reconstructed_frame.slice(
FRAME_BOUNDARY.len() - 1
..reconstructed_frame.len(),
))
.await
.unwrap();
} else {
tx.send(reconstructed_frame).await.unwrap();
}
}
}
}
offset = i + FRAME_BOUNDARY.len();
}
// We got a partial chunk if there were no boundaries found, so the chunk couldn't be
// split to be sent to tx, or there is a leftover slice at the end that doesn't have the
// ending frame signaling end of a send()
if boundaries.is_empty()
|| (offset + FRAME_BOUNDARY.len() != bytes.len() - 1
|| !bytes.ends_with(FRAME_BOUNDARY))
{
let prefix_part = bytes.slice(offset..bytes.len());
match partial_chunk.take() {
None => {
partial_chunk = Some(prefix_part);
}
Some(part) => {
partial_chunk =
Some(Bytes::from([part, prefix_part].concat()))
}
}
}
}
}
}
};
let receive_thread: JoinHandle<()> = match runtime.as_ref() {
None => tokio::spawn(task),
Some(runtime) => runtime.spawn(task),
};
rxs.insert(id, (RwLock::new(rx), receive_thread));
}