Skip to main content

eggfetch_core/
network_stream.rs

1//! Network stream types for connection metadata and upgraded connections.
2//!
3//! This module provides:
4//!
5//! - [`ConnectionMetadata`]: read-only metadata about an established
6//!   connection (addresses, TLS info, transport kind).
7//! - [`UpgradedStream`]: an owned post-HTTP IO handle for 101/CONNECT
8//!   upgrade handoff.
9//! - [`NetworkStream`]: a compatibility object exposed on responses for
10//!   metadata access and, where safe, low-level IO.
11
12use std::net::SocketAddr;
13use std::pin::Pin;
14use std::sync::Arc;
15use std::task::{Context, Poll};
16
17use bytes::Bytes;
18use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
19
20use crate::error::{Error, Result};
21
22/// The kind of transport used for a connection.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum TransportKind {
25    /// Plain TCP.
26    Tcp,
27    /// Unix domain socket (no IP addresses; local/peer remain `None`).
28    Unix,
29    /// TLS-wrapped TCP (rustls).
30    Tls,
31    /// TLS-wrapped Unix domain socket.
32    TlsUnix,
33    /// QUIC (HTTP/3) via Quinn.
34    ///
35    /// Reserved for H3 endpoint information where Quinn exposes it
36    /// (remote address). Per-response H3 metadata is currently
37    /// explicitly unavailable (`Response::network_stream()` is `None`
38    /// for ordinary H3 responses); this variant documents the transport
39    /// kind for future connector-derived metadata without inventing
40    /// values today.
41    Quic,
42}
43
44/// Read-only TLS session metadata captured after handshake.
45///
46/// This is an EggFetch-specific type; it does **not** masquerade as
47/// `ssl.SSLObject` or any Python SSL type.
48#[derive(Debug, Clone)]
49pub struct TlsInfo {
50    /// Negotiated ALPN protocol (e.g. `"http/1.1"`, `"h2"`).
51    pub alpn_protocol: Option<String>,
52    /// TLS version string (e.g. `"TLSv1.3"`).
53    pub tls_version: Option<String>,
54    /// Cipher suite identifier.
55    pub cipher_suite: Option<String>,
56    /// Server name used for SNI.
57    pub server_name: Option<String>,
58}
59
60/// Read-only metadata about an established connection.
61///
62/// All fields are captured at connection time and never mutated.
63/// Shared through `Arc` so multiple responses (H2) can reference the
64/// same connection metadata.
65#[derive(Debug, Clone)]
66pub struct ConnectionMetadata {
67    /// Local (client) socket address, if available.
68    pub local_addr: Option<SocketAddr>,
69    /// Remote (peer/server) socket address, if available.
70    pub peer_addr: Option<SocketAddr>,
71    /// Transport kind.
72    pub transport_kind: TransportKind,
73    /// TLS session info, if the connection is TLS.
74    pub tls_info: Option<TlsInfo>,
75}
76
77impl Default for ConnectionMetadata {
78    fn default() -> Self {
79        Self {
80            local_addr: None,
81            peer_addr: None,
82            transport_kind: TransportKind::Tcp,
83            tls_info: None,
84        }
85    }
86}
87
88/// Build [`TlsInfo`] from a rustls client connection.
89///
90/// Extracts ALPN, TLS version, and cipher suite where rustls exposes them
91/// safely. `server_name` is the SNI hostname when known (direct-connector
92/// TLS host); `None` explicitly marks unavailable rather than inventing a
93/// value. No secret-bearing material is included.
94#[cfg(feature = "tls-rustls")]
95pub(crate) fn tls_info_from_rustls(
96    conn: &rustls::ClientConnection,
97    server_name: Option<String>,
98) -> TlsInfo {
99    TlsInfo {
100        alpn_protocol: conn
101            .alpn_protocol()
102            .map(|p| String::from_utf8_lossy(p).into_owned()),
103        tls_version: conn.protocol_version().map(|v| format!("{v:?}")),
104        cipher_suite: conn.negotiated_cipher_suite().map(|c| format!("{c:?}")),
105        server_name,
106    }
107}
108
109/// An owned post-HTTP IO handle for upgraded connections (101, CONNECT).
110///
111/// After Hyper transfers ownership of the underlying IO through its
112/// upgrade mechanism, this type owns the raw stream and provides
113/// async read/write, TLS upgrade, and metadata access.
114///
115/// # Ownership rules
116///
117/// - Once created, the connection is removed from the HTTP pool and
118///   must never be reused.
119/// - `close()` is idempotent.
120/// - Cancellation during `start_tls()` closes or leaves the stream
121///   in a deterministic state.
122pub struct UpgradedStream {
123    inner: UpgradedStreamInner,
124    metadata: Arc<ConnectionMetadata>,
125    /// Keeps connector-lifecycle resources alive after Hyper hands off a 101
126    /// stream. The concrete resource is intentionally private to transport.
127    connection_guard: Option<Box<dyn Send>>,
128    /// Leading bytes already read from the connection before the
129    /// upgrade completed (e.g. data sent by the server in the same
130    /// write as the 101/CONNECT response headers).
131    leading_data: Bytes,
132}
133
134/// Classification of the concrete IO inside an [`UpgradedStream`].
135///
136/// Used by the Python bindings to refuse `start_tls` on streams where
137/// the underlying socket cannot be recovered (Hyper's opaque adapter).
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum UpgradedStreamVariant {
140    /// Plain TCP.
141    Tcp,
142    /// Already TLS-wrapped.
143    Tls,
144    /// Opaque adapter (Hyper's `Upgraded` wrapper).
145    Adapter,
146}
147
148/// The concrete IO inside an upgraded stream.
149enum UpgradedStreamInner {
150    /// Plain TCP stream.
151    Tcp(tokio::net::TcpStream),
152    /// TLS stream already established before upgrade.
153    #[cfg(feature = "tls-rustls")]
154    Tls(Box<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>),
155    /// Opaque adapter (e.g. Hyper's Upgraded wrapper).
156    Adapter(Pin<Box<dyn TokioIoBox>>),
157}
158
159/// Trait alias for `AsyncRead + AsyncWrite + Send` objects that can
160/// be stored in a trait object.
161pub(crate) trait TokioIoBox:
162    tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin
163{
164}
165impl<T: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + Unpin> TokioIoBox for T {}
166
167impl AsyncRead for UpgradedStreamInner {
168    fn poll_read(
169        mut self: Pin<&mut Self>,
170        cx: &mut Context<'_>,
171        buf: &mut ReadBuf<'_>,
172    ) -> Poll<std::io::Result<()>> {
173        match &mut *self {
174            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_read(cx, buf),
175            #[cfg(feature = "tls-rustls")]
176            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_read(cx, buf),
177            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_read(cx, buf),
178        }
179    }
180}
181
182impl AsyncWrite for UpgradedStreamInner {
183    fn poll_write(
184        mut self: Pin<&mut Self>,
185        cx: &mut Context<'_>,
186        buf: &[u8],
187    ) -> Poll<std::io::Result<usize>> {
188        match &mut *self {
189            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_write(cx, buf),
190            #[cfg(feature = "tls-rustls")]
191            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_write(cx, buf),
192            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_write(cx, buf),
193        }
194    }
195
196    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
197        match &mut *self {
198            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_flush(cx),
199            #[cfg(feature = "tls-rustls")]
200            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_flush(cx),
201            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_flush(cx),
202        }
203    }
204
205    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
206        match &mut *self {
207            UpgradedStreamInner::Tcp(s) => Pin::new(s).poll_shutdown(cx),
208            #[cfg(feature = "tls-rustls")]
209            UpgradedStreamInner::Tls(s) => Pin::new(s).poll_shutdown(cx),
210            UpgradedStreamInner::Adapter(a) => a.as_mut().poll_shutdown(cx),
211        }
212    }
213}
214
215impl UpgradedStream {
216    /// Wrap a tokio TCP stream into an upgraded stream.
217    ///
218    /// Leading data is bytes already read from the connection before
219    /// the upgrade handshake completed (preserved by Hyper in its
220    /// `Upgraded::read_buf`).
221    pub fn from_tcp(stream: tokio::net::TcpStream, leading_data: Bytes) -> Self {
222        let metadata = Arc::new(ConnectionMetadata {
223            local_addr: stream.local_addr().ok(),
224            peer_addr: stream.peer_addr().ok(),
225            transport_kind: TransportKind::Tcp,
226            tls_info: None,
227        });
228        Self {
229            inner: UpgradedStreamInner::Tcp(stream),
230            metadata,
231            leading_data,
232            connection_guard: None,
233        }
234    }
235
236    /// Wrap an adapter implementing `AsyncRead + AsyncWrite` into an
237    /// upgraded stream.
238    ///
239    /// Used when the underlying IO type is opaque (e.g. Hyper's
240    /// `Upgraded` wrapper) and cannot be downcast to a concrete type.
241    /// The metadata must be provided by the caller.
242    pub(crate) fn from_adapter(
243        adapter: impl TokioIoBox + 'static,
244        leading_data: Bytes,
245        metadata: Arc<ConnectionMetadata>,
246    ) -> Self {
247        let pinned: Pin<Box<dyn TokioIoBox>> = Box::pin(adapter);
248        Self {
249            inner: UpgradedStreamInner::Adapter(pinned),
250            metadata,
251            leading_data,
252            connection_guard: None,
253        }
254    }
255
256    /// Retain a connector-owned resource until this upgraded stream closes.
257    pub(crate) fn hold_connection_guard(&mut self, guard: Box<dyn Send>) {
258        self.connection_guard = Some(guard);
259    }
260
261    /// Wrap a TLS stream into an upgraded stream.
262    #[cfg(feature = "tls-rustls")]
263    pub fn from_tls(
264        stream: tokio_rustls::client::TlsStream<tokio::net::TcpStream>,
265        leading_data: Bytes,
266        tls_info: TlsInfo,
267    ) -> Self {
268        // Extract peer/local addr from the underlying TcpStream through
269        // the TLS stream's `get_ref()` which returns (&TcpStream, &ClientConnection).
270        let (inner_tcp, _) = stream.get_ref();
271        let local_addr = inner_tcp.local_addr().ok();
272        let peer_addr = inner_tcp.peer_addr().ok();
273        let metadata = Arc::new(ConnectionMetadata {
274            local_addr,
275            peer_addr,
276            transport_kind: TransportKind::Tls,
277            tls_info: Some(tls_info),
278        });
279        Self {
280            inner: UpgradedStreamInner::Tls(Box::new(stream)),
281            metadata,
282            leading_data,
283            connection_guard: None,
284        }
285    }
286
287    /// Returns a reference to the connection metadata.
288    #[must_use]
289    pub fn metadata(&self) -> &Arc<ConnectionMetadata> {
290        &self.metadata
291    }
292
293    /// Returns the concrete variant of the inner stream.
294    ///
295    /// The Python bindings use this to refuse `start_tls` on streams
296    /// backed by Hyper's opaque adapter (where the underlying TCP socket
297    /// is not recoverable).
298    #[must_use]
299    pub fn variant(&self) -> UpgradedStreamVariant {
300        match &self.inner {
301            UpgradedStreamInner::Tcp(_) => UpgradedStreamVariant::Tcp,
302            #[cfg(feature = "tls-rustls")]
303            UpgradedStreamInner::Tls(_) => UpgradedStreamVariant::Tls,
304            UpgradedStreamInner::Adapter(_) => UpgradedStreamVariant::Adapter,
305        }
306    }
307
308    /// Returns the leading data that was buffered before the upgrade.
309    ///
310    /// These are bytes already read from the connection after the
311    /// HTTP response headers but before the caller consumed the
312    /// upgrade. They must be returned before any new socket reads.
313    #[must_use]
314    pub fn leading_data(&self) -> &Bytes {
315        &self.leading_data
316    }
317
318    /// Consume leading data, returning it.
319    pub fn take_leading_data(&mut self) -> Bytes {
320        std::mem::take(&mut self.leading_data)
321    }
322
323    /// Read up to `max_bytes` from the stream.
324    ///
325    /// Returns the bytes read. Returns empty bytes on EOF.
326    ///
327    /// # Errors
328    ///
329    /// Returns `Error::Io` if the underlying read fails.
330    pub async fn read(&mut self, max_bytes: usize) -> Result<Bytes> {
331        // First drain leading data.
332        if !self.leading_data.is_empty() {
333            let available = self.leading_data.len().min(max_bytes);
334            return Ok(self.leading_data.split_to(available));
335        }
336        let mut buf = vec![0u8; max_bytes];
337        let n = tokio::io::AsyncReadExt::read(self, &mut buf)
338            .await
339            .map_err(|e| Error::Io(std::sync::Arc::new(e)))?;
340        if n == 0 {
341            Ok(Bytes::new())
342        } else {
343            Ok(Bytes::copy_from_slice(&buf[..n]))
344        }
345    }
346
347    /// Write all supplied bytes to the stream.
348    ///
349    /// # Errors
350    ///
351    /// Returns `Error::Io` if the underlying write fails.
352    pub async fn write_all(&mut self, buf: &[u8]) -> Result<()> {
353        tokio::io::AsyncWriteExt::write_all(self, buf)
354            .await
355            .map_err(|e| Error::Io(std::sync::Arc::new(e)))
356    }
357
358    /// Flush the stream.
359    ///
360    /// # Errors
361    ///
362    /// Returns `Error::Io` if the underlying flush fails.
363    pub async fn flush(&mut self) -> Result<()> {
364        tokio::io::AsyncWriteExt::flush(self)
365            .await
366            .map_err(|e| Error::Io(std::sync::Arc::new(e)))
367    }
368
369    /// Shut down the stream (idempotent).
370    ///
371    /// # Errors
372    ///
373    /// This method currently always succeeds; errors are silently
374    /// discarded to maintain idempotent close semantics.
375    pub async fn close(&mut self) -> Result<()> {
376        let _ = tokio::io::AsyncWriteExt::shutdown(self).await;
377        Ok(())
378    }
379
380    /// Upgrade this TCP stream to TLS.
381    ///
382    /// Wraps the inner TCP stream with a new TLS layer using the
383    /// provided connector and server name. On success, returns a new
384    /// `UpgradedStream` with TLS metadata. The stream is consumed whether
385    /// the handshake succeeds or fails; callers that need a fallback must
386    /// retain their own connection before calling this method.
387    ///
388    /// Only works for streams backed by a concrete `TcpStream`.
389    /// Adapter-based streams (from Hyper's Upgraded) return an error
390    /// because the concrete type cannot be recovered.
391    ///
392    /// # Errors
393    ///
394    /// Returns `Error::Tls` if the handshake fails or the stream type
395    /// does not support TLS upgrade.
396    #[cfg(feature = "tls-rustls")]
397    pub async fn start_tls(
398        mut self,
399        tls_connector: &tokio_rustls::TlsConnector,
400        server_name: &str,
401    ) -> Result<Self> {
402        let tcp = match std::mem::replace(
403            &mut self.inner,
404            // Placeholder that we'll immediately replace.
405            // A zero-capacity in-memory stream avoids allocating a real
406            // socket solely to move the enum value out.
407            UpgradedStreamInner::Adapter(Box::pin(tokio::io::duplex(0).0)),
408        ) {
409            UpgradedStreamInner::Tcp(s) => s,
410            UpgradedStreamInner::Tls(_) => {
411                return Err(Error::Tls("stream is already TLS-wrapped".into()));
412            }
413            UpgradedStreamInner::Adapter(_) => {
414                return Err(Error::Tls(
415                    "cannot start TLS on an opaque adapter stream; \
416                     use a concrete TcpStream-backed UpgradedStream"
417                        .into(),
418                ));
419            }
420        };
421
422        let sn = crate::transport::direct_connector::tls_server_name(server_name)
423            .map_err(|e| Error::Tls(format!("invalid server name '{server_name}': {e}")))?;
424
425        let tls_stream = tls_connector
426            .connect(sn, tcp)
427            .await
428            .map_err(|e| Error::Tls(format!("TLS handshake failed: {e}")))?;
429
430        // Extract TLS info from the negotiated parameters.
431        let (inner_tcp, connection_info) = tls_stream.get_ref();
432        let tls_info = tls_info_from_rustls(connection_info, Some(server_name.to_owned()));
433
434        let local_addr = inner_tcp.local_addr().ok();
435        let peer_addr = inner_tcp.peer_addr().ok();
436
437        let metadata = Arc::new(ConnectionMetadata {
438            local_addr,
439            peer_addr,
440            transport_kind: TransportKind::Tls,
441            tls_info: Some(tls_info),
442        });
443
444        Ok(UpgradedStream {
445            inner: UpgradedStreamInner::Tls(Box::new(tls_stream)),
446            metadata,
447            // Carry any leading data buffered before the TLS handshake so
448            // pipelined bytes from the 101 upgrade are not dropped.
449            leading_data: std::mem::take(&mut self.leading_data),
450            connection_guard: self.connection_guard.take(),
451        })
452    }
453}
454
455impl AsyncRead for UpgradedStream {
456    fn poll_read(
457        mut self: Pin<&mut Self>,
458        cx: &mut Context<'_>,
459        buf: &mut ReadBuf<'_>,
460    ) -> Poll<std::io::Result<()>> {
461        // Drain leading data first.
462        if !self.leading_data.is_empty() {
463            let available = self.leading_data.len().min(buf.remaining());
464            let chunk = self.leading_data.split_to(available);
465            buf.put_slice(&chunk);
466            return Poll::Ready(Ok(()));
467        }
468        Pin::new(&mut self.inner).poll_read(cx, buf)
469    }
470}
471
472impl AsyncWrite for UpgradedStream {
473    fn poll_write(
474        mut self: Pin<&mut Self>,
475        cx: &mut Context<'_>,
476        buf: &[u8],
477    ) -> Poll<std::io::Result<usize>> {
478        Pin::new(&mut self.inner).poll_write(cx, buf)
479    }
480
481    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
482        Pin::new(&mut self.inner).poll_flush(cx)
483    }
484
485    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
486        Pin::new(&mut self.inner).poll_shutdown(cx)
487    }
488}
489
490/// A network stream handle exposed on responses for metadata access.
491///
492/// For upgraded connections (101/CONNECT), this provides full
493/// read/write/close/TLS access. For ordinary pooled connections,
494/// this provides read-only metadata — raw IO operations are not
495/// exposed while Hyper still owns the connection.
496///
497/// # Ordinal response limitation
498///
499/// Hyper's legacy client pool retains ownership of socket connections
500/// for ordinary HTTP/1.1 and HTTP/2 responses. The pool does not expose
501/// per-response socket metadata, and raw IO operations would corrupt
502/// pool state. Therefore, `NetworkStream::Metadata` is currently only
503/// constructed for responses where socket metadata can be safely
504/// captured without interfering with the pool. For ordinary responses,
505/// `network_stream` on `Response` is `None`.
506///
507/// This is a documented bounded difference from httpcore, which owns
508/// its connections directly and can expose metadata on every response.
509pub enum NetworkStream {
510    /// An upgraded stream with full IO access.
511    Upgraded(UpgradedStream),
512    /// Read-only metadata for an ordinary pooled connection.
513    ///
514    /// Currently reserved for future use when socket metadata can be
515    /// safely captured from Hyper's connection pool. For ordinary
516    /// responses, `Response::network_stream()` returns `None`.
517    Metadata(Arc<ConnectionMetadata>),
518}
519
520impl NetworkStream {
521    /// Returns the connection metadata.
522    #[must_use]
523    pub fn metadata(&self) -> &Arc<ConnectionMetadata> {
524        match self {
525            NetworkStream::Upgraded(s) => s.metadata(),
526            NetworkStream::Metadata(m) => m,
527        }
528    }
529
530    /// Returns `true` if this is an upgraded stream with IO access.
531    #[must_use]
532    pub fn is_upgraded(&self) -> bool {
533        matches!(self, NetworkStream::Upgraded(_))
534    }
535
536    /// If this is an upgraded stream, returns a reference to it.
537    #[must_use]
538    pub fn as_upgraded(&self) -> Option<&UpgradedStream> {
539        match self {
540            NetworkStream::Upgraded(s) => Some(s),
541            NetworkStream::Metadata(_) => None,
542        }
543    }
544
545    /// If this is an upgraded stream, returns a mutable reference.
546    pub fn as_upgraded_mut(&mut self) -> Option<&mut UpgradedStream> {
547        match self {
548            NetworkStream::Upgraded(s) => Some(s),
549            NetworkStream::Metadata(_) => None,
550        }
551    }
552
553    /// If this is an upgraded stream, consume and return it.
554    pub fn into_upgraded(self) -> Option<UpgradedStream> {
555        match self {
556            NetworkStream::Upgraded(s) => Some(s),
557            NetworkStream::Metadata(_) => None,
558        }
559    }
560}
561
562/// Read-only metadata accessible through `get_extra_info()`.
563#[derive(Debug, Clone)]
564pub struct ExtraInfo {
565    /// Local address (`client_addr`).
566    pub client_addr: Option<SocketAddr>,
567    /// Remote address (`server_addr`).
568    pub server_addr: Option<SocketAddr>,
569    /// TLS info, if available.
570    pub tls_info: Option<TlsInfo>,
571}
572
573impl ExtraInfo {
574    /// Create from connection metadata.
575    #[must_use]
576    pub fn from_metadata(meta: &ConnectionMetadata) -> Self {
577        Self {
578            client_addr: meta.local_addr,
579            server_addr: meta.peer_addr,
580            tls_info: meta.tls_info.clone(),
581        }
582    }
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588
589    #[test]
590    fn connection_metadata_default() {
591        let meta = ConnectionMetadata::default();
592        assert!(meta.local_addr.is_none());
593        assert!(meta.peer_addr.is_none());
594        assert_eq!(meta.transport_kind, TransportKind::Tcp);
595        assert!(meta.tls_info.is_none());
596    }
597
598    #[test]
599    fn network_stream_metadata_only() {
600        let meta = Arc::new(ConnectionMetadata {
601            local_addr: Some("127.0.0.1:12345".parse().unwrap()),
602            peer_addr: Some("93.184.216.34:443".parse().unwrap()),
603            transport_kind: TransportKind::Tls,
604            tls_info: Some(TlsInfo {
605                alpn_protocol: Some("h2".into()),
606                tls_version: Some("TLSv1.3".into()),
607                cipher_suite: Some("TLS_AES_256_GCM_SHA384".into()),
608                server_name: Some("example.com".into()),
609            }),
610        });
611        let ns = NetworkStream::Metadata(meta.clone());
612        assert!(!ns.is_upgraded());
613        assert!(ns.as_upgraded().is_none());
614        let info = ns.metadata();
615        assert_eq!(info.local_addr.unwrap().port(), 12345);
616        assert_eq!(info.peer_addr.unwrap().port(), 443);
617    }
618
619    #[test]
620    fn extra_info_from_metadata() {
621        let meta = ConnectionMetadata {
622            local_addr: Some("127.0.0.1:1000".parse().unwrap()),
623            peer_addr: Some("10.0.0.1:443".parse().unwrap()),
624            transport_kind: TransportKind::Tcp,
625            tls_info: None,
626        };
627        let info = ExtraInfo::from_metadata(&meta);
628        assert_eq!(info.client_addr.unwrap().port(), 1000);
629        assert_eq!(info.server_addr.unwrap().port(), 443);
630        assert!(info.tls_info.is_none());
631    }
632}