No sound way to zero-copy from socketaddr_in

未关闭
#323 6 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
35/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
rust
领域
networking

调研方向

首先检查 socket2::SockAddr 及其 as_socket() 解析路径,并将 issue 中的 SOCKADDR 和 SOCKADDR_STORAGE 示例作为安全边界。将提议的借用 SockAddrRef 方法与执行复制的构造函数进行比较,并将完成定义为:安全处理仅在所提供长度范围内有效的指针,而不要求调用方复制到 SOCKADDR_STORAGE 中。

由索引模型根据 Issue 内容生成。

描述

enhancement

This is most painful on Windows, where SOCKADDR_STORAGE is 132 bytes long.

Consider the following naive example code, where the SOCKADDR pointer here is a pointer to an ipv4/ipv6 address obtained via syscall:

unsafe fn sock_addr_to_ip(ptr: *const SOCKADDR, length: i32) -> Option<IpAddr> {
    let sa = socket2::SockAddr::new(*(ptr as *const SOCKADDR_STORAGE), length);
    sa.as_socket().map(|s| s.ip())
}

The issue is that SOCKADDR_STORAGE is larger than SOCKADDR, the pointer is only guaranteed to be valid through length bytes, and so casting it to *const SOCKADDR_STORAGE and dereferencing immediately introduces UB.

The correct code looks more like this:

unsafe fn sock_addr_to_ip(ptr: *const SOCKADDR, length: i32) -> Option<IpAddr> {
    assert!(length as usize <= std::mem::size_of::<SOCKADDR_STORAGE>());
    let mut storage = std::mem::MaybeUninit::<SOCKADDR_STORAGE>::uninit();
    std::ptr::copy_nonoverlapping(ptr, &mut storage as *mut _ as *mut _, length as _);
    let sa = socket2::SockAddr::new(storage.assume_init(), length);
    sa.as_socket().map(|s| s.ip())
}

Since the backing storage for SockAddr is owning, we have to make a copy. It's incredibly awkward and a bit slower. And that's just so we can safely invoke the nice parsing logic in as_socket().

To fix this we'd probably have to add a SockAddrRef<'a> type that doesn't own its backing storage. If that's not immediately feasible, providing a constructor that performs this unsafe copy inside socket2 would also solve the immediate issue.

主要语言
Rust
星标
885
派生
328
平均合并
6 天 12 小时
30 天内合并 PR
2

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

rust-lang/socket2 的其他 Issue

查看 rust-lang/socket2 的全部 Issue

相似的 Issue

更多 Rust Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。