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
// 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
#![allow(deprecated)]

use crate::{IOStream, SocketConnectable, TlsCertificateFlags, TlsConnection};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::{boxed::Box as Box_, fmt, mem::transmute, ptr};

glib::wrapper! {
    /// [`TlsClientConnection`][crate::TlsClientConnection] is the client-side subclass of
    /// [`TlsConnection`][crate::TlsConnection], representing a client-side TLS connection.
    ///
    /// ## Properties
    ///
    ///
    /// #### `accepted-cas`
    ///  A list of the distinguished names of the Certificate Authorities
    /// that the server will accept client certificates signed by. If the
    /// server requests a client certificate during the handshake, then
    /// this property will be set after the handshake completes.
    ///
    /// Each item in the list is a [`glib::ByteArray`][crate::glib::ByteArray] which contains the complete
    /// subject DN of the certificate authority.
    ///
    /// Readable
    ///
    ///
    /// #### `server-identity`
    ///  A [`SocketConnectable`][crate::SocketConnectable] describing the identity of the server that
    /// is expected on the other end of the connection.
    ///
    /// If the [`TlsCertificateFlags::BAD_IDENTITY`][crate::TlsCertificateFlags::BAD_IDENTITY] flag is set in
    /// [`validation-flags`][struct@crate::TlsClientConnection#validation-flags], this object will be used
    /// to determine the expected identify of the remote end of the
    /// connection; if [`server-identity`][struct@crate::TlsClientConnection#server-identity] is not set,
    /// or does not match the identity presented by the server, then the
    /// [`TlsCertificateFlags::BAD_IDENTITY`][crate::TlsCertificateFlags::BAD_IDENTITY] validation will fail.
    ///
    /// In addition to its use in verifying the server certificate,
    /// this is also used to give a hint to the server about what
    /// certificate we expect, which is useful for servers that serve
    /// virtual hosts.
    ///
    /// Readable | Writeable | Construct
    ///
    ///
    /// #### `use-ssl3`
    ///  SSL 3.0 is no longer supported. See
    /// `g_tls_client_connection_set_use_ssl3()` for details.
    ///
    /// Readable | Writeable | Construct
    ///
    ///
    /// #### `validation-flags`
    ///  What steps to perform when validating a certificate received from
    /// a server. Server certificates that fail to validate in any of the
    /// ways indicated here will be rejected unless the application
    /// overrides the default via [`accept-certificate`][struct@crate::TlsConnection#accept-certificate].
    ///
    /// GLib guarantees that if certificate verification fails, at least one
    /// flag will be set, but it does not guarantee that all possible flags
    /// 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. Therefore, there is no
    /// safe way to use this property. This is not a horrible problem,
    /// though, because you should not be attempting to ignore validation
    /// errors anyway. If you really must ignore TLS certificate errors,
    /// connect to [`accept-certificate`][struct@crate::TlsConnection#accept-certificate].
    ///
    /// Readable | Writeable | Construct
    /// <details><summary><h4>TlsConnection</h4></summary>
    ///
    ///
    /// #### `advertised-protocols`
    ///  The list of application-layer protocols that the connection
    /// advertises that it is willing to speak. See
    /// [`TlsConnectionExtManual::set_advertised_protocols()`][crate::prelude::TlsConnectionExtManual::set_advertised_protocols()].
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `base-io-stream`
    ///  The [`IOStream`][crate::IOStream] that the connection wraps. The connection holds a reference
    /// to this stream, and may run operations on the stream from other threads
    /// throughout its lifetime. Consequently, after the [`IOStream`][crate::IOStream] has been
    /// constructed, application code may only run its own operations on this
    /// stream when no [`IOStream`][crate::IOStream] operations are running.
    ///
    /// Readable | Writeable | Construct Only
    ///
    ///
    /// #### `certificate`
    ///  The connection's certificate; see
    /// [`TlsConnectionExt::set_certificate()`][crate::prelude::TlsConnectionExt::set_certificate()].
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `ciphersuite-name`
    ///  The name of the TLS ciphersuite in use. See [`TlsConnectionExt::ciphersuite_name()`][crate::prelude::TlsConnectionExt::ciphersuite_name()].
    ///
    /// Readable
    ///
    ///
    /// #### `database`
    ///  The certificate database to use when verifying this TLS connection.
    /// If no certificate database is set, then the default database will be
    /// used. See [`TlsBackendExt::default_database()`][crate::prelude::TlsBackendExt::default_database()].
    ///
    /// When using a non-default database, [`TlsConnection`][crate::TlsConnection] must fall back to using
    /// the [`TlsDatabase`][crate::TlsDatabase] to perform certificate verification using
    /// [`TlsDatabaseExt::verify_chain()`][crate::prelude::TlsDatabaseExt::verify_chain()], which means certificate verification will
    /// not be able to make use of TLS session context. This may be less secure.
    /// For example, if you create your own [`TlsDatabase`][crate::TlsDatabase] that just wraps the
    /// default [`TlsDatabase`][crate::TlsDatabase], you might expect that you have not changed anything,
    /// but this is not true because you may have altered the behavior of
    /// [`TlsConnection`][crate::TlsConnection] by causing it to use [`TlsDatabaseExt::verify_chain()`][crate::prelude::TlsDatabaseExt::verify_chain()]. See the
    /// documentation of [`TlsDatabaseExt::verify_chain()`][crate::prelude::TlsDatabaseExt::verify_chain()] for more details on specific
    /// security checks that may not be performed. Accordingly, setting a
    /// non-default database is discouraged except for specialty applications with
    /// unusual security requirements.
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `interaction`
    ///  A [`TlsInteraction`][crate::TlsInteraction] object to be used when the connection or certificate
    /// database need to interact with the user. This will be used to prompt the
    /// user for passwords where necessary.
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `negotiated-protocol`
    ///  The application-layer protocol negotiated during the TLS
    /// handshake. See [`TlsConnectionExt::negotiated_protocol()`][crate::prelude::TlsConnectionExt::negotiated_protocol()].
    ///
    /// Readable
    ///
    ///
    /// #### `peer-certificate`
    ///  The connection's peer's certificate, after the TLS handshake has
    /// completed or failed. Note in particular that this is not yet set
    /// during the emission of [`accept-certificate`][struct@crate::TlsConnection#accept-certificate].
    ///
    /// (You can watch for a [`notify`][struct@crate::glib::Object#notify] signal on this property to
    /// detect when a handshake has occurred.)
    ///
    /// Readable
    ///
    ///
    /// #### `peer-certificate-errors`
    ///  The errors noticed while verifying
    /// [`peer-certificate`][struct@crate::TlsConnection#peer-certificate]. Normally this should be 0, but
    /// it may not be if [`validation-flags`][struct@crate::TlsClientConnection#validation-flags] is not
    /// [`TlsCertificateFlags::VALIDATE_ALL`][crate::TlsCertificateFlags::VALIDATE_ALL], or if
    /// [`accept-certificate`][struct@crate::TlsConnection#accept-certificate] overrode the default
    /// behavior.
    ///
    /// GLib guarantees that if certificate verification fails, at least
    /// one error will be set, 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.
    ///
    /// Readable
    ///
    ///
    /// #### `protocol-version`
    ///  The TLS protocol version in use. See [`TlsConnectionExt::protocol_version()`][crate::prelude::TlsConnectionExt::protocol_version()].
    ///
    /// Readable
    ///
    ///
    /// #### `rehandshake-mode`
    ///  The rehandshaking mode. See
    /// [`TlsConnectionExt::set_rehandshake_mode()`][crate::prelude::TlsConnectionExt::set_rehandshake_mode()].
    ///
    /// Readable | Writeable | Construct
    ///
    ///
    /// #### `require-close-notify`
    ///  Whether or not proper TLS close notification is required.
    /// See [`TlsConnectionExt::set_require_close_notify()`][crate::prelude::TlsConnectionExt::set_require_close_notify()].
    ///
    /// Readable | Writeable | Construct
    ///
    ///
    /// #### `use-system-certdb`
    ///  Whether or not the system certificate database will be used to
    /// verify peer certificates. See
    /// `g_tls_connection_set_use_system_certdb()`.
    ///
    /// Readable | Writeable | Construct
    /// </details>
    /// <details><summary><h4>IOStream</h4></summary>
    ///
    ///
    /// #### `closed`
    ///  Readable
    ///
    ///
    /// #### `input-stream`
    ///  Readable
    ///
    ///
    /// #### `output-stream`
    ///  Readable
    /// </details>
    ///
    /// # Implements
    ///
    /// [`TlsClientConnectionExt`][trait@crate::prelude::TlsClientConnectionExt], [`TlsConnectionExt`][trait@crate::prelude::TlsConnectionExt], [`IOStreamExt`][trait@crate::prelude::IOStreamExt], [`trait@glib::ObjectExt`], [`TlsConnectionExtManual`][trait@crate::prelude::TlsConnectionExtManual], [`IOStreamExtManual`][trait@crate::prelude::IOStreamExtManual]
    #[doc(alias = "GTlsClientConnection")]
    pub struct TlsClientConnection(Interface<ffi::GTlsClientConnection, ffi::GTlsClientConnectionInterface>) @requires TlsConnection, IOStream;

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

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

    /// Creates a new [`TlsClientConnection`][crate::TlsClientConnection] wrapping `base_io_stream` (which
    /// must have pollable input and output streams) which is assumed to
    /// communicate with the server identified by `server_identity`.
    ///
    /// See the documentation for [`base-io-stream`][struct@crate::TlsConnection#base-io-stream] for restrictions
    /// on when application code can run operations on the `base_io_stream` after
    /// this function has returned.
    /// ## `base_io_stream`
    /// the [`IOStream`][crate::IOStream] to wrap
    /// ## `server_identity`
    /// the expected identity of the server
    ///
    /// # Returns
    ///
    /// the new
    /// [`TlsClientConnection`][crate::TlsClientConnection], or [`None`] on error
    #[doc(alias = "g_tls_client_connection_new")]
    pub fn new(
        base_io_stream: &impl IsA<IOStream>,
        server_identity: Option<&impl IsA<SocketConnectable>>,
    ) -> Result<TlsClientConnection, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_tls_client_connection_new(
                base_io_stream.as_ref().to_glib_none().0,
                server_identity.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))
            }
        }
    }
}

/// Trait containing all [`struct@TlsClientConnection`] methods.
///
/// # Implementors
///
/// [`TlsClientConnection`][struct@crate::TlsClientConnection]
pub trait TlsClientConnectionExt: 'static {
    /// Possibly copies session state from one connection to another, for use
    /// in TLS session resumption. This is not normally needed, but may be
    /// used when the same session needs to be used between different
    /// endpoints, as is required by some protocols, such as FTP over TLS.
    /// `source` should have already completed a handshake and, since TLS 1.3,
    /// it should have been used to read data at least once. `self` should not
    /// have completed a handshake.
    ///
    /// It is not possible to know whether a call to this function will
    /// actually do anything. Because session resumption is normally used
    /// only for performance benefit, the TLS backend might not implement
    /// this function. Even if implemented, it may not actually succeed in
    /// allowing `self` to resume `source`'s TLS session, because the server
    /// may not have sent a session resumption token to `source`, or it may
    /// refuse to accept the token from `self`. There is no way to know
    /// whether a call to this function is actually successful.
    ///
    /// Using this function is not required to benefit from session
    /// resumption. If the TLS backend supports session resumption, the
    /// session will be resumed automatically if it is possible to do so
    /// without weakening the privacy guarantees normally provided by TLS,
    /// without need to call this function. For example, with TLS 1.3,
    /// a session ticket will be automatically copied from any
    /// [`TlsClientConnection`][crate::TlsClientConnection] that has previously received session tickets
    /// from the server, provided a ticket is available that has not
    /// previously been used for session resumption, since session ticket
    /// reuse would be a privacy weakness. Using this function causes the
    /// ticket to be copied without regard for privacy considerations.
    /// ## `source`
    /// a [`TlsClientConnection`][crate::TlsClientConnection]
    #[doc(alias = "g_tls_client_connection_copy_session_state")]
    fn copy_session_state(&self, source: &impl IsA<TlsClientConnection>);

    /// Gets the list of distinguished names of the Certificate Authorities
    /// that the server will accept certificates from. This will be set
    /// during the TLS handshake if the server requests a certificate.
    /// Otherwise, it will be [`None`].
    ///
    /// Each item in the list is a [`glib::ByteArray`][crate::glib::ByteArray] which contains the complete
    /// subject DN of the certificate authority.
    ///
    /// # Returns
    ///
    /// the list of
    /// CA DNs. You should unref each element with `g_byte_array_unref()` and then
    /// the free the list with `g_list_free()`.
    #[doc(alias = "g_tls_client_connection_get_accepted_cas")]
    #[doc(alias = "get_accepted_cas")]
    fn accepted_cas(&self) -> Vec<glib::ByteArray>;

    /// Gets `self`'s expected server identity
    ///
    /// # Returns
    ///
    /// a [`SocketConnectable`][crate::SocketConnectable] describing the
    /// expected server identity, or [`None`] if the expected identity is not
    /// known.
    #[doc(alias = "g_tls_client_connection_get_server_identity")]
    #[doc(alias = "get_server_identity")]
    fn server_identity(&self) -> Option<SocketConnectable>;

    /// Gets `self`'s validation flags
    ///
    /// This function does not work as originally designed and is impossible
    /// to use correctly. See [`validation-flags`][struct@crate::TlsClientConnection#validation-flags] for more
    /// information.
    ///
    /// # Deprecated since 2.72
    ///
    /// Do not attempt to ignore validation errors.
    ///
    /// # Returns
    ///
    /// the validation flags
    #[cfg_attr(feature = "v2_72", deprecated = "Since 2.72")]
    #[allow(deprecated)]
    #[doc(alias = "g_tls_client_connection_get_validation_flags")]
    #[doc(alias = "get_validation_flags")]
    fn validation_flags(&self) -> TlsCertificateFlags;

    /// Sets `self`'s expected server identity, which is used both to tell
    /// servers on virtual hosts which certificate to present, and also
    /// to let `self` know what name to look for in the certificate when
    /// performing [`TlsCertificateFlags::BAD_IDENTITY`][crate::TlsCertificateFlags::BAD_IDENTITY] validation, if enabled.
    /// ## `identity`
    /// a [`SocketConnectable`][crate::SocketConnectable] describing the expected server identity
    #[doc(alias = "g_tls_client_connection_set_server_identity")]
    fn set_server_identity(&self, identity: &impl IsA<SocketConnectable>);

    /// Sets `self`'s validation flags, to override the default set of
    /// checks performed when validating a server certificate. By default,
    /// [`TlsCertificateFlags::VALIDATE_ALL`][crate::TlsCertificateFlags::VALIDATE_ALL] is used.
    ///
    /// This function does not work as originally designed and is impossible
    /// to use correctly. See [`validation-flags`][struct@crate::TlsClientConnection#validation-flags] for more
    /// information.
    ///
    /// # Deprecated since 2.72
    ///
    /// Do not attempt to ignore validation errors.
    /// ## `flags`
    /// the [`TlsCertificateFlags`][crate::TlsCertificateFlags] to use
    #[cfg_attr(feature = "v2_72", deprecated = "Since 2.72")]
    #[allow(deprecated)]
    #[doc(alias = "g_tls_client_connection_set_validation_flags")]
    fn set_validation_flags(&self, flags: TlsCertificateFlags);

    #[doc(alias = "accepted-cas")]
    fn connect_accepted_cas_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;

    #[doc(alias = "server-identity")]
    fn connect_server_identity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;

    #[cfg_attr(feature = "v2_72", deprecated = "Since 2.72")]
    #[doc(alias = "validation-flags")]
    fn connect_validation_flags_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}

impl<O: IsA<TlsClientConnection>> TlsClientConnectionExt for O {
    fn copy_session_state(&self, source: &impl IsA<TlsClientConnection>) {
        unsafe {
            ffi::g_tls_client_connection_copy_session_state(
                self.as_ref().to_glib_none().0,
                source.as_ref().to_glib_none().0,
            );
        }
    }

    fn accepted_cas(&self) -> Vec<glib::ByteArray> {
        unsafe {
            FromGlibPtrContainer::from_glib_full(ffi::g_tls_client_connection_get_accepted_cas(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn server_identity(&self) -> Option<SocketConnectable> {
        unsafe {
            from_glib_none(ffi::g_tls_client_connection_get_server_identity(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    #[allow(deprecated)]
    fn validation_flags(&self) -> TlsCertificateFlags {
        unsafe {
            from_glib(ffi::g_tls_client_connection_get_validation_flags(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    fn set_server_identity(&self, identity: &impl IsA<SocketConnectable>) {
        unsafe {
            ffi::g_tls_client_connection_set_server_identity(
                self.as_ref().to_glib_none().0,
                identity.as_ref().to_glib_none().0,
            );
        }
    }

    #[allow(deprecated)]
    fn set_validation_flags(&self, flags: TlsCertificateFlags) {
        unsafe {
            ffi::g_tls_client_connection_set_validation_flags(
                self.as_ref().to_glib_none().0,
                flags.into_glib(),
            );
        }
    }

    fn connect_accepted_cas_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_accepted_cas_trampoline<
            P: IsA<TlsClientConnection>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GTlsClientConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(TlsClientConnection::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::accepted-cas\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_accepted_cas_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    fn connect_server_identity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_server_identity_trampoline<
            P: IsA<TlsClientConnection>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GTlsClientConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(TlsClientConnection::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::server-identity\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_server_identity_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    fn connect_validation_flags_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_validation_flags_trampoline<
            P: IsA<TlsClientConnection>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GTlsClientConnection,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(TlsClientConnection::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::validation-flags\0".as_ptr() as *const _,
                Some(transmute::<_, unsafe extern "C" fn()>(
                    notify_validation_flags_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl fmt::Display for TlsClientConnection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("TlsClientConnection")
    }
}