replace deprecated re-handshake feature with session-resumption-enabled property set

This commit is contained in:
yggverse 2024-12-01 02:57:21 +02:00
parent 911fb13a69
commit 3cc9fcd86b
5 changed files with 68 additions and 259 deletions

View file

@ -4,12 +4,10 @@
pub mod connection; pub mod connection;
pub mod error; pub mod error;
pub mod response; pub mod response;
pub mod session;
pub use connection::Connection; pub use connection::Connection;
pub use error::Error; pub use error::Error;
pub use response::Response; pub use response::Response;
pub use session::Session;
use gio::{ use gio::{
prelude::{IOStreamExt, OutputStreamExt, SocketClientExt, TlsConnectionExt}, prelude::{IOStreamExt, OutputStreamExt, SocketClientExt, TlsConnectionExt},
@ -26,7 +24,6 @@ pub const DEFAULT_TIMEOUT: u32 = 10;
/// Provides high-level API for session-safe interaction with /// Provides high-level API for session-safe interaction with
/// [Gemini](https://geminiprotocol.net) socket server /// [Gemini](https://geminiprotocol.net) socket server
pub struct Client { pub struct Client {
session: Rc<Session>,
pub socket: SocketClient, pub socket: SocketClient,
} }
@ -63,23 +60,13 @@ impl Client {
}); });
// Done // Done
Self { Self { socket }
session: Rc::new(Session::new()),
socket,
}
} }
// Actions // Actions
/// High-level method make new async request to given [Uri](https://docs.gtk.org/glib/struct.Uri.html), /// High-level method make new async request to given [Uri](https://docs.gtk.org/glib/struct.Uri.html),
/// callback with new `Response`on success or `Error` on failure /// callback with new `Response`on success or `Error` on failure
///
/// * implement `certificate` comparison with previously defined for this `uri`, force rehandshake if does not match
/// * method does not close new `Connection` by default, hold it in `Session`,
/// expect from user manual `Response` handle with close act on complete
/// * ignores default session resumption provided by Glib TLS backend,
/// instead, applies new `certificate` to available sessions match
/// `uri` [scope](https://geminiprotocol.net/docs/protocol-specification.gmi#status-60)
pub fn request_async( pub fn request_async(
&self, &self,
uri: Uri, uri: Uri,
@ -92,56 +79,43 @@ impl Client {
// * guest sessions will not work without! // * guest sessions will not work without!
self.socket.set_tls(certificate.is_none()); self.socket.set_tls(certificate.is_none());
// Update previous session if available for this `uri`, does force rehandshake on `certificate` change // Begin new connection
match self.session.update(&uri, certificate.as_ref()) { // * [NetworkAddress](https://docs.gtk.org/gio/class.NetworkAddress.html) required for valid
// Begin new connection // [SNI](https://geminiprotocol.net/docs/protocol-specification.gmi#server-name-indication)
// * [NetworkAddress](https://docs.gtk.org/gio/class.NetworkAddress.html) required for valid match crate::gio::network_address::from_uri(&uri, crate::DEFAULT_PORT) {
// [SNI](https://geminiprotocol.net/docs/protocol-specification.gmi#server-name-indication) Ok(network_address) => self.socket.connect_async(
Ok(()) => match crate::gio::network_address::from_uri(&uri, crate::DEFAULT_PORT) { &network_address.clone(),
Ok(network_address) => self.socket.connect_async( match cancellable {
&network_address.clone(), Some(ref cancellable) => Some(cancellable.clone()),
match cancellable { None => None::<Cancellable>,
Some(ref cancellable) => Some(cancellable.clone()), }
None => None::<Cancellable>, .as_ref(),
} move |result| match result {
.as_ref(), Ok(connection) => {
{ // Wrap required connection dependencies into the struct holder
let session = self.session.clone(); match Connection::new(
move |result| match result { connection,
certificate,
Some(network_address),
cancellable.clone(),
) {
Ok(connection) => { Ok(connection) => {
// Wrap required connection dependencies into the struct holder // Begin new request
match Connection::new_wrap( request_async(
connection, Rc::new(connection),
certificate, uri.to_string(),
Some(network_address), priority,
cancellable.clone(), cancellable,
) { callback, // result
Ok(connection) => { )
// Wrap to shared reference support clone semantics
let connection = Rc::new(connection);
// Renew session
session.set(uri.to_string(), connection.clone());
// Begin new request
request_async(
connection,
uri.to_string(),
priority,
cancellable,
callback, // result
)
}
Err(e) => callback(Err(Error::Connection(e))),
}
} }
Err(e) => callback(Err(Error::Connect(e))), Err(e) => callback(Err(Error::Connection(e))),
} }
}, }
), Err(e) => callback(Err(Error::Connect(e))),
Err(e) => callback(Err(Error::NetworkAddress(e))), },
}, ),
Err(e) => callback(Err(Error::Session(e))), Err(e) => callback(Err(Error::NetworkAddress(e))),
} }
} }
} }

View file

@ -5,20 +5,20 @@ use gio::{
prelude::{CancellableExt, IOStreamExt, TlsConnectionExt}, prelude::{CancellableExt, IOStreamExt, TlsConnectionExt},
Cancellable, IOStream, NetworkAddress, SocketConnection, TlsCertificate, TlsClientConnection, Cancellable, IOStream, NetworkAddress, SocketConnection, TlsCertificate, TlsClientConnection,
}; };
use glib::object::{Cast, IsA}; use glib::object::{Cast, IsA, ObjectExt};
pub struct Connection { pub struct Connection {
pub cancellable: Option<Cancellable>, pub cancellable: Option<Cancellable>,
pub server_identity: Option<NetworkAddress>, pub certificate: Option<TlsCertificate>,
pub socket_connection: SocketConnection, pub socket_connection: SocketConnection,
pub tls_client_connection: Option<TlsClientConnection>, pub tls_client_connection: TlsClientConnection,
} }
impl Connection { impl Connection {
// Constructors // Constructors
/// Create new `Self` /// Create new `Self`
pub fn new_wrap( pub fn new(
socket_connection: SocketConnection, socket_connection: SocketConnection,
certificate: Option<TlsCertificate>, certificate: Option<TlsCertificate>,
server_identity: Option<NetworkAddress>, server_identity: Option<NetworkAddress>,
@ -30,20 +30,32 @@ impl Connection {
Ok(Self { Ok(Self {
cancellable, cancellable,
server_identity: server_identity.clone(), certificate: certificate.clone(),
socket_connection: socket_connection.clone(), socket_connection: socket_connection.clone(),
tls_client_connection: match certificate { tls_client_connection: match TlsClientConnection::new(
Some(certificate) => { &socket_connection.clone(),
match new_tls_client_connection( server_identity.as_ref(),
&socket_connection, ) {
&certificate, Ok(tls_client_connection) => {
server_identity.as_ref(), // Prevent session resumption (on certificate change in runtime)
) { tls_client_connection.set_property("session-resumption-enabled", &false);
Ok(tls_client_connection) => Some(tls_client_connection),
Err(e) => return Err(e), // Is user session
// https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates
if let Some(ref certificate) = certificate {
tls_client_connection.set_certificate(certificate);
} }
// @TODO handle
// https://geminiprotocol.net/docs/protocol-specification.gmi#closing-connections
tls_client_connection.set_require_close_notify(true);
// @TODO validate
// https://geminiprotocol.net/docs/protocol-specification.gmi#tls-server-certificate-validation
tls_client_connection.connect_accept_certificate(move |_, _, _| true);
tls_client_connection
} }
None => None, Err(e) => return Err(Error::TlsClientConnection(e)),
}, },
}) })
} }
@ -71,77 +83,18 @@ impl Connection {
} }
} }
/// Force non-cancellable handshake request for `Self`
/// * useful for certificate change in runtime
/// * support guest and user sessions
pub fn rehandshake(&self) -> Result<(), Error> {
match self.tls_client_connection()?.handshake(Cancellable::NONE) {
Ok(()) => Ok(()),
Err(e) => Err(Error::Rehandshake(e)),
}
}
// Getters // Getters
/// Upcast [IOStream](https://docs.gtk.org/gio/class.IOStream.html) /// Get [IOStream](https://docs.gtk.org/gio/class.IOStream.html)
/// for [SocketConnection](https://docs.gtk.org/gio/class.SocketConnection.html) /// for [SocketConnection](https://docs.gtk.org/gio/class.SocketConnection.html)
/// or [TlsClientConnection](https://docs.gtk.org/gio/iface.TlsClientConnection.html) (if available) /// or [TlsClientConnection](https://docs.gtk.org/gio/iface.TlsClientConnection.html) (if available)
/// * wanted to keep `Connection` active in async I/O context /// * useful also to keep `Connection` active in async I/O context
pub fn stream(&self) -> impl IsA<IOStream> { pub fn stream(&self) -> impl IsA<IOStream> {
match self.tls_client_connection.clone() { // * do not replace with `tls_client_connection.base_io_stream()`
Some(tls_client_connection) => tls_client_connection.upcast::<IOStream>(), // as it will not work for user certificate sessions!
match self.certificate {
Some(_) => self.tls_client_connection.clone().upcast::<IOStream>(),
None => self.socket_connection.clone().upcast::<IOStream>(), None => self.socket_connection.clone().upcast::<IOStream>(),
} }
} }
/// Get [TlsClientConnection](https://docs.gtk.org/gio/iface.TlsClientConnection.html) for `Self`
/// * compatible with both user and guest connection types
pub fn tls_client_connection(&self) -> Result<TlsClientConnection, Error> {
match self.tls_client_connection.clone() {
// User session
Some(tls_client_connection) => Ok(tls_client_connection),
// Guest session
None => {
// Create new wrapper for `IOStream` to interact `TlsClientConnection` API
match TlsClientConnection::new(
self.stream().as_ref(),
self.server_identity.as_ref(),
) {
Ok(tls_client_connection) => Ok(tls_client_connection),
Err(e) => Err(Error::TlsClientConnection(e)),
}
}
}
}
}
// Tools
pub fn new_tls_client_connection(
socket_connection: &SocketConnection,
certificate: &TlsCertificate,
server_identity: Option<&NetworkAddress>,
) -> Result<TlsClientConnection, Error> {
if socket_connection.is_closed() {
return Err(Error::Closed);
}
// https://geminiprotocol.net/docs/protocol-specification.gmi#the-use-of-tls
match TlsClientConnection::new(socket_connection, server_identity) {
Ok(tls_client_connection) => {
// https://geminiprotocol.net/docs/protocol-specification.gmi#client-certificates
tls_client_connection.set_certificate(certificate);
// @TODO handle exceptions
// https://geminiprotocol.net/docs/protocol-specification.gmi#closing-connections
tls_client_connection.set_require_close_notify(true);
// @TODO host validation
// https://geminiprotocol.net/docs/protocol-specification.gmi#tls-server-certificate-validation
tls_client_connection.connect_accept_certificate(move |_, _, _| true);
Ok(tls_client_connection)
}
Err(e) => Err(Error::TlsClientConnection(e)),
}
} }

View file

@ -9,7 +9,6 @@ pub enum Error {
OutputStream(glib::Error), OutputStream(glib::Error),
Request(glib::Error), Request(glib::Error),
Response(crate::client::response::Error), Response(crate::client::response::Error),
Session(crate::client::session::Error),
} }
impl Display for Error { impl Display for Error {
@ -36,9 +35,6 @@ impl Display for Error {
Self::Response(e) => { Self::Response(e) => {
write!(f, "Response error: {e}") write!(f, "Response error: {e}")
} }
Self::Session(e) => {
write!(f, "Session error: {e}")
}
} }
} }
} }

View file

@ -1,98 +0,0 @@
mod error;
pub use error::Error;
use super::Connection;
use gio::{
prelude::{TlsCertificateExt, TlsConnectionExt},
TlsCertificate,
};
use glib::{Uri, UriHideFlags};
use std::{cell::RefCell, collections::HashMap, rc::Rc};
/// Request sessions holder
/// * useful to keep connections open in async context and / or validate TLS certificate updates in runtime
pub struct Session {
index: RefCell<HashMap<String, Rc<Connection>>>,
}
impl Default for Session {
fn default() -> Self {
Self::new()
}
}
impl Session {
pub fn new() -> Self {
Self {
index: RefCell::new(HashMap::new()),
}
}
pub fn set(&self, request: String, connection: Rc<Connection>) -> Option<Rc<Connection>> {
self.index.borrow_mut().insert(request, connection)
}
/// Update existing session match [scope](https://geminiprotocol.net/docs/protocol-specification.gmi#status-60)
/// for given [Uri](https://docs.gtk.org/glib/struct.Uri.html)
/// and [TlsCertificate](https://docs.gtk.org/gio/class.TlsCertificate.html)
///
/// * force rehandshake on user certificate change in runtime (ignore default session resumption by Glib TLS backend)
pub fn update(&self, uri: &Uri, certificate: Option<&TlsCertificate>) -> Result<(), Error> {
// Get cached `Client` connections match `uri` scope
// https://geminiprotocol.net/docs/protocol-specification.gmi#status-60
for (request, connection) in self.index.borrow().iter() {
if request.starts_with(
uri.to_string_partial(UriHideFlags::QUERY | UriHideFlags::FRAGMENT)
.as_str(),
) {
// Begin re-handshake on `certificate` change
match connection.tls_client_connection {
// User certificate session
Some(ref tls_client_connection) => {
match certificate {
Some(new) => {
// Get previous certificate
if let Some(ref old) = tls_client_connection.certificate() {
// User -> User
if !new.is_same(old) {
rehandshake(connection.as_ref());
}
}
}
// User -> Guest
None => rehandshake(connection.as_ref()),
}
}
// Guest
None => {
// Guest -> User
if certificate.is_some() {
rehandshake(connection.as_ref())
}
}
}
}
// Cancel previous session operations
if let Err(e) = connection.cancel() {
return Err(Error::Connection(e));
}
// Close previous session connections
if let Err(e) = connection.close() {
return Err(Error::Connection(e));
}
}
Ok(())
}
}
// Tools
/// Applies re-handshake to `Connection`
/// to prevent default session resumption on user certificate change in runtime
pub fn rehandshake(connection: &Connection) {
if let Err(e) = connection.rehandshake() {
println!("warning: {e}"); // @TODO keep in mind until solution for TLS 1.3
}
}

View file

@ -1,16 +0,0 @@
use std::fmt::{Display, Formatter, Result};
#[derive(Debug)]
pub enum Error {
Connection(crate::client::connection::Error),
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
match self {
Self::Connection(e) => {
write!(f, "Connection error: {e}")
}
}
}
}