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
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT

use crate::{
    AsyncResult, Cancellable, SocketConnectable, TlsCertificate, TlsCertificateFlags,
    TlsDatabaseLookupFlags, TlsDatabaseVerifyFlags, TlsInteraction,
};
use glib::{prelude::*, translate::*};
use std::{boxed::Box as Box_, pin::Pin};

glib::wrapper! {
    /// `GTlsDatabase` is used to look up certificates and other information
    /// from a certificate or key store. It is an abstract base class which
    /// TLS library specific subtypes override.
    ///
    /// A `GTlsDatabase` may be accessed from multiple threads by the TLS backend.
    /// All implementations are required to be fully thread-safe.
    ///
    /// Most common client applications will not directly interact with
    /// `GTlsDatabase`. It is used internally by [`TlsConnection`][crate::TlsConnection].
    ///
    /// This is an Abstract Base Class, you cannot instantiate it.
    ///
    /// # Implements
    ///
    /// [`TlsDatabaseExt`][trait@crate::prelude::TlsDatabaseExt], [`trait@glib::ObjectExt`]
    #[doc(alias = "GTlsDatabase")]
    pub struct TlsDatabase(Object<ffi::GTlsDatabase, ffi::GTlsDatabaseClass>);

    match fn {
        type_ => || ffi::g_tls_database_get_type(),
    }
}

impl TlsDatabase {
    pub const NONE: Option<&'static TlsDatabase> = None;
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::TlsDatabase>> Sealed for T {}
}

/// Trait containing all [`struct@TlsDatabase`] methods.
///
/// # Implementors
///
/// [`TlsDatabase`][struct@crate::TlsDatabase], [`TlsFileDatabase`][struct@crate::TlsFileDatabase]
pub trait TlsDatabaseExt: IsA<TlsDatabase> + sealed::Sealed + 'static {
    /// Create a handle string for the certificate. The database will only be able
    /// to create a handle for certificates that originate from the database. In
    /// cases where the database cannot create a handle for a certificate, [`None`]
    /// will be returned.
    ///
    /// This handle should be stable across various instances of the application,
    /// and between applications. If a certificate is modified in the database,
    /// then it is not guaranteed that this handle will continue to point to it.
    /// ## `certificate`
    /// certificate for which to create a handle.
    ///
    /// # Returns
    ///
    /// a newly allocated string containing the
    /// handle.
    #[doc(alias = "g_tls_database_create_certificate_handle")]
    fn create_certificate_handle(
        &self,
        certificate: &impl IsA<TlsCertificate>,
    ) -> Option<glib::GString> {
        unsafe {
            from_glib_full(ffi::g_tls_database_create_certificate_handle(
                self.as_ref().to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Look up a certificate by its handle.
    ///
    /// The handle should have been created by calling
    /// g_tls_database_create_certificate_handle() on a #GTlsDatabase object of
    /// the same TLS backend. The handle is designed to remain valid across
    /// instantiations of the database.
    ///
    /// If the handle is no longer valid, or does not point to a certificate in
    /// this database, then [`None`] will be returned.
    ///
    /// This function can block, use g_tls_database_lookup_certificate_for_handle_async() to perform
    /// the lookup operation asynchronously.
    /// ## `handle`
    /// a certificate handle
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// Flags which affect the lookup.
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    ///
    /// # Returns
    ///
    /// a newly allocated
    /// #GTlsCertificate, or [`None`]. Use g_object_unref() to release the certificate.
    #[doc(alias = "g_tls_database_lookup_certificate_for_handle")]
    fn lookup_certificate_for_handle(
        &self,
        handle: &str,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<Option<TlsCertificate>, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_for_handle(
                self.as_ref().to_glib_none().0,
                handle.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously look up a certificate by its handle in the database. See
    /// g_tls_database_lookup_certificate_for_handle() for more information.
    /// ## `handle`
    /// a certificate handle
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// Flags which affect the lookup.
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    /// ## `callback`
    /// callback to call when the operation completes
    #[doc(alias = "g_tls_database_lookup_certificate_for_handle_async")]
    fn lookup_certificate_for_handle_async<
        P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static,
    >(
        &self,
        handle: &str,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn lookup_certificate_for_handle_async_trampoline<
            P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_for_handle_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = lookup_certificate_for_handle_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_lookup_certificate_for_handle_async(
                self.as_ref().to_glib_none().0,
                handle.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn lookup_certificate_for_handle_future(
        &self,
        handle: &str,
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseLookupFlags,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<TlsCertificate, glib::Error>> + 'static>>
    {
        let handle = String::from(handle);
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.lookup_certificate_for_handle_async(
                    &handle,
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Look up the issuer of @certificate in the database. The
    /// #GTlsCertificate:issuer property of @certificate is not modified, and
    /// the two certificates are not hooked into a chain.
    ///
    /// This function can block. Use g_tls_database_lookup_certificate_issuer_async()
    /// to perform the lookup operation asynchronously.
    ///
    /// Beware this function cannot be used to build certification paths. The
    /// issuer certificate returned by this function may not be the same as
    /// the certificate that would actually be used to construct a valid
    /// certification path during certificate verification.
    /// [RFC 4158](https://datatracker.ietf.org/doc/html/rfc4158) explains
    /// why an issuer certificate cannot be naively assumed to be part of the
    /// the certification path (though GLib's TLS backends may not follow the
    /// path building strategies outlined in this RFC). Due to the complexity
    /// of certification path building, GLib does not provide any way to know
    /// which certification path will actually be used when verifying a TLS
    /// certificate. Accordingly, this function cannot be used to make
    /// security-related decisions. Only GLib itself should make security
    /// decisions about TLS certificates.
    /// ## `certificate`
    /// a #GTlsCertificate
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// flags which affect the lookup operation
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    ///
    /// # Returns
    ///
    /// a newly allocated issuer #GTlsCertificate,
    /// or [`None`]. Use g_object_unref() to release the certificate.
    #[doc(alias = "g_tls_database_lookup_certificate_issuer")]
    fn lookup_certificate_issuer(
        &self,
        certificate: &impl IsA<TlsCertificate>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<TlsCertificate, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_issuer(
                self.as_ref().to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously look up the issuer of @certificate in the database. See
    /// g_tls_database_lookup_certificate_issuer() for more information.
    /// ## `certificate`
    /// a #GTlsCertificate
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// flags which affect the lookup operation
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    /// ## `callback`
    /// callback to call when the operation completes
    #[doc(alias = "g_tls_database_lookup_certificate_issuer_async")]
    fn lookup_certificate_issuer_async<P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static>(
        &self,
        certificate: &impl IsA<TlsCertificate>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn lookup_certificate_issuer_async_trampoline<
            P: FnOnce(Result<TlsCertificate, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificate_issuer_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = lookup_certificate_issuer_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_lookup_certificate_issuer_async(
                self.as_ref().to_glib_none().0,
                certificate.as_ref().to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn lookup_certificate_issuer_future(
        &self,
        certificate: &(impl IsA<TlsCertificate> + Clone + 'static),
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseLookupFlags,
    ) -> Pin<Box_<dyn std::future::Future<Output = Result<TlsCertificate, glib::Error>> + 'static>>
    {
        let certificate = certificate.clone();
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.lookup_certificate_issuer_async(
                    &certificate,
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Look up certificates issued by this issuer in the database.
    ///
    /// This function can block, use g_tls_database_lookup_certificates_issued_by_async() to perform
    /// the lookup operation asynchronously.
    /// ## `issuer_raw_dn`
    /// a #GByteArray which holds the DER encoded issuer DN.
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// Flags which affect the lookup operation.
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    ///
    /// # Returns
    ///
    /// a newly allocated list of #GTlsCertificate
    /// objects. Use g_object_unref() on each certificate, and g_list_free() on the release the list.
    #[doc(alias = "g_tls_database_lookup_certificates_issued_by")]
    fn lookup_certificates_issued_by(
        &self,
        issuer_raw_dn: &glib::ByteArray,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<Vec<TlsCertificate>, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificates_issued_by(
                self.as_ref().to_glib_none().0,
                issuer_raw_dn.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(FromGlibPtrContainer::from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously look up certificates issued by this issuer in the database. See
    /// g_tls_database_lookup_certificates_issued_by() for more information.
    ///
    /// The database may choose to hold a reference to the issuer byte array for the duration
    /// of this asynchronous operation. The byte array should not be modified during
    /// this time.
    /// ## `issuer_raw_dn`
    /// a #GByteArray which holds the DER encoded issuer DN.
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// Flags which affect the lookup operation.
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    /// ## `callback`
    /// callback to call when the operation completes
    #[doc(alias = "g_tls_database_lookup_certificates_issued_by_async")]
    fn lookup_certificates_issued_by_async<
        P: FnOnce(Result<Vec<TlsCertificate>, glib::Error>) + 'static,
    >(
        &self,
        issuer_raw_dn: &glib::ByteArray,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseLookupFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn lookup_certificates_issued_by_async_trampoline<
            P: FnOnce(Result<Vec<TlsCertificate>, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_lookup_certificates_issued_by_finish(
                _source_object as *mut _,
                res,
                &mut error,
            );
            let result = if error.is_null() {
                Ok(FromGlibPtrContainer::from_glib_full(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = lookup_certificates_issued_by_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_lookup_certificates_issued_by_async(
                self.as_ref().to_glib_none().0,
                issuer_raw_dn.to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn lookup_certificates_issued_by_future(
        &self,
        issuer_raw_dn: &glib::ByteArray,
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseLookupFlags,
    ) -> Pin<
        Box_<dyn std::future::Future<Output = Result<Vec<TlsCertificate>, glib::Error>> + 'static>,
    > {
        let issuer_raw_dn = issuer_raw_dn.clone();
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.lookup_certificates_issued_by_async(
                    &issuer_raw_dn,
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }

    /// Determines the validity of a certificate chain, outside the context
    /// of a TLS session.
    ///
    /// @chain is a chain of #GTlsCertificate objects each pointing to the next
    /// certificate in the chain by its #GTlsCertificate:issuer property.
    ///
    /// @purpose describes the purpose (or usage) for which the certificate
    /// is being used. Typically @purpose will be set to [`TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER`][crate::TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER]
    /// which means that the certificate is being used to authenticate a server
    /// (and we are acting as the client).
    ///
    /// The @identity is used to ensure the server certificate is valid for
    /// the expected peer identity. If the identity does not match the
    /// certificate, [`TlsCertificateFlags::BAD_IDENTITY`][crate::TlsCertificateFlags::BAD_IDENTITY] will be set in the
    /// return value. If @identity is [`None`], that bit will never be set in
    /// the return value. The peer identity may also be used to check for
    /// pinned certificates (trust exceptions) in the database. These may
    /// override the normal verification process on a host-by-host basis.
    ///
    /// Currently there are no @flags, and [`TlsDatabaseVerifyFlags::NONE`][crate::TlsDatabaseVerifyFlags::NONE] should be
    /// used.
    ///
    /// If @chain is found to be valid, then the return value will be 0. If
    /// @chain is found to be invalid, then the return value will indicate at
    /// least one problem found. If the function is unable to determine
    /// whether @chain is valid (for example, because @cancellable is
    /// triggered before it completes) then the return value will be
    /// [`TlsCertificateFlags::GENERIC_ERROR`][crate::TlsCertificateFlags::GENERIC_ERROR] and @error will be set accordingly.
    /// @error is not set when @chain is successfully analyzed but found to
    /// be invalid.
    ///
    /// GLib guarantees that if certificate verification fails, at least one
    /// error will be set in the return value, but it does not guarantee
    /// that all possible errors will be set. Accordingly, you may not safely
    /// decide to ignore any particular type of error. For example, it would
    /// be incorrect to mask [`TlsCertificateFlags::EXPIRED`][crate::TlsCertificateFlags::EXPIRED] if you want to allow
    /// expired certificates, because this could potentially be the only
    /// error flag set even if other problems exist with the certificate.
    ///
    /// Prior to GLib 2.48, GLib's default TLS backend modified @chain to
    /// represent the certification path built by #GTlsDatabase during
    /// certificate verification by adjusting the #GTlsCertificate:issuer
    /// property of each certificate in @chain. Since GLib 2.48, this no
    /// longer occurs, so you cannot rely on #GTlsCertificate:issuer to
    /// represent the actual certification path used during certificate
    /// verification.
    ///
    /// Because TLS session context is not used, #GTlsDatabase may not
    /// perform as many checks on the certificates as #GTlsConnection would.
    /// For example, certificate constraints may not be honored, and
    /// revocation checks may not be performed. The best way to verify TLS
    /// certificates used by a TLS connection is to let #GTlsConnection
    /// handle the verification.
    ///
    /// The TLS backend may attempt to look up and add missing certificates
    /// to the chain. This may involve HTTP requests to download missing
    /// certificates.
    ///
    /// This function can block. Use g_tls_database_verify_chain_async() to
    /// perform the verification operation asynchronously.
    /// ## `chain`
    /// a #GTlsCertificate chain
    /// ## `purpose`
    /// the purpose that this certificate chain will be used for.
    /// ## `identity`
    /// the expected peer identity
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// additional verify flags
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    ///
    /// # Returns
    ///
    /// the appropriate #GTlsCertificateFlags which represents the
    /// result of verification.
    #[doc(alias = "g_tls_database_verify_chain")]
    fn verify_chain(
        &self,
        chain: &impl IsA<TlsCertificate>,
        purpose: &str,
        identity: Option<&impl IsA<SocketConnectable>>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseVerifyFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<TlsCertificateFlags, glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let ret = ffi::g_tls_database_verify_chain(
                self.as_ref().to_glib_none().0,
                chain.as_ref().to_glib_none().0,
                purpose.to_glib_none().0,
                identity.map(|p| p.as_ref()).to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(from_glib(ret))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Asynchronously determines the validity of a certificate chain after
    /// looking up and adding any missing certificates to the chain. See
    /// g_tls_database_verify_chain() for more information.
    /// ## `chain`
    /// a #GTlsCertificate chain
    /// ## `purpose`
    /// the purpose that this certificate chain will be used for.
    /// ## `identity`
    /// the expected peer identity
    /// ## `interaction`
    /// used to interact with the user if necessary
    /// ## `flags`
    /// additional verify flags
    /// ## `cancellable`
    /// a #GCancellable, or [`None`]
    /// ## `callback`
    /// callback to call when the operation completes
    #[doc(alias = "g_tls_database_verify_chain_async")]
    fn verify_chain_async<P: FnOnce(Result<TlsCertificateFlags, glib::Error>) + 'static>(
        &self,
        chain: &impl IsA<TlsCertificate>,
        purpose: &str,
        identity: Option<&impl IsA<SocketConnectable>>,
        interaction: Option<&impl IsA<TlsInteraction>>,
        flags: TlsDatabaseVerifyFlags,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
            Box_::new(glib::thread_guard::ThreadGuard::new(callback));
        unsafe extern "C" fn verify_chain_async_trampoline<
            P: FnOnce(Result<TlsCertificateFlags, glib::Error>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut crate::ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut error = std::ptr::null_mut();
            let ret =
                ffi::g_tls_database_verify_chain_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok(from_glib(ret))
            } else {
                Err(from_glib_full(error))
            };
            let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
                Box_::from_raw(user_data as *mut _);
            let callback: P = callback.into_inner();
            callback(result);
        }
        let callback = verify_chain_async_trampoline::<P>;
        unsafe {
            ffi::g_tls_database_verify_chain_async(
                self.as_ref().to_glib_none().0,
                chain.as_ref().to_glib_none().0,
                purpose.to_glib_none().0,
                identity.map(|p| p.as_ref()).to_glib_none().0,
                interaction.map(|p| p.as_ref()).to_glib_none().0,
                flags.into_glib(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                Some(callback),
                Box_::into_raw(user_data) as *mut _,
            );
        }
    }

    fn verify_chain_future(
        &self,
        chain: &(impl IsA<TlsCertificate> + Clone + 'static),
        purpose: &str,
        identity: Option<&(impl IsA<SocketConnectable> + Clone + 'static)>,
        interaction: Option<&(impl IsA<TlsInteraction> + Clone + 'static)>,
        flags: TlsDatabaseVerifyFlags,
    ) -> Pin<
        Box_<dyn std::future::Future<Output = Result<TlsCertificateFlags, glib::Error>> + 'static>,
    > {
        let chain = chain.clone();
        let purpose = String::from(purpose);
        let identity = identity.map(ToOwned::to_owned);
        let interaction = interaction.map(ToOwned::to_owned);
        Box_::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.verify_chain_async(
                    &chain,
                    &purpose,
                    identity.as_ref().map(::std::borrow::Borrow::borrow),
                    interaction.as_ref().map(::std::borrow::Borrow::borrow),
                    flags,
                    Some(cancellable),
                    move |res| {
                        send.resolve(res);
                    },
                );
            },
        ))
    }
}

impl<O: IsA<TlsDatabase>> TlsDatabaseExt for O {}