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
use super::agent_transport::*;
use super::*;
use crate::candidate::candidate_base::{CandidateBase, CandidateBaseConfig};
use crate::candidate::candidate_peer_reflexive::CandidatePeerReflexiveConfig;
use crate::util::*;
pub type ChanCandidateTx = Option<Arc<mpsc::Sender<Option<Arc<dyn Candidate + Send + Sync>>>>>;
pub struct AgentInternal {
pub(crate) on_connected_tx: Option<mpsc::Sender<()>>,
pub(crate) on_connected_rx: Option<mpsc::Receiver<()>>,
pub(crate) done_tx: Option<mpsc::Sender<()>>,
pub(crate) done_rx: Option<mpsc::Receiver<()>>,
pub(crate) chan_candidate_tx: ChanCandidateTx,
pub(crate) chan_candidate_pair_tx: Option<mpsc::Sender<()>>,
pub(crate) chan_state_tx: Option<mpsc::Sender<ConnectionState>>,
pub(crate) on_connection_state_change_hdlr: Option<OnConnectionStateChangeHdlrFn>,
pub(crate) on_selected_candidate_pair_change_hdlr: Option<OnSelectedCandidatePairChangeHdlrFn>,
pub(crate) on_candidate_hdlr: Option<OnCandidateHdlrFn>,
pub(crate) force_candidate_contact_tx: mpsc::Sender<bool>,
pub(crate) force_candidate_contact_rx: Option<mpsc::Receiver<bool>>,
pub(crate) tie_breaker: u64,
pub(crate) is_controlling: bool,
pub(crate) lite: bool,
pub(crate) start_time: Instant,
pub(crate) nominated_pair: Option<Arc<CandidatePair>>,
pub(crate) connection_state: ConnectionState,
pub(crate) started_ch_tx: Option<broadcast::Sender<()>>,
pub(crate) max_binding_requests: u16,
pub(crate) host_acceptance_min_wait: Duration,
pub(crate) srflx_acceptance_min_wait: Duration,
pub(crate) prflx_acceptance_min_wait: Duration,
pub(crate) relay_acceptance_min_wait: Duration,
pub(crate) disconnected_timeout: Duration,
pub(crate) failed_timeout: Duration,
pub(crate) keepalive_interval: Duration,
pub(crate) check_interval: Duration,
pub(crate) local_ufrag: String,
pub(crate) local_pwd: String,
pub(crate) local_candidates: HashMap<NetworkType, Vec<Arc<dyn Candidate + Send + Sync>>>,
pub(crate) remote_ufrag: String,
pub(crate) remote_pwd: String,
pub(crate) remote_candidates: HashMap<NetworkType, Vec<Arc<dyn Candidate + Send + Sync>>>,
pub(crate) pending_binding_requests: Vec<BindingRequest>,
pub(crate) insecure_skip_verify: bool,
pub(crate) agent_conn: Arc<AgentConn>,
}
unsafe impl Send for AgentInternal {}
unsafe impl Sync for AgentInternal {}
impl AgentInternal {
pub(crate) async fn start_connectivity_checks(
&mut self,
agent_internal: Arc<Mutex<Self>>,
is_controlling: bool,
remote_ufrag: String,
remote_pwd: String,
) -> Result<(), Error> {
if self.started_ch_tx.is_none() {
return Err(ERR_MULTIPLE_START.to_owned());
}
log::debug!(
"Started agent: isControlling? {}, remoteUfrag: {}, remotePwd: {}",
is_controlling,
remote_ufrag,
remote_pwd
);
self.set_remote_credentials(remote_ufrag, remote_pwd)?;
self.is_controlling = is_controlling;
self.start();
self.started_ch_tx.take();
self.update_connection_state(ConnectionState::Checking)
.await;
self.request_connectivity_check();
self.connectivity_checks(agent_internal).await;
Ok(())
}
async fn contact(
agent_internal: &Arc<Mutex<Self>>,
last_connection_state: &mut ConnectionState,
checking_duration: &mut Instant,
) {
let mut ai = agent_internal.lock().await;
if ai.connection_state == ConnectionState::Failed {
*last_connection_state = ai.connection_state;
return;
}
if ai.connection_state == ConnectionState::Checking {
if *last_connection_state != ai.connection_state {
*checking_duration = Instant::now();
}
if Instant::now().duration_since(*checking_duration)
> ai.disconnected_timeout + ai.failed_timeout
{
ai.update_connection_state(ConnectionState::Failed).await;
*last_connection_state = ai.connection_state;
return;
}
}
ai.contact_candidates().await;
*last_connection_state = ai.connection_state;
}
async fn connectivity_checks(&mut self, agent_internal: Arc<Mutex<Self>>) {
const ZERO_DURATION: Duration = Duration::from_secs(0);
let mut last_connection_state = ConnectionState::Unspecified;
let mut checking_duration = Instant::now();
let (check_interval, keepalive_interval, disconnected_timeout, failed_timeout) = (
self.check_interval,
self.keepalive_interval,
self.disconnected_timeout,
self.failed_timeout,
);
if let (Some(mut force_candidate_contact_rx), Some(mut done_rx)) =
(self.force_candidate_contact_rx.take(), self.done_rx.take())
{
tokio::spawn(async move {
loop {
let mut interval = DEFAULT_CHECK_INTERVAL;
let mut update_interval = |x: Duration| {
if x != ZERO_DURATION && (interval == ZERO_DURATION || interval > x) {
interval = x;
}
};
match last_connection_state {
ConnectionState::New | ConnectionState::Checking => {
update_interval(check_interval);
}
ConnectionState::Connected | ConnectionState::Disconnected => {
update_interval(keepalive_interval);
}
_ => {}
};
update_interval(disconnected_timeout);
update_interval(failed_timeout);
let t = tokio::time::sleep(interval);
tokio::pin!(t);
tokio::select! {
_ = t.as_mut() => {
Self::contact(&agent_internal, &mut last_connection_state, &mut checking_duration).await;
},
_ = force_candidate_contact_rx.recv() => {
Self::contact(&agent_internal, &mut last_connection_state, &mut checking_duration).await;
},
_ = done_rx.recv() => {
return;
}
}
}
});
}
}
pub(crate) async fn update_connection_state(&mut self, new_state: ConnectionState) {
if self.connection_state != new_state {
if new_state == ConnectionState::Failed {
self.delete_all_candidates().await;
}
log::info!("Setting new connection state: {}", new_state);
self.connection_state = new_state;
if let Some(chan_state_tx) = &self.chan_state_tx {
let _ = chan_state_tx.send(new_state).await;
}
}
}
pub(crate) async fn set_selected_pair(&mut self, p: Option<Arc<CandidatePair>>) {
log::trace!("Set selected candidate pair: {:?}", p);
if let Some(p) = p {
p.nominated.store(true, Ordering::SeqCst);
{
let mut selected_pair = self.agent_conn.selected_pair.lock().await;
*selected_pair = Some(p);
}
self.update_connection_state(ConnectionState::Connected)
.await;
if let Some(chan_candidate_pair_tx) = &self.chan_candidate_pair_tx {
let _ = chan_candidate_pair_tx.send(()).await;
}
self.on_connected_tx.take();
} else {
let mut selected_pair = self.agent_conn.selected_pair.lock().await;
*selected_pair = None;
}
}
pub(crate) async fn ping_all_candidates(&mut self) {
log::trace!("pinging all candidates");
let mut pairs: Vec<(
Arc<dyn Candidate + Send + Sync>,
Arc<dyn Candidate + Send + Sync>,
)> = vec![];
{
let mut checklist = self.agent_conn.checklist.lock().await;
if checklist.is_empty() {
log::warn!(
"pingAllCandidates called with no candidate pairs. Connection is not possible yet."
);
}
for p in &mut *checklist {
let p_state = p.state.load(Ordering::SeqCst);
if p_state == CandidatePairState::Waiting as u8 {
p.state
.store(CandidatePairState::InProgress as u8, Ordering::SeqCst);
} else if p_state != CandidatePairState::InProgress as u8 {
continue;
}
if p.binding_request_count.load(Ordering::SeqCst) > self.max_binding_requests {
log::trace!("max requests reached for pair {}, marking it as failed", p);
p.state
.store(CandidatePairState::Failed as u8, Ordering::SeqCst);
} else {
p.binding_request_count.fetch_add(1, Ordering::SeqCst);
let local = p.local.clone();
let remote = p.remote.clone();
pairs.push((local, remote));
}
}
}
for (local, remote) in pairs {
self.ping_candidate(&local, &remote).await;
}
}
pub(crate) async fn add_pair(
&mut self,
local: Arc<dyn Candidate + Send + Sync>,
remote: Arc<dyn Candidate + Send + Sync>,
) {
let p = Arc::new(CandidatePair::new(local, remote, self.is_controlling));
let mut checklist = self.agent_conn.checklist.lock().await;
checklist.push(p);
}
pub(crate) async fn find_pair(
&self,
local: &Arc<dyn Candidate + Send + Sync>,
remote: &Arc<dyn Candidate + Send + Sync>,
) -> Option<Arc<CandidatePair>> {
let checklist = self.agent_conn.checklist.lock().await;
for p in &*checklist {
if p.local.equal(&**local) && p.remote.equal(&**remote) {
return Some(p.clone());
}
}
None
}
pub(crate) async fn validate_selected_pair(&mut self) -> bool {
let (valid, disconnected_time) = {
let selected_pair = self.agent_conn.selected_pair.lock().await;
(*selected_pair).as_ref().map_or_else(
|| (false, Duration::from_secs(0)),
|selected_pair| {
let disconnected_time = match SystemTime::now()
.duration_since(selected_pair.remote.last_received())
{
Ok(d) => d,
Err(_) => Duration::from_secs(0),
};
(true, disconnected_time)
},
)
};
if valid {
let mut total_time_to_failure = self.failed_timeout;
if total_time_to_failure != Duration::from_secs(0) {
total_time_to_failure += self.disconnected_timeout;
}
if total_time_to_failure != Duration::from_secs(0)
&& disconnected_time > total_time_to_failure
{
self.update_connection_state(ConnectionState::Failed).await;
} else if self.disconnected_timeout != Duration::from_secs(0)
&& disconnected_time > self.disconnected_timeout
{
self.update_connection_state(ConnectionState::Disconnected)
.await;
} else {
self.update_connection_state(ConnectionState::Connected)
.await;
}
}
valid
}
pub(crate) async fn check_keepalive(&mut self) {
let (local, remote) = {
let selected_pair = self.agent_conn.selected_pair.lock().await;
(*selected_pair)
.as_ref()
.map_or((None, None), |selected_pair| {
(
Some(selected_pair.local.clone()),
Some(selected_pair.remote.clone()),
)
})
};
if let (Some(local), Some(remote)) = (local, remote) {
let last_sent = match SystemTime::now().duration_since(local.last_sent()) {
Ok(d) => d,
Err(_) => Duration::from_secs(0),
};
let last_received = match SystemTime::now().duration_since(remote.last_received()) {
Ok(d) => d,
Err(_) => Duration::from_secs(0),
};
if (self.keepalive_interval != Duration::from_secs(0))
&& ((last_sent > self.keepalive_interval)
|| (last_received > self.keepalive_interval))
{
self.ping_candidate(&local, &remote).await;
}
}
}
fn request_connectivity_check(&self) {
let _ = self.force_candidate_contact_tx.try_send(true);
}
pub(crate) async fn add_remote_candidate(&mut self, c: &Arc<dyn Candidate + Send + Sync>) {
let network_type = c.network_type();
if let Some(cands) = self.remote_candidates.get(&network_type) {
for cand in cands {
if cand.equal(&**c) {
return;
}
}
}
if let Some(cands) = self.remote_candidates.get_mut(&network_type) {
cands.push(c.clone());
} else {
self.remote_candidates.insert(network_type, vec![c.clone()]);
}
let mut local_cands = vec![];
if let Some(cands) = self.local_candidates.get(&network_type) {
local_cands = cands.clone();
}
for cand in local_cands {
self.add_pair(cand, c.clone()).await;
}
self.request_connectivity_check();
}
pub(crate) async fn add_candidate(
&mut self,
c: &Arc<dyn Candidate + Send + Sync>,
) -> Result<(), Error> {
let initialized_ch = self
.started_ch_tx
.as_ref()
.map(tokio::sync::broadcast::Sender::subscribe);
self.start_candidate(c, initialized_ch).await;
let network_type = c.network_type();
if let Some(cands) = self.local_candidates.get(&network_type) {
for cand in cands {
if cand.equal(&**c) {
if let Err(err) = c.close().await {
log::warn!("Failed to close duplicate candidate: {}", err);
}
return Ok(());
}
}
}
if let Some(cands) = self.local_candidates.get_mut(&network_type) {
cands.push(c.clone());
} else {
self.local_candidates.insert(network_type, vec![c.clone()]);
}
let mut remote_cands = vec![];
if let Some(cands) = self.remote_candidates.get(&network_type) {
remote_cands = cands.clone();
}
for cand in remote_cands {
self.add_pair(c.clone(), cand).await;
}
self.request_connectivity_check();
if let Some(chan_candidate_tx) = &self.chan_candidate_tx {
let _ = chan_candidate_tx.send(Some(c.clone())).await;
}
Ok(())
}
pub(crate) async fn close(&mut self) -> Result<(), Error> {
if self.done_tx.is_none() {
return Err(ERR_CLOSED.to_owned());
}
self.delete_all_candidates().await;
self.started_ch_tx.take();
self.agent_conn.buffer.close().await;
self.update_connection_state(ConnectionState::Closed).await;
self.done_tx.take();
self.chan_candidate_tx.take();
self.chan_candidate_pair_tx.take();
self.chan_state_tx.take();
self.agent_conn.done.store(true, Ordering::SeqCst);
Ok(())
}
pub(crate) async fn delete_all_candidates(&mut self) {
for cs in &mut self.local_candidates.values_mut() {
for c in cs {
if let Err(err) = c.close().await {
log::warn!("Failed to close candidate {}: {}", c, err);
}
}
}
self.local_candidates.clear();
for cs in self.remote_candidates.values_mut() {
for c in cs {
if let Err(err) = c.close().await {
log::warn!("Failed to close candidate {}: {}", c, err);
}
}
}
self.remote_candidates.clear();
}
pub(crate) fn find_remote_candidate(
&self,
network_type: NetworkType,
addr: SocketAddr,
) -> Option<Arc<dyn Candidate + Send + Sync>> {
let (ip, port) = (addr.ip(), addr.port());
if let Some(cands) = self.remote_candidates.get(&network_type) {
for c in cands {
if c.address() == ip.to_string() && c.port() == port {
return Some(c.clone());
}
}
}
None
}
pub(crate) async fn send_binding_request(
&mut self,
m: &Message,
local: &Arc<dyn Candidate + Send + Sync>,
remote: &Arc<dyn Candidate + Send + Sync>,
) {
log::trace!("ping STUN from {} to {}", local, remote);
self.invalidate_pending_binding_requests(Instant::now());
self.pending_binding_requests.push(BindingRequest {
timestamp: Instant::now(),
transaction_id: m.transaction_id,
destination: remote.addr().await,
is_use_candidate: m.contains(ATTR_USE_CANDIDATE),
});
self.send_stun(m, local, remote).await;
}
pub(crate) async fn send_binding_success(
&mut self,
m: &Message,
local: &Arc<dyn Candidate + Send + Sync>,
remote: &Arc<dyn Candidate + Send + Sync>,
) {
let addr = remote.addr().await;
let (ip, port) = (addr.ip(), addr.port());
let (out, result) = {
let mut out = Message::new();
let result = out.build(&[
Box::new(m.clone()),
Box::new(BINDING_SUCCESS),
Box::new(XorMappedAddress { ip, port }),
Box::new(MessageIntegrity::new_short_term_integrity(
self.local_pwd.clone(),
)),
Box::new(FINGERPRINT),
]);
(out, result)
};
if let Err(err) = result {
log::warn!(
"Failed to handle inbound ICE from: {} to: {} error: {}",
local,
remote,
err
);
} else {
self.send_stun(&out, local, remote).await;
}
}
pub(crate) fn invalidate_pending_binding_requests(&mut self, filter_time: Instant) {
let initial_size = self.pending_binding_requests.len();
let mut temp = vec![];
for binding_request in self.pending_binding_requests.drain(..) {
if filter_time.duration_since(binding_request.timestamp) < MAX_BINDING_REQUEST_TIMEOUT {
temp.push(binding_request);
}
}
self.pending_binding_requests = temp;
let bind_requests_removed = initial_size - self.pending_binding_requests.len();
if bind_requests_removed > 0 {
log::trace!(
"Discarded {} binding requests because they expired",
bind_requests_removed
);
}
}
pub(crate) fn handle_inbound_binding_success(
&mut self,
id: TransactionId,
) -> Option<BindingRequest> {
self.invalidate_pending_binding_requests(Instant::now());
for i in 0..self.pending_binding_requests.len() {
if self.pending_binding_requests[i].transaction_id == id {
let valid_binding_request = self.pending_binding_requests.remove(i);
return Some(valid_binding_request);
}
}
None
}
pub(crate) async fn handle_inbound(
&mut self,
m: &mut Message,
local: &Arc<dyn Candidate + Send + Sync>,
remote: SocketAddr,
agent_internal: Arc<Mutex<Self>>,
) {
if m.typ.method != METHOD_BINDING
|| !(m.typ.class == CLASS_SUCCESS_RESPONSE
|| m.typ.class == CLASS_REQUEST
|| m.typ.class == CLASS_INDICATION)
{
log::trace!(
"unhandled STUN from {} to {} class({}) method({})",
remote,
local,
m.typ.class,
m.typ.method
);
return;
}
if self.is_controlling {
if m.contains(ATTR_ICE_CONTROLLING) {
log::debug!("inbound isControlling && a.isControlling == true");
return;
} else if m.contains(ATTR_USE_CANDIDATE) {
log::debug!("useCandidate && a.isControlling == true");
return;
}
} else if m.contains(ATTR_ICE_CONTROLLED) {
log::debug!("inbound isControlled && a.isControlling == false");
return;
}
let mut remote_candidate = self.find_remote_candidate(local.network_type(), remote);
if m.typ.class == CLASS_SUCCESS_RESPONSE {
if let Err(err) = assert_inbound_message_integrity(m, self.remote_pwd.as_bytes()) {
log::warn!("discard message from ({}), {}", remote, err);
return;
}
if let Some(rc) = &remote_candidate {
self.handle_success_response(m, local, rc, remote).await;
} else {
log::warn!("discard success message from ({}), no such remote", remote);
return;
}
} else if m.typ.class == CLASS_REQUEST {
let username = self.local_ufrag.clone() + ":" + self.remote_ufrag.as_str();
if let Err(err) = assert_inbound_username(m, &username) {
log::warn!("discard message from ({}), {}", remote, err);
return;
} else if let Err(err) = assert_inbound_message_integrity(m, self.local_pwd.as_bytes())
{
log::warn!("discard message from ({}), {}", remote, err);
return;
}
if remote_candidate.is_none() {
let (ip, port, network_type) = (remote.ip(), remote.port(), NetworkType::Udp4);
let prflx_candidate_config = CandidatePeerReflexiveConfig {
base_config: CandidateBaseConfig {
network: network_type.to_string(),
address: ip.to_string(),
port,
component: local.component(),
..CandidateBaseConfig::default()
},
rel_addr: "".to_owned(),
rel_port: 0,
};
match prflx_candidate_config
.new_candidate_peer_reflexive(Some(agent_internal))
.await
{
Ok(prflx_candidate) => remote_candidate = Some(Arc::new(prflx_candidate)),
Err(err) => {
log::error!("Failed to create new remote prflx candidate ({})", err);
return;
}
};
log::debug!("adding a new peer-reflexive candidate: {} ", remote);
if let Some(rc) = &remote_candidate {
self.add_remote_candidate(rc).await;
}
}
log::trace!("inbound STUN (Request) from {} to {}", remote, local);
if let Some(rc) = &remote_candidate {
self.handle_binding_request(m, local, rc).await;
}
}
if let Some(rc) = remote_candidate {
rc.seen(false);
}
}
pub(crate) async fn validate_non_stun_traffic(
&self,
local: &Arc<dyn Candidate + Send + Sync>,
remote: SocketAddr,
) -> bool {
self.find_remote_candidate(local.network_type(), remote)
.map_or(false, |remote_candidate| {
remote_candidate.seen(false);
true
})
}
pub(crate) fn set_remote_credentials(
&mut self,
remote_ufrag: String,
remote_pwd: String,
) -> Result<(), Error> {
if remote_ufrag.is_empty() {
return Err(ERR_REMOTE_UFRAG_EMPTY.to_owned());
} else if remote_pwd.is_empty() {
return Err(ERR_REMOTE_PWD_EMPTY.to_owned());
}
self.remote_ufrag = remote_ufrag;
self.remote_pwd = remote_pwd;
Ok(())
}
pub(crate) async fn send_stun(
&self,
msg: &Message,
local: &Arc<dyn Candidate + Send + Sync>,
remote: &Arc<dyn Candidate + Send + Sync>,
) {
if let Err(err) = local.write_to(&msg.raw, &**remote).await {
log::trace!("failed to send STUN message: {}", err);
}
}
async fn start_candidate(
&self,
candidate: &Arc<dyn Candidate + Send + Sync>,
initialized_ch: Option<broadcast::Receiver<()>>,
) {
let (closed_ch_tx, closed_ch_rx) = broadcast::channel(1);
{
let closed_ch = candidate.get_closed_ch();
let mut closed = closed_ch.lock().await;
*closed = Some(closed_ch_tx);
}
let cand = Arc::clone(candidate);
if let (Some(conn), Some(ai)) = (candidate.get_conn(), candidate.get_agent()) {
let conn = Arc::clone(conn);
let addr = candidate.addr().await;
let agent_internal = Arc::clone(ai);
tokio::spawn(async move {
let _ = CandidateBase::recv_loop(
cand,
agent_internal,
closed_ch_rx,
initialized_ch,
conn,
addr,
)
.await;
});
} else {
log::error!("Can't start due to conn is_none");
}
}
}