rmux-server 0.10.0

Tokio daemon and request dispatcher for the RMUX terminal multiplexer.
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
use std::fs;
use std::io;
use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt, PermissionsExt};
use std::os::unix::net::UnixStream as StdUnixStream;
use std::path::{Path, PathBuf};

use rmux_ipc::{LocalEndpoint, LocalListener};
use tracing::debug;

pub(crate) const OWNER_ONLY_DIRECTORY_MODE: u32 = 0o700;
pub(crate) const SHARED_DIRECTORY_MODE: u32 = 0o711;
pub(crate) const OWNER_ONLY_SOCKET_MODE: u32 = 0o600;
pub(crate) const SHARED_SOCKET_MODE: u32 = 0o666;
const SOCKET_DIR_PREFIX: &str = "rmux";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum UnixTransportAccess {
    OwnerOnly,
    AllowListed,
}

impl UnixTransportAccess {
    #[must_use]
    pub(crate) const fn directory_mode(self) -> u32 {
        match self {
            Self::OwnerOnly => OWNER_ONLY_DIRECTORY_MODE,
            Self::AllowListed => SHARED_DIRECTORY_MODE,
        }
    }

    #[must_use]
    pub(crate) const fn socket_mode(self) -> u32 {
        match self {
            Self::OwnerOnly => OWNER_ONLY_SOCKET_MODE,
            Self::AllowListed => SHARED_SOCKET_MODE,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SocketFileIdentity {
    pub(crate) device: u64,
    pub(crate) inode: u64,
}

pub(crate) struct BoundUnixListener {
    pub(crate) listener: LocalListener,
    pub(crate) identity: Option<SocketFileIdentity>,
}

pub(crate) fn bind_unix_listener_at(socket_path: &Path) -> io::Result<BoundUnixListener> {
    if socket_path.as_os_str().is_empty() {
        return bind_empty_socket_listener();
    }
    prepare_socket_path(socket_path, UnixTransportAccess::OwnerOnly)?;
    bind_prepared_unix_listener(socket_path, UnixTransportAccess::OwnerOnly)
}

pub(crate) fn rebind_unix_listener_at(
    socket_path: &Path,
    current_identity: Option<SocketFileIdentity>,
    access: UnixTransportAccess,
) -> io::Result<BoundUnixListener> {
    if socket_path.as_os_str().is_empty() {
        return bind_empty_socket_listener();
    }
    prepare_socket_parent(socket_path, access)?;
    remove_rebindable_socket(socket_path, current_identity)?;
    bind_prepared_unix_listener(socket_path, access)
}

fn bind_prepared_unix_listener(
    socket_path: &Path,
    access: UnixTransportAccess,
) -> io::Result<BoundUnixListener> {
    let endpoint = LocalEndpoint::from_path(socket_path.to_path_buf());
    let listener = LocalListener::bind(&endpoint)?;
    enforce_bound_socket_permissions(socket_path, access.socket_mode())?;
    let identity = socket_file_identity(socket_path)?;
    Ok(BoundUnixListener {
        listener,
        identity: Some(identity),
    })
}

fn bind_empty_socket_listener() -> io::Result<BoundUnixListener> {
    let endpoint = rmux_ipc::resolve_endpoint(None, Some(Path::new("")))?;
    let listener = LocalListener::bind(&endpoint)?;
    Ok(BoundUnixListener {
        listener,
        identity: None,
    })
}

fn prepare_socket_path(socket_path: &Path, access: UnixTransportAccess) -> io::Result<()> {
    prepare_socket_parent(socket_path, access)?;
    remove_stale_socket_if_needed(socket_path)
}

fn prepare_socket_parent(socket_path: &Path, access: UnixTransportAccess) -> io::Result<()> {
    ensure_parent_directory_for_access(socket_parent_or_current(socket_path)?, access)
}

#[cfg(test)]
pub(crate) fn ensure_parent_directory(parent: &Path) -> io::Result<()> {
    ensure_parent_directory_for_access(parent, UnixTransportAccess::OwnerOnly)
}

fn ensure_parent_directory_for_access(
    parent: &Path,
    access: UnixTransportAccess,
) -> io::Result<()> {
    let mut builder = fs::DirBuilder::new();
    builder.recursive(true).mode(OWNER_ONLY_DIRECTORY_MODE);
    match builder.create(parent) {
        Ok(()) => {}
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
            if !fs::metadata(parent)?.is_dir() {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    format!("socket parent '{}' is not a directory", parent.display()),
                ));
            }
        }
        Err(error) => return Err(error),
    }

    if let Some(managed_directory) = managed_rmux_socket_directory(parent)? {
        ensure_safe_rmux_socket_directory(&managed_directory, access)?;
    }
    Ok(())
}

fn ensure_directory(path: &Path) -> io::Result<()> {
    let metadata = fs::metadata(path)?;
    if !metadata.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("socket directory '{}' is not a directory", path.display()),
        ));
    }
    Ok(())
}

pub(crate) fn managed_rmux_socket_directory(path: &Path) -> io::Result<Option<PathBuf>> {
    let expected = format!("{SOCKET_DIR_PREFIX}-{}", real_user_id()?);
    for ancestor in path.ancestors() {
        if ancestor.file_name().and_then(|name| name.to_str()) == Some(expected.as_str()) {
            return Ok(Some(ancestor.to_path_buf()));
        }
    }
    Ok(None)
}

fn ensure_safe_rmux_socket_directory(path: &Path, access: UnixTransportAccess) -> io::Result<()> {
    let metadata = fs::symlink_metadata(path)?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "socket directory '{}' is not a plain directory",
                path.display()
            ),
        ));
    }
    let mode = metadata.permissions().mode() & 0o777;
    if mode != OWNER_ONLY_DIRECTORY_MODE && mode != SHARED_DIRECTORY_MODE {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "socket directory '{}' has unsafe permissions",
                path.display()
            ),
        ));
    }
    let user_id = real_user_id()?;
    if metadata.uid() != user_id {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("socket directory '{}' has unsafe ownership", path.display()),
        ));
    }
    let expected_mode = access.directory_mode();
    if mode != expected_mode {
        fs::set_permissions(path, fs::Permissions::from_mode(expected_mode))?;
        let updated = fs::symlink_metadata(path)?;
        if updated.file_type().is_symlink()
            || !updated.is_dir()
            || updated.uid() != user_id
            || updated.permissions().mode() & 0o777 != expected_mode
        {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!(
                    "socket directory '{}' changed while applying permissions",
                    path.display()
                ),
            ));
        }
    }
    Ok(())
}

fn enforce_bound_socket_permissions(socket_path: &Path, expected_mode: u32) -> io::Result<()> {
    validate_bound_socket(socket_path, None)?;
    fs::set_permissions(socket_path, fs::Permissions::from_mode(expected_mode))?;
    validate_bound_socket(socket_path, Some(expected_mode))
}

fn validate_bound_socket(socket_path: &Path, expected_mode: Option<u32>) -> io::Result<()> {
    let metadata = socket_metadata(socket_path, io::ErrorKind::PermissionDenied)?;
    ensure_directory(socket_parent_or_current(socket_path)?)?;
    let user_id = real_user_id()?;
    if metadata.uid() != user_id {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("socket {} has unsafe ownership", socket_path.display()),
        ));
    }
    if expected_mode.is_some_and(|mode| metadata.permissions().mode() & 0o777 != mode) {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("socket {} has unsafe permissions", socket_path.display()),
        ));
    }
    Ok(())
}

fn socket_parent_or_current(socket_path: &Path) -> io::Result<&Path> {
    let Some(parent) = rmux_os::path::parent_or_current(socket_path) else {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "socket path '{}' has no parent directory",
                socket_path.display()
            ),
        ));
    };
    Ok(parent)
}

pub(crate) fn socket_file_identity(socket_path: &Path) -> io::Result<SocketFileIdentity> {
    let metadata = socket_metadata(socket_path, io::ErrorKind::PermissionDenied)?;
    ensure_socket_owner(&metadata, socket_path)?;
    Ok(identity_from_metadata(&metadata))
}

pub(crate) fn remove_stale_socket_if_needed(socket_path: &Path) -> io::Result<()> {
    let metadata = match fs::symlink_metadata(socket_path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error),
    };

    if metadata.file_type().is_symlink() || !metadata.file_type().is_socket() {
        return Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            format!(
                "socket path '{}' exists but is not a Unix socket",
                socket_path.display()
            ),
        ));
    }

    match StdUnixStream::connect(socket_path) {
        Ok(_stream) => Err(io::Error::new(
            io::ErrorKind::AddrInUse,
            format!("socket '{}' is already in use", socket_path.display()),
        )),
        Err(error) if indicates_stale_socket(&error) => {
            debug!(
                "removing stale socket '{}' after failed connect probe: {error}",
                socket_path.display()
            );
            match fs::remove_file(socket_path) {
                Ok(()) => Ok(()),
                Err(remove_error) if remove_error.kind() == io::ErrorKind::NotFound => Ok(()),
                Err(remove_error) => Err(remove_error),
            }
        }
        Err(error) => Err(error),
    }
}

pub(crate) fn remove_socket_file_if_identity_matches(
    socket_path: &Path,
    expected_identity: SocketFileIdentity,
) -> io::Result<bool> {
    let metadata = match owned_socket_metadata(socket_path, io::ErrorKind::PermissionDenied) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
        Err(error) => return Err(error),
    };

    if identity_from_metadata(&metadata) != expected_identity {
        return Ok(false);
    }

    match fs::remove_file(socket_path) {
        Ok(()) => Ok(true),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error),
    }
}

fn remove_rebindable_socket(
    socket_path: &Path,
    current_identity: Option<SocketFileIdentity>,
) -> io::Result<()> {
    let metadata = match owned_socket_metadata(socket_path, io::ErrorKind::AlreadyExists) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error),
    };

    if current_identity.is_some_and(|identity| identity == identity_from_metadata(&metadata)) {
        return remove_file_if_present(socket_path);
    }

    remove_stale_socket_if_needed(socket_path)
}

fn owned_socket_metadata(
    socket_path: &Path,
    wrong_type_kind: io::ErrorKind,
) -> io::Result<fs::Metadata> {
    let metadata = socket_metadata(socket_path, wrong_type_kind)?;
    ensure_socket_owner(&metadata, socket_path)?;
    Ok(metadata)
}

fn socket_metadata(socket_path: &Path, wrong_type_kind: io::ErrorKind) -> io::Result<fs::Metadata> {
    let metadata = fs::symlink_metadata(socket_path)?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_socket() {
        return Err(io::Error::new(
            wrong_type_kind,
            format!(
                "socket path '{}' is not a plain Unix socket",
                socket_path.display()
            ),
        ));
    }
    Ok(metadata)
}

fn ensure_socket_owner(metadata: &fs::Metadata, socket_path: &Path) -> io::Result<()> {
    let user_id = real_user_id()?;
    if metadata.uid() != user_id {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!("socket {} has unsafe ownership", socket_path.display()),
        ));
    }
    Ok(())
}

fn identity_from_metadata(metadata: &fs::Metadata) -> SocketFileIdentity {
    SocketFileIdentity {
        device: metadata.dev(),
        inode: metadata.ino(),
    }
}

fn remove_file_if_present(socket_path: &Path) -> io::Result<()> {
    match fs::remove_file(socket_path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

pub(crate) fn indicates_stale_socket(error: &io::Error) -> bool {
    matches!(
        error.kind(),
        io::ErrorKind::ConnectionRefused | io::ErrorKind::NotFound
    )
}

pub(crate) fn real_user_id() -> io::Result<u32> {
    Ok(rmux_os::identity::real_user_id())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::net::{UnixListener as StdUnixListener, UnixStream};
    use std::sync::atomic::{AtomicUsize, Ordering};

    static UNIQUE_ID: AtomicUsize = AtomicUsize::new(0);

    #[test]
    fn sigusr1_rebind_refuses_a_live_foreign_socket() {
        let socket_path = unique_socket_path("live-foreign-rebind");
        let parent = socket_path.parent().expect("socket parent");
        fs::create_dir_all(parent).expect("create socket parent");
        let foreign = StdUnixListener::bind(&socket_path).expect("bind foreign socket");

        let error =
            match rebind_unix_listener_at(&socket_path, None, UnixTransportAccess::OwnerOnly) {
                Ok(_) => panic!("live foreign socket must not be unlinked"),
                Err(error) => error,
            };

        assert_eq!(error.kind(), io::ErrorKind::AddrInUse);
        assert!(
            UnixStream::connect(&socket_path).is_ok(),
            "foreign socket must remain connectable"
        );
        drop(foreign);
        cleanup_socket_dir(&socket_path);
    }

    #[tokio::test]
    async fn socket_cleanup_identity_does_not_remove_recreated_foreign_socket() {
        let socket_path = unique_socket_path("foreign-cleanup");
        let bound = bind_unix_listener_at(&socket_path).expect("bind first socket");
        remove_file_if_present(&socket_path).expect("unlink first socket path");
        let foreign = StdUnixListener::bind(&socket_path).expect("bind foreign replacement");

        let removed = remove_socket_file_if_identity_matches(
            &socket_path,
            bound.identity.expect("filesystem socket identity"),
        )
        .expect("identity guarded cleanup");

        assert!(!removed, "cleanup must not remove a different socket inode");
        assert!(
            UnixStream::connect(&socket_path).is_ok(),
            "foreign socket must remain connectable"
        );
        drop(foreign);
        drop(bound.listener);
        cleanup_socket_dir(&socket_path);
    }

    #[tokio::test]
    async fn sigusr1_rebind_can_replace_the_current_socket_identity() {
        let socket_path = unique_socket_path("current-rebind");
        let bound = bind_unix_listener_at(&socket_path).expect("bind first socket");

        let rebound =
            rebind_unix_listener_at(&socket_path, bound.identity, UnixTransportAccess::OwnerOnly)
                .expect("rebind current socket");

        assert!(UnixStream::connect(&socket_path).is_ok());
        drop(rebound.listener);
        drop(bound.listener);
        cleanup_socket_dir(&socket_path);
    }

    fn unique_socket_path(label: &str) -> PathBuf {
        let unique_id = UNIQUE_ID.fetch_add(1, Ordering::Relaxed);
        PathBuf::from(format!(
            "/tmp/rmx{}{}{}",
            std::process::id(),
            label.as_bytes()[0],
            unique_id
        ))
        .join("s")
    }

    fn cleanup_socket_dir(socket_path: &Path) {
        let _ = fs::remove_file(socket_path);
        if let Some(parent) = socket_path.parent() {
            let _ = fs::remove_dir_all(parent);
        }
    }
}