l2tp 0.4.0

High-level L2TP interface for Linux kernel
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
// SPDX-License-Identifier: MIT

//! Blocking counterparts of the async API.
//!
//! [`L2tpHandle`] runs a dedicated thread with its own current-thread Tokio
//! runtime that owns the async [`crate::L2tpHandle`]. Every blocking call
//! hands its work to that thread and waits on a channel, so it never blocks
//! on or nests inside the caller's runtime: calling it from a plain thread,
//! from `tokio::task::spawn_blocking`, or from inside another runtime all
//! work. Calling it from an async task blocks that task's thread, as any
//! blocking call would.
//!
//! The handles returned here own their async counterparts and hand them back
//! to the worker thread when dropped, so the best-effort deletion on drop
//! keeps working. The worker thread stops once the last [`L2tpHandle`] clone
//! and every handle created from it are gone, after pending deletions have
//! completed.

use std::{
    future::Future,
    pin::Pin,
    sync::{Arc, Mutex, mpsc},
    thread::{JoinHandle, ThreadId},
};

use futures::{
    StreamExt,
    future::{self, Either},
};

use crate::{
    IpEndpoint, L2tpEvent, L2tpIfName, NetNs, SessionConfig, SessionId,
    SessionInfo, SessionModify, SessionStats, TunnelConfig, TunnelId,
    TunnelInfo, TunnelSocket, TunnelStats, UdpEndpoint,
};

type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
type Task = Box<dyn FnOnce(crate::L2tpHandle) -> BoxFuture + Send + 'static>;

struct Worker {
    tasks: Option<tokio::sync::mpsc::UnboundedSender<Task>>,
    thread: Mutex<Option<JoinHandle<()>>>,
    thread_id: ThreadId,
}

impl Worker {
    fn send(&self, task: Task) -> crate::Result<()> {
        self.tasks
            .as_ref()
            .and_then(|tasks| tasks.send(task).ok())
            .ok_or_else(|| crate::Error::other("the l2tp worker has stopped"))
    }
}

impl Drop for Worker {
    fn drop(&mut self) {
        // Closing the channel lets the worker finish pending deletions and
        // exit; joining it is only possible from another thread.
        drop(self.tasks.take());
        if std::thread::current().id() != self.thread_id
            && let Ok(mut thread) = self.thread.lock()
            && let Some(thread) = thread.take()
        {
            let _ = thread.join();
        }
    }
}

/// Blocking counterpart of [`crate::L2tpHandle`].
///
/// Clones share the worker thread and its netlink connection.
#[derive(Clone)]
pub struct L2tpHandle {
    worker: Arc<Worker>,
}

impl std::fmt::Debug for L2tpHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("blocking::L2tpHandle")
            .field("thread_id", &self.worker.thread_id)
            .finish_non_exhaustive()
    }
}

impl L2tpHandle {
    /// Starts the worker thread and opens the netlink connection in the
    /// calling thread's network namespace.
    pub fn new() -> crate::Result<Self> {
        Self::start(None)
    }

    /// Starts the worker thread with its netlink connection in `netns`,
    /// which needs `CAP_SYS_ADMIN`; see [`NetNs`].
    pub fn new_in(netns: &NetNs) -> crate::Result<Self> {
        Self::start(Some(netns.try_clone()?))
    }

    fn start(netns: Option<NetNs>) -> crate::Result<Self> {
        let (task_tx, mut task_rx) =
            tokio::sync::mpsc::unbounded_channel::<Task>();
        let (ready_tx, ready_rx) = mpsc::sync_channel::<crate::Result<()>>(1);
        let thread = std::thread::Builder::new()
            .name("l2tp-blocking".to_string())
            .spawn(move || {
                let runtime =
                    match tokio::runtime::Builder::new_current_thread()
                        .enable_io()
                        .build()
                    {
                        Ok(runtime) => runtime,
                        Err(err) => {
                            let _ = ready_tx.send(Err(err.into()));
                            return;
                        }
                    };
                runtime.block_on(async move {
                    let handle = match &netns {
                        None => crate::L2tpHandle::new().await,
                        Some(netns) => crate::L2tpHandle::new_in(netns).await,
                    };
                    let handle = match handle {
                        Ok(handle) => handle,
                        Err(err) => {
                            let _ = ready_tx.send(Err(err));
                            return;
                        }
                    };
                    if ready_tx.send(Ok(())).is_err() {
                        return;
                    }
                    let mut tasks = tokio::task::JoinSet::new();
                    loop {
                        // Reap finished tasks while accepting new ones, so
                        // the set holds only the work in flight.
                        let task = if tasks.is_empty() {
                            task_rx.recv().await
                        } else {
                            let recv = task_rx.recv();
                            futures::pin_mut!(recv);
                            let join = tasks.join_next();
                            futures::pin_mut!(join);
                            match future::select(recv, join).await {
                                Either::Left((task, _)) => task,
                                Either::Right(_) => continue,
                            }
                        };
                        match task {
                            Some(task) => {
                                tasks.spawn(task(handle.clone()));
                            }
                            None => break,
                        }
                    }
                    // Let deletions queued by dropped handles finish.
                    while tasks.join_next().await.is_some() {}
                });
            })?;
        let thread_id = thread.thread().id();
        ready_rx.recv().map_err(|_| {
            crate::Error::other("the l2tp worker stopped during startup")
        })??;
        Ok(Self {
            worker: Arc::new(Worker {
                tasks: Some(task_tx),
                thread: Mutex::new(Some(thread)),
                thread_id,
            }),
        })
    }

    /// Runs `f` on the worker and waits for its result.
    fn call<T, F, Fut>(&self, f: F) -> crate::Result<T>
    where
        T: Send + 'static,
        F: FnOnce(crate::L2tpHandle) -> Fut + Send + 'static,
        Fut: Future<Output = crate::Result<T>> + Send + 'static,
    {
        let (tx, rx) = mpsc::sync_channel(1);
        self.worker.send(Box::new(move |handle| {
            Box::pin(async move {
                let _ = tx.send(f(handle).await);
            })
        }))?;
        rx.recv().unwrap_or_else(|_| {
            Err(crate::Error::other("the l2tp worker dropped the request"))
        })
    }

    /// Runs `f` on the worker without waiting for it.
    fn detach<F, Fut>(&self, f: F)
    where
        F: FnOnce(crate::L2tpHandle) -> Fut + Send + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let _ = self
            .worker
            .send(Box::new(move |handle| Box::pin(f(handle))));
    }

    /// See [`crate::L2tpHandle::create_tunnel`].
    pub fn create_tunnel(
        &self,
        config: TunnelConfig,
        socket: TunnelSocket,
    ) -> crate::Result<TunnelHandle> {
        let inner = self.call(move |handle| async move {
            handle.create_tunnel(config, socket).await
        })?;
        Ok(TunnelHandle::new(inner, self.clone()))
    }

    /// See [`crate::L2tpHandle::create_unmanaged_tunnel`].
    pub fn create_unmanaged_tunnel(
        &self,
        config: TunnelConfig,
    ) -> crate::Result<TunnelHandle> {
        let inner = self.call(move |handle| async move {
            handle.create_unmanaged_tunnel(config).await
        })?;
        Ok(TunnelHandle::new(inner, self.clone()))
    }

    /// See [`crate::L2tpHandle::open_tunnel`].
    pub fn open_tunnel(
        &self,
        tunnel_id: TunnelId,
    ) -> crate::Result<TunnelHandle> {
        let inner = self.call(move |handle| async move {
            handle.open_tunnel(tunnel_id).await
        })?;
        Ok(TunnelHandle::new(inner, self.clone()))
    }

    /// See [`crate::L2tpHandle::create_session`].
    pub fn create_session(
        &self,
        config: SessionConfig,
    ) -> crate::Result<SessionHandle> {
        let inner = self.call(move |handle| async move {
            handle.create_session(config).await
        })?;
        Ok(SessionHandle::new(inner, self.clone()))
    }

    /// See [`crate::L2tpHandle::open_session`].
    pub fn open_session(
        &self,
        tunnel_id: TunnelId,
        session_id: SessionId,
    ) -> crate::Result<SessionHandle> {
        let inner = self.call(move |handle| async move {
            handle.open_session(tunnel_id, session_id).await
        })?;
        Ok(SessionHandle::new(inner, self.clone()))
    }

    /// See [`crate::L2tpHandle::open_session_by_ifname`].
    pub fn open_session_by_ifname(
        &self,
        ifname: L2tpIfName,
    ) -> crate::Result<SessionHandle> {
        let inner = self.call(move |handle| async move {
            handle.open_session_by_ifname(&ifname).await
        })?;
        Ok(SessionHandle::new(inner, self.clone()))
    }

    /// See [`crate::L2tpHandle::get_tunnel`].
    pub fn get_tunnel(&self, tunnel_id: TunnelId) -> crate::Result<TunnelInfo> {
        self.call(
            move |handle| async move { handle.get_tunnel(tunnel_id).await },
        )
    }

    /// See [`crate::L2tpHandle::get_session`].
    pub fn get_session(
        &self,
        tunnel_id: TunnelId,
        session_id: SessionId,
    ) -> crate::Result<SessionInfo> {
        self.call(move |handle| async move {
            handle.get_session(tunnel_id, session_id).await
        })
    }

    /// See [`crate::L2tpHandle::get_session_by_ifname`].
    pub fn get_session_by_ifname(
        &self,
        ifname: L2tpIfName,
    ) -> crate::Result<SessionInfo> {
        self.call(move |handle| async move {
            handle.get_session_by_ifname(&ifname).await
        })
    }

    /// See [`crate::L2tpHandle::list_tunnels`].
    pub fn list_tunnels(&self) -> crate::Result<Vec<TunnelInfo>> {
        self.call(|handle| async move { handle.list_tunnels().await })
    }

    /// See [`crate::L2tpHandle::list_sessions`].
    pub fn list_sessions(
        &self,
        tunnel_id: TunnelId,
    ) -> crate::Result<Vec<SessionInfo>> {
        self.call(
            move |handle| async move { handle.list_sessions(tunnel_id).await },
        )
    }

    /// See [`crate::L2tpHandle::list_all_sessions`].
    pub fn list_all_sessions(&self) -> crate::Result<Vec<SessionInfo>> {
        self.call(|handle| async move { handle.list_all_sessions().await })
    }

    /// See [`crate::L2tpHandle::delete_tunnel`].
    pub fn delete_tunnel(&self, tunnel_id: TunnelId) -> crate::Result<()> {
        self.call(
            move |handle| async move { handle.delete_tunnel(tunnel_id).await },
        )
    }

    /// See [`crate::L2tpHandle::delete_session`].
    pub fn delete_session(
        &self,
        tunnel_id: TunnelId,
        session_id: SessionId,
    ) -> crate::Result<()> {
        self.call(move |handle| async move {
            handle.delete_session(tunnel_id, session_id).await
        })
    }

    /// See [`crate::L2tpHandle::delete_session_by_ifname`].
    pub fn delete_session_by_ifname(
        &self,
        ifname: L2tpIfName,
    ) -> crate::Result<()> {
        self.call(move |handle| async move {
            handle.delete_session_by_ifname(&ifname).await
        })
    }

    /// See [`crate::L2tpHandle::tunnel_stats`].
    pub fn tunnel_stats(
        &self,
        tunnel_id: TunnelId,
    ) -> crate::Result<TunnelStats> {
        self.call(
            move |handle| async move { handle.tunnel_stats(tunnel_id).await },
        )
    }

    /// See [`crate::L2tpHandle::session_stats`].
    pub fn session_stats(
        &self,
        tunnel_id: TunnelId,
        session_id: SessionId,
    ) -> crate::Result<SessionStats> {
        self.call(move |handle| async move {
            handle.session_stats(tunnel_id, session_id).await
        })
    }

    /// See [`crate::L2tpHandle::session_stats_by_ifname`].
    pub fn session_stats_by_ifname(
        &self,
        ifname: L2tpIfName,
    ) -> crate::Result<SessionStats> {
        self.call(move |handle| async move {
            handle.session_stats_by_ifname(&ifname).await
        })
    }

    /// See [`crate::L2tpHandle::modify_session`].
    pub fn modify_session(
        &self,
        tunnel_id: TunnelId,
        session_id: SessionId,
        params: SessionModify,
    ) -> crate::Result<()> {
        self.call(move |handle| async move {
            handle.modify_session(tunnel_id, session_id, params).await
        })
    }

    /// See [`crate::L2tpHandle::modify_session_by_ifname`].
    pub fn modify_session_by_ifname(
        &self,
        ifname: L2tpIfName,
        params: SessionModify,
    ) -> crate::Result<()> {
        self.call(move |handle| async move {
            handle.modify_session_by_ifname(&ifname, params).await
        })
    }

    /// Subscribes to kernel notifications; see
    /// [`crate::L2tpHandle::events`].
    ///
    /// The returned iterator blocks in `next` until an event arrives and
    /// ends when the subscription's connection closes. It keeps the worker
    /// alive while it exists. On kernels that multicast across namespaces,
    /// events may describe objects outside this handle's namespace; use them
    /// as hints to query local state, as described by [`crate::L2tpEvent`].
    pub fn events(&self) -> crate::Result<EventIter> {
        // A std channel carries the events, so `next` blocks without
        // touching any Tokio context; the oneshot tells the forwarder that
        // the iterator is gone.
        let (event_tx, event_rx) = mpsc::channel();
        let (stop_tx, mut stop_rx) = tokio::sync::oneshot::channel::<()>();
        let (ready_tx, ready_rx) = mpsc::sync_channel::<crate::Result<()>>(1);
        self.detach(move |handle| async move {
            let mut events = match handle.events().await {
                Ok(events) => events,
                Err(err) => {
                    let _ = ready_tx.send(Err(err));
                    return;
                }
            };
            if ready_tx.send(Ok(())).is_err() {
                return;
            }
            // Stop as soon as the iterator is dropped, so the worker never
            // waits on this task at shutdown.
            loop {
                match future::select(&mut stop_rx, events.next()).await {
                    Either::Left(_) => break,
                    Either::Right((Some(item), _)) => {
                        if event_tx.send(item).is_err() {
                            break;
                        }
                    }
                    Either::Right((None, _)) => break,
                }
            }
        });
        ready_rx.recv().map_err(|_| {
            crate::Error::other("the l2tp worker dropped the subscription")
        })??;
        Ok(EventIter {
            receiver: event_rx,
            _stop: stop_tx,
            _worker: self.clone(),
        })
    }
}

/// Blocking iterator over kernel notifications; see [`L2tpHandle::events`].
///
/// `next` blocks the calling thread without depending on a Tokio context,
/// so it also works from `spawn_blocking` or an async task, where it blocks
/// that task's thread. Dropping the iterator leaves the multicast group.
#[derive(Debug)]
pub struct EventIter {
    receiver: mpsc::Receiver<crate::Result<L2tpEvent>>,
    _stop: tokio::sync::oneshot::Sender<()>,
    _worker: L2tpHandle,
}

impl Iterator for EventIter {
    type Item = crate::Result<L2tpEvent>;

    fn next(&mut self) -> Option<Self::Item> {
        self.receiver.recv().ok()
    }
}

/// Blocking counterpart of [`crate::TunnelHandle`].
///
/// The handle owns the async handle and its managed socket. On drop it is
/// returned to the worker thread, which performs the best-effort deletion
/// when auto-delete is enabled.
#[derive(Debug)]
pub struct TunnelHandle {
    tunnel_id: TunnelId,
    inner: Option<crate::TunnelHandle>,
    l2tp: L2tpHandle,
}

impl TunnelHandle {
    fn new(inner: crate::TunnelHandle, l2tp: L2tpHandle) -> Self {
        Self {
            tunnel_id: inner.tunnel_id(),
            inner: Some(inner),
            l2tp,
        }
    }

    /// Returns this handle's tunnel identifier.
    pub fn tunnel_id(&self) -> TunnelId {
        self.tunnel_id
    }

    /// Returns the managed socket, if the tunnel was created as managed.
    pub fn socket(&self) -> Option<&TunnelSocket> {
        self.inner.as_ref().and_then(|inner| inner.socket())
    }

    /// Returns a mutable managed socket reference, if present.
    pub fn socket_mut(&mut self) -> Option<&mut TunnelSocket> {
        self.inner.as_mut().and_then(|inner| inner.socket_mut())
    }

    /// See [`crate::TunnelHandle::auto_delete`].
    pub fn auto_delete(&self) -> bool {
        self.inner.as_ref().is_some_and(|inner| inner.auto_delete())
    }

    /// See [`crate::TunnelHandle::set_auto_delete`].
    pub fn set_auto_delete(&mut self, v: bool) {
        if let Some(inner) = &mut self.inner {
            inner.set_auto_delete(v);
        }
    }

    /// Fetches current tunnel information from the kernel.
    pub fn get(&self) -> crate::Result<TunnelInfo> {
        self.l2tp.get_tunnel(self.tunnel_id)
    }

    /// Fetches tunnel statistics from the kernel.
    pub fn stats(&self) -> crate::Result<TunnelStats> {
        self.l2tp.tunnel_stats(self.tunnel_id)
    }

    /// Deletes the tunnel and waits until the kernel has removed it; see
    /// [`crate::L2tpHandle::delete_tunnel`].
    pub fn delete(mut self) -> crate::Result<()> {
        let Some(inner) = self.inner.take() else {
            return Err(crate::Error::other("the tunnel handle was consumed"));
        };
        self.l2tp.call(move |_| inner.delete())
    }

    /// Reconnects a managed UDP tunnel socket to a new remote endpoint.
    pub fn reconnect_udp(&self, new_remote: &UdpEndpoint) -> crate::Result<()> {
        self.socket()
            .ok_or(crate::Error::UnmanagedSocket)?
            .reconnect_udp(new_remote)
    }

    /// Reconnects a managed IP tunnel socket to a new remote endpoint.
    pub fn reconnect_ip(&self, new_remote: &IpEndpoint) -> crate::Result<()> {
        self.socket()
            .ok_or(crate::Error::UnmanagedSocket)?
            .reconnect_ip(new_remote)
    }
}

impl Drop for TunnelHandle {
    fn drop(&mut self) {
        // Delete on the worker and await it there, so the worker's shutdown
        // waits for the deletion instead of abandoning a task the async
        // handle's own drop would merely spawn.
        if let Some(inner) = self.inner.take()
            && inner.auto_delete()
        {
            self.l2tp.detach(move |_| async move {
                let _ = inner.delete().await;
            });
        }
    }
}

/// Blocking counterpart of [`crate::SessionHandle`].
#[derive(Debug)]
pub struct SessionHandle {
    tunnel_id: TunnelId,
    session_id: SessionId,
    ifname: Option<L2tpIfName>,
    ifindex: Option<u32>,
    inner: Option<crate::SessionHandle>,
    l2tp: L2tpHandle,
}

impl SessionHandle {
    fn new(inner: crate::SessionHandle, l2tp: L2tpHandle) -> Self {
        Self {
            tunnel_id: inner.tunnel_id(),
            session_id: inner.session_id(),
            ifname: inner.ifname().copied(),
            ifindex: inner.ifindex(),
            inner: Some(inner),
            l2tp,
        }
    }

    /// Returns the parent tunnel identifier.
    pub fn tunnel_id(&self) -> TunnelId {
        self.tunnel_id
    }

    /// Returns this handle's session identifier.
    pub fn session_id(&self) -> SessionId {
        self.session_id
    }

    /// Returns the interface name the session was created with; see
    /// [`crate::SessionHandle::ifname`].
    pub fn ifname(&self) -> Option<&L2tpIfName> {
        self.ifname.as_ref()
    }

    /// Returns the interface index of the session's device; see
    /// [`crate::SessionHandle::ifindex`].
    pub fn ifindex(&self) -> Option<u32> {
        self.ifindex
    }

    /// See [`crate::SessionHandle::auto_delete`].
    pub fn auto_delete(&self) -> bool {
        self.inner.as_ref().is_some_and(|inner| inner.auto_delete())
    }

    /// See [`crate::SessionHandle::set_auto_delete`].
    pub fn set_auto_delete(&mut self, v: bool) {
        if let Some(inner) = &mut self.inner {
            inner.set_auto_delete(v);
        }
    }

    /// Fetches current session information from the kernel.
    pub fn get(&self) -> crate::Result<SessionInfo> {
        self.l2tp.get_session(self.tunnel_id, self.session_id)
    }

    /// Fetches session statistics from the kernel.
    pub fn stats(&self) -> crate::Result<SessionStats> {
        self.l2tp.session_stats(self.tunnel_id, self.session_id)
    }

    /// Applies mutable session parameters.
    pub fn modify(&self, params: SessionModify) -> crate::Result<()> {
        self.l2tp
            .modify_session(self.tunnel_id, self.session_id, params)
    }

    /// Deletes the session and waits for the kernel to acknowledge it.
    pub fn delete(mut self) -> crate::Result<()> {
        let Some(inner) = self.inner.take() else {
            return Err(crate::Error::other("the session handle was consumed"));
        };
        self.l2tp.call(move |_| inner.delete())
    }
}

impl Drop for SessionHandle {
    fn drop(&mut self) {
        if let Some(inner) = self.inner.take()
            && inner.auto_delete()
        {
            self.l2tp.detach(move |_| async move {
                let _ = inner.delete().await;
            });
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// ENODEV as root, EPERM unprivileged, or no `l2tp` family at all where
    /// the module is not loaded (CI runners).
    fn permission_or_missing(err: &crate::Error) {
        let errno = err.raw_os_error();
        assert!(
            errno == Some(libc::EPERM)
                || errno == Some(libc::ENODEV)
                || matches!(err, crate::Error::FamilyResolution(_)),
            "{err:?}"
        );
    }

    #[test]
    fn requests_complete_from_a_plain_thread() {
        let handle = L2tpHandle::new().unwrap();
        let err = handle.get_tunnel(TunnelId(u32::MAX)).unwrap_err();
        permission_or_missing(&err);
        let clone = handle.clone();
        let err = std::thread::spawn(move || {
            clone.open_tunnel(TunnelId(u32::MAX)).unwrap_err()
        })
        .join()
        .unwrap();
        permission_or_missing(&err);
    }

    #[test]
    fn requests_complete_inside_spawn_blocking() {
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .worker_threads(1)
            .enable_all()
            .build()
            .unwrap();
        let err = runtime.block_on(async {
            // A nested `block_on` would panic here; the worker thread does
            // not need the caller's runtime at all.
            tokio::task::spawn_blocking(|| {
                let handle = L2tpHandle::new().unwrap();
                // Fails as root (no such tunnel) and unprivileged (EPERM).
                handle
                    .open_tunnel(TunnelId(u32::MAX))
                    .map(|_| ())
                    .unwrap_err()
            })
            .await
            .unwrap()
        });
        permission_or_missing(&err);

        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let err = runtime.block_on(async {
            tokio::task::spawn_blocking(|| {
                L2tpHandle::new()
                    .unwrap()
                    .get_session(TunnelId(u32::MAX), SessionId(1))
                    .unwrap_err()
            })
            .await
            .unwrap()
        });
        permission_or_missing(&err);
    }

    #[test]
    fn worker_stops_when_the_last_handle_drops() {
        let handle = L2tpHandle::new().unwrap();
        let worker = Arc::downgrade(&handle.worker);
        drop(handle);
        assert!(worker.upgrade().is_none());
    }

    #[test]
    fn event_iterator_blocks_without_a_tokio_context() {
        let handle = L2tpHandle::new().unwrap();
        let (tx, rx) = mpsc::channel();
        let (stop_tx, stop_rx) = tokio::sync::oneshot::channel();
        tx.send(Err(crate::Error::other("probe"))).unwrap();
        drop(tx);
        let mut iter = EventIter {
            receiver: rx,
            _stop: stop_tx,
            _worker: handle,
        };
        // Inside an async context a Tokio blocking receive would panic.
        let runtime = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let (first, second) = runtime
            .block_on(async { (iter.next().is_some(), iter.next().is_none()) });
        assert!(first);
        assert!(second);
        // Dropping the iterator tells the forwarder to stop.
        drop(iter);
        assert!(runtime.block_on(stop_rx).is_err());
    }

    #[test]
    fn event_subscription_can_be_opened_and_dropped() {
        let handle = L2tpHandle::new().unwrap();
        match handle.events() {
            Ok(events) => drop(events),
            // Without the l2tp family (module not loaded) resolution fails.
            Err(crate::Error::FamilyResolution(_)) => {}
            Err(err) => panic!("unexpected error: {err:?}"),
        }
    }
}