rsipstack 0.8.3

SIP Stack Rust library for building SIP applications
Documentation
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
use super::{
    key::TransactionKey,
    make_via_branch,
    timer::Timer,
    transaction::{Transaction, TransactionEvent, TransactionEventSender},
    CallIdFormat, SipConnection, TransactionReceiver, TransactionSender, TransactionTimer,
};
use crate::platform::mpsc::{error, unbounded_channel};
use crate::platform::sync::Mutex;
use crate::platform::sync::RwMap;
use crate::platform::CancellationToken;
use crate::prelude::*;
use crate::sip::{prelude::HeadersExt, SipMessage};
use crate::{
    dialog::DialogId,
    transport::{transport_layer::DomainResolver, SipAddr, TransportEvent, TransportLayer},
    Error, Result, VERSION,
};
use async_trait::async_trait;
use tracing::{debug, info, trace, warn};

pub trait MessageInspector: Send + Sync {
    fn before_send(&self, msg: SipMessage, dest: Option<&SipAddr>) -> SipMessage;
    fn after_received(&self, msg: SipMessage, from: Option<&SipAddr>) -> SipMessage;
}

#[async_trait]
pub trait TargetLocator: Send + Sync {
    async fn locate(&self, uri: &crate::sip::Uri) -> Result<SipAddr>;
}

#[async_trait]
pub trait TransportEventInspector: Send + Sync {
    async fn handle(&self, event: TransportEvent) -> Option<TransportEvent>;
}

pub struct EndpointOption {
    pub t1: Duration,
    /// RFC 3261 T2: the maximum retransmission interval for non-INVITE
    /// requests and INVITE responses (default 4s).
    pub t2: Duration,
    pub t4: Duration,
    pub t1x64: Duration,
    pub timerc: Duration,
    pub callid_suffix: Option<String>,
    pub callid_format: CallIdFormat,
    /// RFC 7044: advertise `histinfo` support on outgoing initial requests so
    /// remote proxies/UAs include History-Info in responses. Session-ID
    /// (RFC 7989) needs no switch: dialogs participate only when the
    /// application supplies a UUID or the peer sends a Session-ID header.
    pub history_info_enabled: bool,
    /// Whether a client INVITE transaction ACKs a 2xx final itself (default `true`).
    /// With `false` a 2xx moves the transaction straight to
    /// Terminated: no automatic ACK, no stored ACK.
    /// RFC 3261 section 17.1.1.2: the 2xx ACK is the TU's, end-to-end;
    /// proxies (section 16) must not ACK a 2xx and must see retransmitted 2xx.
    /// `true` keeps the UA behavior the dialog layer relies on.
    pub auto_ack_2xx: bool,
}

impl Default for EndpointOption {
    fn default() -> Self {
        EndpointOption {
            t1: Duration::from_millis(500),
            t2: Duration::from_secs(4),
            t4: Duration::from_secs(5),
            t1x64: Duration::from_millis(64 * 500),
            timerc: Duration::from_secs(180),
            callid_suffix: None,
            callid_format: CallIdFormat::default(),
            history_info_enabled: false,
            auto_ack_2xx: true,
        }
    }
}

pub struct EndpointStats {
    pub running_transactions: usize,
    pub finished_transactions: usize,
    pub waiting_ack: usize,
}

/// SIP Endpoint Core Implementation
///
/// `EndpointInner` is the core implementation of a SIP endpoint that manages
/// transactions, timers, and transport layer communication. It serves as the
/// central coordination point for all SIP protocol operations.
///
/// # Key Responsibilities
///
/// * Managing active SIP transactions
/// * Handling SIP timers (Timer A, B, D, E, F, G, K)
/// * Coordinating with the transport layer
/// * Processing incoming and outgoing SIP messages
/// * Maintaining transaction state and cleanup
///
/// # Fields
///
/// * `allows` - List of supported SIP methods
/// * `user_agent` - User-Agent header value for outgoing messages
/// * `timers` - Timer management system for SIP timers
/// * `transport_layer` - Transport layer for network communication
/// * `finished_transactions` - Cache of completed transactions
/// * `transactions` - Active transaction senders
/// * `incoming_sender` - Channel for incoming transaction notifications
/// * `cancel_token` - Cancellation token for graceful shutdown
/// * `timer_interval` - Interval for timer processing
/// * `t1`, `t4`, `t1x64` - SIP timer values as per RFC 3261
///
/// # Timer Values
///
/// * `t1` - RTT estimate (default 500ms)
/// * `t4` - Maximum duration a message will remain in the network (default 4s)
/// * `t1x64` - Maximum retransmission timeout (default 32s)
pub struct EndpointInner {
    pub allows: Mutex<Option<Vec<crate::sip::Method>>>,
    pub user_agent: String,
    pub timers: Timer<TransactionTimer>,
    pub transport_layer: TransportLayer,
    pub finished_transactions: RwMap<TransactionKey, Option<SipMessage>>,
    pub transactions: RwMap<TransactionKey, TransactionEventSender>,
    pub(crate) record_receipt_times: core::sync::atomic::AtomicBool,
    pub(crate) receipt_times: RwMap<TransactionKey, Arc<super::receipt::ReceiptTimes>>,
    pub(crate) legacy_ack_tags: RwMap<TransactionKey, Option<String>>,
    pub waiting_ack: RwMap<DialogId, TransactionKey>,
    /// Server INVITE transactions waiting for the ACK of their 2xx, by dialog
    /// and INVITE CSeq number: `waiting_ack` holds only a dialog's latest
    /// INVITE, and the ACK of an earlier one can arrive after it (§13.2.2.4).
    pub(crate) waiting_ack_cseq: RwMap<(DialogId, u32), TransactionKey>,
    incoming_sender: TransactionSender,
    incoming_receiver: Mutex<Option<TransactionReceiver>>,
    cancel_token: CancellationToken,
    #[allow(dead_code)]
    timer_interval: Duration,
    pub(super) message_inspector: Option<Box<dyn MessageInspector>>,
    pub(crate) locator: Option<Box<dyn TargetLocator>>,
    pub(super) transport_inspector: Option<Box<dyn TransportEventInspector>>,
    pub option: EndpointOption,
}
pub type EndpointInnerRef = Arc<EndpointInner>;

/// SIP Endpoint Builder
///
/// `EndpointBuilder` provides a fluent interface for constructing SIP endpoints
/// with custom configuration. It follows the builder pattern to allow flexible
/// endpoint configuration.
///
/// # Examples
///
/// ```rust
/// use rsipstack::EndpointBuilder;
/// use core::time::Duration;
///
/// let endpoint = EndpointBuilder::new()
///     .with_user_agent("MyApp/1.0")
///     .with_timer_interval(Duration::from_millis(10))
///     .with_allows(vec![rsipstack::sip::Method::Invite, rsipstack::sip::Method::Bye])
///     .build();
/// ```
pub struct EndpointBuilder {
    allows: Vec<crate::sip::Method>,
    user_agent: String,
    transport_layer: Option<TransportLayer>,
    cancel_token: Option<CancellationToken>,
    timer_interval: Option<Duration>,
    option: Option<EndpointOption>,
    message_inspector: Option<Box<dyn MessageInspector>>,
    target_locator: Option<Box<dyn TargetLocator>>,
    transport_inspector: Option<Box<dyn TransportEventInspector>>,
    domain_resolver: Option<Box<dyn DomainResolver>>,
}

/// SIP Endpoint
///
/// `Endpoint` is the main entry point for SIP protocol operations. It provides
/// a high-level interface for creating and managing SIP transactions, handling
/// incoming requests, and coordinating with the transport layer.
///
/// # Key Features
///
/// * Transaction management and lifecycle
/// * Automatic timer handling per RFC 3261
/// * Transport layer abstraction
/// * Graceful shutdown support
/// * Incoming request processing
///
/// # Examples
///
/// ```rust,no_run
/// use rsipstack::EndpointBuilder;
/// use tokio_util::sync::CancellationToken;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let endpoint = EndpointBuilder::new()
///         .with_user_agent("MyApp/1.0")
///         .build();
///     
///     // Get incoming transactions
///     let mut incoming = endpoint.incoming_transactions().expect("incoming_transactions");
///     
///     // Start the endpoint
///     let endpoint_inner = endpoint.inner.clone();
///     tokio::spawn(async move {
///          endpoint_inner.serve().await.ok();
///     });
///     
///     // Process incoming transactions
///     while let Some(transaction) = incoming.recv().await {
///         // Handle transaction
///         break; // Exit for example
///     }
///     
///     Ok(())
/// }
/// ```
///
/// # Lifecycle
///
/// 1. Create endpoint using `EndpointBuilder`
/// 2. Start serving with `serve()` method
/// 3. Process incoming transactions via `incoming_transactions()`
/// 4. Shutdown gracefully with `shutdown()`
pub struct Endpoint {
    pub inner: EndpointInnerRef,
}

impl EndpointInner {
    pub fn new(
        user_agent: String,
        transport_layer: TransportLayer,
        cancel_token: CancellationToken,
        timer_interval: Option<Duration>,
        allows: Vec<crate::sip::Method>,
        option: Option<EndpointOption>,
        message_inspector: Option<Box<dyn MessageInspector>>,
        locator: Option<Box<dyn TargetLocator>>,
        transport_inspector: Option<Box<dyn TransportEventInspector>>,
    ) -> Arc<Self> {
        let (incoming_sender, incoming_receiver) = unbounded_channel();
        Arc::new(EndpointInner {
            allows: Mutex::new(Some(allows)),
            user_agent,
            timers: Timer::new(),
            transport_layer,
            transactions: RwMap::<TransactionKey, TransactionEventSender>::new(),
            record_receipt_times: core::sync::atomic::AtomicBool::new(false),
            receipt_times: RwMap::new(),
            legacy_ack_tags: RwMap::new(),
            finished_transactions: RwMap::<TransactionKey, Option<SipMessage>>::new(),
            waiting_ack: RwMap::<DialogId, TransactionKey>::new(),
            waiting_ack_cseq: RwMap::new(),
            timer_interval: timer_interval.unwrap_or(Duration::from_millis(20)),
            cancel_token,
            incoming_sender,
            incoming_receiver: Mutex::new(Some(incoming_receiver)),
            option: option.unwrap_or_default(),
            message_inspector,
            locator,
            transport_inspector,
        })
    }

    pub async fn serve(self: &Arc<Self>) -> Result<()> {
        use crate::platform::select::Which3;
        let mut cancelled_f = core::pin::pin!(self.cancel_token.cancelled());
        let mut timer_f = core::pin::pin!(self.process_timer());
        let mut transport_f = core::pin::pin!(self.clone().process_transport_layer());
        match crate::platform::select::select3(&mut cancelled_f, &mut timer_f, &mut transport_f)
            .await
        {
            Which3::A(()) => {}
            Which3::B(()) => {}
            Which3::C(r) => {
                r?;
            }
        }
        Ok(())
    }

    // process transport layer, receive message from transport layer
    async fn process_transport_layer(self: Arc<Self>) -> Result<()> {
        #[cfg_attr(not(feature = "platform-tokio"), allow(unused_mut))]
        let mut transport_rx = match self.transport_layer.inner.transport_rx.lock().take() {
            Some(rx) => rx,
            None => {
                return Err(Error::EndpointError("transport_rx not set".to_string()));
            }
        };

        // Claim the receiver before starting listeners: another serve() call
        // must fail without spawning a second reader on the same socket.
        self.transport_layer.serve_listens().await.ok();

        while let Some(mut event) = transport_rx.recv().await {
            if let Some(transport_inspector) = &self.transport_inspector {
                match transport_inspector.handle(event).await {
                    Some(e) => {
                        event = e;
                    }
                    None => {
                        continue;
                    }
                }
            }

            match event {
                TransportEvent::Incoming(msg, connection, from) => {
                    match self.on_received_message(msg, connection, &from).await {
                        Ok(()) => {}
                        Err(e) => {
                            warn!(addr = %from, error = %e, "on_received_message error");
                        }
                    }
                }
                TransportEvent::New(t) => {
                    debug!(addr=%t.get_addr(), "new connection");
                }
                TransportEvent::Closed(t) => {
                    debug!(addr=%t.get_addr(), "closed connection");
                }
            }
        }
        Ok(())
    }

    pub async fn process_timer(&self) {
        loop {
            for t in self.timers.wait_for_ready().await.into_iter() {
                if let TransactionTimer::TimerCleanup(key) = t {
                    trace!(%key, "TimerCleanup");
                    self.transactions.remove(&key);
                    self.finished_transactions.remove(&key);
                    self.legacy_ack_tags.remove(&key);
                    self.waiting_ack.retain(|_, v| v != &key);
                    self.waiting_ack_cseq.retain(|_, v| v != &key);
                    continue;
                }

                if let Some(tu) = self.transactions.get(t.key()) {
                    match tu.send(TransactionEvent::Timer(t)) {
                        Ok(_) => {}
                        Err(error::SendError(t)) => {
                            if let TransactionEvent::Timer(t) = t {
                                self.detach_transaction(t.key(), None);
                            }
                        }
                    }
                }
            }
        }
    }

    // Note: This function used for determine destination of response message, from via of the request
    pub async fn get_destination_from_request(&self, req: &crate::sip::Request) -> Option<SipAddr> {
        let (transport, host_with_port) =
            SipConnection::parse_target_from_via(req.via_header().ok()?).ok()?;

        let sip_addr = SipAddr {
            r#type: Some(transport),
            addr: host_with_port,
        };

        if matches!(sip_addr.addr.host, crate::sip::Host::Domain(_)) {
            return self
                .transport_layer
                .inner
                .domain_resolver
                .resolve(&sip_addr)
                .await
                .ok();
        }
        Some(sip_addr)
    }

    // receive message from transport layer
    pub async fn on_received_message(
        self: &Arc<Self>,
        msg: SipMessage,
        connection: SipConnection,
        from: &SipAddr,
    ) -> Result<()> {
        let received_at = self
            .record_receipt_times
            .load(core::sync::atomic::Ordering::Relaxed)
            .then(crate::dialog::lifecycle::LifecycleTime::now);
        let mut key = match &msg {
            SipMessage::Request(req) => {
                TransactionKey::from_request(req, super::key::TransactionRole::Server)?
            }
            SipMessage::Response(resp) => {
                TransactionKey::from_response(resp, super::key::TransactionRole::Client)?
            }
        };
        match &msg {
            SipMessage::Request(req) => {
                if key.is_legacy() && req.method != crate::sip::Method::Ack {
                    if let Some(existing) = self.match_legacy_request(&key) {
                        key = existing;
                    }
                }
                if req.method == crate::sip::Method::Ack {
                    // A 2xx ACK follows dialog/CSeq rules, even for a legacy
                    // INVITE. A non-2xx ACK follows transaction rules instead.
                    let accepted = DialogId::try_from((req, super::key::TransactionRole::Server))
                        .ok()
                        .and_then(|id| {
                            req.cseq_header()
                                .and_then(|c| c.seq())
                                .ok()
                                .and_then(|seq| self.waiting_ack_cseq.get(&(id, seq)))
                        });
                    if let Some(accepted) = accepted {
                        key = accepted;
                    } else if key.is_legacy() {
                        let candidate = self.legacy_ack_tags.with(|m| {
                            key.candidates(m).find_map(|(candidate, tag)| {
                                key.matches_legacy_ack(candidate, tag)
                                    .then(|| candidate.clone())
                            })
                        });
                        let Some(candidate) = candidate else {
                            return Ok(());
                        };
                        key = candidate;
                    }
                }
                // check is the termination of an existing transaction
                let last_message = self.finished_transactions.get(&key).and_then(|v| v.clone());

                if let Some(last_message) = last_message {
                    // ACK for a completed ServerInvite transaction: absorb it silently
                    // and clean up the waiting_ack entry.
                    if req.method() == &crate::sip::Method::Ack {
                        if let Ok(dialog_id) =
                            DialogId::try_from((req, super::key::TransactionRole::Server))
                        {
                            self.forget_waiting_ack(dialog_id, req, &key);
                        }
                        return Ok(());
                    }
                    // For INVITE retransmissions, re-send the last response
                    let dest = if !connection.is_reliable() {
                        self.get_destination_from_request(req).await
                    } else {
                        None
                    };
                    connection.send(last_message, dest.as_ref()).await?;
                    return Ok(());
                }
                if req.method == crate::sip::Method::Cancel && !self.transactions.contains_key(&key)
                {
                    // A CANCEL has its own key/cache. Only this explicit lookup
                    // associates it with a request being cancelled (§9.2).
                    if let Some(original) = self.transactions.with(|m| {
                        key.candidates(m)
                            .map(|(k, _)| k)
                            .find(|k| key.cancels(k))
                            .cloned()
                    }) {
                        key = original;
                    } else {
                        let response = self.finished_transactions.with(|m| {
                            key.candidates(m).find_map(|(k, v)| {
                                if !key.cancels(k) {
                                    return None;
                                }
                                match v {
                                    Some(SipMessage::Response(r))
                                        if r.status_code.kind()
                                            != crate::sip::StatusCodeKind::Provisional =>
                                    {
                                        Some(r.clone())
                                    }
                                    _ => None,
                                }
                            })
                        });
                        let status = if response.is_some() {
                            crate::sip::StatusCode::OK
                        } else {
                            crate::sip::StatusCode::CallTransactionDoesNotExist
                        };
                        return self
                            .reply_cancel(req, status, response.as_ref(), &connection)
                            .await;
                    }
                }
            }
            SipMessage::Response(resp) => {
                let last_message = self
                    .finished_transactions
                    .get(&key)
                    .and_then(|v| v.clone())
                    .filter(|_| {
                        // Never replay a cached ACK for a successful response
                        // that still has an upstream recipient.
                        !(resp.status_code.kind() == crate::sip::StatusCodeKind::Successful
                            && resp.has_multiple_vias())
                    });

                if let Some(mut last_message) = last_message {
                    if let SipMessage::Request(ref mut last_req) = last_message {
                        if last_req.method() == &crate::sip::Method::Ack {
                            match resp.status_code.kind() {
                                crate::sip::StatusCodeKind::Provisional => {
                                    return Ok(());
                                }
                                crate::sip::StatusCodeKind::Successful
                                    if last_req.to_header()?.tag().ok().is_none() =>
                                {
                                    // don't ack 2xx response when ack is placeholder
                                    return Ok(());
                                }
                                _ => {}
                            }

                            if let Ok(Some(tag)) = resp.to_header().and_then(|h| h.tag()) {
                                last_req.to_header_mut().and_then(|h| h.mut_tag(tag)).ok();
                            }

                            if let crate::sip::StatusCodeKind::RequestFailure =
                                resp.status_code.kind()
                            {
                                // for ACK to 487, send it where it came from
                                connection.send(last_message, Some(from)).await?;
                                return Ok(());
                            }

                            let dest_uri = last_req.destination();
                            let dest = match SipAddr::try_from(&dest_uri).ok() {
                                Some(addr)
                                    if matches!(addr.addr.host, crate::sip::Host::Domain(_)) =>
                                {
                                    self.transport_layer
                                        .inner
                                        .domain_resolver
                                        .resolve(&addr)
                                        .await
                                        .ok()
                                }
                                addr => addr,
                            };

                            connection.send(last_message, dest.as_ref()).await?;
                        }
                    }
                    return Ok(());
                }
            }
        };

        let msg = if let Some(inspector) = &self.message_inspector {
            inspector.after_received(msg, Some(from))
        } else {
            msg
        };

        if let Some(tu) = self.transactions.get(&key) {
            if let (Some(time), Some(receipts)) = (received_at, self.receipt_times.get(&key)) {
                receipts.record(&msg, time);
            }
            tu.send(TransactionEvent::Received(msg, Some(connection)))
                .map_err(|e| Error::TransactionError(e.to_string(), key))?;
            return Ok(());
        }
        // if the transaction is not exist, create a new transaction
        let request = match msg {
            SipMessage::Request(req) => req,
            SipMessage::Response(resp) => {
                if resp.cseq_header()?.method()? != crate::sip::Method::Cancel {
                    debug!(%key, response = %resp, "the transaction does not exist");
                }
                return Ok(());
            }
        };

        match request.method {
            crate::sip::Method::Cancel => {
                let status = crate::sip::StatusCode::CallTransactionDoesNotExist;
                return self.reply_cancel(&request, status, None, &connection).await;
            }
            crate::sip::Method::Ack => return Ok(()),
            _ => {}
        }

        let mut tx =
            Transaction::new_server(key.clone(), request.clone(), self.clone(), Some(connection));
        tx.original_received_at = received_at;

        self.incoming_sender.send(tx).ok();
        Ok(())
    }

    fn match_legacy_request(&self, incoming: &TransactionKey) -> Option<TransactionKey> {
        self.transactions
            .with(|m| {
                incoming
                    .candidates(m)
                    .map(|(k, _)| k)
                    .find(|k| incoming.matches_request(k))
                    .cloned()
            })
            .or_else(|| {
                self.finished_transactions.with(|m| {
                    incoming
                        .candidates(m)
                        .map(|(k, _)| k)
                        .find(|k| incoming.matches_request(k))
                        .cloned()
                })
            })
    }

    pub(crate) fn cached_cancel_response(&self, req: &crate::sip::Request) -> Option<SipMessage> {
        let key = TransactionKey::from_request(req, super::key::TransactionRole::Server).ok()?;
        if key.is_legacy() {
            self.finished_transactions.with(|m| {
                key.candidates(m)
                    .find_map(|(k, v)| key.matches_request(k).then(|| v.clone()).flatten())
            })
        } else {
            self.finished_transactions.get(&key).flatten()
        }
    }

    /// A CANCEL is immediately answered with a final response. Keep its own
    /// Completed transaction for Timer J on an unreliable transport (§17.2.2).
    pub(crate) fn cache_cancel_response(
        &self,
        req: &crate::sip::Request,
        response: &SipMessage,
        reliable: bool,
    ) {
        if reliable {
            return;
        }
        if let Ok(key) = TransactionKey::from_request(req, super::key::TransactionRole::Server) {
            if self.cached_cancel_response(req).is_some() {
                return;
            }
            self.finished_transactions
                .insert(key.clone(), Some(response.clone()));
            self.timers
                .timeout(self.option.t1x64, TransactionTimer::TimerCleanup(key));
        }
    }

    /// Answer a CANCEL that no live transaction handles.
    async fn reply_cancel(
        &self,
        req: &crate::sip::Request,
        status: crate::sip::StatusCode,
        invite_response: Option<&crate::sip::Response>,
        connection: &SipConnection,
    ) -> Result<()> {
        let resp = self.make_cancel_response(req, status, invite_response);
        let resp = if let Some(ref inspector) = self.message_inspector {
            inspector.before_send(resp.into(), None)
        } else {
            resp.into()
        };
        let dest = if !connection.is_reliable() {
            self.get_destination_from_request(req).await
        } else {
            None
        };
        self.cache_cancel_response(req, &resp, connection.is_reliable());
        connection.send(resp, dest.as_ref()).await
    }

    pub fn attach_transaction(&self, key: &TransactionKey, tu_sender: TransactionEventSender) {
        trace!(%key, "attach transaction");
        self.transactions.insert(key.clone(), tu_sender);
    }

    pub fn detach_transaction(&self, key: &TransactionKey, last_message: Option<SipMessage>) {
        trace!(%key, "detach transaction");
        self.transactions.remove(key);
        self.receipt_times.remove(key);

        if last_message.is_none() {
            self.legacy_ack_tags.remove(key);
        }
        if let Some(msg) = last_message {
            self.timers.timeout(
                self.option.t1x64,
                TransactionTimer::TimerCleanup(key.clone()), // maybe use TimerK ???
            );

            self.finished_transactions.insert(key.clone(), Some(msg));
        }
    }

    pub fn get_addrs(&self) -> Vec<SipAddr> {
        self.transport_layer.get_addrs()
    }

    pub fn get_record_route(&self) -> Result<crate::sip::typed::RecordRoute> {
        let first_addr = self
            .transport_layer
            .get_addrs()
            .first()
            .ok_or(Error::EndpointError("not sipaddrs".to_string()))
            .cloned()?;
        Ok(self.get_record_route_with_addr(first_addr))
    }

    /// Record-Route advertising `addr` instead of the endpoint's first listener, for an
    /// endpoint with several listeners where the one a peer must use is not the first.
    pub fn get_record_route_with_addr(&self, addr: SipAddr) -> crate::sip::typed::RecordRoute {
        let mut uri: crate::sip::Uri = addr.into();
        uri.params.push(crate::sip::Param::Lr);
        crate::sip::typed::RecordRoute {
            display_name: None,
            uri,
            params: vec![],
        }
    }

    pub fn get_via(
        &self,
        addr: Option<crate::transport::SipAddr>,
        branch: Option<crate::sip::Param>,
    ) -> Result<crate::sip::typed::Via> {
        let first_addr = match addr {
            Some(addr) => addr,
            None => self
                .transport_layer
                .get_addrs()
                .first()
                .ok_or(Error::EndpointError("not sipaddrs".to_string()))
                .cloned()?,
        };

        let transport = first_addr.r#type.unwrap_or_default();
        let mut params = vec![
            branch.unwrap_or_else(make_via_branch),
            crate::sip::Param::Rport(None),
        ];
        // RFC 5923: alias parameter tells the proxy to reuse this TCP connection
        // for sending requests back to us (essential for NAT traversal over TCP).
        if transport == crate::sip::Transport::Tcp || transport == crate::sip::Transport::Tls {
            params.push(crate::sip::Param::Other("alias".into(), None));
        }
        let via = crate::sip::typed::Via {
            version: crate::sip::Version::V2,
            transport,
            uri: first_addr.addr.into(),
            params,
        };
        Ok(via)
    }

    /// Drop `key`'s ACK routes for `dialog_id`, never another transaction's.
    pub(crate) fn forget_waiting_ack(
        &self,
        dialog_id: DialogId,
        req: &crate::sip::Request,
        key: &TransactionKey,
    ) {
        if let Ok(seq) = req.cseq_header().and_then(|c| c.seq()) {
            let route = (dialog_id.clone(), seq);
            self.waiting_ack_cseq.with_mut(|m| {
                if m.get(&route) == Some(key) {
                    m.remove(&route);
                }
            });
        }
        self.waiting_ack.with_mut(|m| {
            if m.get(&dialog_id) == Some(key) {
                m.remove(&dialog_id);
            }
        });
    }

    pub fn get_running_transactions(&self) -> Option<Vec<TransactionKey>> {
        Some(self.transactions.with(|m| m.keys().cloned().collect()))
    }

    pub fn get_stats(&self) -> EndpointStats {
        let waiting_ack = self.waiting_ack.len();
        let running_transactions = self.transactions.len();
        let finished_transactions = self.finished_transactions.len();

        EndpointStats {
            running_transactions,
            finished_transactions,
            waiting_ack,
        }
    }
}

impl Default for EndpointBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl EndpointBuilder {
    pub fn new() -> Self {
        EndpointBuilder {
            allows: Vec::new(),
            user_agent: VERSION.to_string(),
            transport_layer: None,
            cancel_token: None,
            timer_interval: None,
            option: None,
            message_inspector: None,
            target_locator: None,
            transport_inspector: None,
            domain_resolver: None,
        }
    }

    pub fn with_option(&mut self, option: EndpointOption) -> &mut Self {
        self.option = Some(option);
        self
    }

    pub fn with_user_agent(&mut self, user_agent: &str) -> &mut Self {
        self.user_agent = user_agent.to_string();
        self
    }

    pub fn with_transport_layer(&mut self, transport_layer: TransportLayer) -> &mut Self {
        self.transport_layer.replace(transport_layer);
        self
    }

    pub fn with_cancel_token(&mut self, cancel_token: CancellationToken) -> &mut Self {
        self.cancel_token.replace(cancel_token);
        self
    }

    pub fn with_timer_interval(&mut self, timer_interval: Duration) -> &mut Self {
        self.timer_interval.replace(timer_interval);
        self
    }
    pub fn with_allows(&mut self, allows: Vec<crate::sip::Method>) -> &mut Self {
        self.allows = allows;
        self
    }
    pub fn with_inspector(&mut self, inspector: Box<dyn MessageInspector>) -> &mut Self {
        self.message_inspector = Some(inspector);
        self
    }
    pub fn with_target_locator(&mut self, locator: Box<dyn TargetLocator>) -> &mut Self {
        self.target_locator = Some(locator);
        self
    }

    pub fn with_transport_inspector(
        &mut self,
        inspector: Box<dyn TransportEventInspector>,
    ) -> &mut Self {
        self.transport_inspector = Some(inspector);
        self
    }

    pub fn with_domain_resolver(&mut self, resolver: Box<dyn DomainResolver>) -> &mut Self {
        self.domain_resolver = Some(resolver);
        self
    }

    pub fn build(&mut self) -> Endpoint {
        let cancel_token = self.cancel_token.take().unwrap_or_default();
        let transport_layer = self.transport_layer.take().unwrap_or_else(|| {
            if let Some(resolver) = self.domain_resolver.take() {
                TransportLayer::new_with_domain_resolver(cancel_token.clone(), resolver)
            } else {
                TransportLayer::new(cancel_token.clone())
            }
        });

        let allows = self.allows.to_owned();
        let user_agent = self.user_agent.to_owned();
        let timer_interval = self.timer_interval.to_owned();
        let option = self.option.take();
        let message_inspector = self.message_inspector.take();
        let locator = self.target_locator.take();
        let transport_inspector = self.transport_inspector.take();

        let core = EndpointInner::new(
            user_agent,
            transport_layer,
            cancel_token,
            timer_interval,
            allows,
            option,
            message_inspector,
            locator,
            transport_inspector,
        );

        Endpoint { inner: core }
    }
}

impl Endpoint {
    /// Start the registered transport listeners and process SIP transactions.
    /// Configure transports before calling this method, and call it only once
    /// per endpoint. Further calls log an error without starting more listeners.
    pub async fn serve(&self) {
        let inner = self.inner.clone();
        match inner.serve().await {
            Ok(()) => {
                info!("endpoint shutdown");
            }
            Err(e) => {
                warn!(error = ?e, "endpoint serve error");
            }
        }
    }

    pub fn shutdown(&self) {
        info!("endpoint shutdown requested");
        self.inner.cancel_token.cancel();
    }

    //
    // get incoming requests from the endpoint
    // don't call repeat!
    pub fn incoming_transactions(&self) -> Result<TransactionReceiver> {
        self.inner
            .incoming_receiver
            .lock()
            .take()
            .ok_or_else(|| Error::EndpointError("incoming recevier taken".to_string()))
    }

    pub fn get_addrs(&self) -> Vec<SipAddr> {
        self.inner.transport_layer.get_addrs()
    }
}