"Official" way to read the raw bytes of a `struct` I didn't define

I am writing a client library for a bespoke local RPC protocol. The service implementation is not under my control, so I can't change the protocol. Inconveniently, the protocol packet format embeds libc::sockaddr_* structs directly in each message; the message format looks something like this

#[repr(C)]
union PacketAddr {
    sin: libc::sockaddr_in,
    sin6: libc::sockaddr_in6,
    ss: libc::sockaddr_storage,
}

#[repr(C)]
struct Packet {
    packet_len: u32,
    proto_ver: u32,
    msg_type: u32,
    addr_len: u32, 
    addr: PacketAddr,
    annotation: [u8],
};

(The addr_len field tells you which field of the PacketAddr union is live but does not control where annotation starts; addr is always the full size of the union, zero-padded internally if necessary. annotation runs from that point to the end of the packet as defined by packet_len.)

Now, in order to talk this protocol over a local communication channel, one must somehow go from the above struct definition to a &[u8] that can be passed to libc::send. The problem is, the fields of sockaddr_* are not fully pinned down by any standard and in practice do vary between Unixes (N.B. this software is never going to support Windows), so I cannot copy addresses (along with the rest of the packet) field by field into a Cursor<Vec<u8>>, which is what I would usually do.

zerocopy's IntoBytes trait would be just the ticket, but I cannot use it because of the orphan rule (I'm not allowed to #[derive(IntoBytes)] for sockaddr_in because neither of those is defined by my crate).

Instead I came up with this hack:

/// Coerce an arbitrary type S (presumably some kind of struct sockaddr_XX)
/// to a &[u8] slice covering its bytes.
unsafe fn sockaddr_as_bytes<S>(sa: &S) -> &[u8] {
    // SAFETY: This fabricates an &[u8] slice that covers `sa`
    // exactly.  Each byte of the slice is valid for read because `sa`
    // itself was valid for read.  &[u8] cannot be misaligned and u8
    // has no invalid states.  Caller is responsible for ensuring S
    // has a fixed layout and `sa` is fully initialized including padding.
    unsafe {
        slice::from_raw_parts(sa as *const S as *const u8, mem::size_of::<S>())
    }
}

... which is basically what zerocopy's IntoBytes would do for me, but with fewer safety rails. It works, but I don't feel particularly good about it.

So the questions I have are:

  1. Is there a more "official" way to do the above? That is, did I miss something in std::mem or std::ptr that encapsulates at least some of the unsafety?
  2. Is there a way to subvert the orphan rule so I can use zerocopy? Or is there some other third-party crate that would be helpful?
  3. Supposing I'm stuck with the unsafe hack, is my understanding of what needs to be true for the function to be OK to use (as encapsulated by the safety comment) accurate? Did I miss anything important?

creating a slice reference &[u8] to padding bytes is UB, unless you wrap it in MaybeUninit, such as &[MaybeUninit<u8>].

alternatively, you can use a raw pointer *const u8 plus the length, instead of slice reference &[u8]. raw pointers doesn't have the validity requirement, and is ok to be passed to ffi functions such as libc::send(), but make sure you don't dereference the raw pointer in rust.

for this particular use case,

What about manually adding padding, like

const PADDED_LEN: usize = /* maximum of the three sizes */;

#[repr(C)]
struct PaddedSockAddrIn {
    pub data: libc::sockaddr_in,
    pub padding: [u8; { PADDED_LEN - size_of::<libc::sockaddr_in>() }],
}

// and so on

Then, assuming the libc::sockaddr_* types consist entirely of plain-old-bytes (no uninit or pointers), one could fearlessly use mem::transmute<PacketAddr, [u8: PADDED_LEN]>(_) (or cast the references, or whatever) as both the input and output type would have no safety or validity invariants beyond being PADDED_LEN-many pointer-provenance-free initialized bytes.

For 3: “u8 has no invalid states” is false. Bytes in Rust’s Abstract Machine look something like

enum AbstractByte {
    Uninit,
    Init(u8, Option<PointerProvenance>),
}

and valid states (more precisely, valid “representations”) of u8s are abstract bytes matching AbstractByte::Init(_, None).

Would the following not work and be a touch safer?

  1. Vec with capacity packet_len
  2. push 1st 4 fields
  3. unsafe slice from raw parts addr & copy into Vec
  4. unsafe slice from raw parts annotation & copy into Vec

That's the issue I was trying to cover with "Caller is responsible for ensuring ... sa is fully initialized including padding". It is probably the most likely real-world problem considering I currently have to trust that either there is no padding, or the conversion chain from std::net::SockAddrV4 to nix::SockaddrIn to libc::sockaddr_in fully initializes every byte including padding; I'm very open to better ideas here. (But I am 100% stuck with "the format of this field is whatever libc::sockaddr_in{,6} is on this target", so "better ideas" somehow have to involve knowing all the fields of those structures. I can imagine terrible bindgen hacks but I would prefer not to make bindgen a dependency of the main library (using it in tests would be fine though).

That is indeed what I am doing: sockaddr_as_bytes is applied only to the socket address structs, not to the whole packet. (The annotation is a string, so there's no need for unsafe for that part.)

Ah - I see I left off the "using len from addr_len and then adding your own padding to the full size of the field" at step 3 in my haste...
(So if using a dedicated function for that it would need to be unsafe fn sockaddr_as_bytes<S>(sa: &S, len: usize) -> &[u8]

[EDIT: and now I realise, the padding is not just at the end but also potentially between the fields]

In Rust, the only way to know that memory for a struct is initialized including the padding between the fields is to write all fields individually at their correct offset (in addition to initializing the padding, perhaps by starting with zeroed memory). Every write operation that uses the struct type as a whole is allowed to write uninit to padding areas, even if it's a move from a location where the padding was initialized. So, you cannot do this without knowing field offsets or knowing there is no padding.

Ugh. The most common implementations should avoid having any padding but I do not know that for sure. I feel like "allowed to write uninit to padding areas even if..." is a bad rule in general, but let's not derail this thread with that conversation; anyway it's much more of an IRLO conversation.

Given the hard constraints -- I cannot change the packet format, I need to copy the native-endian bytes of every field (standardized or not) of a sockaddr_in[6] to the appropriate location within a larger &mut [u8], and zero all the bytes that were padding in the source, and the set of fields and their offsets is OS-dependent -- how would you proceed?

I think you will need to know which bytes are padding and which ones are not. If you do know that then you can first copy the struct into a MaybeUninit buffer, then zero the padding and then copy it into the output.

If you did not care about the value of the padding bytes on the wire you could have used something like the probably coming freeze operation, but if they need to be zero, i don't think this would help at all.

If you cannot guarantee it has a deterministic layout and no padding bytes, you just cannot.

Please understand that this is the part I need help with.

Just to illustrate the problem, this is the definition of struct sockaddr_in from the Linux kernel's UAPI headers (after erasing a bunch of macro gunk and replacing typedefs with their definitions):

struct in_addr {
    unsigned int s_addr;
};
struct sockaddr_in {
    unsigned short  sin_family;
    unsigned short  sin_port;
    struct in_addr  sin_addr;
    unsigned char   sin_zero[
      16 - (sizeof(unsigned short)
            + sizeof(unsigned short)
            + sizeof(struct in_addr))
    ];
};

And this is the definition from NetBSD:

struct in_addr {
    unsigned int    s_addr;
};
struct sockaddr_in {
    unsigned char   sin_len;
    unsigned char   sin_family;
    unsigned short  sin_port;
    struct in_addr  sin_addr;
    signed char     sin_zero[8];
};

Notice how even the fields common to all sockaddr structures are not the same between the two clades.

I can guarantee a deterministic layout, but not no padding, and more importantly, I can't guarantee a target-independent layout. If the layout were target-independent I could just copy all of the fields to the right locations and be done.

I believe there are at least two reasons for this:

  • Being able to pass the struct fields one by one in registers rather than on the stack.
  • It might be cheaper (or required) on some architectures to write whole aligned words, so any smaller unit means reading a word in, modifying it and writing it back. Being able to ignore padding allows optimising away such reads sometimes.

I'm going to leave out the discussions about if those optimisations are worth it or not.

If you know which fields exist (and that does unfortunately seem to differ between platforms) perhaps you could do something really awkward with offset_of and size_of to copy the init values field by field. Otherwise sticking entirely to MaybeUninit or raw pointers is the way to go.

&mut [u8] just won't cut it. The other option is to only support specific white listed platforms, since this is clearly not portable anyway.

Could you x-y this? If I understand correctly:

  • you receive a Paket over the wire as an &[u8] and at this point you have a guarantee that any padding is \0
  • the problem comes that as soon as this is interpreted as a Packet future moves invalidate that padding guarantee

What would break if you internally stored the addr as a [u8] exactly as it was received, thus preserving any \0 padding?

Instead of trying to recreate the \0s when sending, would it be possible to only interpret the addr when needed. Something a bit like:

enum PacketAddr {
    sin(libc::sockaddr_in),
    sin6(libc::sockaddr_in6),
    ss(libc::sockaddr_storage),
}

struct Packet {
    packet_len: u32,
    proto_ver: u32,
    msg_type: u32,
    addr_len: u32, 
    addr: [u8; ..], // including the original null-bytes
    annotation: [u8],
}

impl Packet {
    fn addr(&self) -> PacketAddr {
        match self.addr_len {
            // select variant based on value of addr_len
        }
    }
}

impl PacketAddr {
    fn from_raw_bytes(&[u8]) -> Self {
        // ...
    }

    fn to_socket_addr(&self) -> SocketAddr {
        match self { ... }
    }
}

I believe the problem is the other way round - the need is to build a Packet to send to another binary on the same host (so libc::sockaddr_in et al have the same definition), and the question boils down to "how do I convert PacketAddr to [u8; std::mem::size_of::<PacketAddr>] soundly"?

@farnz is correct: I'm writing a client library for a service I didn't design. I start with a Rust-native SocketAddrV4 (or V6) and I need to turn that into the native byte serialization of a C sockaddr_in (or _in6), which will be embedded in the larger packet as shown and sent off to the service. It's a completely fire-and-forget protocol, the server never replies to anything, so I only need to encode packets. And it doesn't make sense to run this particular service on a different host from its clients, so the C sockaddr_in will always line up between server and client ... unless we get some virtual machines involved, I suppose, but I don't think the service's authors were thinking about that at all.

(I probably am going to end up writing my own server implementation eventually, but that is not today's problem.)

So, XY is a fair question, but I really don't see an alternative. I would not have designed this protocol this way, but I don't get to change it.

I'm not ready to share my crate publicly, [EDIT: Now I am! zwol/ip_banhammer: Compatible client library (and eventually daemon) for blocklistd - Codeberg.org ] but the service is NetBSD's blocklistd, and if you would like to see the C protocol implementation, it can be found here: bl.c. And the reason I'm writing my own client is because there are several things about the bl.c client implementation that make it unpleasant to call via FFI from Rust. It seems to have been designed with "we want to patch existing network daemons to use this, but we have no plans to upstream those patches so we need them to be minimally invasive so we can carry them indefinitely" as a top-priority design goal.

I don't think either MaybeUninit or raw pointers will actually help, because I need the entire packet to be fully initialized by the time I feed it to send. If I used a copy method that copied uninitialized bytes safely, I would then need to find those uninitialized bytes (if any) and initialize them. Which reduces to the same problem of needing to know which bytes are padding.

My current vague plan is to have a module with a bunch of #[cfg()] conditionals that knows how to build up a sockaddr_in(6) field by field, and then use bindgen to generate a test that validates what that module knows, thus avoiding having the crate proper depend on bindgen.

Given that both of those definitions from Linux and NetBSD have no padding (assuming that an int is at most twice the size of a short which is at most twice the size of a char, and likewise for their alignments, as should be the case in sane C environments), is the problem that you can’t guarantee there’s no padding on every OS?

If you’re considering using cfg to initialize field-by-field… perhaps it would be better to use cfg to enforce that only targets with known-sane definitions of the packet structs are supported.

Given that this is effectively an FFI boundary, maybe make use of the fact that reading padding bytes is defined in C as returning an arbitrary byte value that can change on every read?

Something along the lines of (rigorously untested and may not compile):

fn packet_addr_to_byte_array(pa: PacketAddr) -> [u8; std::mem::size_of::<PacketAddr>] {
    let mut out = [0u8; std::mem::size_of::<PacketAddr>];
    // SAFETY: Destination allocated above, so guaranteed large enough
    unsafe { libc::memcpy(&mut out, &pa, std::mem::size_of::<PacketAddr>()); }
}

This way, you're doing what the C code would do, which is defined behaviour in C, and has a Rust story making it legal to do via FFI (you're reading the bytes of PacketAddr, replacing the padding with arbitrary values).