scion-stack 0.5.2

SCION endhost network stack
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
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
// Copyright 2025 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! # The SCION endhost stack.
//!
//! [ScionStack] is a stateful object that is the conceptual equivalent of the
//! TCP/IP-stack found in today's common operating systems. It is meant to be
//! instantiated once per process.
//!
//! ## Basic Usage
//!
//! ### Creating a path-aware socket (recommended)
//!
//! ```
//! use scion_proto::address::SocketAddr;
//! use scion_stack::scionstack::{ScionStack, ScionStackBuilder};
//! use url::Url;
//!
//! # async fn socket_example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a SCION stack builder
//! let control_plane_addr: url::Url = "http://127.0.0.1:1234".parse()?;
//! let builder = ScionStackBuilder::new().with_auth_token("SNAP token".to_string());
//!
//! let scion_stack = builder.build().await?;
//! let socket = scion_stack.bind(None).await?;
//!
//! // Parse destination address
//! let destination: SocketAddr = "1-ff00:0:111,[192.168.1.1]:8080".parse()?;
//!
//! socket.send_to(b"hello", destination).await?;
//! let mut buffer = [0u8; 1024];
//! let (len, src) = socket.recv_from(&mut buffer).await?;
//! println!("Received: {:?} from {:?}", &buffer[..len], src);
//!
//! # Ok(())
//! # }
//! ```
//!
//! ### Creating a connected socket.
//!
//! ```
//! use scion_proto::address::SocketAddr;
//! use scion_stack::scionstack::{ScionStack, ScionStackBuilder};
//! use url::Url;
//!
//! # async fn connected_socket_example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a SCION stack builder
//! let control_plane_addr: url::Url = "http://127.0.0.1:1234".parse()?;
//! let builder = ScionStackBuilder::new().with_auth_token("SNAP token".to_string());
//!
//! // Parse destination address
//! let destination: SocketAddr = "1-ff00:0:111,[192.168.1.1]:8080".parse()?;
//!
//! let scion_stack = builder.build().await?;
//! let connected_socket = scion_stack.connect(destination, None).await?;
//! connected_socket.send(b"hello").await?;
//! let mut buffer = [0u8; 1024];
//! let len = connected_socket.recv(&mut buffer).await?;
//! println!("Received: {:?}", &buffer[..len]);
//!
//! # Ok(())
//! # }
//! ```
//!
//! ### Creating a path-unaware socket
//!
//! ```
//! use scion_proto::{address::SocketAddr, path::Path};
//! use scion_stack::scionstack::{ScionStack, ScionStackBuilder};
//! use url::Url;
//!
//! # async fn basic_socket_example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a SCION stack builder
//! let control_plane_addr: url::Url = "http://127.0.0.1:1234".parse()?;
//! let builder = ScionStackBuilder::new().with_auth_token("SNAP token".to_string());
//!
//! // Parse addresses
//! let bind_addr: SocketAddr = "1-ff00:0:110,[127.0.0.1]:8080".parse()?;
//! let destination: SocketAddr = "1-ff00:0:111,[127.0.0.1]:9090".parse()?;
//!
//! // Create a local path for demonstration
//! let path: scion_proto::path::Path<bytes::Bytes> = Path::local(bind_addr.isd_asn());
//!
//! let scion_stack = builder.build().await?;
//! let socket = scion_stack.bind_path_unaware(Some(bind_addr)).await?;
//! socket
//!     .send_to_via(b"hello", destination, &path.to_slice_path())
//!     .await?;
//! let mut buffer = [0u8; 1024];
//! let (len, sender) = socket.recv_from(&mut buffer).await?;
//! println!("Received: {:?} from {:?}", &buffer[..len], sender);
//!
//! # Ok(())
//! # }
//! ```
//!
//! ### Resolving SCION TXT records
//!
//! ```
//! use scion_stack::resolver::{ScionDnsResolver, txt::ScionTxtDnsResolver};
//!
//! # async fn resolve_example() -> Result<(), Box<dyn std::error::Error>> {
//! let resolver = ScionTxtDnsResolver::new()?;
//! let addresses = resolver.resolve("example.com").await?;
//!
//! for address in addresses {
//!     println!("Resolved: {}", address);
//! }
//!
//! # Ok(())
//! # }
//! ```
//!
//! ## Advanced Usage
//!
//! ### Custom path selection
//!
//! ```
//! // Implement your own path selection logic
//! use std::{sync::Arc, time::Duration};
//!
//! use bytes::Bytes;
//! use chrono::{DateTime, Utc};
//! use scion_proto::{
//!     address::{IsdAsn, SocketAddr},
//!     path::Path,
//! };
//! use scion_stack::{
//!     path::manager::traits::PathManager,
//!     scionstack::{ScionStack, ScionStackBuilder, UdpScionSocket},
//!     types::ResFut,
//! };
//!
//! struct MyCustomPathManager;
//!
//! impl scion_stack::path::manager::traits::SyncPathManager for MyCustomPathManager {
//!     fn register_path(
//!         &self,
//!         _src: IsdAsn,
//!         _dst: IsdAsn,
//!         _now: DateTime<Utc>,
//!         _path: Path<Bytes>,
//!     ) {
//!         // Optionally implement registration logic
//!     }
//!
//!     fn try_cached_path(
//!         &self,
//!         _src: IsdAsn,
//!         _dst: IsdAsn,
//!         _now: DateTime<Utc>,
//!     ) -> std::io::Result<Option<Path<Bytes>>> {
//!         todo!()
//!     }
//! }
//!
//! impl scion_stack::path::manager::traits::PathManager for MyCustomPathManager {
//!     fn path_wait(
//!         &self,
//!         src: IsdAsn,
//!         _dst: IsdAsn,
//!         _now: DateTime<Utc>,
//!     ) -> impl ResFut<'_, Path<Bytes>, scion_stack::path::manager::traits::PathWaitError>
//!     {
//!         async move { Ok(Path::local(src)) }
//!     }
//! }
//!
//! # async fn custom_pather_example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a SCION stack builder
//! let control_plane_addr: url::Url = "http://127.0.0.1:1234".parse()?;
//! let builder = ScionStackBuilder::new()
//!     .with_endhost_api(control_plane_addr)
//!     .with_auth_token("SNAP token".to_string());
//!
//! // Parse addresses
//! let bind_addr: SocketAddr = "1-ff00:0:110,[127.0.0.1]:8080".parse()?;
//! let destination: SocketAddr = "1-ff00:0:111,[127.0.0.1]:9090".parse()?;
//!
//! let scion_stack = builder.build().await?;
//! let path_unaware_socket = scion_stack.bind_path_unaware(Some(bind_addr)).await?;
//! let socket = UdpScionSocket::new(
//!     path_unaware_socket,
//!     Arc::new(MyCustomPathManager),
//!     Duration::from_secs(30),
//!     scion_stack::types::Subscribers::new(),
//! );
//! socket.send_to(b"hello", destination).await?;
//!
//! # Ok(())
//! # }
//! ```

pub mod builder;
pub mod quic;
pub mod scmp_handler;
pub mod socket;
pub(crate) mod udp_polling;

use std::{
    borrow::Cow,
    fmt, net,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
    time::Duration,
};

use anyhow::Context as _;
use bytes::Bytes;
use endhost_api_client::client::EndhostApiClient;
use futures::future::BoxFuture;
use quic::{AddressTranslator, Endpoint, ScionAsyncUdpSocket};
use scion_proto::{
    address::{Isd, IsdAsn, SocketAddr},
    packet::ScionPacketRaw,
    path::Path,
};
use scion_sdk_reqwest_connect_rpc::client::CrpcClientError;
use snap_tun::client::ConnectSnapTunSocketError;
pub use socket::{PathUnawareUdpScionSocket, RawScionSocket, ScmpScionSocket, UdpScionSocket};
use url::Url;

// Re-export the main types from the modules
pub use self::builder::ScionStackBuilder;
use crate::{
    path::{
        PathStrategy,
        fetcher::{EndhostApiSegmentFetcher, PathFetcherImpl, traits::SegmentFetcher},
        manager::{
            MultiPathManager, MultiPathManagerConfig,
            traits::{PathWaitError, PathWaitTimeoutError},
        },
        policy::PathPolicy,
        scoring::PathScoring,
    },
    scionstack::{
        scmp_handler::{ScmpErrorHandler, ScmpErrorReceiver, ScmpHandler},
        socket::SendErrorReceiver,
    },
    types::Subscribers,
};

/// The SCION stack can be used to create path-aware SCION sockets or even Quic over SCION
/// connections.
///
/// The SCION stack abstracts over the underlay stack that is used for the underlying
/// transport.
pub struct ScionStack {
    endhost_api: Option<Url>,
    client: Arc<dyn EndhostApiClient>,
    underlay: Arc<dyn DynUnderlayStack>,
    scmp_error_receivers: Subscribers<dyn ScmpErrorReceiver>,
    send_error_receivers: Subscribers<dyn SendErrorReceiver>,
}

impl fmt::Debug for ScionStack {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScionStack")
            .field("client", &"Arc<ConnectRpcClient>")
            .field("underlay", &"Arc<dyn DynUnderlayStack>")
            .finish()
    }
}

impl ScionStack {
    pub(crate) fn new(
        endhost_api: Option<Url>,
        client: Arc<dyn EndhostApiClient>,
        underlay: Arc<dyn DynUnderlayStack>,
    ) -> Self {
        Self {
            endhost_api,
            client,
            underlay,
            scmp_error_receivers: Subscribers::new(),
            send_error_receivers: Subscribers::new(),
        }
    }

    /// Create a path-aware SCION socket with automatic path management.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    ///
    /// # Returns
    /// A path-aware SCION socket.
    pub async fn bind(
        &self,
        bind_addr: Option<SocketAddr>,
    ) -> Result<UdpScionSocket, ScionSocketBindError> {
        self.bind_with_config(bind_addr, SocketConfig::default())
            .await
    }

    /// Create a path-aware SCION socket with custom configuration.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    /// * `socket_config` - Configuration for the socket.
    ///
    /// # Returns
    /// A path-aware SCION socket.
    pub async fn bind_with_config(
        &self,
        bind_addr: Option<SocketAddr>,
        mut socket_config: SocketConfig,
    ) -> Result<UdpScionSocket, ScionSocketBindError> {
        let socket = PathUnawareUdpScionSocket::new(
            self.underlay
                .bind_socket(SocketKind::Udp, bind_addr)
                .await?,
            vec![Box::new(ScmpErrorHandler::new(
                self.scmp_error_receivers.clone(),
            ))],
        );

        if !socket_config.disable_endhost_api_segment_fetcher {
            let connect_rpc_fetcher: Box<dyn SegmentFetcher> =
                Box::new(EndhostApiSegmentFetcher::new(self.client.clone()));
            socket_config
                .segment_fetchers
                .push(("Endhost API".into(), connect_rpc_fetcher));
        }
        let fetcher = PathFetcherImpl::new(
            socket_config.segment_fetchers,
            socket_config.segment_fetcher_timeout,
        );

        // Use default scorers if none are configured.
        if socket_config.path_strategy.scoring.is_empty() {
            socket_config.path_strategy.scoring.use_default_scorers();
        }

        let pather = Arc::new(
            MultiPathManager::new(
                MultiPathManagerConfig::default(),
                fetcher,
                socket_config.path_strategy,
            )
            .expect("should not fail with default configuration"),
        );

        // Register the path manager as a SCMP error receiver and send error receiver.
        self.scmp_error_receivers.register(pather.clone());
        self.send_error_receivers.register(pather.clone());

        Ok(UdpScionSocket::new(
            socket,
            pather,
            socket_config.connect_timeout,
            self.send_error_receivers.clone(),
        ))
    }

    /// Create a connected path-aware SCION socket with automatic path management.
    ///
    /// # Arguments
    /// * `remote_addr` - The remote address to connect to.
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    ///
    /// # Returns
    /// A connected path-aware SCION socket.
    pub async fn connect(
        &self,
        remote_addr: SocketAddr,
        bind_addr: Option<SocketAddr>,
    ) -> Result<UdpScionSocket, ScionSocketConnectError> {
        let socket = self.bind(bind_addr).await?;
        socket.connect(remote_addr).await
    }

    /// Create a connected path-aware SCION socket with custom configuration.
    ///
    /// # Arguments
    /// * `remote_addr` - The remote address to connect to.
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    /// * `socket_config` - Configuration for the socket
    ///
    /// # Returns
    /// A connected path-aware SCION socket.
    pub async fn connect_with_config(
        &self,
        remote_addr: SocketAddr,
        bind_addr: Option<SocketAddr>,
        socket_config: SocketConfig,
    ) -> Result<UdpScionSocket, ScionSocketConnectError> {
        let socket = self.bind_with_config(bind_addr, socket_config).await?;
        socket.connect(remote_addr).await
    }

    /// Create a socket that can send and receive SCMP messages.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    ///
    /// # Returns
    /// A SCMP socket.
    pub async fn bind_scmp(
        &self,
        bind_addr: Option<SocketAddr>,
    ) -> Result<ScmpScionSocket, ScionSocketBindError> {
        let socket = self
            .underlay
            .bind_socket(SocketKind::Scmp, bind_addr)
            .await?;
        Ok(ScmpScionSocket::new(socket))
    }

    /// Create a raw SCION socket.
    /// A raw SCION socket can be used to send and receive raw SCION packets.
    /// It is still bound to a specific UDP port because this is needed for packets
    /// to be routed in a dispatcherless autonomous system. See <https://docs.scion.org/en/latest/dev/design/router-port-dispatch.html> for a more detailed explanation.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    ///
    /// # Returns
    /// A raw SCION socket.
    pub async fn bind_raw(
        &self,
        bind_addr: Option<SocketAddr>,
    ) -> Result<RawScionSocket, ScionSocketBindError> {
        let socket = self
            .underlay
            .bind_socket(SocketKind::Raw, bind_addr)
            .await?;
        Ok(RawScionSocket::new(socket))
    }

    /// Create a path-unaware SCION socket for advanced use cases.
    ///
    /// This socket can send and receive datagrams, but requires explicit paths for sending.
    /// Use this when you need full control over path selection.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    ///
    /// # Returns
    /// A path-unaware SCION socket.
    pub async fn bind_path_unaware(
        &self,
        bind_addr: Option<SocketAddr>,
    ) -> Result<PathUnawareUdpScionSocket, ScionSocketBindError> {
        let socket = self
            .underlay
            .bind_socket(SocketKind::Udp, bind_addr)
            .await?;

        Ok(PathUnawareUdpScionSocket::new(socket, vec![]))
    }

    /// Create a QUIC over SCION endpoint.
    ///
    /// This is a convenience method that creates a QUIC (quinn) endpoint over a SCION socket.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    /// * `config` - The quinn endpoint configuration.
    /// * `server_config` - The quinn server configuration.
    /// * `runtime` - The runtime to spawn tasks on.
    ///
    /// # Returns
    /// A QUIC endpoint that can be used to accept or create QUIC connections.
    #[deprecated(
        since = "0.4.0",
        note = "will soon be removed; use the quic-scion crate instead"
    )]
    pub async fn quic_endpoint(
        &self,
        bind_addr: Option<SocketAddr>,
        config: anapaya_quinn::EndpointConfig,
        server_config: Option<anapaya_quinn::ServerConfig>,
        runtime: Option<Arc<dyn anapaya_quinn::Runtime>>,
    ) -> anyhow::Result<Endpoint> {
        #[allow(deprecated)]
        self.quic_endpoint_with_config(
            bind_addr,
            config,
            server_config,
            runtime,
            SocketConfig::default(),
        )
        .await
    }

    /// Create a QUIC over SCION endpoint using custom socket configuration.
    ///
    /// This is a convenience method that creates a QUIC (quinn) endpoint over a SCION socket.
    ///
    /// # Arguments
    /// * `bind_addr` - The address to bind the socket to. If None, an available address will be
    ///   used.
    /// * `config` - The quinn endpoint configuration.
    /// * `server_config` - The quinn server configuration.
    /// * `runtime` - The runtime to spawn tasks on.
    /// * `socket_config` - Scion Socket configuration
    ///
    /// # Returns
    /// A QUIC endpoint that can be used to accept or create QUIC connections.
    #[deprecated(
        since = "0.4.0",
        note = "will soon be removed; use the quic-scion crate instead"
    )]
    pub async fn quic_endpoint_with_config(
        &self,
        bind_addr: Option<SocketAddr>,
        config: anapaya_quinn::EndpointConfig,
        server_config: Option<anapaya_quinn::ServerConfig>,
        runtime: Option<Arc<dyn anapaya_quinn::Runtime>>,
        socket_config: SocketConfig,
    ) -> anyhow::Result<Endpoint> {
        let scmp_handlers: Vec<Box<dyn ScmpHandler>> = vec![Box::new(ScmpErrorHandler::new(
            self.scmp_error_receivers.clone(),
        ))];
        let socket = self
            .underlay
            .bind_async_udp_socket(bind_addr, scmp_handlers)
            .await?;
        let address_translator = Arc::new(AddressTranslator::default());

        let pather = {
            let mut segment_fetchers = socket_config.segment_fetchers;
            if !socket_config.disable_endhost_api_segment_fetcher {
                let connect_rpc_fetcher: Box<dyn SegmentFetcher> =
                    Box::new(EndhostApiSegmentFetcher::new(self.client.clone()));
                segment_fetchers.push(("Endhost API".into(), connect_rpc_fetcher));
            }
            let fetcher =
                PathFetcherImpl::new(segment_fetchers, socket_config.segment_fetcher_timeout);

            // Use default scorers if none are configured.
            let mut strategy = socket_config.path_strategy;
            if strategy.scoring.is_empty() {
                strategy.scoring.use_default_scorers();
            }

            Arc::new(
                MultiPathManager::new(MultiPathManagerConfig::default(), fetcher, strategy)
                    .map_err(|e| anyhow::anyhow!("failed to create path manager: {}", e))?,
            )
        };

        // Register the path manager as a SCMP error receiver.
        self.scmp_error_receivers.register(pather.clone());

        let local_scion_addr = socket.local_addr();

        let socket = Arc::new(ScionAsyncUdpSocket::new(
            socket,
            pather.clone(),
            address_translator.clone(),
        ));

        let runtime = match runtime {
            Some(runtime) => runtime,
            None => anapaya_quinn::default_runtime().context("No runtime found")?,
        };

        Ok(Endpoint::new_with_abstract_socket(
            config,
            server_config,
            socket,
            local_scion_addr,
            runtime,
            pather,
            address_translator,
        )?)
    }

    /// Get the list of local ISD-ASes available on the endhost.
    ///
    /// # Returns
    ///
    /// A list of local ISD-AS identifiers.
    pub fn local_ases(&self) -> Vec<IsdAsn> {
        self.underlay.local_ases()
    }

    /// Get the currently selected endhost API URL, if any.
    pub fn endhost_api(&self) -> Option<Url> {
        self.endhost_api.clone()
    }

    /// Creates a path manager with default configuration.
    pub fn create_path_manager(&self) -> MultiPathManager<PathFetcherImpl> {
        let fetcher = PathFetcherImpl::new(
            vec![(
                "Endhost API".into(),
                Box::new(EndhostApiSegmentFetcher::new(self.client.clone())),
            )],
            DEFAULT_SEGMENT_FETCHER_TIMEOUT,
        );
        let mut strategy = PathStrategy::default();

        strategy.scoring.use_default_scorers();

        MultiPathManager::new(MultiPathManagerConfig::default(), fetcher, strategy)
            .expect("should not fail with default configuration")
    }
}

/// Default timeout for creating a connected socket
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(30);

/// Default timeout for segment fetchers to avoid waiting indefinitely for slow or unresponsive
/// fetchers.
pub const DEFAULT_SEGMENT_FETCHER_TIMEOUT: Duration = Duration::from_secs(60);

/// Configuration for a path aware socket.
pub struct SocketConfig {
    pub(crate) segment_fetchers: Vec<(String, Box<dyn SegmentFetcher>)>,
    pub(crate) segment_fetcher_timeout: Duration,
    pub(crate) disable_endhost_api_segment_fetcher: bool,
    pub(crate) path_strategy: PathStrategy,
    pub(crate) connect_timeout: Duration,
}

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

impl SocketConfig {
    /// Creates a new default socket configuration.
    pub fn new() -> Self {
        Self {
            segment_fetchers: Vec::new(),
            segment_fetcher_timeout: DEFAULT_SEGMENT_FETCHER_TIMEOUT,
            disable_endhost_api_segment_fetcher: false,
            path_strategy: Default::default(),
            connect_timeout: DEFAULT_CONNECT_TIMEOUT,
        }
    }

    /// Adds a path policy.
    ///
    /// Path policies can restrict the set of usable paths based on their characteristics.
    /// E.g. filtering out paths that go through certain ASes.
    ///
    /// See [`HopPatternPolicy`](scion_proto::path::policy::hop_pattern::HopPatternPolicy) and
    /// [`AclPolicy`](scion_proto::path::policy::acl::AclPolicy)
    pub fn with_path_policy(mut self, policy: impl PathPolicy) -> Self {
        self.path_strategy.add_policy(policy);
        self
    }

    /// Add a path scoring strategy.
    ///
    /// Path scores signal which paths to prioritize based on their characteristics.
    ///
    /// `scoring` - The path scoring strategy to add.
    /// `impact` - The impact weight of the scoring strategy. Higher values increase the influence
    ///
    /// If no scoring strategies are added, scoring defaults to preferring shorter and more reliable
    /// paths.
    pub fn with_path_scoring(mut self, scoring: impl PathScoring, impact: f32) -> Self {
        self.path_strategy.scoring = self.path_strategy.scoring.with_scorer(scoring, impact);
        self
    }

    /// Sets connection timeout for `connect` functions
    ///
    /// Defaults to [DEFAULT_CONNECT_TIMEOUT]
    pub fn with_connection_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Add an additional segment fetcher.
    ///
    /// By default, only path segments retrieved via the endhost API are used. Adding additional
    /// segment fetchers enables to build paths from different segment sources.
    pub fn with_segment_fetcher(mut self, name: String, fetcher: Box<dyn SegmentFetcher>) -> Self {
        self.segment_fetchers.push((name, fetcher));
        self
    }

    /// Disable fetching path segments from the endhost API.
    pub fn disable_endhost_api_segment_fetcher(mut self) -> Self {
        self.disable_endhost_api_segment_fetcher = true;
        self
    }

    /// Sets the segment fetcher timeout. The timeout prevents waiting indefinitely for slow or
    /// unresponsive segment fetchers. If a fetcher does not respond within the timeout, it will be
    /// skipped for the current path lookup.
    ///
    /// Defaults to [DEFAULT_SEGMENT_FETCHER_TIMEOUT].
    pub fn with_segment_fetcher_timeout(mut self, timeout: Duration) -> Self {
        self.segment_fetcher_timeout = timeout;
        self
    }
}

/// Error return when binding a socket.
#[derive(Debug, thiserror::Error)]
pub enum ScionSocketBindError {
    /// The provided bind address cannot be bound to.
    /// E.g. because it is not assigned to the endhost or because the address
    /// type is not supported.
    #[error(transparent)]
    InvalidBindAddress(InvalidBindAddressError),
    /// The provided port is already in use.
    #[error("port {0} is already in use")]
    PortAlreadyInUse(u16),
    /// Failed to connect to SNAP data plane.
    #[error(transparent)]
    SnapConnectionError(SnapConnectionError),
    /// No underlay available to bind the requested address.
    #[error("underlay unavailable for the requested ISD: {0}")]
    NoUnderlayAvailable(Isd),
    /// An error that is not covered by the variants above.
    #[error("other error: {0}")]
    Other(#[from] Box<dyn std::error::Error + Send + Sync>),
}

/// Error related to the bind address of the socket.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum InvalidBindAddressError {
    /// The provided bind address is a service address.
    #[error("cannot bind to service addresses: {0}")]
    ServiceAddress(SocketAddr),
    /// The requested bind address cannot be bound to.
    #[error("cannot bind to requested address: {0}")]
    CannotBindToRequestedAddress(SocketAddr, Cow<'static, str>),
    /// The assigned address does not match the requested address.
    /// This is likely due to NAT.
    #[error(
        "assigned address ({assigned_addr}) does not match requested address ({bind_addr}), likely due to NAT"
    )]
    AddressMismatch {
        /// The assigned address.
        assigned_addr: SocketAddr,
        /// The requested bind address.
        bind_addr: SocketAddr,
    },
    /// Could not find any local IP address to bind to.
    #[error("could not find any local IP address to bind to")]
    NoLocalIpAddressFound,
}

/// Error related to the connection to the SNAP data plane.
#[derive(Debug, thiserror::Error)]
pub enum SnapConnectionError {
    /// Snap sockets cannot be bound without a SNAP token source.
    #[error("SNAP token source is missing")]
    SnapTokenSourceMissing,
    /// Error establishing the SNAP tunnel.
    #[error("error establishing SNAP tunnel: {0}")]
    TunnelEstablishmentError(#[from] ConnectSnapTunSocketError),
    /// Failed to create the SNAP control plane client.
    #[error("failed to create SNAP control plane client: {0}")]
    ControlPlaneClientCreationError(anyhow::Error),
    /// Failed to discover the SNAP data plane.
    #[error("failed to discover SNAP data plane: {0}")]
    DataPlaneDiscoveryError(CrpcClientError),
}

/// Available kinds of SCION sockets.
#[derive(Hash, Eq, PartialEq, Clone, Debug, Ord, PartialOrd)]
pub enum SocketKind {
    /// UDP socket.
    Udp,
    /// SCMP socket.
    Scmp,
    /// Raw socket.
    Raw,
}
/// A trait that defines the underlay stack.
///
/// The underlay stack is the underlying transport layer that is used to send and receive SCION
/// packets. Sockets returned by the underlay stack have no path management but allow
/// sending and receiving SCION packets.
pub(crate) trait UnderlayStack: Send + Sync {
    type Socket: UnderlaySocket + 'static;
    type AsyncUdpSocket: AsyncUdpUnderlaySocket + 'static;

    fn bind_socket(
        &self,
        kind: SocketKind,
        bind_addr: Option<SocketAddr>,
    ) -> BoxFuture<'_, Result<Self::Socket, ScionSocketBindError>>;

    fn bind_async_udp_socket(
        &self,
        bind_addr: Option<SocketAddr>,
        scmp_handlers: Vec<Box<dyn ScmpHandler>>,
    ) -> BoxFuture<'_, Result<Self::AsyncUdpSocket, ScionSocketBindError>>;

    /// Get the list of local ISD-ASes available on the endhost.
    fn local_ases(&self) -> Vec<IsdAsn>;
}

/// Dyn safe trait for an underlay stack.
pub(crate) trait DynUnderlayStack: Send + Sync {
    fn bind_socket(
        &self,
        kind: SocketKind,
        bind_addr: Option<SocketAddr>,
    ) -> BoxFuture<'_, Result<Box<dyn UnderlaySocket>, ScionSocketBindError>>;

    fn bind_async_udp_socket(
        &self,
        bind_addr: Option<SocketAddr>,
        scmp_handlers: Vec<Box<dyn ScmpHandler>>,
    ) -> BoxFuture<'_, Result<Arc<dyn AsyncUdpUnderlaySocket>, ScionSocketBindError>>;

    fn local_ases(&self) -> Vec<IsdAsn>;
}

impl<U: UnderlayStack> DynUnderlayStack for U {
    fn bind_socket(
        &self,
        kind: SocketKind,
        bind_addr: Option<SocketAddr>,
    ) -> BoxFuture<'_, Result<Box<dyn UnderlaySocket>, ScionSocketBindError>> {
        Box::pin(async move {
            let socket = self.bind_socket(kind, bind_addr).await?;
            Ok(Box::new(socket) as Box<dyn UnderlaySocket>)
        })
    }

    fn bind_async_udp_socket(
        &self,
        bind_addr: Option<SocketAddr>,
        scmp_handlers: Vec<Box<dyn ScmpHandler>>,
    ) -> BoxFuture<'_, Result<Arc<dyn AsyncUdpUnderlaySocket>, ScionSocketBindError>> {
        Box::pin(async move {
            let socket = self.bind_async_udp_socket(bind_addr, scmp_handlers).await?;
            Ok(Arc::new(socket) as Arc<dyn AsyncUdpUnderlaySocket>)
        })
    }

    fn local_ases(&self) -> Vec<IsdAsn> {
        <Self as UnderlayStack>::local_ases(self)
    }
}

/// SCION socket connect errors.
#[derive(Debug, thiserror::Error)]
pub enum ScionSocketConnectError {
    /// Could not get a path to the destination
    #[error("failed to get path to destination: {0}")]
    PathLookupError(#[from] PathWaitTimeoutError),
    /// Could not bind the socket
    #[error(transparent)]
    BindError(#[from] ScionSocketBindError),
}

/// SCION socket send errors.
#[derive(Debug, thiserror::Error)]
pub enum ScionSocketSendError {
    /// There was an error looking up the path in the path registry.
    #[error("path lookup error: {0}")]
    PathLookupError(#[from] PathWaitError),
    /// UDP underlay next hop unreachable. This is only
    /// returned if the selected underlay is UDP.
    #[error("udp next hop {address:?} unreachable: {isd_as}#{interface_id}: {msg}")]
    UnderlayNextHopUnreachable {
        /// ISD-AS of the next hop.
        isd_as: IsdAsn,
        /// Interface ID of the next hop.
        interface_id: u16,
        /// Address of the next hop, if known.
        address: Option<net::SocketAddr>,
        /// Additional message.
        msg: String,
    },
    /// The provided packet is invalid. The underlying socket is
    /// not able to process the packet.
    #[error("invalid packet: {0}")]
    InvalidPacket(Cow<'static, str>),
    /// The underlying socket is closed.
    #[error("underlying socket is closed")]
    Closed,
    /// IO Error from the underlying connection.
    #[error("underlying connection returned an I/O error: {0:?}")]
    IoError(#[from] std::io::Error),
    /// Error return when send is called on a socket that is not connected.
    #[error("socket is not connected")]
    NotConnected,
}

/// Minimum size of the path buffer required by [`ScionSocketReceiveError::PathBufTooSmall`].
///
/// This constant can be used to allocate a correctly-sized path buffer when calling
/// [`UdpScionSocket::recv_from_with_path`](crate::scionstack::UdpScionSocket::recv_from_with_path)
/// or the corresponding method on [`PathUnawareUdpScionSocket`].
pub const MIN_PATH_BUFFER_SIZE: usize = 1024;

/// SCION socket receive errors.
#[derive(Debug, thiserror::Error)]
pub enum ScionSocketReceiveError {
    /// Path buffer too small.
    #[error("provided path buffer is too small (at least {MIN_PATH_BUFFER_SIZE} bytes required)")]
    PathBufTooSmall,
    /// I/O error.
    #[error("i/o error: {0:?}")]
    IoError(#[from] std::io::Error),
    /// Error return when recv is called on a socket that is not connected.
    #[error("socket is not connected")]
    NotConnected,
}

/// A trait that defines an abstraction over an asynchronous underlay socket.
/// The socket sends and receives raw SCION packets. Decoding of the next layer
/// protocol or SCMP handling is left to the caller.
pub(crate) trait UnderlaySocket: 'static + Send + Sync {
    /// Send a raw packet. Takes a ScionPacketRaw because it needs to read the path
    /// to resolve the underlay next hop.
    fn send<'a>(
        &'a self,
        packet: ScionPacketRaw,
    ) -> BoxFuture<'a, Result<(), ScionSocketSendError>>;

    /// Try to send a raw packet immediately. Takes a ScionPacketRaw because it needs to read the
    /// path to resolve the underlay next hop.
    fn try_send(&self, packet: ScionPacketRaw) -> Result<(), ScionSocketSendError>;

    /// Receive a raw SCION packet.
    fn recv<'a>(&'a self) -> BoxFuture<'a, Result<ScionPacketRaw, ScionSocketReceiveError>>;

    /// Get the local socket address of this socket.
    fn local_addr(&self) -> SocketAddr;

    /// The SNAP data plane the socket is connected to (if SNAP underlay is used).
    fn snap_data_plane(&self) -> Option<net::SocketAddr>;
}

/// A trait that defines an asynchronous path unaware UDP socket.
/// This can be used to implement the [anapaya_quinn::AsyncUdpSocket] trait.
pub(crate) trait AsyncUdpUnderlaySocket: Send + Sync {
    fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn udp_polling::UdpPoller>>;
    /// Try to send a raw SCION UDP packet. Path resolution and packet encoding is
    /// left to the caller.
    /// This function should return std::io::ErrorKind::WouldBlock if the packet cannot be sent
    /// immediately.
    fn try_send(&self, raw_packet: ScionPacketRaw) -> Result<(), std::io::Error>;
    /// Poll for receiving a SCION packet with sender and path.
    /// This function will only return valid UDP packets.
    /// SCMP packets will be handled internally.
    fn poll_recv_from_with_path(
        &self,
        cx: &mut Context,
    ) -> Poll<std::io::Result<(SocketAddr, Bytes, Path)>>;
    /// Get the local socket address of this socket.
    fn local_addr(&self) -> SocketAddr;
    /// The SNAP data plane the socket is connected to (if SNAP underlay is used).
    fn snap_data_plane(&self) -> Option<net::SocketAddr>;
}

impl Drop for ScionStack {
    fn drop(&mut self) {
        tracing::warn!("ScionStack was dropped");
    }
}