websocat 4.0.0-alpha3

Command-line client for web sockets, like netcat/curl/socat for ws://.
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
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::time::Duration;

use tokio::net::{TcpListener, TcpSocket, TcpStream, UdpSocket};
use tracing::{debug, warn};

pub struct BindOptions {
    pub(crate) bind_before_connecting: Option<SocketAddr>,
    pub(crate) reuseaddr: Option<bool>,
    pub(crate) reuseport: bool,
    pub(crate) bind_device: Option<String>,
    pub(crate) listen_backlog: u32,
    pub(crate) freebind: bool,
    pub(crate) transparent: bool,
    pub(crate) only_v6: Option<bool>,
}

pub struct TcpStreamOptions {
    pub(crate) tclass_v6: Option<u32>,
    pub(crate) tos_v4: Option<u32>,
    /// Or hops limit for IPv6
    pub(crate) ttl: Option<u32>,
    pub(crate) linger_s: Option<u32>,
    pub(crate) out_of_band_inline: bool,
    pub(crate) nodelay: Option<bool>,

    pub(crate) tcp_congestion: Option<String>,
    pub(crate) cpu_affinity: Option<usize>,
    pub(crate) user_timeout_s: Option<u32>,
    pub(crate) priority: Option<u32>,
    pub(crate) recv_buffer_size: Option<usize>,
    pub(crate) send_buffer_size: Option<usize>,
    pub(crate) mss: Option<u32>,
    pub(crate) mark: Option<u32>,
    pub(crate) thin_linear_timeouts: Option<bool>,
    pub(crate) notsent_lowat: Option<u32>,

    pub(crate) keepalive: Option<bool>,
    pub(crate) keepalive_retries: Option<u32>,
    pub(crate) keepalive_interval_s: Option<u32>,
    pub(crate) keepalive_idletime_s: Option<u32>,
}

/// UDP options, besides the one used for binding the socket to address
pub struct UdpOptions {
    pub(crate) tclass_v6: Option<u32>,
    pub(crate) tos_v4: Option<u32>,
    /// Or hops limit for IPv6
    pub(crate) ttl: Option<u32>,

    pub(crate) cpu_affinity: Option<usize>,
    pub(crate) priority: Option<u32>,
    pub(crate) recv_buffer_size: Option<usize>,
    pub(crate) send_buffer_size: Option<usize>,

    pub(crate) mark: Option<u32>,

    pub(crate) broadcast: bool,

    pub(crate) multicast: Option<IpAddr>,
    pub(crate) multicast_interface_addr: Option<Ipv4Addr>,
    pub(crate) multicast_interface_index: Option<u32>,
    pub(crate) multicast_specific_source: Option<Ipv4Addr>,
    pub(crate) multicast_all: Option<bool>,
    pub(crate) multicast_loop: Option<bool>,
    pub(crate) multicast_ttl: Option<u32>,
}

macro_rules! cfg_gated_block_or_err {
    ($feature:literal, #[cfg($($c:tt)*)], $b:block$ (,)?) => {
        #[allow(unused_labels)]
        'a: {
            #[cfg($($c)*)] {
                $b;
                break 'a;
            }
            #[allow(unreachable_code)]
            return Err(std::io::Error::new(std::io::ErrorKind::Other, concat!("Not supported on this platform: `",$feature,"`")))
        }
    };
}

#[macro_export]
macro_rules! copy_common_bind_options {
    ($target:ident, $source:ident) => {
        $target.reuseaddr = $source.reuseaddr;
        $target.reuseport = $source.reuseport;
        $target.bind_device = $source.bind_device;
        $target.freebind = $source.freebind;
        $target.transparent = $source.transparent;
        $target.only_v6 = $source.only_v6;
    };
}

#[macro_export]
macro_rules! copy_common_tcp_stream_options {
    ($target:ident, $source:ident) => {
        $target.tclass_v6 = $source.tclass_v6;
        $target.tos_v4 = $source.tos_v4;
        $target.ttl = $source.ttl;
        $target.linger_s = $source.linger_s;
        $target.out_of_band_inline = $source.out_of_band_inline;
        $target.nodelay = $source.nodelay;
        $target.tcp_congestion = $source.tcp_congestion;
        $target.cpu_affinity = $source.cpu_affinity;
        $target.user_timeout_s = $source.user_timeout_s;
        $target.priority = $source.priority;
        $target.recv_buffer_size = $source.recv_buffer_size;
        $target.send_buffer_size = $source.send_buffer_size;
        $target.mss = $source.mss;
        $target.mark = $source.mark;
        $target.thin_linear_timeouts = $source.thin_linear_timeouts;
        $target.notsent_lowat = $source.notsent_lowat;
        $target.keepalive = $source.keepalive;
        $target.keepalive_retries = $source.keepalive_retries;
        $target.keepalive_interval_s = $source.keepalive_interval_s;
        $target.keepalive_idletime_s = $source.keepalive_idletime_s;
    };
}

#[macro_export]
macro_rules! copy_common_udp_options {
    ($target:ident, $source:ident) => {
        $target.tclass_v6 = $source.tclass_v6;
        $target.tos_v4 = $source.tos_v4;
        $target.ttl = $source.ttl;
        $target.cpu_affinity = $source.cpu_affinity;
        $target.priority = $source.priority;
        $target.recv_buffer_size = $source.recv_buffer_size;
        $target.send_buffer_size = $source.send_buffer_size;
        $target.mark = $source.mark;
        $target.broadcast = $source.broadcast;
        $target.multicast = $source.multicast;
        $target.multicast_interface_addr = $source.multicast_interface_addr;
        $target.multicast_interface_index = $source.multicast_interface_index;
        $target.multicast_specific_source = $source.multicast_specific_source;
        $target.multicast_all = $source.multicast_all;
        $target.multicast_loop = $source.multicast_loop;
        $target.multicast_ttl = $source.multicast_ttl;
    };
}

/// socket2::Socket wrapper that forgets the socket on drop instead of closing it
struct SocketWrapper(Option<socket2::Socket>);

#[cfg(unix)]
impl Drop for SocketWrapper {
    fn drop(&mut self) {
        use std::os::fd::IntoRawFd;
        if let Some(s) = self.0.take() {
            let _ = s.into_raw_fd();
        }
    }
}

#[cfg(unix)]
impl<T> From<&T> for SocketWrapper
where
    T: std::os::fd::AsRawFd,
{
    fn from(s: &T) -> Self {
        use std::os::fd::FromRawFd;
        SocketWrapper(Some(
            // Safety: resulting `socket2::Socket` is expected to only be used from this module to set some options and
            // is quickly forgotten (by `Drop` implementation above), so it feels it should be more or less OK.
            unsafe { socket2::Socket::from_raw_fd(s.as_raw_fd()) },
        ))
    }
}

#[cfg(windows)]
impl Drop for SocketWrapper {
    fn drop(&mut self) {
        use std::os::windows::io::IntoRawSocket;
        if let Some(s) = self.0.take() {
            let _ = s.into_raw_socket();
        }
    }
}

#[cfg(windows)]
impl<T> From<&T> for SocketWrapper
where
    T: std::os::windows::io::AsRawSocket,
{
    fn from(s: &T) -> Self {
        use std::os::windows::io::FromRawSocket;
        SocketWrapper(Some(
            // Safety: resulting `socket2::Socket` is expected to only be used from this module to set some options and
            // is quickly forgotten (by `Drop` implementation above), so it feels it should be more or less OK.
            unsafe { socket2::Socket::from_raw_socket(s.as_raw_socket()) },
        ))
    }
}

impl std::ops::Deref for SocketWrapper {
    type Target = socket2::Socket;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref().unwrap()
    }
}

impl BindOptions {
    pub fn new() -> BindOptions {
        Self {
            bind_before_connecting: None,
            reuseaddr: None,
            reuseport: false,
            bind_device: None,
            listen_backlog: 1024,

            freebind: false,
            transparent: false,

            only_v6: None,
        }
    }

    fn gs4a(addr: SocketAddr) -> std::io::Result<TcpSocket> {
        if addr.is_ipv4() {
            TcpSocket::new_v4()
        } else if addr.is_ipv6() {
            TcpSocket::new_v6()
        } else {
            panic!("Non IPv4 or IPv6 address is specified for a TCP socket");
        }
    }

    fn setopts(&self, s: &TcpSocket, v6: bool, pending_listen: bool) -> std::io::Result<()> {
        if let Some(v) = self.reuseaddr {
            debug!("Setting SO_REUSEADDR");
            s.set_reuseaddr(v)?;
        } else if pending_listen {
            #[cfg(not(windows))]
            s.set_reuseaddr(true)?;
        }
        if self.reuseport {
            debug!("Setting SO_REUSEPORT");
            cfg_gated_block_or_err!(
                "reuseport",
                #[cfg(all(
                    unix,
                    not(target_os = "solaris"),
                    not(target_os = "illumos"),
                    not(target_os = "cygwin"),
                ))],
                {
                    s.set_reuseport(true)?;
                },
            );
        }
        if self.transparent {
            debug!("Setting IP_TRANSPARENT");
            cfg_gated_block_or_err!(
                "transparent",
                #[cfg(target_os = "linux")],
                {
                    let ss : SocketWrapper = s.into();
                    ss.set_ip_transparent_v4(true)?;
                },
            );
        }
        if self.freebind {
            if v6 {
                debug!("Setting IPV6_FREEBIND");
                cfg_gated_block_or_err!(
                    "freebind",
                    #[cfg(any(target_os = "android", target_os = "linux"))],
                    {
                        let ss : SocketWrapper = s.into();
                        ss.set_freebind_v6(true)?;
                    },
                );
            } else {
                debug!("Setting IP_FREEBIND");
                cfg_gated_block_or_err!(
                    "freebind",
                    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                    {
                        let ss : SocketWrapper = s.into();
                        ss.set_freebind_v4(true)?;
                    },
                );
            }
        }
        if let Some(ref v) = self.bind_device {
            debug!("Setting SO_BINDTODEVICE");
            cfg_gated_block_or_err!(
                "bind_device",
                #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                {
                    s.bind_device(Some(v.as_bytes()))?;
                },
            );
        }

        if v6 {
            #[cfg(any(windows, unix))]
            if let Some(v) = self.only_v6 {
                let ss: SocketWrapper = s.into();
                ss.set_only_v6(v)?;
            }
        }
        Ok(())
    }

    pub fn setopts_udp(&self, ss: &socket2::Socket, v6: bool) -> std::io::Result<()> {
        if let Some(v) = self.reuseaddr {
            debug!("Setting SO_REUSEADDR");
            ss.set_reuse_address(v)?;
        }
        if self.reuseport {
            debug!("Setting SO_REUSEPORT");
            cfg_gated_block_or_err!(
                "reuseport",
                #[cfg(all(
                    unix,
                    not(target_os = "solaris"),
                    not(target_os = "illumos"),
                    not(target_os = "cygwin"),
                ))],
                {
                    ss.set_reuse_port(true)?;
                },
            );
        }
        if self.transparent {
            debug!("Setting IP_TRANSPARENT");
            cfg_gated_block_or_err!(
                "transparent",
                #[cfg(target_os = "linux")],
                {
                    ss.set_ip_transparent_v4(true)?;
                },
            );
        }
        if self.freebind {
            if v6 {
                debug!("Setting IPV6_FREEBIND");
                cfg_gated_block_or_err!(
                    "freebind",
                    #[cfg(any(target_os = "android", target_os = "linux"))],
                    {
                        ss.set_freebind_v6(true)?;
                    },
                );
            } else {
                debug!("Setting IP_FREEBIND");
                cfg_gated_block_or_err!(
                    "freebind",
                    #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                    {
                        ss.set_freebind_v4(true)?;
                    },
                );
            }
        }
        if let Some(ref v) = self.bind_device {
            debug!("Setting SO_BINDTODEVICE");
            cfg_gated_block_or_err!(
                "bind_device",
                #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                {
                    ss.bind_device(Some(v.as_bytes()))?;
                },
            );
        }

        if v6 {
            #[cfg(any(windows, unix))]
            if let Some(v) = self.only_v6 {
                ss.set_only_v6(v)?;
            }
        }
        Ok(())
    }

    pub async fn connect(
        &self,
        addr: SocketAddr,
        stream_opts: &TcpStreamOptions,
    ) -> std::io::Result<TcpStream> {
        let s = Self::gs4a(addr)?;
        self.setopts(&s, addr.is_ipv6(), false)?;
        if let Some(bbc) = self.bind_before_connecting {
            debug!("Using bind before connect");
            s.bind(bbc)?;
        }
        let ss = s.connect(addr).await?;
        stream_opts.apply_socket_opts(&ss, addr.is_ipv6())?;
        Ok(ss)
        //TcpStream::connect(addr).await
    }

    pub async fn bind_tcp(&self, addr: SocketAddr) -> std::io::Result<TcpListener> {
        let s = Self::gs4a(addr)?;
        self.setopts(&s, addr.is_ipv6(), true)?;
        s.bind(addr)?;
        s.listen(self.listen_backlog)
        //TcpListener::bind(addr).await
    }

    pub async fn bind_udp(&self, addr: SocketAddr) -> std::io::Result<UdpSocket> {
        // let s = Self::gs4a(addr)?;
        let s = socket2::Socket::new(
            socket2::Domain::for_address(addr),
            socket2::Type::DGRAM,
            None,
        )?;
        self.setopts_udp(&s, addr.is_ipv6())?;
        s.set_nonblocking(true)?;
        s.bind(&addr.into())?;
        UdpSocket::from_std(s.into())

        //UdpSocket::bind(addr).await
    }

    pub fn warn_if_options_set(&self) {
        let mut warn_ = false;
        if self.bind_before_connecting.is_some() {
            warn_ = true;
        }
        if self.reuseaddr.is_some() {
            warn_ = true;
        }
        if self.reuseport {
            warn_ = true;
        }
        if self.bind_device.is_some() {
            warn_ = true;
        }
        if self.freebind {
            warn_ = true;
        }
        if self.transparent {
            warn_ = true;
        }
        if self.only_v6.is_some() {
            warn_ = true;
        }
        if warn_ {
            warn!("Not applying socket bind options, as the socket was pre-opened");
        }
    }
}

impl TcpStreamOptions {
    pub fn new() -> TcpStreamOptions {
        Self {
            tclass_v6: None,
            tos_v4: None,
            ttl: None,
            tcp_congestion: None,
            cpu_affinity: None,
            user_timeout_s: None,
            linger_s: None,
            out_of_band_inline: false,
            priority: None,
            recv_buffer_size: None,
            send_buffer_size: None,
            nodelay: None,
            mss: None,
            mark: None,
            thin_linear_timeouts: None,
            notsent_lowat: None,
            keepalive: None,
            keepalive_retries: None,
            keepalive_interval_s: None,
            keepalive_idletime_s: None,
        }
    }

    pub fn apply_socket_opts(&self, s: &TcpStream, v6: bool) -> std::io::Result<()> {
        if let Some(v) = self.nodelay {
            debug!("Setting TCP_NODELAY");
            s.set_nodelay(v)?;
        }
        if let Some(v) = self.linger_s {
            debug!("Setting SO_LINGER");
            s.set_linger(Some(Duration::from_secs(v.into())))?;
        }
        if !v6 {
            if let Some(v) = self.ttl {
                debug!("Setting IP_TTL");
                s.set_ttl(v)?;
            }
        }

        let ss: SocketWrapper;
        #[cfg(any(unix, windows))]
        {
            ss = s.into();
        }
        #[cfg(not(any(unix, windows)))]
        {
            return Ok(());
        }

        if v6 {
            if let Some(v) = self.ttl {
                debug!("Setting IPV6_UNICAST_HOPS");
                ss.set_unicast_hops_v6(v)?;
            }
        }

        if v6 {
            if let Some(v) = self.tclass_v6 {
                debug!("Setting IPV6_TCLASS");
                cfg_gated_block_or_err!(
                    "tclass_v6",
                    #[cfg(any(
                        target_os = "android",
                        target_os = "dragonfly",
                        target_os = "freebsd",
                        target_os = "fuchsia",
                        target_os = "linux",
                        target_os = "macos",
                        target_os = "netbsd",
                        target_os = "openbsd"
                    ))],
                    {
                        ss.set_tclass_v6(v)?;
                    },
                );
            }
        } else if let Some(v) = self.tos_v4 {
            debug!("Setting IP_TOS");
            cfg_gated_block_or_err!(
                "tos_v4",
                #[cfg(not(any(
                    target_os = "fuchsia",
                    target_os = "redox",
                    target_os = "solaris",
                    target_os = "illumos",
                    target_os = "haiku",
                )))],
                {
                    ss.set_tos_v4(v)?;
                },
            );
        }

        if self.out_of_band_inline {
            debug!("Setting SO_OOBINLINE");
            #[cfg(not(target_os = "redox"))]
            ss.set_out_of_band_inline(true)?;
        }

        if let Some(v) = &self.tcp_congestion {
            debug!("Setting TCP_CONGESTION");
            cfg_gated_block_or_err!(
                "tcp_congestion",
                #[cfg(any(target_os = "freebsd", target_os = "linux"))],
                {
                    ss.set_tcp_congestion(v.as_bytes())?;
                },
            );
        }
        if let Some(v) = self.cpu_affinity {
            debug!("Setting SO_INCOMING_CPU");
            cfg_gated_block_or_err!(
                "cpu_affinity",
                #[cfg(target_os = "linux")],
                {
                    ss.set_cpu_affinity(v)?;
                },
            );
        }
        if let Some(v) = self.user_timeout_s {
            debug!("Setting TCP_USER_TIMEOUT");
            cfg_gated_block_or_err!(
                "user_timeout_s",
                #[cfg(any(
                    target_os = "android",
                    target_os = "fuchsia",
                    target_os = "linux",
                    target_os = "cygwin",
                ))],
                {
                    ss.set_tcp_user_timeout(Some(Duration::from_secs(v.into())))?;
                },
            );
        }
        if let Some(v) = self.priority {
            debug!("Setting SO_PRIORITY");
            cfg_gated_block_or_err!(
                "priority",
                #[cfg(any(target_os = "linux", target_os = "android", target_os = "fuchsia"))],
                {
                    ss.set_priority(v)?;
                },
            );
        }
        if let Some(v) = self.recv_buffer_size {
            debug!("Setting SO_RCVBUF");
            ss.set_recv_buffer_size(v)?;
        }
        if let Some(v) = self.send_buffer_size {
            debug!("Setting SO_SNDBUF");
            ss.set_send_buffer_size(v)?;
        }
        if let Some(v) = self.mss {
            debug!("Setting TCP_MAXSEG");
            cfg_gated_block_or_err!(
                "mss",
                #[cfg(all(unix, not(target_os = "redox")))],
                {
                    ss.set_tcp_mss(v)?;
                },
            );
        }
        if let Some(v) = self.mark {
            debug!("Setting SO_MARK");
            cfg_gated_block_or_err!(
                "mark",
                #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                {
                    ss.set_mark(v)?;
                },
            );
        }
        if let Some(v) = self.thin_linear_timeouts {
            debug!("Setting TCP_THIN_LINEAR_TIMEOUTS");
            cfg_gated_block_or_err!(
                "thin_linear_timeouts",
                #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                {
                    ss.set_tcp_thin_linear_timeouts(v)?;
                },
            );
        }
        if let Some(v) = self.notsent_lowat {
            debug!("Setting TCP_NOTSENT_LOWAT");
            cfg_gated_block_or_err!(
                "notsent_lowat",
                #[cfg(any(target_os = "android", target_os = "linux"))],
                {
                    ss.set_tcp_notsent_lowat(v)?;
                },
            );
        }

        if let Some(v) = self.keepalive {
            debug!("Setting SO_KEEPALIVE");
            if v {
                #[allow(unused_mut)]
                let mut ka = socket2::TcpKeepalive::new();

                if let Some(w) = self.keepalive_interval_s {
                    cfg_gated_block_or_err!(
                        "keepalive_interval_s",
                        #[cfg(any(
                            target_os = "android",
                            target_os = "dragonfly",
                            target_os = "freebsd",
                            target_os = "fuchsia",
                            target_os = "illumos",
                            target_os = "ios",
                            target_os = "visionos",
                            target_os = "linux",
                            target_os = "macos",
                            target_os = "netbsd",
                            target_os = "tvos",
                            target_os = "watchos",
                            target_os = "windows",
                            target_os = "cygwin",
                        ))],
                        {
                            ka = ka.with_interval(Duration::from_secs(w.into()));
                        },
                    );
                }

                if let Some(w) = self.keepalive_idletime_s {
                    ka = ka.with_time(Duration::from_secs(w.into()));
                }

                if let Some(w) = self.keepalive_retries {
                    cfg_gated_block_or_err!(
                        "keepalive_interval_s",
                        #[cfg(any(
                            target_os = "android",
                            target_os = "dragonfly",
                            target_os = "freebsd",
                            target_os = "fuchsia",
                            target_os = "illumos",
                            target_os = "ios",
                            target_os = "visionos",
                            target_os = "linux",
                            target_os = "macos",
                            target_os = "netbsd",
                            target_os = "tvos",
                            target_os = "watchos",
                            target_os = "cygwin",
                            target_os = "windows",
                        ))],
                        {
                            ka = ka.with_retries(w);
                        },
                    );
                }

                ss.set_tcp_keepalive(&ka)?;
            } else {
                ss.set_keepalive(false)?;
            }
        }

        Ok(())
    }
}

impl UdpOptions {
    pub fn new() -> UdpOptions {
        Self {
            tclass_v6: None,
            tos_v4: None,
            ttl: None,
            cpu_affinity: None,
            priority: None,
            recv_buffer_size: None,
            send_buffer_size: None,
            mark: None,
            broadcast: false,
            multicast: None,
            multicast_interface_addr: None,
            multicast_interface_index: None,
            multicast_specific_source: None,
            multicast_all: None,
            multicast_loop: None,
            multicast_ttl: None,
        }
    }

    pub fn apply_socket_opts(&self, s: &UdpSocket, v6: bool) -> std::io::Result<()> {
        if !v6 {
            if let Some(v) = self.ttl {
                debug!("Setting IP_TTL");
                s.set_ttl(v)?;
            }
        }

        let ss: SocketWrapper;
        #[cfg(any(unix, windows))]
        {
            ss = s.into();
        }
        #[cfg(not(any(unix, windows)))]
        {
            return Ok(());
        }

        if v6 {
            if let Some(v) = self.ttl {
                debug!("Setting IPV6_UNICAST_HOPS");
                ss.set_unicast_hops_v6(v)?;
            }
        }

        if v6 {
            if let Some(v) = self.tclass_v6 {
                debug!("Setting IPV6_TCLASS");
                cfg_gated_block_or_err!(
                    "tclass_v6",
                    #[cfg(any(
                        target_os = "android",
                        target_os = "dragonfly",
                        target_os = "freebsd",
                        target_os = "fuchsia",
                        target_os = "linux",
                        target_os = "macos",
                        target_os = "netbsd",
                        target_os = "openbsd"
                    ))],
                    {
                        ss.set_tclass_v6(v)?;
                    },
                );
            }
        } else if let Some(v) = self.tos_v4 {
            debug!("Setting IP_TOS");
            cfg_gated_block_or_err!(
                "tos_v4",
                #[cfg(not(any(
                    target_os = "fuchsia",
                    target_os = "redox",
                    target_os = "solaris",
                    target_os = "illumos",
                    target_os = "haiku",
                )))],
                {
                    ss.set_tos_v4(v)?;
                },
            );
        }

        if let Some(v) = self.cpu_affinity {
            debug!("Setting SO_INCOMING_CPU");
            cfg_gated_block_or_err!(
                "cpu_affinity",
                #[cfg(target_os = "linux")],
                {
                    ss.set_cpu_affinity(v)?;
                },
            );
        }
        if let Some(v) = self.priority {
            debug!("Setting SO_PRIORITY");
            cfg_gated_block_or_err!(
                "priority",
                #[cfg(any(target_os = "linux", target_os = "android", target_os = "fuchsia"))],
                {
                    ss.set_priority(v)?;
                },
            );
        }
        if let Some(v) = self.recv_buffer_size {
            debug!("Setting SO_RCVBUF");
            ss.set_recv_buffer_size(v)?;
        }
        if let Some(v) = self.send_buffer_size {
            debug!("Setting SO_SNDBUF");
            ss.set_send_buffer_size(v)?;
        }
        if let Some(v) = self.mark {
            debug!("Setting SO_MARK");
            cfg_gated_block_or_err!(
                "mark",
                #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))],
                {
                    ss.set_mark(v)?;
                },
            );
        }

        if self.broadcast {
            debug!("Setting SO_BROADCAST");
            ss.set_broadcast(true)?;
        }

        if self.multicast_interface_addr.is_some() && self.multicast_interface_index.is_some() {
            return Err(std::io::Error::other(
                "Trying to specify multicast interface both by index and IP address simultaneously",
            ));
        }

        if let Some(ma) = self.multicast {
            match ma {
                IpAddr::V4(ma) => {
                    if let Some(spsrc) = self.multicast_specific_source {
                        if self.multicast_interface_index.is_some() {
                            return Err(std::io::Error::other(
                                "When multicast specific source is specified, interface cannot be specified by index, only by IP",
                            ));
                        }
                        let ifa = self
                            .multicast_interface_addr
                            .unwrap_or(Ipv4Addr::UNSPECIFIED);
                        cfg_gated_block_or_err!("",
                            #[cfg(not(any(
                                target_os = "dragonfly",
                                target_os = "haiku",
                                target_os = "hurd",
                                target_os = "netbsd",
                                target_os = "openbsd",
                                target_os = "redox",
                                target_os = "fuchsia",
                                target_os = "nto",
                                target_os = "espidf",
                                target_os = "vita",
                            )))],
                            {
                                debug!("Issuing IP_ADD_SOURCE_MEMBERSHIP");
                                ss.join_ssm_v4(&spsrc, &ma, &ifa)?;
                            }
                        );
                    } else if let Some(ifi) = self.multicast_interface_index {
                        cfg_gated_block_or_err!(
                            "join_multicast_v4_n",
                            #[cfg(not(any(
                                target_os = "aix",
                                target_os = "haiku",
                                target_os = "illumos",
                                target_os = "netbsd",
                                target_os = "openbsd",
                                target_os = "redox",
                                target_os = "solaris",
                                target_os = "nto",
                                target_os = "espidf",
                                target_os = "vita",
                                target_os = "cygwin",
                            )))],
                            {
                                debug!("Issuing IP_ADD_MEMBERSHIP");
                                ss.join_multicast_v4_n(&ma, &socket2::InterfaceIndexOrAddress::Index(ifi))?;
                            },
                        );
                    } else {
                        let ifa = self
                            .multicast_interface_addr
                            .unwrap_or(Ipv4Addr::UNSPECIFIED);

                        debug!("Issuing IP_ADD_MEMBERSHIP");
                        ss.join_multicast_v4(&ma, &ifa)?;
                    }

                    if let Some(v) = self.multicast_all {
                        cfg_gated_block_or_err!(
                            "multicast_all",
                            #[cfg(target_os = "linux")],
                            {
                                debug!("Setting IP_MULTICAST_ALL");
                                ss.set_multicast_all_v4(v)?;
                            }
                        );
                    }
                    if let Some(v) = self.multicast_ttl {
                        debug!("Setting IP_MULTICAST_TTL");
                        ss.set_multicast_ttl_v4(v)?;
                    }
                    if let Some(v) = self.multicast_loop {
                        debug!("Setting IP_MULTICAST_LOOP");
                        ss.set_multicast_loop_v4(v)?;
                    }
                }
                IpAddr::V6(ma) => {
                    if self.multicast_interface_addr.is_some() {
                        return Err(std::io::Error::other(
                            "Interface address should be specified by index for IPv6 multicast",
                        ));
                    }
                    if self.multicast_specific_source.is_some() {
                        return Err(std::io::Error::other(
                            "multicast_specific_source is not supported for IPv6",
                        ));
                    }
                    let ifindex = self.multicast_interface_index.unwrap_or(0);

                    cfg_gated_block_or_err!(
                        "join_multicast_v6",
                        #[cfg(not(target_os = "nto"))],
                        {
                            debug!("Setting IPV6_ADD_MEMBERSHIP");
                            ss.join_multicast_v6(&ma, ifindex)?;
                        }
                    );


                    if let Some(v) = self.multicast_all {
                        cfg_gated_block_or_err!(
                            "multicast_all",
                            #[cfg(target_os = "linux")],
                            {
                                debug!("Setting IPV6_MULTICAST_ALL");
                                ss.set_multicast_all_v6(v)?;
                            }
                        );
                    }
                    if let Some(v) = self.multicast_ttl {
                        debug!("Setting IPV6_MULTICAST_HOPS");
                        ss.set_multicast_hops_v6(v)?;
                    }
                    if let Some(v) = self.multicast_loop {
                        debug!("Setting IPV6_MULTICAST_LOOP");
                        ss.set_multicast_loop_v6(v)?;
                    }
                }
            }
        } else if self.multicast_all.is_some()
            || self.multicast_interface_addr.is_some()
            || self.multicast_interface_index.is_some()
            || self.multicast_loop.is_some()
            || self.multicast_specific_source.is_some()
            || self.multicast_ttl.is_some()
        {
            return Err(std::io::Error::other(
                "Trying to set socket multicast options without enabling multicast itself",
            ));
        }

        Ok(())
    }
}