dslite-b4 0.1.0

DS-Lite B4 tunnel management daemon
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! illumos backend, DS-Lite B4 tunnel via libdladm + libipadm + direct ioctls.
//!
//! Three layers of the illumos networking stack are used here:
//! - libdladm: datalink/tunnel management (the iptun link itself).
//! - libipadm: IP interface lifecycle (create/delete the IP interface
//!   on top of the link).
//! - kernel ioctls on a socket: IPv4 address assignment. Bypass
//!   libipadm here because of illumos issue 17851, 32-bit `ipmgmtd`
//!   ABI vs this 64-bit daemon.
//!
//! C-side bindings (constants, FFI, `repr(C)` mirrors) live in `sys.rs`.

mod pf_route;
mod sys;

use crate::tunnel::illumos::pf_route::RouteSocket;
use crate::tunnel::{
    AFTR_V4_ELEMENT, B4_V4_PREFIX_LEN, DesiredState, EncapsulationLimit, Observed, TunnelBackend,
    TunnelError, TunnelUpdate,
};
use std::io;
use std::mem::MaybeUninit;
use std::{
    ffi::{CStr, CString, c_char, c_uint, c_void},
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    os::fd::{AsRawFd, FromRawFd, OwnedFd},
};
use sys::*;

pub(crate) use sys::{
    RTM_ADD, RTM_CHANGE, RTM_CHGADDR, RTM_DELADDR, RTM_DELETE, RTM_FREEADDR, RTM_IFINFO,
    RTM_NEWADDR, rt_msghdr,
};

// /29 -> 255.255.255.248
const B4_V4_NETMASK: Ipv4Addr = Ipv4Addr::from_bits(u32::MAX << (32 - B4_V4_PREFIX_LEN));

pub struct IllumosBackend {
    cname: CString,
}

impl IllumosBackend {
    pub fn new(name: String) -> Result<Self, std::ffi::NulError> {
        let cname = std::ffi::CString::new(name)?;

        Ok(Self { cname })
    }
    fn create_tunnel(
        &self,
        handle: &DladmHandle,
        desired: &DesiredState,
    ) -> Result<u32, TunnelError> {
        let mut params = build_tunnel_params(&desired.local_v6, &desired.remote_v6);

        // SAFETY:
        // - `handle.ptr` was produced by a successful `dladm_open` (see
        //   `open_dladm`) and remains live for the `&DladmHandle` borrow.
        // - `self.cname.as_ptr()` returns a NUL-terminated `*const c_char`
        //   from the `CString` field, valid for reads for the `&self`
        //   borrow.
        // - `&mut params` is a stack-local `IpTunParams` owned exclusively
        //   here, valid for writes (libdladm populates `link_id`).
        let status = unsafe {
            dladm_iptun_create(
                handle.ptr,
                self.cname.as_ptr(),
                &mut params,
                DLADM_OPT_ACTIVE,
            )
        };
        if status != DLADM_STATUS_OK {
            return Err(TunnelError::CreationFailed(format!(
                "dladm_iptun_create failed with status {}",
                status
            )));
        }
        tracing::debug!(link_id = params.link_id, "tunnel created");

        Ok(params.link_id)
    }

    fn create_if(&self, handle: &IpadmHandle) -> Result<(), TunnelError> {
        // libipadm may write back the canonical interface name into the
        // buffer on success. The writeback happens unconditionally in
        // `i_ipadm_plumb_if` (for the IPv6-type tunnel used here it is
        // normally a no-op, but the API contract requires a writable
        // LIFNAMSIZ buffer).
        // <https://github.com/illumos/illumos-gate/blob/0764e87f4a667f36d63262fcdd690064929acc48/usr/src/lib/libipadm/common/ipadm_if.c#L1105>
        // Allocate a local buffer rather than aliasing the immutable
        // `self.cname` storage. The post-call buffer contents are not
        // read back.
        let src = self.cname.as_bytes_with_nul();
        if src.len() > LIFNAMSIZ {
            return Err(TunnelError::CreationFailed(format!(
                "interface name {} bytes, exceeds LIFNAMSIZ ({})",
                src.len(),
                LIFNAMSIZ
            )));
        }
        let mut name_buf: [c_char; LIFNAMSIZ] = [0; LIFNAMSIZ];

        // SAFETY:
        // - `src` from `as_bytes_with_nul()` is a `&[u8]`, valid for
        //   reads of `src.len()` bytes by the slice-reference guarantee.
        // - `name_buf` is a stack-local `[c_char; LIFNAMSIZ]`, valid for
        //   LIFNAMSIZ writes.
        // - `src.len() <= LIFNAMSIZ` by the prior bounds check.
        // - Both pointers are `u8`-typed. `align_of::<u8>() = 1`, satisfied.
        // - `self.cname` and `name_buf` are distinct allocations, so the
        //   regions cannot overlap.
        unsafe {
            std::ptr::copy_nonoverlapping(
                src.as_ptr(),
                name_buf.as_mut_ptr().cast::<u8>(),
                src.len(),
            )
        };

        // SAFETY:
        // - `handle.ptr` was produced by a successful `ipadm_open` (see
        //   `open_ipadm`) and remains live for the `&IpadmHandle` borrow.
        // - `name_buf.as_mut_ptr()` points to an initialized LIFNAMSIZ
        //   buffer that the library may overwrite on success.
        // - `name_buf` lives until function return, covering the call
        //   duration.
        let status = unsafe {
            ipadm_create_if(handle.ptr, name_buf.as_mut_ptr(), AF_INET, IPADM_OPT_ACTIVE)
        };
        if status != IPADM_STATUS_OK {
            return Err(TunnelError::CreationFailed(format!(
                "ipadm_create_if failed with status {}",
                status
            )));
        }
        tracing::debug!("ip interface assigned to tunnel");
        Ok(())
    }

    fn get_tunnel_params(&self, handle: &DladmHandle) -> Result<Option<IpTunParams>, TunnelError> {
        let (link_id, status) = self.name_to_linkid(handle);
        if status == DLADM_STATUS_NOTFOUND {
            return Ok(None);
        }
        if status != DLADM_STATUS_OK {
            return Err(TunnelError::StatusCheckFailed(format!(
                "failed to get linkid, dladm_name2info status: {}",
                status
            )));
        }

        // SAFETY: Every field of `IpTunParams` accepts an all-zero bit pattern.
        // Integer fields and byte arrays permit zero, and `IpTunType` is a `u32`
        // alias rather than a restricted Rust enum.
        let mut params: IpTunParams = unsafe { MaybeUninit::zeroed().assume_init() };
        params.link_id = link_id;

        // SAFETY:
        // - `handle.ptr` was produced by a successful `dladm_open` (see
        //   `open_dladm`) and remains live for the `&DladmHandle` borrow.
        // - `&mut params` is a stack-local `IpTunParams` owned exclusively
        //   here, valid for writes.
        let status = unsafe { dladm_iptun_getparams(handle.ptr, &mut params, DLADM_OPT_ACTIVE) };
        if status != DLADM_STATUS_OK {
            return Err(TunnelError::StatusCheckFailed(format!(
                "dladm_iptun_getparams failed with status: {}",
                status
            )));
        };
        Ok(Some(params))
    }

    fn get_encapsulation_limit(
        &self,
        handle: &DladmHandle,
        link_id: u32,
    ) -> Result<Option<u8>, TunnelError> {
        let mut value = [0_u8; DLADM_PROP_VAL_MAX];
        let mut values = [value.as_mut_ptr().cast::<c_char>()];
        let mut value_count: c_uint = 1;

        // SAFETY:
        // - `handle.ptr` is a live libdladm handle.
        // - `c"encaplimit"` is a static NUL-terminated string.
        // - `values` contains one pointer to a writable
        //   `DLADM_PROP_VAL_MAX`-byte buffer.
        // - `value_count` initially describes the one available buffer and
        //   remains valid for writes during the call.
        let status = unsafe {
            dladm_get_linkprop(
                handle.ptr,
                link_id,
                DLADM_PROP_VAL_CURRENT,
                c"encaplimit".as_ptr(),
                values.as_mut_ptr(),
                &mut value_count,
            )
        };

        if status != DLADM_STATUS_OK {
            return Err(TunnelError::StatusCheckFailed(format!(
                "reading encaplimit, dladm_get_linkprop status: {status}"
            )));
        }

        let value = CStr::from_bytes_until_nul(&value)
            .map_err(|e| TunnelError::StatusCheckFailed(format!("invalid encaplimit value: {e}")))?
            .to_str()
            .map_err(|e| TunnelError::StatusCheckFailed(format!("encaplimit is not UTF-8: {e}")))?
            .parse::<u8>()
            .map_err(|e| {
                TunnelError::StatusCheckFailed(format!("invalid encaplimit number: {e}"))
            })?;

        Ok((value != 0).then_some(value))
    }

    fn set_encapsulation_limit(
        &self,
        handle: &DladmHandle,
        link_id: u32,
        encapsulation_limit: EncapsulationLimit,
    ) -> Result<(), u32> {
        let value = match encapsulation_limit {
            EncapsulationLimit::Disabled => 0,
            EncapsulationLimit::Value(value) => value.get(),
        };
        let mut value = value.to_string().into_bytes();
        value.push(0);
        let mut values = [value.as_mut_ptr().cast::<c_char>()];

        // SAFETY:
        // - `handle.ptr` is a live libdladm handle.
        // - `link_id` identifies a link returned by libdladm.
        // - `c"encaplimit"` is a static NUL-terminated string.
        // - `values` contains one pointer to a writable, NUL-terminated
        //   decimal string. Both arrays remain live for the call.
        // - `value_count` is one, matching the single pointer in `values`.
        let status = unsafe {
            dladm_set_linkprop(
                handle.ptr,
                link_id,
                c"encaplimit".as_ptr(),
                values.as_mut_ptr(),
                1,
                DLADM_OPT_ACTIVE,
            )
        };

        if status != DLADM_STATUS_OK {
            return Err(status);
        }

        Ok(())
    }

    fn is_admin_up(&self) -> Result<bool, TunnelError> {
        let socket = open_inet_dgram_socket().map_err(|e| {
            TunnelError::StatusCheckFailed(format!("opening interface flags socket: {e}"))
        })?;
        let fd = socket.as_raw_fd();

        // SAFETY: `fd` belongs to the live AF_INET/SOCK_DGRAM `socket`,
        // which accepts SIOCSLIF* ioctls.
        unsafe { is_up(fd, &self.cname) }
            .map_err(|e| TunnelError::StatusCheckFailed(format!("reading interface flags: {e}")))
    }

    fn get_mtu(&self) -> Result<u32, TunnelError> {
        let socket = open_inet_dgram_socket().map_err(|e| {
            TunnelError::StatusCheckFailed(format!("opening interface MTU socket: {e}"))
        })?;
        let fd = socket.as_raw_fd();

        // SAFETY: `fd` belongs to the live AF_INET/SOCK_DGRAM `socket`,
        // which accepts SIOCSLIF* ioctls.
        unsafe { sys::get_mtu(fd, &self.cname) }
            .map_err(|e| TunnelError::StatusCheckFailed(format!("reading interface MTU: {e}")))
    }

    fn delete_tunnel(&self, handle: &DladmHandle) -> Result<(), TunnelError> {
        let (link_id, status) = self.name_to_linkid(handle);
        if status != DLADM_STATUS_OK {
            return Err(TunnelError::DestroyFailed(format!(
                "failed to get linkid, dladm_name2info status: {}",
                status
            )));
        }
        tracing::debug!(link_id, "resolved link id for deletion");

        // SAFETY:
        // - `handle.ptr` was produced by a successful `dladm_open` (see
        //   `open_dladm`) and remains live for the `&DladmHandle` borrow.
        // - `link_id` is a `u32` returned by `dladm_name2info` above,
        //   identifying the link to delete.
        let status = unsafe { dladm_iptun_delete(handle.ptr, link_id, DLADM_OPT_ACTIVE) };
        if status != DLADM_STATUS_OK {
            return Err(TunnelError::DestroyFailed(format!(
                "dladm_iptun_delete failed with status {}",
                status
            )));
        }

        Ok(())
    }

    fn delete_if(&self, handle: &IpadmHandle) -> Result<(), TunnelError> {
        // SAFETY:
        // - `handle.ptr` was produced by a successful `ipadm_open` (see
        //   `open_ipadm`) and remains live for the `&IpadmHandle` borrow.
        // - `self.cname.as_ptr()` returns a NUL-terminated `*const c_char`
        //   from the `CString` field, valid for reads for the `&self`
        //   borrow. `ipadm_delete_if` declares its name parameter `const`
        //   and does not mutate the buffer.
        let status =
            unsafe { ipadm_delete_if(handle.ptr, self.cname.as_ptr(), AF_INET, IPADM_OPT_ACTIVE) };
        if status != IPADM_STATUS_OK {
            return Err(TunnelError::DestroyFailed(format!(
                "ipadm_delete_if failed with status {}",
                status
            )));
        }
        tracing::debug!("ip interface deleted");
        Ok(())
    }

    fn rollback_setup(
        &self,
        dladm_handle: &DladmHandle,
        interface_created: bool,
        local_v4_configured: bool,
        default_route_may_exist: bool,
    ) {
        let mut failures = Vec::new();

        if default_route_may_exist {
            match RouteSocket::open().and_then(|route| route.delete_default_v4(AFTR_V4_ELEMENT)) {
                Ok(()) => {}
                Err(error) if error.raw_os_error() == Some(libc::ESRCH) => {}
                Err(error) => failures.push(format!("removing default route: {error}")),
            }
        }

        if local_v4_configured {
            match open_inet_dgram_socket() {
                Ok(socket) => {
                    // SAFETY: `socket` is an AF_INET/SOCK_DGRAM socket suitable
                    // for SIOCSLIF* ioctls and remains live for the call.
                    if let Err(error) = unsafe {
                        set_local_addr(socket.as_raw_fd(), &self.cname, Ipv4Addr::UNSPECIFIED)
                    } {
                        failures.push(format!("clearing local IPv4 address: {error}"));
                    }
                }
                Err(error) => failures.push(format!(
                    "opening address configuration socket for rollback: {error}"
                )),
            }
        }

        if interface_created {
            match open_ipadm() {
                Ok(handle) => {
                    if let Err(error) = self.delete_if(&handle) {
                        failures.push(error.to_string());
                    }
                }
                Err(status) => failures.push(format!(
                    "opening libipadm handle for rollback failed with status {status}"
                )),
            }
        }

        if let Err(error) = self.delete_tunnel(dladm_handle) {
            failures.push(error.to_string());
        }

        if failures.is_empty() {
            tracing::debug!("rolled back partially created tunnel");
        } else {
            tracing::warn!(
                errors = %failures.join("; "),
                "failed to fully roll back partially created tunnel"
            );
        }
    }

    fn name_to_linkid(&self, handle: &DladmHandle) -> (u32, u32) {
        let mut link_id: u32 = 0;

        // SAFETY:
        // - `handle.ptr` was produced by a successful `dladm_open` (see
        //   `open_dladm`) and remains live for the `&DladmHandle` borrow.
        // - `self.cname.as_ptr()` returns a NUL-terminated `*const c_char`,
        //   valid for reads for the `&self` borrow.
        // - `&mut link_id` points to a stack-local `u32` valid for writes.
        // - The remaining `flagp` / `classp` / `mediap` arguments are
        //   explicitly null. `dladm_name2info` checks each out-pointer
        //   against NULL before writing.
        //   <https://github.com/illumos/illumos-gate/blob/0764e87f4a667f36d63262fcdd690064929acc48/usr/src/lib/libdladm/common/libdlmgmt.c#L578>
        let status = unsafe {
            dladm_name2info(
                handle.ptr,
                self.cname.as_ptr(),
                &mut link_id,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        (link_id, status)
    }
}

impl TunnelBackend for IllumosBackend {
    async fn setup(&self, desired: DesiredState) -> Result<(), TunnelError> {
        let handle = open_dladm().map_err(|e| {
            TunnelError::CreationFailed(format!("unable to open handle, dladm_open status {}", e))
        })?;
        let link_id = self.create_tunnel(&handle, &desired)?;
        let mut interface_created = false;
        let mut local_v4_configured = false;
        let mut default_route_may_exist = false;

        let setup_result = (|| -> Result<(), TunnelError> {
            if let Some(encapsulation_limit) = desired.encapsulation_limit {
                self.set_encapsulation_limit(&handle, link_id, encapsulation_limit)
                    .map_err(|status| {
                        TunnelError::CreationFailed(format!(
                            "setting encaplimit, dladm_set_linkprop status: {status}"
                        ))
                    })?;
            }

            let ip_handle = open_ipadm().map_err(|e| {
                TunnelError::CreationFailed(format!("unable to open handle, ipadm_open status {e}"))
            })?;
            self.create_if(&ip_handle)?;
            interface_created = true;

            let sock_fd = open_inet_dgram_socket().map_err(|e| {
                TunnelError::CreationFailed(format!("opening address configuration socket: {e}"))
            })?;
            let fd = sock_fd.as_raw_fd();

            // The calls below each require an fd that accepts SIOCSLIF* ioctls.
            // `open_inet_dgram_socket` returns an AF_INET/SOCK_DGRAM socket.
            // `sock_fd` (the `OwnedFd`) lives until function return,
            // so `fd` remains valid across all calls.

            if let Some(mtu) = desired.mtu {
                // SAFETY: `fd` is a valid SIOCSLIF*-capable socket (see above).
                unsafe { set_mtu(fd, &self.cname, mtu) }
                    .map_err(|e| TunnelError::CreationFailed(format!("set_mtu: {e}")))?;
            }

            // SAFETY: `fd` is a valid SIOCSLIF*-capable socket (see above).
            unsafe { set_local_addr(fd, &self.cname, desired.local_v4) }
                .map_err(|e| TunnelError::CreationFailed(format!("set_local_addr: {e}")))?;
            local_v4_configured = true;
            // SAFETY: `fd` is a valid SIOCSLIF*-capable socket (see above).
            unsafe { set_dst_addr(fd, &self.cname, AFTR_V4_ELEMENT) }
                .map_err(|e| TunnelError::CreationFailed(format!("set_dst_addr: {e}")))?;
            // SAFETY: `fd` is a valid SIOCSLIF*-capable socket (see above).
            unsafe { set_netmask(fd, &self.cname, B4_V4_NETMASK) }
                .map_err(|e| TunnelError::CreationFailed(format!("set_netmask: {e}")))?;
            // SAFETY: `fd` is a valid SIOCSLIF*-capable socket (see above).
            unsafe { bring_up(fd, &self.cname) }
                .map_err(|e| TunnelError::CreationFailed(format!("bring_up: {e}")))?;
            let route_sock = RouteSocket::open()
                .map_err(|e| TunnelError::CreationFailed(format!("PF_ROUTE open: {e}")))?;
            // A timeout or malformed acknowledgement does not prove that the
            // kernel rejected the preceding route request, so rollback must
            // attempt deletion once the add has been issued.
            default_route_may_exist = true;
            route_sock
                .add_default_v4(AFTR_V4_ELEMENT)
                .map_err(|e| TunnelError::CreationFailed(format!("add default route: {e}")))?;

            Ok(())
        })();

        if let Err(error) = setup_result {
            self.rollback_setup(
                &handle,
                interface_created,
                local_v4_configured,
                default_route_may_exist,
            );
            return Err(error);
        }

        tracing::info!(
            name = %self.cname.to_string_lossy(),
            local_v6 = %desired.local_v6,
            remote_v6 = %desired.remote_v6,
            local_v4 = %desired.local_v4,
            mtu = ?desired.mtu,
            encapsulation_limit = ?desired.encapsulation_limit,
            "tunnel established"
        );

        Ok(())
    }

    async fn update(
        &self,
        _desired: DesiredState,
        update: TunnelUpdate,
    ) -> Result<(), TunnelError> {
        if let Some(encapsulation_limit) = update.encapsulation_limit {
            let handle = open_dladm().map_err(|status| {
                TunnelError::UpdateFailed(format!(
                    "opening libdladm handle, dladm_open status: {status}"
                ))
            })?;
            let (link_id, status) = self.name_to_linkid(&handle);
            if status != DLADM_STATUS_OK {
                return Err(TunnelError::UpdateFailed(format!(
                    "resolving link id, dladm_name2info status: {status}"
                )));
            }

            self.set_encapsulation_limit(&handle, link_id, encapsulation_limit)
                .map_err(|status| {
                    TunnelError::UpdateFailed(format!(
                        "setting encaplimit, dladm_set_linkprop status: {status}"
                    ))
                })?;
        }

        if update.mtu.is_some() || update.bring_up {
            let socket = open_inet_dgram_socket().map_err(|e| {
                TunnelError::UpdateFailed(format!("opening interface configuration socket: {e}"))
            })?;
            let fd = socket.as_raw_fd();

            if let Some(mtu) = update.mtu {
                // SAFETY: `fd` belongs to the live AF_INET/SOCK_DGRAM
                // `socket`, which accepts SIOCSLIF* ioctls.
                unsafe { sys::set_mtu(fd, &self.cname, mtu) }.map_err(|e| {
                    TunnelError::UpdateFailed(format!("setting interface MTU: {e}"))
                })?;
            }

            if update.bring_up {
                // SAFETY: `fd` belongs to the live AF_INET/SOCK_DGRAM
                // `socket`, which accepts SIOCSLIF* ioctls.
                unsafe { sys::bring_up(fd, &self.cname) }.map_err(|e| {
                    TunnelError::UpdateFailed(format!("setting interface flags: {e}"))
                })?;
            }
        }

        tracing::info!(
            name = %self.cname.to_string_lossy(),
            mtu = ?update.mtu,
            encapsulation_limit = ?update.encapsulation_limit,
            bring_up = update.bring_up,
            "interface updated"
        );

        Ok(())
    }

    async fn teardown(&self) -> Result<(), TunnelError> {
        let ip_handle = open_ipadm().map_err(|e| {
            TunnelError::DestroyFailed(format!("unable to open handle, ipadm_open status {}", e))
        })?;

        // clear the address
        let sock_fd = open_inet_dgram_socket().map_err(|e| {
            TunnelError::DestroyFailed(format!("opening address configuration socket: {e}"))
        })?;
        let fd = sock_fd.as_raw_fd();

        // SAFETY: `fd` is a fresh AF_INET/SOCK_DGRAM socket from
        // `open_inet_dgram_socket`, which is suitable for SIOCSLIF*.
        // `sock_fd` lives until function return.
        unsafe { set_local_addr(fd, &self.cname, Ipv4Addr::UNSPECIFIED) }
            .map_err(|e| TunnelError::DestroyFailed(format!("zero local_v4: {}", e)))?;

        let route_sock = RouteSocket::open()
            .map_err(|e| TunnelError::DestroyFailed(format!("PF_ROUTE open: {e}")))?;
        if let Err(e) = route_sock.delete_default_v4(AFTR_V4_ELEMENT) {
            if e.raw_os_error() == Some(libc::ESRCH) {
                tracing::warn!(error = %e, "default route already gone");
            } else {
                return Err(TunnelError::DestroyFailed(format!(
                    "delete default route: {e}"
                )));
            }
        }

        self.delete_if(&ip_handle)?;

        let handle = open_dladm().map_err(|e| {
            TunnelError::DestroyFailed(format!("unable to open handle, dladm_open status {}", e))
        })?;
        self.delete_tunnel(&handle)?;

        tracing::info!(
            name = %self.cname.to_string_lossy(),
            "tunnel removed"
        );

        Ok(())
    }

    async fn observe(&self) -> Result<Observed, TunnelError> {
        let handle = open_dladm().map_err(|e| {
            TunnelError::StatusCheckFailed(format!(
                "unable to open handle, dladm_open status {}",
                e
            ))
        })?;

        let Some(params) = self.get_tunnel_params(&handle)? else {
            return Ok(Observed::Absent);
        };

        if params.ip_tun_type != IPTUN_TYPE_IPV6 {
            return Err(TunnelError::StatusCheckFailed(format!(
                "expected IPv6 tunnel type, got {}",
                params.ip_tun_type
            )));
        }

        if params.flags & IPTUN_PARAM_LADDR == 0 {
            return Err(TunnelError::StatusCheckFailed(
                "tunnel local endpoint missing".to_string(),
            ));
        }

        if params.flags & IPTUN_PARAM_RADDR == 0 {
            return Err(TunnelError::StatusCheckFailed(
                "tunnel remote endpoint missing".to_string(),
            ));
        }
        let local_v6 = parse_tunnel_addr(&params.l_addr, "local")?;
        let remote_v6 = parse_tunnel_addr(&params.r_addr, "remote")?;
        let admin_up = self.is_admin_up()?;
        let mtu = self.get_mtu()?;
        let encapsulation_limit = self.get_encapsulation_limit(&handle, params.link_id)?;

        Ok(Observed::Present {
            local_v6,
            remote_v6,
            mtu,
            encapsulation_limit,
            admin_up,
        })
    }
}

/// RAII wrapper for a libdladm handle.
///
/// # Invariants
///
/// - `ptr` is non-null and points to a libdladm handle obtained from a
///   successful `dladm_open`. libdladm only returns `DLADM_STATUS_OK`
///   after writing a non-null, malloc-allocated handle into `*handle`.
///   <https://github.com/illumos/illumos-gate/blob/0764e87f4a667f36d63262fcdd690064929acc48/usr/src/lib/libdladm/common/libdladm.c#L127-L136>
/// - The handle is exclusively owned by this instance and closed
///   exactly once via `dladm_close` on `Drop`.
///
/// # Threading
///
/// `!Send` and `!Sync` (raw pointer field). libdladm caches a per-handle
/// `door_fd` that is opened on demand and not safe to share across
/// threads. Use a per-thread handle if cross-thread access is needed.
struct DladmHandle {
    ptr: *mut c_void,
}

impl Drop for DladmHandle {
    fn drop(&mut self) {
        // SAFETY:
        // - `self.ptr` is a live libdladm handle (struct invariant).
        // - `dladm_close` is the matching destructor for `dladm_open`.
        // - `Drop::drop` runs exactly once per instance, so the handle
        //   is closed exactly once.
        unsafe { dladm_close(self.ptr) };
    }
}

/// RAII wrapper for a libipadm handle.
///
/// # Invariants
///
/// - `ptr` is non-null and points to a libipadm handle obtained from a
///   successful `ipadm_open`. libipadm sets `*handle` to NULL up front
///   and only assigns a non-null calloc-allocated handle on the success
///   path that returns `IPADM_SUCCESS`.
///   <https://github.com/illumos/illumos-gate/blob/0764e87f4a667f36d63262fcdd690064929acc48/usr/src/lib/libipadm/common/libipadm.c#L181-L264>
/// - The handle is exclusively owned by this instance and closed
///   exactly once via `ipadm_close` on `Drop`.
///
/// # Threading
///
/// `!Send` and `!Sync` (raw pointer field). libipadm holds an internal
/// mutex but also caches sockets and a door fd per handle. Treat the
/// handle as single-thread-owned. Use a per-thread handle if cross-thread
/// access is needed.
struct IpadmHandle {
    ptr: *mut c_void,
}

impl Drop for IpadmHandle {
    fn drop(&mut self) {
        // SAFETY:
        // - `self.ptr` is a live libipadm handle (struct invariant).
        // - `ipadm_close` is the matching destructor for `ipadm_open`.
        // - `Drop::drop` runs exactly once per instance, so the handle
        //   is closed exactly once.
        unsafe { ipadm_close(self.ptr) };
    }
}

fn addr_to_caddr(addr: &std::net::IpAddr) -> [c_char; NI_MAXHOST] {
    let s = addr.to_string();
    let bytes = s.as_bytes();
    let mut caddr = [0 as c_char; NI_MAXHOST];
    // IPv6 address string is at most 45 bytes, always fits in NI_MAXHOST
    for (i, &b) in bytes.iter().enumerate() {
        caddr[i] = b as c_char;
    }
    caddr
}

fn build_tunnel_params(local: &Ipv6Addr, remote: &Ipv6Addr) -> IpTunParams {
    IpTunParams {
        link_id: 0,
        flags: IPTUN_PARAM_TYPE | IPTUN_PARAM_LADDR | IPTUN_PARAM_RADDR,
        ip_tun_type: IPTUN_TYPE_IPV6,
        l_addr: addr_to_caddr(&IpAddr::V6(*local)),
        r_addr: addr_to_caddr(&IpAddr::V6(*remote)),
        sec_info: IpsecReq {
            ipsr_ah_req: 0,
            ipsr_esp_req: 0,
            ipsr_self_encap_req: 0,
            ipsr_auth_alg: 0,
            ipsr_esp_alg: 0,
            ipsr_esp_auth_alg: 0,
        },
    }
}

fn open_dladm() -> Result<DladmHandle, u32> {
    let mut ptr: *mut c_void = std::ptr::null_mut();
    // SAFETY: FFI call with no outstanding preconditions.
    let status = unsafe { dladm_open(&mut ptr) };
    if status != DLADM_STATUS_OK {
        return Err(status);
    }
    // `DLADM_STATUS_OK` implies `ptr` is non-null (see `DladmHandle`
    // invariants), so constructing the wrapper here establishes both
    // struct invariants.
    Ok(DladmHandle { ptr })
}

fn open_ipadm() -> Result<IpadmHandle, u32> {
    let mut ptr: *mut c_void = std::ptr::null_mut();
    // SAFETY: FFI call with no outstanding preconditions.
    let status = unsafe { ipadm_open(&mut ptr, 0) };
    if status != IPADM_STATUS_OK {
        return Err(status);
    }
    // `IPADM_SUCCESS` implies `ptr` is non-null (see `IpadmHandle`
    // invariants), so constructing the wrapper here establishes both
    // struct invariants.
    Ok(IpadmHandle { ptr })
}

fn open_inet_dgram_socket() -> io::Result<OwnedFd> {
    // SAFETY: FFI call with no outstanding preconditions.
    let raw = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0) };

    if raw == -1 {
        return Err(io::Error::last_os_error());
    }

    // SAFETY:
    // - `raw` was returned by `libc::socket` and is non-negative
    //   (the prior `== -1` check rejects the error case), so it is a
    //   valid open file descriptor.
    // - `raw` was created by the call above and has not been observed
    //   by any other code, so this `from_raw_fd` is the sole owner.
    // - The returned `OwnedFd` will close the descriptor on drop.
    Ok(unsafe { OwnedFd::from_raw_fd(raw) })
}

fn parse_tunnel_addr(
    value: &[c_char; NI_MAXHOST],
    endpoint: &str,
) -> Result<Ipv6Addr, TunnelError> {
    let nul = value.iter().position(|&byte| byte == 0).ok_or_else(|| {
        TunnelError::StatusCheckFailed(format!("{endpoint} tunnel address is not NUL-terminated"))
    })?;

    let bytes: Vec<u8> = value[..nul].iter().map(|&byte| byte as u8).collect();

    let text = str::from_utf8(&bytes).map_err(|e| {
        TunnelError::StatusCheckFailed(format!("invalid {endpoint} tunnel address: {e}"))
    })?;

    text.parse::<Ipv6Addr>().map_err(|e| {
        TunnelError::StatusCheckFailed(format!("invalid {endpoint} IPv6 address {text:?}: {e}"))
    })
}

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

    fn test_desired_state() -> DesiredState {
        DesiredState {
            local_v6: Ipv6Addr::UNSPECIFIED,
            remote_v6: Ipv6Addr::UNSPECIFIED,
            local_v4: Ipv4Addr::UNSPECIFIED,
            mtu: None,
            encapsulation_limit: None,
        }
    }

    fn test_encapsulation_limit_value() -> u8 {
        std::env::var("DSLITE_TEST_ENCAP_LIMIT")
            .expect("DSLITE_TEST_ENCAP_LIMIT must contain the prepared encapsulation limit")
            .parse()
            .expect("DSLITE_TEST_ENCAP_LIMIT must be an integer from 0 through 255")
    }

    fn c_addr(value: &str) -> [c_char; NI_MAXHOST] {
        let mut result = [0; NI_MAXHOST];

        for (destination, source) in result.iter_mut().zip(value.bytes()) {
            *destination = source as c_char;
        }

        result
    }

    #[test]
    fn parses_ipv6_tunnel_address() {
        let value = c_addr("2001:db8::1");

        let address = parse_tunnel_addr(&value, "local").unwrap();

        assert_eq!(address, "2001:db8::1".parse::<Ipv6Addr>().unwrap());
    }

    #[test]
    fn rejects_invalid_ipv6_tunnel_address() {
        let value = c_addr("not-an-address");

        let error = parse_tunnel_addr(&value, "remote").unwrap_err();

        assert!(error.to_string().contains("invalid remote IPv6 address"));
    }

    #[test]
    fn rejects_non_terminated_tunnel_address() {
        let value = [b'a' as c_char; NI_MAXHOST];

        let error = parse_tunnel_addr(&value, "local").unwrap_err();

        assert!(
            error
                .to_string()
                .contains("local tunnel address is not NUL-terminated")
        );
    }

    #[tokio::test]
    #[ignore = "requires tunnel state prepared by crates/dslite-b4/scripts/test-illumos-observe.sh"]
    async fn sets_illumos_tunnel_mtu() {
        let name = std::env::var("DSLITE_TEST_TUNNEL")
            .expect("DSLITE_TEST_TUNNEL must name the prepared test tunnel");
        let mtu = std::env::var("DSLITE_TEST_MTU")
            .expect("DSLITE_TEST_MTU must contain the requested tunnel MTU")
            .parse()
            .expect("DSLITE_TEST_MTU must be an unsigned integer");
        let backend = IllumosBackend::new(name).unwrap();

        backend
            .update(
                test_desired_state(),
                TunnelUpdate {
                    mtu: Some(mtu),
                    encapsulation_limit: None,
                    bring_up: false,
                },
            )
            .await
            .unwrap();

        assert_eq!(backend.get_mtu().unwrap(), mtu);
    }

    #[tokio::test]
    #[ignore = "requires tunnel state prepared by crates/dslite-b4/scripts/test-illumos-observe.sh"]
    async fn observes_illumos_tunnel() {
        let name = std::env::var("DSLITE_TEST_TUNNEL")
            .expect("DSLITE_TEST_TUNNEL must name the prepared test tunnel");
        let expected = std::env::var("DSLITE_TEST_EXPECT")
            .expect("DSLITE_TEST_EXPECT must be present-up, present-down, or absent");
        let backend = IllumosBackend::new(name).unwrap();

        let observed = backend.observe().await.unwrap();

        if expected == "absent" {
            assert_eq!(observed, Observed::Absent);
            return;
        }

        let local_v6 = std::env::var("DSLITE_TEST_LOCAL_V6")
            .expect("DSLITE_TEST_LOCAL_V6 must contain the prepared local endpoint")
            .parse()
            .expect("DSLITE_TEST_LOCAL_V6 must be an IPv6 address");
        let remote_v6 = std::env::var("DSLITE_TEST_REMOTE_V6")
            .expect("DSLITE_TEST_REMOTE_V6 must contain the prepared remote endpoint")
            .parse()
            .expect("DSLITE_TEST_REMOTE_V6 must be an IPv6 address");
        let mtu = std::env::var("DSLITE_TEST_MTU")
            .expect("DSLITE_TEST_MTU must contain the prepared tunnel MTU")
            .parse()
            .expect("DSLITE_TEST_MTU must be an unsigned integer");
        let encapsulation_limit = test_encapsulation_limit_value();
        let admin_up = match expected.as_str() {
            "present-up" => true,
            "present-down" => false,
            value => panic!("unexpected DSLITE_TEST_EXPECT value: {value}"),
        };

        assert_eq!(
            observed,
            Observed::Present {
                local_v6,
                remote_v6,
                mtu,
                encapsulation_limit: (encapsulation_limit != 0).then_some(encapsulation_limit),
                admin_up,
            }
        );
    }

    #[tokio::test]
    #[ignore = "requires tunnel state prepared by crates/dslite-b4/scripts/test-illumos-observe.sh"]
    async fn sets_illumos_tunnel_encapsulation_limit() {
        let name = std::env::var("DSLITE_TEST_TUNNEL")
            .expect("DSLITE_TEST_TUNNEL must name the prepared test tunnel");
        let value = test_encapsulation_limit_value();
        let configured = match NonZeroU8::new(value) {
            Some(value) => EncapsulationLimit::Value(value),
            None => EncapsulationLimit::Disabled,
        };
        let backend = IllumosBackend::new(name).unwrap();

        backend
            .update(
                test_desired_state(),
                TunnelUpdate {
                    mtu: None,
                    encapsulation_limit: Some(configured),
                    bring_up: false,
                },
            )
            .await
            .unwrap();

        let Observed::Present {
            encapsulation_limit,
            ..
        } = backend.observe().await.unwrap()
        else {
            panic!("prepared tunnel is absent");
        };

        assert_eq!(encapsulation_limit, (value != 0).then_some(value),);
    }

    #[tokio::test]
    #[ignore = "requires tunnel state prepared by crates/dslite-b4/scripts/test-illumos-observe.sh"]
    async fn brings_up_illumos_tunnel() {
        let name = std::env::var("DSLITE_TEST_TUNNEL")
            .expect("DSLITE_TEST_TUNNEL must name the prepared test tunnel");
        let local_v6 = std::env::var("DSLITE_TEST_LOCAL_V6")
            .expect("DSLITE_TEST_LOCAL_V6 must contain the prepared local endpoint")
            .parse()
            .expect("DSLITE_TEST_LOCAL_V6 must be an IPv6 address");
        let remote_v6 = std::env::var("DSLITE_TEST_REMOTE_V6")
            .expect("DSLITE_TEST_REMOTE_V6 must contain the prepared remote endpoint")
            .parse()
            .expect("DSLITE_TEST_REMOTE_V6 must be an IPv6 address");
        let mtu = std::env::var("DSLITE_TEST_MTU")
            .expect("DSLITE_TEST_MTU must contain the prepared tunnel MTU")
            .parse()
            .expect("DSLITE_TEST_MTU must be an unsigned integer");
        let encapsulation_limit = test_encapsulation_limit_value();
        let backend = IllumosBackend::new(name).unwrap();

        backend
            .update(
                test_desired_state(),
                TunnelUpdate {
                    mtu: None,
                    encapsulation_limit: None,
                    bring_up: true,
                },
            )
            .await
            .unwrap();

        assert_eq!(
            backend.observe().await.unwrap(),
            Observed::Present {
                local_v6,
                remote_v6,
                mtu,
                encapsulation_limit: (encapsulation_limit != 0).then_some(encapsulation_limit),
                admin_up: true,
            }
        );
    }
}