Skip to content

Visual Studio Code, rebuilt in Rust

Rust
25.0 KB
Raw Blame
//! platform/webview on Linux: a WebKitGTK view in a GTK window reparented into GPUI's X11 window, loading upstream's
//! host page (src/vs/workbench/contrib/webview/browser/pre/index.html) as macos.rs does. WebKitGTK refuses a scheme
//! handler on `https`, so a TLS proxy on loopback, set as the view's https proxy, stands in for the service worker:
//! it answers `https://*.vscode-webview.vscode-cdn.net` and `https://*.vscode-resource.vscode-cdn.net` with a
//! certificate the view's context trusts for those hosts only, and tunnels every other host. A script message handler
//! stands in for the window `message` event, as on macOS. GTK runs on GPUI's main thread, iterated by `pump_gtk`.

use std::cell::{OnceCell, RefCell};
use std::collections::HashSet;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::os::unix::fs::MetadataExt;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::OnceLock;
use std::time::Duration;

use async_openssl::SslStream;
use futures::channel::oneshot;
use futures::io::{AsyncBufRead, AsyncBufReadExt, AsyncWriteExt, BufReader};
use gpui::{App, Bounds, Pixels, Window};
use gtk::glib::translate::{FromGlibPtrFull, ToGlibPtr};
use gtk::prelude::*;
use gtk::{gdk, gio, glib};
use openssl::pkey::PKey;
use openssl::ssl::{Ssl, SslContext, SslMethod};
use openssl::x509::X509;
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
pub use std::rc::Rc as Retained;
use webkit2gtk::{
    NetworkProxyMode, NetworkProxySettings, SecurityManagerExt, SettingsExt, UserContentInjectedFrames, UserContentManager, UserContentManagerExt, UserScript, UserScriptInjectionTime, WebContext, WebContextExt, WebInspectorExt,
    WebViewExt, WebsiteDataManagerExt,
};
use x11::xlib;

use super::{BRIDGE_SCRIPT, HOST_SITE, HTTP_LOOPBACK_ONLY_RULES, MESSAGE_HANDLER, RESOURCE_AUTHORITY, Resources, Response, Webview, is_subdomain};

/// The native view of a webview, which `place` shows.
pub type View = webkit2gtk::WebView;

thread_local! {
    static SUPPORTED: OnceCell<bool> = const { OnceCell::new() };
}

/// GTK lives on the thread that initialized it: GPUI's main thread on X11, which unit tests do not run on. GPUI on
/// Wayland has no X window to hold the view.
pub fn supported() -> bool {
    SUPPORTED.with(|supported| *supported.get_or_init(|| std::thread::current().name() == Some("main") && gpui::guess_compositor() == "X11" && gtk::init().is_ok()))
}

/// Runs GTK's pending events from GPUI's loop, which has no glib main context to share.
pub fn pump_gtk(cx: &mut App) {
    // shortcut: polls every 8 ms; hand glib's poll fds to GPUI's loop if the wakeups show up in power use.
    cx.spawn(async move |cx| {
        loop {
            if SUPPORTED.with(|supported| supported.get() == Some(&true)) {
                let context = glib::MainContext::default();
                while context.iteration(false) {}
            }
            cx.background_executor().timer(Duration::from_millis(8)).await;
        }
    })
    .detach();
}

pub(super) struct Native {
    view: View,
    /// The GTK window the view sits in until a `ClipView` takes it.
    window: gtk::Window,
    content: UserContentManager,
    proxy: gio::SocketService,
    /// GPUI's X window, which gets the keyboard back.
    parent: xlib::Window,
}

impl Native {
    pub(super) fn new(window: &Window, resources: Rc<Resources>, url: String) -> Self {
        let context = WebContext::new_ephemeral();
        let (certificate, tls) = proxy_certificate();
        let proxy = gio::SocketService::new();
        let address = gio::InetSocketAddress::new(&gio::InetAddress::new_loopback(gio::SocketFamily::Ipv4), 0);
        let address = proxy.add_address(&address, gio::SocketType::Stream, gio::SocketProtocol::Tcp, None::<&glib::Object>).expect("a loopback port");
        let port = address.downcast::<gio::InetSocketAddress>().expect("an inet address").port();
        let state = Rc::new(ProxyState { resources: resources.clone(), context: context.clone(), certificate, tls, trusted_hosts: RefCell::default(), port });
        proxy.connect_incoming(move |_, connection, _| {
            glib::MainContext::default().spawn_local(serve(connection.clone(), state.clone()));
            false
        });
        proxy.start();
        let mut settings = NetworkProxySettings::new(None, &[]);
        settings.add_proxy_for_scheme("https", &format!("http://127.0.0.1:{port}"));
        context.website_data_manager().expect("a context has a data manager").set_network_proxy_settings(NetworkProxyMode::Custom, Some(&mut settings));
        // HTTP_LOOPBACK_ONLY_RULES keep http to loopback.
        context.security_manager().expect("a context has a security manager").register_uri_scheme_as_secure("http");

        let content = UserContentManager::new();
        content.register_script_message_handler(MESSAGE_HANDLER);
        content.connect_script_message_received(Some(MESSAGE_HANDLER), move |_, result| {
            let Some(text) = result.js_value().map(|value| value.to_string()) else { return };
            resources.receive(&text);
        });
        content.add_script(&UserScript::new(BRIDGE_SCRIPT, UserContentInjectedFrames::TopFrame, UserScriptInjectionTime::Start, &[], &[]));

        let view = webkit2gtk::WebView::builder().web_context(&context).user_content_manager(&content).build();
        // The page background shows until the host page paints, as the transparent iframe does upstream.
        view.set_background_color(&gdk::RGBA::new(0., 0., 0., 0.));
        view.connect_button_press_event(|view, _| {
            focus_x_window(view);
            glib::Propagation::Proceed
        });
        let parent = gpui_x_window(window);
        let gtk_window = embedded_window(parent);
        gtk_window.add(&view);
        load_with_http_rules(&view, &content, url);
        Native { view, window: gtk_window, content, proxy, parent }
    }

    pub(super) fn view(&self) -> View {
        self.view.clone()
    }

    pub(super) fn hide(&self) {
        if !self.view.is_visible() {
            return;
        }
        self.release_keyboard();
        self.view.hide();
        self.window.hide();
    }

    /// WebKitGTK's editing commands in the page, as Ctrl+C runs them, for the reason macos.rs gives.
    pub(super) fn clipboard_command(&self, command: &str) {
        self.view.execute_editing_command(match command {
            "cut" => "Cut",
            "copy" => "Copy",
            _ => "Paste",
        });
    }

    /// Gives the view's X window the keyboard, as a click into it does.
    pub(super) fn take_keyboard(&self) {
        if !self.has_keyboard() {
            focus_x_window(&self.view);
        }
    }

    /// Gives the keyboard back to GPUI's X window.
    pub(super) fn release_keyboard(&self) {
        if self.has_keyboard() {
            set_input_focus(self.parent);
        }
    }

    /// Whether the X window holding the view has the keyboard.
    pub(super) fn has_keyboard(&self) -> bool {
        let Some(holder) = x_window_of(&self.view) else { return false };
        let (mut focused, mut revert) = (0, 0);
        // SAFETY: GTK's open X display; the out pointers are locals.
        unsafe { xlib::XGetInputFocus(x_display(), &mut focused, &mut revert) };
        focused == holder
    }

    /// The Web Inspector of the view.
    pub(super) fn open_inspector(&self) {
        if let Some(settings) = WebViewExt::settings(&self.view) {
            settings.set_enable_developer_extras(true);
        }
        if let Some(inspector) = self.view.inspector() {
            inspector.show();
        }
    }

    pub(super) fn evaluate(&self, script: &str) {
        self.view.evaluate_javascript(script, None, None, None::<&gio::Cancellable>, |_| {});
    }
}

/// Loads `url` in `view` once HTTP_LOOPBACK_ONLY_RULES are a filter of `content`; webkit2gtk-rs binds no filter store.
fn load_with_http_rules(view: &webkit2gtk::WebView, content: &UserContentManager, url: String) {
    unsafe extern "C" fn saved(store: *mut glib::gobject_ffi::GObject, result: *mut gio::ffi::GAsyncResult, data: glib::ffi::gpointer) {
        // SAFETY: `data` is the box made below, `store` the filter store it saved to.
        let (view, content, url) = *unsafe { Box::from_raw(data as *mut (webkit2gtk::WebView, UserContentManager, String)) };
        let mut error = std::ptr::null_mut();
        // SAFETY: `store` and `result` are what GIO passed this callback; `error` is a local the call fills.
        let filter = unsafe { webkit2gtk::ffi::webkit_user_content_filter_store_save_finish(store.cast(), result, &mut error) };
        // SAFETY: a null filter means the call set `error`, owned by us.
        assert!(!filter.is_null(), "HTTP_LOOPBACK_ONLY_RULES: {}", unsafe { glib::Error::from_glib_full(error) });
        // SAFETY: `filter` is non-null (asserted above); the manager takes its own reference, so ours is dropped here.
        unsafe {
            webkit2gtk::ffi::webkit_user_content_manager_add_filter(content.to_glib_none().0, filter);
            webkit2gtk::ffi::webkit_user_content_filter_unref(filter);
        }
        view.load_uri(&url);
    }
    let path = glib::user_cache_dir().join("vsrustium").join("webview-content-filters");
    let rules = glib::Bytes::from_static(HTTP_LOOPBACK_ONLY_RULES.as_bytes());
    let data = Box::into_raw(Box::new((view.clone(), content.clone(), url)));
    // SAFETY: webkit_user_content_filter_store_save (WebKitGTK 2.24+) holds the store until `saved` runs.
    unsafe {
        let store = webkit2gtk::ffi::webkit_user_content_filter_store_new(path.to_glib_none().0);
        webkit2gtk::ffi::webkit_user_content_filter_store_save(store, c"http-loopback-only".as_ptr(), rules.to_glib_none().0, std::ptr::null_mut(), Some(saved), data.cast());
        glib::gobject_ffi::g_object_unref(store.cast());
    }
}

impl Drop for Native {
    fn drop(&mut self) {
        self.content.unregister_script_message_handler(MESSAGE_HANDLER);
        self.release_keyboard();
        self.proxy.stop();
        self.proxy.close();
        // SAFETY: the view and its own window are this webview's; a clip view holding the view drops its reference.
        unsafe {
            self.view.destroy();
            self.window.destroy();
        }
    }
}

/// Shows `view` over `bounds`, in GPUI window coordinates.
pub fn place(view: &View, window: &Window, bounds: Bounds<Pixels>) {
    let Some(holder) = view.toplevel().and_then(|toplevel| toplevel.downcast::<gtk::Window>().ok()) else { return };
    move_window(&holder, window, bounds);
    view.show();
    holder.show();
}

/// The notebook's back layer webview (backLayerWebView.ts) lies behind the cells upstream; here it floats over GPUI's
/// layer, so a clip window holds it: it shows the webview inside the notebook list only, and presses reach the
/// webview over its outputs and markdown previews only, GPUI's cells everywhere else.
pub struct ClipView {
    window: gtk::Window,
    fixed: gtk::Fixed,
    /// The input shape last set: the hit rects without the hole, in clip coordinates.
    shape: RefCell<Option<(Vec<gdk::Rectangle>, Option<gdk::Rectangle>)>>,
}

impl ClipView {
    pub fn hide(&self) {
        self.window.hide();
    }

    pub fn remove(&self) {
        // SAFETY: the clip window is this clip view's; the webview it holds keeps its own reference.
        unsafe { self.window.destroy() };
    }

    /// A hidden clip window over `window` holding `webview`.
    pub fn new(window: &Window, webview: &Webview) -> Retained<Self> {
        let clip = embedded_window(gpui_x_window(window));
        let fixed = gtk::Fixed::new();
        clip.add(&fixed);
        let native = &webview.native;
        native.window.remove(&native.view);
        fixed.put(&native.view, 0, 0);
        native.view.show();
        fixed.show();
        Rc::new(ClipView { window: clip, fixed, shape: RefCell::default() })
    }

    /// Shows the clip over `bounds` in GPUI window coordinates, its webview at `webview` (relative to the clip's
    /// origin, as `hit_rects` are).
    pub fn place(&self, webview: &View, window: &Window, bounds: Bounds<Pixels>, webview_frame: Bounds<Pixels>, hit_rects: Vec<Bounds<Pixels>>, hole: Option<Bounds<Pixels>>) {
        move_window(&self.window, window, bounds);
        let frame = gtk_rect(&self.window, window, webview_frame);
        self.fixed.move_(webview, frame.x(), frame.y());
        webview.set_size_request(frame.width(), frame.height());
        self.window.show();
        let rects: Vec<gdk::Rectangle> = hit_rects.into_iter().map(|rect| gtk_rect(&self.window, window, rect)).collect();
        let hole = hole.map(|hole| gtk_rect(&self.window, window, hole));
        if self.shape.borrow().as_ref() != Some(&(rects.clone(), hole)) {
            self.set_shapes(&rects, hole);
            *self.shape.borrow_mut() = Some((rects, hole));
        }
    }

    /// Presses reach the clip over `rects` only, never over `hole` (a GPUI widget over the clip: the notebook find
    /// widget), which the clip also leaves undrawn.
    fn set_shapes(&self, rects: &[gdk::Rectangle], hole: Option<gdk::Rectangle>) {
        let Some(gdk_window) = self.window.window() else { return };
        let input = gtk::cairo::Region::create();
        for rect in rects {
            let _ = input.union_rectangle(&cairo_rect(rect));
        }
        let drawn = gtk::cairo::Region::create_rectangle(&gtk::cairo::RectangleInt::new(0, 0, i32::MAX / 2, i32::MAX / 2));
        if let Some(hole) = hole {
            let _ = input.subtract_rectangle(&cairo_rect(&hole));
            let _ = drawn.subtract_rectangle(&cairo_rect(&hole));
        }
        gdk_window.input_shape_combine_region(&input, 0, 0);
        gdk_window.shape_combine_region(Some(&drawn), 0, 0);
    }
}

fn cairo_rect(rect: &gdk::Rectangle) -> gtk::cairo::RectangleInt {
    gtk::cairo::RectangleInt::new(rect.x(), rect.y(), rect.width(), rect.height())
}

/// `bounds` in GPUI's logical pixels as GTK's, which count device pixels over GTK's own scale.
fn gtk_rect(holder: &gtk::Window, window: &Window, bounds: Bounds<Pixels>) -> gdk::Rectangle {
    let scale = window.scale_factor() / holder.scale_factor() as f32;
    let value = |pixels: Pixels| (f32::from(pixels) * scale).round() as i32;
    gdk::Rectangle::new(value(bounds.origin.x), value(bounds.origin.y), value(bounds.size.width).max(1), value(bounds.size.height).max(1))
}

fn move_window(holder: &gtk::Window, window: &Window, bounds: Bounds<Pixels>) {
    let rect = gtk_rect(holder, window, bounds);
    if holder.position() != (rect.x(), rect.y()) {
        holder.move_(rect.x(), rect.y());
    }
    if holder.size() != (rect.width(), rect.height()) {
        holder.resize(rect.width(), rect.height());
    }
}

/// A hidden, undecorated GTK window whose X window is a child of `parent`.
fn embedded_window(parent: xlib::Window) -> gtk::Window {
    let window = gtk::Window::new(gtk::WindowType::Popup);
    window.realize();
    let display = gdk::Display::default().expect("GTK has a display").downcast::<gdkx11::X11Display>().expect("GTK on X11");
    let parent = gdkx11::X11Window::foreign_new_for_display(&display, parent);
    window.window().expect("a realized window").reparent(parent.upcast_ref::<gdk::Window>(), 0, 0);
    window
}

pub fn gpui_x_window(window: &Window) -> xlib::Window {
    let handle = HasWindowHandle::window_handle(window).expect("an open window has a handle");
    match handle.as_raw() {
        RawWindowHandle::Xcb(handle) => handle.window.get().into(),
        RawWindowHandle::Xlib(handle) => handle.window,
        _ => unreachable!("`supported` holds GPUI to X11"),
    }
}

fn x_window_of(view: &View) -> Option<xlib::Window> {
    let window = view.toplevel()?.window()?;
    Some(window.downcast::<gdkx11::X11Window>().ok()?.xid())
}

fn focus_x_window(view: &View) {
    if let Some(window) = x_window_of(view) {
        set_input_focus(window);
    }
    view.grab_focus();
}

fn set_input_focus(window: xlib::Window) {
    // A window not mapped yet answers BadMatch, which GDK's default X error handler aborts on.
    gdk::error_trap_push();
    // SAFETY: GTK's open X display and a window of GPUI or GTK. A reparented window is no toplevel, so no window
    // manager gives it the focus; X does on this request.
    unsafe {
        xlib::XSetInputFocus(x_display(), window, xlib::RevertToParent, xlib::CurrentTime);
        xlib::XFlush(x_display());
    }
    gdk::error_trap_pop_ignored();
}

fn x_display() -> *mut xlib::Display {
    let display = gdk::Display::default().expect("GTK has a display").downcast::<gdkx11::X11Display>().expect("GTK on X11");
    // SAFETY: an X11 display GTK keeps open.
    unsafe { gdkx11::ffi::gdk_x11_display_get_xdisplay(display.to_glib_none().0) }
}

/// The proxy's certificate, for the view's context to trust, and the TLS context serving it, made once per process.
/// OpenSSL serves it: GnuTLS, glib-networking's backend, refuses a resource host's SNI (`file+.vscode-resource...`).
fn proxy_certificate() -> (gio::TlsCertificate, SslContext) {
    static PEM: OnceLock<(String, String)> = OnceLock::new();
    let (certificate, key) = PEM.get_or_init(|| {
        let names = vec![format!("*.{HOST_SITE}"), format!("*.{RESOURCE_AUTHORITY}")];
        let certified = rcgen::generate_simple_self_signed(names).expect("a self-signed certificate");
        (certified.cert.pem(), certified.signing_key.serialize_pem())
    });
    let trusted = gio::TlsCertificate::from_pem(certificate).expect("rcgen's PEM");
    let mut tls = SslContext::builder(SslMethod::tls_server()).expect("an OpenSSL context");
    tls.set_certificate(&X509::from_pem(certificate.as_bytes()).expect("rcgen's PEM")).expect("the certificate");
    tls.set_private_key(&PKey::private_key_from_pem(key.as_bytes()).expect("rcgen's PEM")).expect("the key");
    (trusted, tls.build())
}

struct ProxyState {
    resources: Rc<Resources>,
    context: WebContext,
    certificate: gio::TlsCertificate,
    tls: SslContext,
    trusted_hosts: RefCell<HashSet<String>>,
    port: u16,
}

/// One proxy connection: `CONNECT host:port`, then the host page or resources over TLS, or a tunnel to another host.
async fn serve(connection: gio::SocketConnection, state: Rc<ProxyState>) {
    let client = connection.remote_address().ok().and_then(|address| address.downcast::<gio::InetSocketAddress>().ok()).map(SocketAddr::from);
    let uid = std::fs::metadata("/proc/self").map(|metadata| metadata.uid());
    let table = std::fs::read_to_string("/proc/net/tcp").unwrap_or_default();
    // Any local user can reach a loopback port; only WebKit's network process, ours, gets an answer.
    let (Some(SocketAddr::V4(client)), Ok(uid)) = (client, uid) else { return };
    if !is_own_connection(&table, client, state.port, uid) {
        return;
    }
    let Ok(stream) = connection.clone().into_async_read_write() else { return };
    let mut stream = BufReader::new(stream);
    let Some(head) = read_head(&mut stream).await else { return };
    let Some(target) = head.line.strip_prefix("CONNECT ").and_then(|rest| rest.split(' ').next()).map(str::to_string) else { return };
    let host = target.rsplit_once(':').map_or(target.as_str(), |(host, _)| host).to_ascii_lowercase();
    let output = connection.output_stream();
    if !is_subdomain(&host, HOST_SITE) && !is_subdomain(&host, RESOURCE_AUTHORITY) {
        let Ok(upstream) = gio::SocketClient::new().connect_to_host_future(&target, 443).await else {
            let _ = output.write_all_future(b"HTTP/1.1 502 Bad Gateway\r\n\r\n", glib::Priority::DEFAULT).await;
            return;
        };
        if output.write_all_future(b"HTTP/1.1 200 Connection Established\r\n\r\n", glib::Priority::DEFAULT).await.is_err() {
            return;
        }
        let flags = gio::OutputStreamSpliceFlags::CLOSE_SOURCE | gio::OutputStreamSpliceFlags::CLOSE_TARGET;
        let up = upstream.output_stream().splice_future(&connection.input_stream(), flags, glib::Priority::DEFAULT);
        let down = output.splice_future(&upstream.input_stream(), flags, glib::Priority::DEFAULT);
        futures::future::select(up, down).await;
        return;
    }
    if state.trusted_hosts.borrow_mut().insert(host.clone()) {
        state.context.allow_tls_certificate_for_host(&state.certificate, &host);
    }
    if output.write_all_future(b"HTTP/1.1 200 Connection Established\r\n\r\n", glib::Priority::DEFAULT).await.is_err() {
        return;
    }
    let Ok(ssl) = Ssl::new(&state.tls) else { return };
    let Ok(mut tls) = SslStream::new(ssl, stream.into_inner()) else { return };
    if Pin::new(&mut tls).accept().await.is_err() {
        return;
    }
    let mut tls = BufReader::new(tls);
    while let Some(head) = read_head(&mut tls).await {
        let (status, headers, body) = answer(&state, &host, &head).await;
        let mut response = format!("HTTP/1.1 {status} {}\r\nContent-Length: {}\r\n", reason(status), body.len());
        for (key, value) in headers {
            response.push_str(&format!("{key}: {value}\r\n"));
        }
        response.push_str("\r\n");
        let mut bytes = response.into_bytes();
        bytes.extend(body);
        if tls.write_all(&bytes).await.is_err() {
            return;
        }
    }
}

struct Head {
    line: String,
    range: Option<String>,
}

/// A request line and its headers, of which the `Range` one is kept; `None` once the connection closed.
async fn read_head(reader: &mut (impl AsyncBufRead + Unpin)) -> Option<Head> {
    let line = read_line(reader).await?;
    let mut range = None;
    loop {
        let header = read_line(reader).await?;
        if header.is_empty() {
            return Some(Head { line, range });
        }
        if let Some((_, value)) = header.split_once(':').filter(|(name, _)| name.eq_ignore_ascii_case("range")) {
            range = Some(value.trim().to_string());
        }
    }
}

/// A line without its line break; `None` once the connection closed.
async fn read_line(reader: &mut (impl AsyncBufRead + Unpin)) -> Option<String> {
    let mut line = String::new();
    match reader.read_line(&mut line).await {
        Ok(0) | Err(_) => None,
        Ok(_) => Some(line.trim_end().to_string()),
    }
}

/// `Resources::serve` for a GET on a host the proxy terminates.
async fn answer(state: &ProxyState, host: &str, head: &Head) -> Response {
    let mut parts = head.line.split(' ');
    let (Some("GET"), Some(target)) = (parts.next(), parts.next()) else { return (405, Vec::new(), Vec::new()) };
    let (path, query) = target.split_once('?').unwrap_or((target, ""));
    let (sender, receiver) = oneshot::channel();
    state.resources.serve(host, &crate::uri::percent_decode(path), &crate::uri::percent_decode(query), head.range.clone(), move |response| {
        let _ = sender.send(response);
    });
    // The workbench dropped the read without an answer.
    receiver.await.unwrap_or((404, Vec::new(), Vec::new()))
}

fn reason(status: u16) -> &'static str {
    match status {
        200 => "OK",
        206 => "Partial Content",
        401 => "Unauthorized",
        404 => "Not Found",
        _ => "Method Not Allowed",
    }
}

/// Whether /proc/net/tcp shows the connection from `client` to the proxy on 127.0.0.1:`proxy_port` owned by `uid`.
/// The whole addresses count: a client on 127.0.0.2 can take the proxy's port.
fn is_own_connection(table: &str, client: SocketAddrV4, proxy_port: u16, uid: u32) -> bool {
    // The kernel prints each IPv4 address as the u32 it holds in network order.
    let address = |ip: Ipv4Addr, port: u16| format!("{:08X}:{port:04X}", u32::from_ne_bytes(ip.octets()));
    let (local, remote) = (address(*client.ip(), client.port()), address(Ipv4Addr::LOCALHOST, proxy_port));
    table.lines().skip(1).any(|line| {
        let fields: Vec<&str> = line.split_whitespace().collect();
        fields.len() > 7 && fields[1] == local && fields[2] == remote && fields[7] == uid.to_string()
    })
}

#[cfg(test)]
mod tests {
    use std::net::{Ipv4Addr, SocketAddrV4};

    use super::is_own_connection;

    fn loopback(last: u8, port: u16) -> SocketAddrV4 {
        SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, last), port)
    }

    #[test]
    fn proxy_answers_only_connections_of_its_user() {
        let table = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n   0: 0100007F:D431 0100007F:A2F0 01 00000000:00000000 00:00000000 00000000  1000        0 123 1\n   1: 0100007F:D432 0100007F:A2F0 01 00000000:00000000 00:00000000 00000000  1001        0 124 1\n";
        assert!(is_own_connection(table, loopback(1, 0xD431), 0xA2F0, 1000));
        assert!(!is_own_connection(table, loopback(1, 0xD432), 0xA2F0, 1000));
        assert!(!is_own_connection(table, loopback(1, 0xD431), 0xA2F1, 1000));
    }

    /// Another user binds 127.0.0.2 on the proxy's port: the proxy's accepted socket, ours, then shows the same ports
    /// reversed.
    #[test]
    fn proxy_refuses_a_client_on_its_own_port_from_another_loopback_address() {
        let table = "  sl  local_address rem_address   st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode\n   0: 0200007F:A2F0 0100007F:A2F0 01 00000000:00000000 00:00000000 00000000  1001        0 123 1\n   1: 0100007F:A2F0 0200007F:A2F0 01 00000000:00000000 00:00000000 00000000  1000        0 124 1\n";
        assert!(!is_own_connection(table, loopback(2, 0xA2F0), 0xA2F0, 1000));
        assert!(is_own_connection(table, loopback(2, 0xA2F0), 0xA2F0, 1001));
    }
}