coreshift-core 1.2.11

Low-level Linux and Android systems primitives for CoreShift
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/

//! Low-level Unix domain socket primitives.
//!
//! This module exposes Linux/Android `AF_UNIX` stream socket mechanics only:
//! bind, listen, accept, connect, chmod for filesystem sockets, peer
//! credentials, and byte I/O through [`Fd`]. Callers own all protocol, message
//! framing, authentication policy, daemon behavior, and socket naming.
//!
//! Abstract socket names are Linux/Android-only. They are encoded with a
//! leading NUL byte in `sun_path`; interior NUL bytes in the caller-provided
//! abstract name are preserved because the kernel uses the explicit sockaddr
//! length, not C string termination.

use crate::CoreError;
use crate::error::syscall_ret;
use crate::reactor::Fd;
use std::io::Error as IoError;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::FileTypeExt;
use std::os::unix::io::AsRawFd;
use std::path::Path;

#[inline(always)]
fn errno() -> i32 {
    IoError::last_os_error().raw_os_error().unwrap_or(0)
}

/// Owned non-blocking Unix listener descriptor.
pub struct UnixListenerFd {
    /// Underlying descriptor for reactor registration and raw byte helpers.
    pub fd: Fd,
}

/// Owned non-blocking Unix stream descriptor.
pub struct UnixStreamFd {
    /// Underlying descriptor for reactor registration and raw byte helpers.
    pub fd: Fd,
}

/// Result of starting a non-blocking Unix stream connection.
pub enum UnixConnectResult {
    /// The socket connected immediately.
    Connected(UnixStreamFd),
    /// The socket connection is in progress; register for writability and call
    /// [`UnixStreamFd::finish_connect`] or [`UnixStreamFd::check_connect_error`].
    InProgress(UnixStreamFd),
}

/// Unix socket address.
#[derive(Clone, Copy, Debug)]
pub enum UnixSocketAddr<'a> {
    /// Filesystem pathname socket.
    Path(&'a Path),
    /// Linux/Android abstract namespace socket name, without the leading NUL.
    Abstract(&'a [u8]),
}

/// Explicit stale pathname behavior for filesystem socket binds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StaleSocketPolicy {
    /// Preserve any existing path and let `bind` report the conflict.
    #[default]
    Preserve,
    /// Unlink only if the existing path is itself a socket.
    UnlinkSocketOnly,
    /// Unlink any existing filesystem path.
    ///
    /// This may delete non-socket files and should only be used when the caller
    /// owns the path namespace.
    UnlinkAnyPath,
}

/// Bind options for a Unix stream listener.
#[derive(Clone, Copy, Debug, Default)]
pub struct UnixSocketBindOptions {
    /// Explicit stale pathname handling for filesystem socket binds.
    pub stale_socket_policy: StaleSocketPolicy,
    /// Optional filesystem socket path mode applied after a successful bind.
    pub mode: Option<u32>,
}

/// Peer process credentials when the platform exposes them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PeerCred {
    /// Peer process id when available.
    pub pid: Option<i32>,
    /// Peer user id.
    pub uid: u32,
    /// Peer group id.
    pub gid: u32,
}

impl UnixListenerFd {
    /// Accept one non-blocking client.
    ///
    /// ### Fork Safety
    /// The listener's file descriptor is `O_CLOEXEC` and will be closed in the
    /// child after `exec`.
    ///
    /// ### Errors
    /// - `EAGAIN`/`EWOULDBLOCK`: No connection is pending.
    /// - `ECONNABORTED`: A connection was aborted before it could be accepted.
    /// - `EMFILE`: Process limit on open file descriptors hit.
    /// - `ENFILE`: System-wide limit on open files hit.
    ///
    /// Returns `Ok(None)` if no client is ready.
    pub fn accept(&self) -> Result<Option<UnixStreamFd>, CoreError> {
        self.accept_timeout(0)
    }

    /// Accept a client with a raw timeout in milliseconds.
    ///
    /// - `-1`: Block indefinitely until a client connects.
    /// - `0`: Return immediately (equivalent to [`Self::accept`]).
    /// - `> 0`: Wait up to the specified milliseconds.
    ///
    /// ### Errors
    /// Returns the same errors as [`Self::accept`], or `poll(2)` errors.
    ///
    /// # Example
    /// ```no_run
    /// # use coreshift_core::unix_socket::{self, UnixListenerFd, UnixSocketAddr, UnixSocketBindOptions};
    /// # let listener = unix_socket::bind_unix_listener(UnixSocketAddr::Abstract(b"test"), UnixSocketBindOptions::default()).unwrap();
    /// let stream = listener.accept_timeout(1000).unwrap();
    /// ```
    pub fn accept_timeout(&self, timeout_ms: i32) -> Result<Option<UnixStreamFd>, CoreError> {
        if timeout_ms != 0 {
            let mut pollfd = libc::pollfd {
                fd: self.fd.as_raw_fd(),
                events: libc::POLLIN,
                revents: 0,
            };
            let ret = unsafe { libc::poll(&mut pollfd, 1, timeout_ms) };
            if ret < 0 {
                let e = errno();
                if e == libc::EINTR {
                    return Ok(None);
                }
                return Err(CoreError::sys(e, "poll(accept)"));
            }
            if ret == 0 {
                return Ok(None);
            }
        }

        loop {
            let fd = unsafe {
                libc::accept4(
                    self.fd.as_raw_fd(),
                    std::ptr::null_mut(),
                    std::ptr::null_mut(),
                    libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
                )
            };
            if fd >= 0 {
                return Ok(Some(UnixStreamFd {
                    fd: Fd::new(fd, "accept4")?,
                }));
            }

            let e = errno();
            if e == libc::EINTR {
                continue;
            }
            if e == libc::EAGAIN || e == libc::EWOULDBLOCK {
                return Ok(None);
            }
            return Err(CoreError::sys(e, "accept4"));
        }
    }
}

impl UnixStreamFd {
    /// Return peer credentials when the platform supports `SO_PEERCRED`.
    ///
    /// ### Errors
    /// - `EBADF`: The file descriptor is invalid.
    /// - `ENOPROTOOPT`: `SO_PEERCRED` is not supported by the socket.
    ///
    /// # Example
    /// ```no_run
    /// # use coreshift_core::unix_socket::UnixStreamFd;
    /// # fn example(stream: UnixStreamFd) {
    /// let creds = stream.peer_cred().unwrap();
    /// if let Some(c) = creds {
    ///     println!("Peer UID: {}", c.uid);
    /// }
    /// # }
    /// ```
    pub fn peer_cred(&self) -> Result<Option<PeerCred>, CoreError> {
        peer_cred_raw(&self.fd)
    }

    /// Return the pending `SO_ERROR` connect status.
    ///
    /// `Ok(None)` means no pending socket error was reported. `Ok(Some(code))`
    /// returns the raw connect error without making a policy decision.
    ///
    /// ### Errors
    /// - `EBADF`: The file descriptor is invalid.
    pub fn check_connect_error(&self) -> Result<Option<i32>, CoreError> {
        let mut code: libc::c_int = 0;
        let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
        let ret = unsafe {
            libc::getsockopt(
                self.fd.as_raw_fd(),
                libc::SOL_SOCKET,
                libc::SO_ERROR,
                (&mut code as *mut libc::c_int).cast(),
                &mut len,
            )
        };
        syscall_ret(ret, "getsockopt(SO_ERROR)")?;
        if code == 0 { Ok(None) } else { Ok(Some(code)) }
    }

    /// Finish a non-blocking connect after the socket becomes writable.
    ///
    /// Returns the stream when `SO_ERROR` is clear; otherwise returns the raw
    /// socket error as [`CoreError`].
    ///
    /// ### Errors
    /// Returns the same errors as [`Self::check_connect_error`], or the
    /// pending connection error itself.
    pub fn finish_connect(self) -> Result<Self, CoreError> {
        match self.check_connect_error()? {
            None => Ok(self),
            Some(code) => Err(CoreError::sys(code, "connect(SO_ERROR)")),
        }
    }
}

/// Bind a new Unix domain stream listener.
///
/// The socket is created with `SOCK_CLOEXEC` set.
///
/// ### Fork Safety
/// The socket is `O_CLOEXEC` and will be closed in the child after `exec`.
///
/// ### Errors
/// - `EACCES`: Permission denied for a component of the path.
/// - `EADDRINUSE`: The address is already in use.
/// - `EINVAL`: Invalid address.
/// - `ELOOP`: Too many symbolic links encountered.
/// - `ENAMETOOLONG`: Path is too long.
/// - `ENOENT`: A component of the path prefix does not exist.
pub fn bind_unix_listener(
    addr: UnixSocketAddr<'_>,
    opts: UnixSocketBindOptions,
) -> Result<UnixListenerFd, CoreError> {
    let encoded = UnixSockAddr::new(addr, "unix bind address")?;

    match addr {
        UnixSocketAddr::Path(path) => {
            apply_stale_socket_policy(path, opts.stale_socket_policy)?;
        }
        UnixSocketAddr::Abstract(_) => {
            if opts.stale_socket_policy != StaleSocketPolicy::Preserve || opts.mode.is_some() {
                return Err(CoreError::sys(libc::EINVAL, "abstract unix bind options"));
            }
        }
    }

    let fd = new_unix_stream_socket()?;
    let ret = unsafe { libc::bind(fd.as_raw_fd(), encoded.as_ptr(), encoded.len()) };
    syscall_ret(ret, "bind")?;

    if let (UnixSocketAddr::Path(path), Some(mode)) = (addr, opts.mode) {
        if let Err(err) = chmod_unix_socket(UnixSocketAddr::Path(path), mode) {
            cleanup_created_path(addr);
            return Err(err);
        }
    }

    let ret = unsafe { libc::listen(fd.as_raw_fd(), libc::SOMAXCONN) };
    if let Err(err) = syscall_ret(ret, "listen") {
        cleanup_created_path(addr);
        return Err(err);
    }

    Ok(UnixListenerFd { fd })
}

/// Connect a non-blocking Unix stream socket.
///
/// ### Fork Safety
/// The socket is `O_CLOEXEC` and will be closed in the child after `exec`.
///
/// ### Errors
/// - `EACCES`: Permission denied.
/// - `ECONNREFUSED`: No one listening on the remote address.
/// - `EINPROGRESS`: Connection is in progress.
/// - `ENOENT`: The socket path does not exist.
pub fn connect_unix_stream(addr: UnixSocketAddr<'_>) -> Result<UnixConnectResult, CoreError> {
    let encoded = UnixSockAddr::new(addr, "unix connect address")?;
    let fd = new_unix_stream_socket()?;

    loop {
        let ret = unsafe { libc::connect(fd.as_raw_fd(), encoded.as_ptr(), encoded.len()) };
        if ret == 0 {
            return Ok(UnixConnectResult::Connected(UnixStreamFd { fd }));
        }

        let e = errno();
        if e == libc::EINTR {
            continue;
        }
        if e == libc::EINPROGRESS || e == libc::EALREADY {
            return Ok(UnixConnectResult::InProgress(UnixStreamFd { fd }));
        }
        if e == libc::EISCONN {
            return Ok(UnixConnectResult::Connected(UnixStreamFd { fd }));
        }
        return Err(CoreError::sys(e, "connect"));
    }
}

/// Change mode bits on a Unix socket filesystem path.
///
/// ### Errors
/// - `EACCES`: Permission denied.
/// - `ENOENT`: The socket path does not exist.
/// - `EPERM`: The caller does not own the file.
pub fn chmod_unix_socket(addr: UnixSocketAddr<'_>, mode: u32) -> Result<(), CoreError> {
    match addr {
        UnixSocketAddr::Path(path) => {
            let metadata = std::fs::symlink_metadata(path).map_err(|err| {
                CoreError::sys(
                    err.raw_os_error().unwrap_or(libc::EIO),
                    "lstat unix socket path",
                )
            })?;
            if !metadata.file_type().is_socket() {
                return Err(CoreError::sys(libc::EINVAL, "chmod unix socket path"));
            }
            let c_path = path_cstring(path, "chmod unix socket path")?;
            let ret = unsafe { libc::chmod(c_path.as_ptr(), mode as libc::mode_t) };
            syscall_ret(ret, "chmod")
        }
        UnixSocketAddr::Abstract(_) => Err(CoreError::sys(libc::EINVAL, "chmod abstract socket")),
    }
}

/// Change mode bits on a Unix socket filesystem path.
pub fn chmod_socket_path(path: impl AsRef<Path>, mode: u32) -> Result<(), CoreError> {
    chmod_unix_socket(UnixSocketAddr::Path(path.as_ref()), mode)
}

/// Connect to a Unix domain stream socket.
///
/// The socket is created with `SOCK_CLOEXEC` and `SOCK_NONBLOCK` set.
fn new_unix_stream_socket() -> Result<Fd, CoreError> {
    let fd = unsafe {
        libc::socket(
            libc::AF_UNIX,
            libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
            0,
        )
    };
    syscall_ret(fd, "socket(AF_UNIX)")?;
    Fd::new(fd, "socket(AF_UNIX)")
}

fn apply_stale_socket_policy(path: &Path, policy: StaleSocketPolicy) -> Result<(), CoreError> {
    match policy {
        StaleSocketPolicy::Preserve => Ok(()),
        StaleSocketPolicy::UnlinkSocketOnly => {
            let metadata = match std::fs::symlink_metadata(path) {
                Ok(metadata) => metadata,
                Err(err) if err.raw_os_error() == Some(libc::ENOENT) => return Ok(()),
                Err(err) => {
                    return Err(CoreError::sys(
                        err.raw_os_error().unwrap_or(libc::EIO),
                        "lstat unix socket path",
                    ));
                }
            };
            if !metadata.file_type().is_socket() {
                return Err(CoreError::sys(libc::EEXIST, "stale unix socket path"));
            }
            unlink_path(path, "unlink stale unix socket")
        }
        StaleSocketPolicy::UnlinkAnyPath => unlink_path(path, "unlink unix socket path"),
    }
}

fn unlink_path(path: &Path, op: &'static str) -> Result<(), CoreError> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(err) if err.raw_os_error() == Some(libc::ENOENT) => Ok(()),
        Err(err) => Err(CoreError::sys(err.raw_os_error().unwrap_or(libc::EIO), op)),
    }
}

fn cleanup_created_path(addr: UnixSocketAddr<'_>) {
    if let UnixSocketAddr::Path(path) = addr {
        let _ = std::fs::remove_file(path);
    }
}

struct UnixSockAddr {
    inner: libc::sockaddr_un,
    len: libc::socklen_t,
}

impl UnixSockAddr {
    fn new(addr: UnixSocketAddr<'_>, op: &'static str) -> Result<Self, CoreError> {
        let mut inner: libc::sockaddr_un = unsafe { std::mem::zeroed() };
        inner.sun_family = libc::AF_UNIX as libc::sa_family_t;
        let sun_path_offset = std::mem::offset_of!(libc::sockaddr_un, sun_path);

        let len = match addr {
            UnixSocketAddr::Path(path) => {
                let bytes = path.as_os_str().as_bytes();
                if bytes.is_empty() {
                    return Err(CoreError::sys(libc::EINVAL, op));
                }
                if bytes.contains(&0) {
                    return Err(CoreError::sys(libc::EINVAL, op));
                }
                if bytes.len() >= inner.sun_path.len() {
                    return Err(CoreError::sys(libc::ENAMETOOLONG, op));
                }

                for (slot, byte) in inner.sun_path.iter_mut().zip(bytes.iter().copied()) {
                    *slot = byte as libc::c_char;
                }
                sun_path_offset + bytes.len() + 1
            }
            UnixSocketAddr::Abstract(name) => {
                validate_abstract_supported()?;
                if name.is_empty() {
                    return Err(CoreError::sys(libc::EINVAL, op));
                }
                if name.len() + 1 > inner.sun_path.len() {
                    return Err(CoreError::sys(libc::ENAMETOOLONG, op));
                }

                inner.sun_path[0] = 0;
                for (slot, byte) in inner.sun_path[1..].iter_mut().zip(name.iter().copied()) {
                    *slot = byte as libc::c_char;
                }
                sun_path_offset + 1 + name.len()
            }
        };
        let len = libc::socklen_t::try_from(len).map_err(|_| CoreError::sys(libc::EINVAL, op))?;

        Ok(Self { inner, len })
    }

    fn len(&self) -> libc::socklen_t {
        self.len
    }

    fn as_ptr(&self) -> *const libc::sockaddr {
        (&self.inner as *const libc::sockaddr_un).cast()
    }
}

fn validate_abstract_supported() -> Result<(), CoreError> {
    if cfg!(any(target_os = "linux", target_os = "android")) {
        Ok(())
    } else {
        Err(CoreError::sys(libc::ENOSYS, "abstract unix socket"))
    }
}

fn path_cstring(path: &Path, op: &'static str) -> Result<std::ffi::CString, CoreError> {
    std::ffi::CString::new(path.as_os_str().as_bytes())
        .map_err(|_| CoreError::sys(libc::EINVAL, op))
}

#[cfg(any(target_os = "linux", target_os = "android"))]
fn peer_cred_raw(fd: &Fd) -> Result<Option<PeerCred>, CoreError> {
    let mut cred: libc::ucred = unsafe { std::mem::zeroed() };
    let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
    let ret = unsafe {
        libc::getsockopt(
            fd.as_raw_fd(),
            libc::SOL_SOCKET,
            libc::SO_PEERCRED,
            (&mut cred as *mut libc::ucred).cast(),
            &mut len,
        )
    };
    syscall_ret(ret, "getsockopt(SO_PEERCRED)")?;

    Ok(Some(PeerCred {
        pid: Some(cred.pid),
        uid: cred.uid,
        gid: cred.gid,
    }))
}

#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn peer_cred_raw(_fd: &Fd) -> Result<Option<PeerCred>, CoreError> {
    Ok(None)
}