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
//! Type safe abstraction for esp-tls

#[cfg(all(esp_idf_esp_tls_psk_verification, feature = "alloc"))]
use core::convert::TryFrom;
use core::fmt::Debug;

use crate::private::cstr::{c_char, CStr};
#[cfg(all(esp_idf_esp_tls_psk_verification, feature = "alloc"))]
use crate::sys::EspError;

#[cfg(all(
    esp_idf_comp_esp_tls_enabled,
    any(esp_idf_esp_tls_using_mbedtls, esp_idf_esp_tls_using_wolfssl)
))]
pub use self::esptls::*;

#[derive(Copy, Clone, Eq, PartialEq)]
pub struct Psk<'a> {
    pub key: &'a [u8],
    pub hint: &'a str,
}

impl<'a> Debug for Psk<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
        f.debug_struct("Psk")
            .field("hint", &self.hint)
            .finish_non_exhaustive()
    }
}

/// Helper for holding PSK data for lately initialized TLS connections.
///
/// It could be easily converted from the public `Psk` configuration and holds the `psk_hint_key_t`
/// along with its (string) data as this data typically needs to be around after initializing a TLS
/// client until it has been started.
#[cfg(all(esp_idf_esp_tls_psk_verification, feature = "alloc"))]
pub(crate) struct TlsPsk {
    pub(crate) psk: alloc::boxed::Box<crate::hal::sys::psk_hint_key_t>,
    pub(crate) _cstrs: crate::private::cstr::RawCstrs,
}
/// Dummy for maintaining the same internal interface whether TLS PSK support is enabled or not.
#[cfg(not(all(esp_idf_esp_tls_psk_verification, feature = "alloc")))]
#[allow(dead_code)]
pub(crate) struct TlsPsk {}

#[cfg(all(esp_idf_esp_tls_psk_verification, feature = "alloc"))]
impl Debug for TlsPsk {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
        f.debug_struct("TlsPsk")
            .field("psk", &self.psk)
            .finish_non_exhaustive()
    }
}

#[cfg(all(esp_idf_esp_tls_psk_verification, feature = "alloc"))]
impl<'a> TryFrom<&'a Psk<'a>> for TlsPsk {
    type Error = EspError;

    fn try_from(conf: &Psk) -> Result<Self, EspError> {
        let mut cstrs = crate::private::cstr::RawCstrs::new();
        let psk = alloc::boxed::Box::new(crate::hal::sys::psk_hint_key_t {
            key: conf.key.as_ptr(),
            key_size: conf.key.len(),
            hint: cstrs.as_ptr(conf.hint)?,
        });

        Ok(TlsPsk { psk, _cstrs: cstrs })
    }
}

#[derive(Copy, Clone, Eq, PartialEq)]
pub struct X509<'a>(&'a [u8]);

impl<'a> X509<'a> {
    pub fn pem(cstr: &'a CStr) -> Self {
        Self(cstr.to_bytes_with_nul())
    }

    pub const fn pem_until_nul(bytes: &'a [u8]) -> Self {
        // TODO: replace with `CStr::from_bytes_until_nul` when stabilized
        let mut nul_pos = 0;
        while nul_pos < bytes.len() {
            if bytes[nul_pos] == 0 {
                // TODO: replace with `<[u8]>::split_at(nul_pos + 1)` when const stabilized
                let slice = unsafe { core::slice::from_raw_parts(bytes.as_ptr(), nul_pos + 1) };
                return Self(slice);
            }
            nul_pos += 1;
        }
        panic!("PEM certificates should end with a NIL (`\\0`) ASCII character.")
    }

    pub const fn der(bytes: &'a [u8]) -> Self {
        Self(bytes)
    }

    pub fn data(&self) -> &[u8] {
        self.0
    }

    #[allow(unused)]
    pub(crate) fn as_esp_idf_raw_ptr(&self) -> *const c_char {
        self.data().as_ptr().cast()
    }

    #[allow(unused)]
    pub(crate) fn as_esp_idf_raw_len(&self) -> usize {
        self.data().len()
    }
}

impl<'a> Debug for X509<'a> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
        f.debug_struct("X509").finish_non_exhaustive()
    }
}

#[cfg(all(
    esp_idf_comp_esp_tls_enabled,
    any(esp_idf_esp_tls_using_mbedtls, esp_idf_esp_tls_using_wolfssl)
))]
mod esptls {
    #[cfg(esp_idf_esp_tls_server_cert_select_hook)]
    use core::ffi::c_int;
    use core::task::{Context, Poll};
    use core::time::Duration;

    use embedded_svc::io;

    use super::X509;

    use crate::{
        io::EspIOError,
        private::cstr::{cstr_arr_from_str_slice, cstr_from_str_truncating, CStr},
        sys::{
            self, EspError, ESP_ERR_NO_MEM, ESP_FAIL, ESP_TLS_ERR_SSL_WANT_READ,
            ESP_TLS_ERR_SSL_WANT_WRITE, EWOULDBLOCK,
        },
    };

    /// see https://www.ietf.org/rfc/rfc3280.txt ub-common-name-length
    const MAX_COMMON_NAME_LENGTH: usize = 64;

    pub struct Config<'a> {
        /// up to 9 ALPNs allowed, with avg 10 bytes for each name
        pub alpn_protos: Option<&'a [&'a str]>,
        pub ca_cert: Option<X509<'a>>,
        pub client_cert: Option<X509<'a>>,
        pub client_key: Option<X509<'a>>,
        pub client_key_password: Option<&'a str>,
        pub non_block: bool,
        pub use_secure_element: bool,
        pub timeout_ms: u32,
        pub use_global_ca_store: bool,
        pub common_name: Option<&'a str>,
        pub skip_common_name: bool,
        pub keep_alive_cfg: Option<KeepAliveConfig>,
        pub psk_hint_key: Option<PskHintKey<'a>>,
        /// whether to use esp_crt_bundle_attach, see https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/protocols/esp_crt_bundle.html
        #[cfg(esp_idf_mbedtls_certificate_bundle)]
        pub use_crt_bundle_attach: bool,
        // TODO ds_data not implemented
        pub is_plain_tcp: bool,
    }

    impl<'a> Config<'a> {
        pub const fn new() -> Self {
            Self {
                alpn_protos: None,
                ca_cert: None,
                client_cert: None,
                client_key: None,
                client_key_password: None,
                non_block: false,
                use_secure_element: false,
                timeout_ms: 4000,
                use_global_ca_store: false,
                common_name: None,
                skip_common_name: false,
                keep_alive_cfg: None,
                psk_hint_key: None,
                #[cfg(esp_idf_mbedtls_certificate_bundle)]
                use_crt_bundle_attach: true,
                is_plain_tcp: false,
            }
        }

        fn try_into_raw(&self, bufs: &mut RawConfigBufs) -> Result<sys::esp_tls_cfg, EspError> {
            let mut rcfg: sys::esp_tls_cfg = Default::default();

            if let Some(ca_cert) = self.ca_cert {
                rcfg.__bindgen_anon_1.cacert_buf = ca_cert.data().as_ptr();
                rcfg.__bindgen_anon_2.cacert_bytes = ca_cert.data().len() as u32;
            }

            if let Some(client_cert) = self.client_cert {
                rcfg.__bindgen_anon_3.clientcert_buf = client_cert.data().as_ptr();
                rcfg.__bindgen_anon_4.clientcert_bytes = client_cert.data().len() as u32;
            }

            if let Some(client_key) = self.client_key {
                rcfg.__bindgen_anon_5.clientkey_buf = client_key.data().as_ptr();
                rcfg.__bindgen_anon_6.clientkey_bytes = client_key.data().len() as u32;
            }

            if let Some(ckp) = self.client_key_password {
                rcfg.clientkey_password = ckp.as_ptr();
                rcfg.clientkey_password_len = ckp.len() as u32;
            }

            // allow up to 9 protocols
            if let Some(protos) = self.alpn_protos {
                bufs.alpn_protos = cstr_arr_from_str_slice(protos, &mut bufs.alpn_protos_cbuf)?;
                rcfg.alpn_protos = bufs.alpn_protos.as_mut_ptr();
            }

            rcfg.non_block = self.non_block;
            rcfg.use_secure_element = self.use_secure_element;
            rcfg.timeout_ms = self.timeout_ms as i32;
            rcfg.use_global_ca_store = self.use_global_ca_store;

            if let Some(common_name) = self.common_name {
                rcfg.common_name =
                    cstr_from_str_truncating(common_name, &mut bufs.common_name_buf).as_ptr();
            }

            rcfg.skip_common_name = self.skip_common_name;

            let mut raw_kac: sys::tls_keep_alive_cfg;
            if let Some(kac) = &self.keep_alive_cfg {
                raw_kac = sys::tls_keep_alive_cfg {
                    keep_alive_enable: kac.enable,
                    keep_alive_idle: kac.idle.as_secs() as i32,
                    keep_alive_interval: kac.interval.as_secs() as i32,
                    keep_alive_count: kac.count as i32,
                };
                rcfg.keep_alive_cfg = &mut raw_kac as *mut _;
            }

            let mut raw_psk: sys::psk_key_hint;
            if let Some(psk) = &self.psk_hint_key {
                raw_psk = sys::psk_key_hint {
                    key: psk.key.as_ptr(),
                    key_size: psk.key.len(),
                    hint: psk.hint.as_ptr(),
                };
                rcfg.psk_hint_key = &mut raw_psk as *mut _;
            }

            #[cfg(esp_idf_mbedtls_certificate_bundle)]
            if self.use_crt_bundle_attach {
                rcfg.crt_bundle_attach = Some(sys::esp_crt_bundle_attach);
            }

            rcfg.is_plain_tcp = self.is_plain_tcp;

            #[cfg(esp_idf_comp_lwip_enabled)]
            {
                rcfg.if_name = core::ptr::null_mut();
            }

            Ok(rcfg)
        }
    }

    impl<'a> Default for Config<'a> {
        fn default() -> Self {
            Self::new()
        }
    }

    struct RawConfigBufs {
        alpn_protos: [*const i8; 10],
        alpn_protos_cbuf: [u8; 99],
        common_name_buf: [u8; MAX_COMMON_NAME_LENGTH + 1],
    }

    unsafe impl Send for RawConfigBufs {}

    impl Default for RawConfigBufs {
        fn default() -> Self {
            RawConfigBufs {
                alpn_protos: [core::ptr::null(); 10],
                alpn_protos_cbuf: [0; 99],
                common_name_buf: [0; MAX_COMMON_NAME_LENGTH + 1],
            }
        }
    }

    type AlpnBuf = [u8; 16];

    #[derive(Clone, Default)]
    pub struct CompletedHandshake {
        alpn: AlpnBuf,
    }

    impl CompletedHandshake {
        pub fn alpn_proto(&self) -> Option<&str> {
            let p = CStr::from_bytes_until_nul(self.alpn.as_slice()).unwrap();
            // Safety: the bytes always come from a user supplied &str.
            let p = unsafe { core::str::from_utf8_unchecked(p.to_bytes()) };

            // A valid protocol is never empty.
            if !p.is_empty() {
                Some(p)
            } else {
                None
            }
        }

        // Safety: Must be called while the configured ALPN protocol strings are valid.
        unsafe fn extract(raw: *mut sys::esp_tls) -> CompletedHandshake {
            CompletedHandshake {
                alpn: unsafe { Self::extract_alpn(raw) }.unwrap_or_default(),
            }
        }

        #[cfg(not(all(
            not(esp_idf_version_major = "4"),
            esp_idf_comp_esp_tls_enabled,
            esp_idf_esp_tls_using_mbedtls,
            esp_idf_mbedtls_ssl_alpn
        )))]
        unsafe fn extract_alpn(_raw: *mut sys::esp_tls) -> Option<AlpnBuf> {
            None
        }

        #[cfg(all(
            not(esp_idf_version_major = "4"),
            esp_idf_comp_esp_tls_enabled,
            esp_idf_esp_tls_using_mbedtls,
            esp_idf_mbedtls_ssl_alpn
        ))]
        #[warn(unsafe_op_in_unsafe_fn)]
        unsafe fn extract_alpn(raw: *mut sys::esp_tls) -> Option<AlpnBuf> {
            let raw: *mut sys::mbedtls_ssl_context =
                unsafe { sys::esp_tls_get_ssl_context(raw) }.cast();

            if raw.is_null() {
                return None;
            }

            let chosen = unsafe { sys::mbedtls_ssl_get_alpn_protocol(raw) };
            if chosen.is_null() {
                return None;
            }

            let mut proto = AlpnBuf::default();
            let chosen = unsafe { CStr::from_ptr(chosen) };
            let chosen_bytes = chosen.to_bytes_with_nul();
            if chosen_bytes.len() > proto.len() {
                return None;
            }

            proto[..chosen_bytes.len()].copy_from_slice(chosen_bytes);

            Some(proto)
        }
    }

    #[derive(Clone, Debug)]
    pub struct KeepAliveConfig {
        /// Enable keep-alive timeout
        pub enable: bool,
        /// Keep-alive idle time (second)
        pub idle: Duration,
        /// Keep-alive interval time (second)
        pub interval: Duration,
        /// Keep-alive packet retry send count
        pub count: u32,
    }

    pub struct PskHintKey<'a> {
        pub key: &'a [u8],
        pub hint: &'a CStr,
    }

    #[cfg(esp_idf_esp_tls_server)]
    pub struct ServerConfig<'a> {
        /// up to 9 ALPNs allowed, with avg 10 bytes for each name
        pub alpn_protos: Option<&'a [&'a str]>,
        pub ca_cert: Option<X509<'a>>,
        pub server_cert: Option<X509<'a>>,
        pub server_key: Option<X509<'a>>,
        pub server_key_password: Option<&'a str>,
        pub use_secure_element: bool,
        #[cfg(esp_idf_esp_tls_server_cert_select_hook)]
        pub handshake_callback: Option<extern "C" fn(*mut sys::mbedtls_ssl_context) -> c_int>,
    }

    #[cfg(esp_idf_esp_tls_server)]
    impl<'a> ServerConfig<'a> {
        pub const fn new() -> Self {
            Self {
                alpn_protos: None,
                ca_cert: None,
                server_cert: None,
                server_key: None,
                server_key_password: None,
                use_secure_element: false,
                #[cfg(esp_idf_esp_tls_server_cert_select_hook)]
                handshake_callback: None,
            }
        }

        fn try_into_raw(
            &self,
            bufs: &mut RawConfigBufs,
        ) -> Result<sys::esp_tls_cfg_server, EspError> {
            let mut rcfg: sys::esp_tls_cfg_server = Default::default();

            if let Some(ca_cert) = self.ca_cert {
                rcfg.__bindgen_anon_1.cacert_buf = ca_cert.data().as_ptr();
                rcfg.__bindgen_anon_2.cacert_bytes = ca_cert.data().len() as u32;
            }

            if let Some(server_cert) = self.server_cert {
                rcfg.__bindgen_anon_3.servercert_buf = server_cert.data().as_ptr();
                rcfg.__bindgen_anon_4.servercert_bytes = server_cert.data().len() as u32;
            }

            if let Some(server_key) = self.server_key {
                rcfg.__bindgen_anon_5.serverkey_buf = server_key.data().as_ptr();
                rcfg.__bindgen_anon_6.serverkey_bytes = server_key.data().len() as u32;
            }

            if let Some(ckp) = self.server_key_password {
                rcfg.serverkey_password = ckp.as_ptr();
                rcfg.serverkey_password_len = ckp.len() as u32;
            }

            // allow up to 9 protocols
            if let Some(protos) = self.alpn_protos {
                bufs.alpn_protos = cstr_arr_from_str_slice(protos, &mut bufs.alpn_protos_cbuf)?;
                rcfg.alpn_protos = bufs.alpn_protos.as_mut_ptr();
            }

            rcfg.use_secure_element = self.use_secure_element;

            #[cfg(esp_idf_esp_tls_server_cert_select_hook)]
            if let Some(cb) = self.handshake_callback {
                rcfg.cert_select_cb = cb;
            }

            Ok(rcfg)
        }
    }

    #[cfg(esp_idf_esp_tls_server)]
    impl<'a> Default for ServerConfig<'a> {
        fn default() -> Self {
            Self::new()
        }
    }

    pub trait Socket {
        /// Returns the integer FD.
        fn handle(&self) -> i32;
        /// This is called before cleaning up the the tls context and is responsible
        /// for essentially giving up ownership of the socket such that it can safely
        /// be closed by the ESP IDF.
        fn release(&mut self) -> Result<(), EspError>;
    }

    pub trait PollableSocket: Socket {
        fn poll_readable(&self, ctx: &mut Context) -> Poll<Result<(), EspError>>;
        fn poll_writable(&self, ctx: &mut Context) -> Poll<Result<(), EspError>>;
    }

    pub struct InternalSocket(());

    impl Socket for InternalSocket {
        fn handle(&self) -> i32 {
            unreachable!()
        }

        fn release(&mut self) -> Result<(), EspError> {
            Ok(())
        }
    }

    /// Wrapper for `esp-tls` module. Only supports synchronous operation for now.
    pub struct EspTls<S>
    where
        S: Socket,
    {
        raw: *mut sys::esp_tls,
        socket: S,
        #[cfg(esp_idf_esp_tls_server)]
        server_session: bool,
    }

    // A single Mbed TLS context itself is safe to send across threads.
    // Require the threading implementation to be enabled since a shared context such as RSA or X509 could be used by multiple threads at once.
    // See https://mbed-tls.readthedocs.io/en/latest/kb/development/thread-safety-and-multi-threading/
    #[cfg(all(
        esp_idf_comp_esp_tls_enabled,
        esp_idf_esp_tls_using_mbedtls,
        esp_idf_mbedtls_threading_c
    ))]
    unsafe impl<S> Send for EspTls<S> where S: Send + Socket {}

    impl EspTls<InternalSocket> {
        /// Create a new `EspTls` instance using internally-managed socket.
        ///
        /// # Errors
        ///
        /// * `ESP_ERR_NO_MEM` if not enough memory to create the TLS connection
        pub fn new() -> Result<Self, EspError> {
            let raw = unsafe { sys::esp_tls_init() };
            if !raw.is_null() {
                Ok(Self {
                    raw,
                    socket: InternalSocket(()),
                    #[cfg(esp_idf_esp_tls_server)]
                    server_session: false,
                })
            } else {
                Err(EspError::from_infallible::<ESP_ERR_NO_MEM>())
            }
        }

        /// Establish a TLS/SSL connection with the specified host and port, using an internally-managed socket.
        ///
        /// # Errors
        ///
        /// * `ESP_ERR_INVALID_SIZE` if `cfg.alpn_protos` exceeds 9 elements or avg 10 bytes/ALPN
        /// * `ESP_FAIL` if connection could not be established
        /// * `ESP_TLS_ERR_SSL_WANT_READ` if the socket is in non-blocking mode and it is not ready for reading
        /// * `ESP_TLS_ERR_SSL_WANT_WRITE` if the socket is in non-blocking mode and it is not ready for writing
        /// * `EWOULDBLOCK` if the socket is in non-blocking mode and it is not ready either for reading or writing (a peculiarity/bug of the `esp-tls` C module)
        pub fn connect(
            &mut self,
            host: &str,
            port: u16,
            cfg: &Config,
        ) -> Result<CompletedHandshake, EspError> {
            let mut bufs = RawConfigBufs::default();
            let rcfg = cfg.try_into_raw(&mut bufs)?;

            let res = self.internal_connect(host, port, cfg.non_block, &rcfg);

            // Make sure buffers are held long enough
            #[allow(clippy::drop_non_drop)]
            drop(bufs);

            res
        }
    }

    impl<S> EspTls<S>
    where
        S: Socket,
    {
        /// Create a new `EspTls` instance adopting the supplied socket.
        /// The socket should be in a connected state.
        ///
        /// # Errors
        ///
        /// * `ESP_ERR_NO_MEM` if not enough memory to create the TLS connection
        #[cfg(all(
            not(esp_idf_version_major = "4"),
            any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
        ))]
        pub fn adopt(socket: S) -> Result<Self, EspError> {
            let raw = unsafe { sys::esp_tls_init() };
            if !raw.is_null() {
                sys::esp!(unsafe { sys::esp_tls_set_conn_sockfd(raw, socket.handle()) })?;

                sys::esp!(unsafe {
                    sys::esp_tls_set_conn_state(raw, sys::esp_tls_conn_state_ESP_TLS_CONNECTING)
                })?;

                Ok(Self {
                    raw,
                    socket,
                    #[cfg(esp_idf_esp_tls_server)]
                    server_session: false,
                })
            } else {
                Err(EspError::from_infallible::<ESP_ERR_NO_MEM>())
            }
        }

        /// Establish a TLS/SSL connection using the adopted socket.
        ///
        /// # Errors
        ///
        /// * `ESP_ERR_INVALID_SIZE` if `cfg.alpn_protos` exceeds 9 elements or avg 10 bytes/ALPN
        /// * `ESP_FAIL` if connection could not be established
        /// * `ESP_TLS_ERR_SSL_WANT_READ` if the socket is in non-blocking mode and it is not ready for reading
        /// * `ESP_TLS_ERR_SSL_WANT_WRITE` if the socket is in non-blocking mode and it is not ready for writing
        /// * `EWOULDBLOCK` if the socket is in non-blocking mode and it is not ready either for reading or writing (a peculiarity/bug of the `esp-tls` C module)
        #[cfg(all(
            not(esp_idf_version_major = "4"),
            any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
        ))]
        pub fn negotiate(
            &mut self,
            host: &str,
            cfg: &Config,
        ) -> Result<CompletedHandshake, EspError> {
            let mut bufs = RawConfigBufs::default();
            let rcfg = cfg.try_into_raw(&mut bufs)?;

            let res = self.internal_connect(host, 0, cfg.non_block, &rcfg);

            // Make sure buffers are held long enough
            #[allow(clippy::drop_non_drop)]
            drop(bufs);

            res
        }

        /// Establish a TLS/SSL connection using the adopted connection, acting as the server.
        ///
        /// # Errors
        ///
        /// * `ESP_FAIL` if connection could not be established
        #[cfg(esp_idf_esp_tls_server)]
        pub fn negotiate_server(&mut self, cfg: &ServerConfig) -> Result<(), EspError> {
            let mut bufs = RawConfigBufs::default();
            let mut rcfg = cfg.try_into_raw(&mut bufs)?;

            unsafe {
                let error =
                    sys::esp_tls_server_session_create(&mut rcfg, self.socket.handle(), self.raw);
                if error != 0 {
                    log::error!("failed to create tls server session (error {error})");
                    return Err(EspError::from_infallible::<ESP_FAIL>());
                }
            }
            self.server_session = true;

            // Make sure buffers are held long enough
            #[allow(clippy::drop_non_drop)]
            drop(bufs);

            Ok(())
        }

        #[allow(clippy::unnecessary_cast)]
        fn internal_connect(
            &mut self,
            host: &str,
            port: u16,
            asynch: bool,
            cfg: &sys::esp_tls_cfg,
        ) -> Result<CompletedHandshake, EspError> {
            let ret = unsafe {
                if asynch {
                    sys::esp_tls_conn_new_async(
                        host.as_bytes().as_ptr() as *const i8,
                        host.len() as i32,
                        port as i32,
                        cfg,
                        self.raw,
                    )
                } else {
                    sys::esp_tls_conn_new_sync(
                        host.as_bytes().as_ptr() as *const i8,
                        host.len() as i32,
                        port as i32,
                        cfg,
                        self.raw,
                    )
                }
            };

            match ret {
                1 => Ok(unsafe { CompletedHandshake::extract(self.raw) }),
                ESP_TLS_ERR_SSL_WANT_READ => Err(EspError::from_infallible::<
                    { ESP_TLS_ERR_SSL_WANT_READ as i32 },
                >()),
                ESP_TLS_ERR_SSL_WANT_WRITE => Err(EspError::from_infallible::<
                    { ESP_TLS_ERR_SSL_WANT_WRITE as i32 },
                >()),
                0 => Err(EspError::from_infallible::<{ EWOULDBLOCK as i32 }>()),
                _ => Err(EspError::from_infallible::<ESP_FAIL>()),
            }
        }

        /// Read in the supplied buffer. Returns the number of bytes read.
        ///
        ///
        /// # Errors
        /// * `ESP_TLS_ERR_SSL_WANT_READ` if the socket is in non-blocking mode and it is not ready for reading
        /// * `ESP_TLS_ERR_SSL_WANT_WRITE` if the socket is in non-blocking mode and it is not ready for writing
        /// * Any other `EspError` for a general error
        pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, EspError> {
            if buf.is_empty() {
                return Ok(0);
            }

            let ret = self.read_raw(buf);
            // ESP docs treat 0 as error, but in Rust it's common to return 0 from `Read::read` to indicate eof
            if ret >= 0 {
                Ok(ret as usize)
            } else {
                Err(EspError::from(ret as i32).unwrap())
            }
        }

        #[cfg(esp_idf_version_major = "4")]
        fn read_raw(&mut self, buf: &mut [u8]) -> isize {
            // cannot call esp_tls_conn_read bc it's inline in v4
            let esp_tls = unsafe { core::ptr::read_unaligned(self.raw) };
            let read_func = esp_tls.read.unwrap();
            unsafe { read_func(self.raw, buf.as_mut_ptr() as *mut i8, buf.len()) }
        }

        #[cfg(not(esp_idf_version_major = "4"))]
        fn read_raw(&mut self, buf: &mut [u8]) -> isize {
            use core::ffi::c_void;

            unsafe { sys::esp_tls_conn_read(self.raw, buf.as_mut_ptr() as *mut c_void, buf.len()) }
        }

        /// Write the supplied buffer. Returns the number of bytes written.
        ///
        /// # Errors
        /// * `ESP_TLS_ERR_SSL_WANT_READ` if the socket is in non-blocking mode and it is not ready for reading
        /// * `ESP_TLS_ERR_SSL_WANT_WRITE` if the socket is in non-blocking mode and it is not ready for writing
        /// * Any other `EspError` for a general error
        pub fn write(&mut self, buf: &[u8]) -> Result<usize, EspError> {
            if buf.is_empty() {
                return Ok(0);
            }

            let ret = self.write_raw(buf);
            if ret >= 0 {
                Ok(ret as usize)
            } else {
                Err(EspError::from(ret as i32).unwrap())
            }
        }

        pub fn write_all(&mut self, buf: &[u8]) -> Result<(), EspError> {
            let mut buf = buf;

            while !buf.is_empty() {
                match self.write(buf) {
                    Ok(0) => panic!("zero-length write."),
                    Ok(n) => buf = &buf[n..],
                    Err(e) => return Err(e),
                }
            }

            Ok(())
        }

        #[cfg(esp_idf_version_major = "4")]
        fn write_raw(&mut self, buf: &[u8]) -> isize {
            // cannot call esp_tls_conn_write bc it's inline
            let esp_tls = unsafe { core::ptr::read_unaligned(self.raw) };
            let write_func = esp_tls.write.unwrap();
            unsafe { write_func(self.raw, buf.as_ptr() as *const i8, buf.len()) }
        }

        #[cfg(not(esp_idf_version_major = "4"))]
        fn write_raw(&mut self, buf: &[u8]) -> isize {
            use core::ffi::c_void;

            unsafe { sys::esp_tls_conn_write(self.raw, buf.as_ptr() as *const c_void, buf.len()) }
        }

        pub fn context_handle(&self) -> *mut sys::esp_tls {
            self.raw
        }
    }

    impl<S> Drop for EspTls<S>
    where
        S: Socket,
    {
        fn drop(&mut self) {
            let _ = self.socket.release();

            unsafe {
                // use esp_tls_conn_destroy for both client and server
                sys::esp_tls_conn_destroy(self.raw);
            }
        }
    }

    impl<S> io::ErrorType for EspTls<S>
    where
        S: Socket,
    {
        type Error = EspIOError;
    }

    impl<S> io::Read for EspTls<S>
    where
        S: Socket,
    {
        fn read(&mut self, buf: &mut [u8]) -> Result<usize, EspIOError> {
            EspTls::read(self, buf).map_err(EspIOError)
        }
    }

    impl<S> io::Write for EspTls<S>
    where
        S: Socket,
    {
        fn write(&mut self, buf: &[u8]) -> Result<usize, EspIOError> {
            EspTls::write(self, buf).map_err(EspIOError)
        }

        fn flush(&mut self) -> Result<(), EspIOError> {
            Ok(())
        }
    }
    #[cfg(all(
        not(esp_idf_version_major = "4"),
        any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
    ))]
    pub struct EspAsyncTls<S>(crate::private::mutex::Mutex<EspTls<S>>)
    where
        S: PollableSocket;

    #[cfg(all(
        not(esp_idf_version_major = "4"),
        any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
    ))]
    impl<S> EspAsyncTls<S>
    where
        S: PollableSocket,
    {
        /// Create a new `AsyncEspTls` instance adopting the supplied socket.
        /// The socket should be in a connected state.
        ///
        /// # Errors
        ///
        /// * `ESP_ERR_NO_MEM` if not enough memory to create the TLS connection
        pub fn adopt(socket: S) -> Result<Self, EspError> {
            Ok(Self(crate::private::mutex::Mutex::new(EspTls::adopt(
                socket,
            )?)))
        }

        /// Establish a TLS/SSL connection using the adopted socket.
        ///
        /// # Errors
        ///
        /// * `ESP_ERR_INVALID_SIZE` if `cfg.alpn_protos` exceeds 9 elements or avg 10 bytes/ALPN
        /// * `ESP_FAIL` if connection could not be established
        pub async fn negotiate(
            &mut self,
            hostname: &str,
            cfg: &Config<'_>,
        ) -> Result<CompletedHandshake, EspError> {
            struct AssertSend<T>(T);
            unsafe impl<T> Send for AssertSend<T> {}

            let mut bufs = RawConfigBufs::default();
            let mut rcfg: AssertSend<sys::esp_tls_cfg> = AssertSend(cfg.try_into_raw(&mut bufs)?);

            // It is a bit unintuitive, but when an async socket is being adopted, `non_block` should be set to false.
            //
            // Background:
            // `non_block = true` is only used at one place in the ESP IDF code and that is to run
            // a check - with `select` - whether the socket is really connected.
            // However, we want to avoid the `select()` call, as
            // (a) It won't work, because we jump directly into the ESP_TLS_CONNECTING state as we adopt a socket.
            //.    As a side effect, the select() call is not properly initialized.
            // (b) The adopted socket might be registered in a select() loop already.
            //
            // Avoiding the connectivity check with `select()` should be fine, as the adopted socket
            // must be already connected anyway (API requirement).
            rcfg.0.non_block = false;

            let res = loop {
                let res = self
                    .0
                    .get_mut()
                    .internal_connect(hostname, 0, true, &rcfg.0);

                match res {
                    Err(e) => self.wait(e).await?,
                    other => break other,
                }
            };

            // Make sure buffers are held long enough
            #[allow(clippy::drop_non_drop)]
            drop(bufs);

            res
        }

        // TODO: Create upstream support for async server negotiation
        // Establish a TLS/SSL connection using the adopted connection, acting as the server.
        //
        // # Errors
        //
        // * `ESP_FAIL` if connection could not be established
        // #[cfg(esp_idf_esp_tls_server)]
        // pub async fn negotiate_server(&mut self, cfg: &ServerConfig<'_>) -> Result<(), EspError> {
        //     // FIXME: this isn't actually async, but esp-idf does not expose anything else.
        //     // we would have to use various hacks to call mbedtls_ssl_handshake by ourself
        //     self.0.borrow_mut().negotiate_server(cfg)
        // }

        /// Read in the supplied buffer. Returns the number of bytes read.
        pub async fn read(&self, buf: &mut [u8]) -> Result<usize, EspError> {
            loop {
                let res = self.0.lock().read(buf);

                match res {
                    Err(e) => self.wait(e).await?,
                    other => break other,
                }
            }
        }

        /// Write the supplied buffer. Returns the number of bytes written.
        pub async fn write(&self, buf: &[u8]) -> Result<usize, EspError> {
            loop {
                let res = self.0.lock().write(buf);

                match res {
                    Err(e) => self.wait(e).await?,
                    other => break other,
                }
            }
        }

        pub async fn write_all(&self, buf: &[u8]) -> Result<(), EspError> {
            let mut buf = buf;

            while !buf.is_empty() {
                match self.write(buf).await {
                    Ok(0) => panic!("zero-length write."),
                    Ok(n) => buf = &buf[n..],
                    Err(e) => return Err(e),
                }
            }

            Ok(())
        }

        async fn wait(&self, error: EspError) -> Result<(), EspError> {
            const EWOULDBLOCK_I32: i32 = EWOULDBLOCK as i32;

            match error.code() {
                // EWOULDBLOCK models the "0" return code of esp_mbedtls_handshake() which does not allow us
                // to figure out whether we need the socket to become readable or writable
                // The code below is therefore a hack which just waits with a timeout for the socket to (eventually)
                // become readable as we actually don't even know if that's what esp_tls wants
                EWOULDBLOCK_I32 => {
                    core::future::poll_fn(|ctx| self.0.lock().socket.poll_writable(ctx)).await?;
                    crate::hal::delay::FreeRtos::delay_ms(0);
                }
                ESP_TLS_ERR_SSL_WANT_READ => {
                    core::future::poll_fn(|ctx| self.0.lock().socket.poll_readable(ctx)).await?
                }

                ESP_TLS_ERR_SSL_WANT_WRITE => {
                    core::future::poll_fn(|ctx| self.0.lock().socket.poll_writable(ctx)).await?
                }
                _ => Err(error)?,
            }

            Ok(())
        }

        pub fn context_handle(&self) -> *mut sys::esp_tls {
            self.0.lock().context_handle()
        }
    }

    #[cfg(all(
        not(esp_idf_version_major = "4"),
        any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
    ))]
    impl<S> io::ErrorType for EspAsyncTls<S>
    where
        S: PollableSocket,
    {
        type Error = EspIOError;
    }

    #[cfg(all(
        not(esp_idf_version_major = "4"),
        any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
    ))]
    impl<S> io::asynch::Read for EspAsyncTls<S>
    where
        S: PollableSocket,
    {
        async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            EspAsyncTls::read(self, buf).await.map_err(EspIOError)
        }
    }

    #[cfg(all(
        not(esp_idf_version_major = "4"),
        any(not(esp_idf_version_major = "5"), not(esp_idf_version_minor = "0"))
    ))]
    impl<S> io::asynch::Write for EspAsyncTls<S>
    where
        S: PollableSocket,
    {
        async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
            EspAsyncTls::write(self, buf).await.map_err(EspIOError)
        }

        async fn flush(&mut self) -> Result<(), Self::Error> {
            Ok(())
        }
    }
}