ztmux 3.7.20

A Rust port of tmux — the full terminal multiplexer, server and client
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
// Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
// IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
// OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
use crate::compat::ACCESSPERMS;
use crate::libc::{
    AF_UNIX, ECHILD, ENAMETOOLONG, S_IRGRP, S_IROTH, S_IRUSR, S_IRWXG, S_IRWXO, S_IXGRP, S_IXOTH,
    S_IXUSR, SIG_BLOCK, SIG_SETMASK, SIGCONT, SIGTTIN, SIGTTOU, SOCK_STREAM, WIFEXITED,
    WIFSIGNALED, WIFSTOPPED, WNOHANG, WSTOPSIG, WUNTRACED, accept, bind, chmod, close,
    gettimeofday, kill, killpg, listen, sigfillset, sigprocmask, sigset_t, sockaddr_storage,
    sockaddr_un, socket, socklen_t, stat, strerror, strsignal, umask, unlink, waitpid,
};
use crate::*;
use crate::options_::*;

pub static mut CLIENTS: clients = unsafe { zeroed() };
pub static mut SERVER_PROC: *mut tmuxproc = null_mut();
pub static mut SERVER_FD: c_int = -1;
pub static mut SERVER_CLIENT_FLAGS: client_flag = client_flag::empty();
pub static mut SERVER_EXIT: c_int = 0;
pub static mut SERVER_EV_ACCEPT: event = unsafe { zeroed() };
pub static mut SERVER_EV_TIDY: event = unsafe { zeroed() };
pub static mut MARKED_PANE: cmd_find_state = unsafe { zeroed() };
pub static mut MESSAGE_NEXT: c_uint = 0;
pub static mut MESSAGE_LOG: message_list = unsafe { zeroed() };
pub static mut CURRENT_TIME: time_t = unsafe { zeroed() };

/// C `vendor/tmux/server.c:68`: `void server_set_marked(struct session *s, struct winlink *wl, struct window_pane *wp)`
pub unsafe fn server_set_marked(s: *mut session, wl: *mut winlink, wp: *mut window_pane) {
    unsafe {
        cmd_find_clear_state(&raw mut MARKED_PANE, cmd_find_flags::empty());
        MARKED_PANE.s = s;
        MARKED_PANE.wl = wl;
        MARKED_PANE.w = (*wl).window;
        MARKED_PANE.wp = wp;
    }
}

/// C `vendor/tmux/server.c:80`: `void server_clear_marked(void)`
pub unsafe fn server_clear_marked() {
    unsafe {
        cmd_find_clear_state(&raw mut MARKED_PANE, cmd_find_flags::empty());
    }
}

/// C `vendor/tmux/server.c:87`: `int server_is_marked(struct session *s, struct winlink *wl, struct window_pane *wp)`
pub unsafe fn server_is_marked(s: *mut session, wl: *mut winlink, wp: *mut window_pane) -> bool {
    if s.is_null() || wl.is_null() || wp.is_null() {
        return false;
    }

    unsafe {
        if MARKED_PANE.s != s || MARKED_PANE.wl != wl {
            return false;
        }
        if MARKED_PANE.wp != wp {
            return false;
        }
        server_check_marked()
    }
}

/// C `vendor/tmux/server.c:100`: `int server_check_marked(void)`
pub unsafe fn server_check_marked() -> bool {
    unsafe { cmd_find_valid_state(&raw mut MARKED_PANE) }
}

/// C `vendor/tmux/server.c:107`: `int server_create_socket(uint64_t flags, char **cause)`
pub unsafe fn server_create_socket(flags: client_flag, cause: *mut *mut u8) -> c_int {
    unsafe {
        'fail: {
            let mut sa: sockaddr_un = zeroed();
            sa.sun_family = AF_UNIX as _;
            let size = strlcpy(
                sa.sun_path.as_mut_ptr().cast(),
                SOCKET_PATH,
                size_of_val(&sa.sun_path),
            );
            if size >= size_of_val(&sa.sun_path) {
                errno!() = ENAMETOOLONG;
                break 'fail;
            }
            unlink(sa.sun_path.as_ptr().cast());

            let fd = socket(AF_UNIX, SOCK_STREAM, 0);
            if fd == -1 {
                break 'fail;
            }

            let mask = if flags.intersects(client_flag::DEFAULTSOCKET) {
                umask(S_IXUSR | S_IXGRP | S_IRWXO)
            } else {
                umask(S_IXUSR | S_IRWXG | S_IRWXO)
            };

            let saved_errno: c_int;
            if bind(fd, &raw const sa as _, size_of::<sockaddr_un>() as _) == -1 {
                saved_errno = errno!();
                close(fd);
                errno!() = saved_errno;
                break 'fail;
            }
            umask(mask);

            if listen(fd, 128) == -1 {
                saved_errno = errno!();
                close(fd);
                errno!() = saved_errno;
                break 'fail;
            }
            setblocking(fd, 0);

            return fd;
        }

        // fail:
        if !cause.is_null() {
            *cause = format_nul!(
                "error creating {} ({})",
                _s(SOCKET_PATH),
                strerror(errno!())
            );
        }
        -1
    }
}

/// Tidy up every hour.
/// C `vendor/tmux/server.c:158`: `static void server_tidy_event(__unused int fd, __unused short events, __unused void *data)`
unsafe extern "C-unwind" fn server_tidy_event(_fd: i32, _events: i16, _data: *mut c_void) {
    let tv = timeval {
        tv_sec: 3600,
        tv_usec: 0,
    };
    unsafe {
        let t = get_timer();

        format_tidy_jobs();

        #[cfg(not(target_os = "macos"))]
        {
            libc::malloc_trim(0);
        }

        log_debug!(
            "{}: took {} milliseconds",
            "server_tidy_event",
            get_timer() - t
        );
        event_add(&raw mut SERVER_EV_TIDY, &raw const tv);
    }
}

/// C `vendor/tmux/server.c:176`: `int server_start(struct tmuxproc *client, uint64_t flags, struct event_base *base, int lockfd, char *lockfile)`
pub unsafe fn server_start(
    client: *mut tmuxproc,
    flags: client_flag,
    base: *mut event_base,
    lockfd: c_int,
    lockfile: *mut u8,
) -> c_int {
    unsafe {
        let mut fd = 0;
        let mut set: sigset_t = zeroed();
        let mut oldset: sigset_t = zeroed();

        let mut c: *mut client = null_mut();
        let mut cause: *mut u8 = null_mut();
        let tv: timeval = timeval {
            tv_sec: 3600,
            tv_usec: 0,
        };

        sigfillset(&raw mut set);
        sigprocmask(SIG_BLOCK, &raw const set, &raw mut oldset);

        if !flags.intersects(client_flag::NOFORK) && proc_fork_and_daemon(&raw mut fd) != 0 {
            // in parent process i.e. client
            sigprocmask(SIG_SETMASK, &raw mut oldset, null_mut());
            return fd;
        }

        std::panic::set_hook(Box::new(|panic_info| {
            use std::fmt::Write;
            let backtrace = std::backtrace::Backtrace::force_capture();
            let location = panic_info.location();

            let mut err_str = String::new();

            if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
                _ = write!(&mut err_str, "panic! {s:?}\n{backtrace:#?}");
                log_debug!(
                    "panic{}: {s}",
                    location
                        .map(|loc| format!(" at {}:{}", loc.file(), loc.line()))
                        .unwrap_or_default()
                );
            } else if let Some(s) = panic_info.payload().downcast_ref::<String>() {
                _ = write!(&mut err_str, "panic! {s:?}\n{backtrace:#?}");
                log_debug!(
                    "panic{}: {s}",
                    location
                        .map(|loc| format!(" at {}:{}", loc.file(), loc.line()))
                        .unwrap_or_default()
                );
            }

            log_close();

            let panic_path = crate::extensions::diagnostics::dir()
                .join(format!("server-panic-{}.txt", std::process::id()));
            if let Err(err) = std::fs::write(&panic_path, err_str) {
                eprintln!("error in panic handler! {err}");
            }
        }));

        crate::extensions::diagnostics::install_crash_handlers();

        // now in child process i.e. server
        proc_clear_signals(client, 0);
        SERVER_CLIENT_FLAGS = flags;

        if event_reinit(base) != 0 {
            fatalx("event_reinit failed");
        }
        SERVER_PROC = proc_start(c"server");

        // proc_start has now opened the log; record that the crash diagnostics
        // (panic hook + fatal-signal handlers) are armed for this server.
        log_debug!(
            "{}: crash diagnostics armed (pid {}), logging to {}",
            "server_start",
            std::process::id(),
            crate::extensions::diagnostics::dir().display(),
        );

        proc_set_signals(SERVER_PROC, Some(server_signal));
        sigprocmask(SIG_SETMASK, &raw mut oldset, null_mut());

        if log_get_level() > 1 {
            tty_create_log();
        }

        // TODO pledge

        input_key_build();
        rb_init(&raw mut WINDOWS);
        rb_init(&raw mut ALL_WINDOW_PANES);
        tailq_init(&raw mut CLIENTS);
        rb_init(&raw mut SESSIONS);
        key_bindings_init();
        tailq_init(&raw mut MESSAGE_LOG);
        gettimeofday(&raw mut START_TIME, null_mut());

        if cfg!(feature = "systemd") {
            // TODO we could be truncating important bits
            SERVER_FD =
                crate::compat::systemd::systemd_create_socket(flags.bits() as i32, &raw mut cause);
        } else {
            SERVER_FD = server_create_socket(flags, &raw mut cause);
        }
        if SERVER_FD != -1 {
            server_update_socket();
        }
        if !flags.intersects(client_flag::NOFORK) {
            c = server_client_create(fd);
        } else {
            options_set_number(GLOBAL_OPTIONS, "exit-empty", 0);
        }

        if lockfd >= 0 {
            unlink(lockfile);
            free_(lockfile);
            close(lockfd);
        }

        if !cause.is_null() {
            if !c.is_null() {
                // Adopt the owned cause string.
                (*c).exit_message = Some(std::ffi::CString::from_raw(cause.cast()));
                (*c).flags |= client_flag::EXIT;
            } else {
                eprintln!("{}", _s(cause));
                libc::exit(1);
            }
        }

        evtimer_set_no_args(&raw mut SERVER_EV_TIDY, server_tidy_event);
        evtimer_add(&raw mut SERVER_EV_TIDY, &raw const tv);

        server_acl_init();

        server_add_accept(0);
        proc_loop(SERVER_PROC, Some(server_loop));

        // The event loop returned: the server is shutting down cleanly
        // (server_loop decided to exit, or proc_exit set the flag). Log why at
        // debug level - this is a normal exit, so it must NOT write a
        // server-crash file (those are reserved for actual faults: fatal/fatalx
        // and the SIGSEGV/SIGBUS/SIGABRT handler).
        let server_exit = (&raw const SERVER_EXIT).read();
        log_debug!("server event loop exited cleanly (SERVER_EXIT={})", server_exit);

        job_kill_all();
        status_prompt_save_history();

        libc::exit(0)
    }
}

/// C `vendor/tmux/server.c:264`: `static int server_loop(void)`
pub unsafe fn server_loop() -> i32 {
    unsafe {
        CURRENT_TIME = libc::time(null_mut());

        loop {
            let mut items = cmdq_next(null_mut());
            for c in tailq_foreach(&raw mut CLIENTS).map(NonNull::as_ptr) {
                if (*c).flags.intersects(client_flag::IDENTIFIED) {
                    items += cmdq_next(c);
                }
            }

            if items == 0 {
                break;
            }
        }

        server_client_loop();

        if options_get_number_(GLOBAL_OPTIONS, "exit-empty") == 0 && SERVER_EXIT == 0 {
            return 0;
        }

        if options_get_number_(GLOBAL_OPTIONS, "exit-unattached") == 0
            && !rb_empty(&raw mut SESSIONS)
        {
            return 0;
        }

        for c in tailq_foreach(&raw mut CLIENTS) {
            if !(*c.as_ptr()).session.is_null() {
                return 0;
            }
        }

        // No attached clients therefore want to exit - flush any waiting
        // clients but don't actually exit until they've gone.
        cmd_wait_for_flush();
        if !tailq_empty(&raw const CLIENTS) {
            return 0;
        }

        if job_still_running() {
            return 0;
        }

        // Returning non-zero here breaks proc_loop and shuts the server down.
        // Log why so an "unexpected" exit is traceable: no attached clients
        // remain and exit-empty/exit-unattached let us go.
        log_debug!(
            "{}: exiting - SERVER_EXIT={}, no attached clients, exit-empty={}, exit-unattached={}",
            "server_loop",
            (&raw const SERVER_EXIT).read(),
            options_get_number_(GLOBAL_OPTIONS, "exit-empty"),
            options_get_number_(GLOBAL_OPTIONS, "exit-unattached"),
        );

        1
    }
}

/// C `vendor/tmux/server.c:310`: `static void server_send_exit(void)`
unsafe fn server_send_exit() {
    unsafe {
        cmd_wait_for_flush();

        for c in tailq_foreach(&raw mut CLIENTS).map(NonNull::as_ptr) {
            if (*c).flags.intersects(client_flag::SUSPENDED) {
                server_client_lost(c);
            } else {
                (*c).flags |= client_flag::EXIT;
                (*c).exit_type = exit_type::CLIENT_EXIT_SHUTDOWN;
            }
            (*c).session = null_mut();
        }

        for s in rb_foreach(&raw mut SESSIONS).map(NonNull::as_ptr) {
            session_destroy(s, 1, c!("server_send_exit"));
        }
    }
}

/// C `vendor/tmux/server.c:333`: `void server_update_socket(void)`
pub unsafe fn server_update_socket() {
    static mut LAST: c_int = -1;
    unsafe {
        let mut sb: stat = zeroed(); // TODO remove unecessary init

        let mut n = 0;
        for s in rb_foreach(&raw mut SESSIONS).map(std::ptr::NonNull::as_ptr) {
            if (*s).attached != 0 {
                n += 1;
                break;
            }
        }

        if n != LAST {
            LAST = n;

            if stat(SOCKET_PATH.cast(), &raw mut sb) != 0 {
                return;
            }
            let mut mode = sb.st_mode & ACCESSPERMS;
            if n != 0 {
                if mode & S_IRUSR != 0 {
                    mode |= S_IXUSR;
                }
                if mode & S_IRGRP != 0 {
                    mode |= S_IXGRP;
                }
                if mode & S_IROTH != 0 {
                    mode |= S_IXOTH;
                }
            } else {
                mode &= !(S_IXUSR | S_IXGRP | S_IXOTH);
            }
            chmod(SOCKET_PATH.cast(), mode);
        }
    }
}

/// C `vendor/tmux/server.c:369`: `static void server_accept(int fd, short events, __unused void *data)`
unsafe extern "C-unwind" fn server_accept(fd: i32, events: i16, _data: *mut c_void) {
    unsafe {
        let mut sa: sockaddr_storage = zeroed(); // TODO remove this init
        let mut slen: socklen_t = size_of::<sockaddr_storage>() as socklen_t;

        server_add_accept(0);
        if events & EV_READ == 0 {
            return;
        }

        let newfd = accept(fd, &raw mut sa as _, &raw mut slen);
        if newfd == -1 {
            match errno!() {
                libc::EAGAIN | libc::EINTR | libc::ECONNABORTED => return,
                libc::ENFILE | libc::EMFILE => {
                    // Delete and don't try again for 1 second.
                    server_add_accept(1);
                    return;
                }
                _ => fatal("accept failed"),
            }
        }

        if SERVER_EXIT != 0 {
            close(newfd);
            return;
        }
        let c = server_client_create(newfd);
        if server_acl_join(c) == 0 {
            (*c).exit_message = Some(c"access not allowed".to_owned());
            (*c).flags |= client_flag::EXIT;
        }
    }
}

/// C `vendor/tmux/server.c:408`: `void server_add_accept(int timeout)`
pub unsafe fn server_add_accept(timeout: c_int) {
    unsafe {
        let mut tv = timeval {
            tv_sec: timeout as i64,
            tv_usec: 0,
        };

        if SERVER_FD == -1 {
            return;
        }

        if event_initialized(&raw mut SERVER_EV_ACCEPT) != 0 {
            event_del(&raw mut SERVER_EV_ACCEPT);
        }

        if timeout == 0 {
            event_set(
                &raw mut SERVER_EV_ACCEPT,
                SERVER_FD,
                EV_READ,
                Some(server_accept),
                null_mut(),
            );
            event_add(&raw mut SERVER_EV_ACCEPT, null_mut());
        } else {
            event_set(
                &raw mut SERVER_EV_ACCEPT,
                SERVER_FD,
                EV_TIMEOUT,
                Some(server_accept),
                null_mut(),
            );
            event_add(&raw mut SERVER_EV_ACCEPT, &raw mut tv);
        }
    }
}

/// Signal handler.
/// C `vendor/tmux/server.c:431`: `static void server_signal(int sig)`
unsafe fn server_signal(sig: i32) {
    unsafe {
        log_debug!("{}: {}", "server_signal", _s(strsignal(sig).cast::<u8>()));
        match sig {
            libc::SIGINT | libc::SIGTERM => {
                SERVER_EXIT = 1;
                server_send_exit();
            }
            libc::SIGCHLD => server_child_signal(),
            libc::SIGUSR1 => {
                event_del(&raw mut SERVER_EV_ACCEPT);
                let fd = server_create_socket(SERVER_CLIENT_FLAGS, null_mut());
                if fd != -1 {
                    close(SERVER_FD);
                    SERVER_FD = fd;
                    server_update_socket();
                }
                server_add_accept(0);
            }
            libc::SIGUSR2 => proc_toggle_log(SERVER_PROC),
            _ => {
                // nop
            }
        }
    }
}

// handle SIGCHLD

/// C `vendor/tmux/server.c:463`: `static void server_child_signal(void)`
unsafe fn server_child_signal() {
    let mut status = 0i32;
    unsafe {
        loop {
            let pid: pid_t = waitpid(
                crate::compat::WAIT_ANY,
                &raw mut status,
                WNOHANG | WUNTRACED,
            );
            match pid {
                -1 => {
                    if errno!() == ECHILD {
                        return;
                    }
                    fatal("waitpid failed");
                }
                0 => return,
                _ => {
                    if WIFSTOPPED(status) {
                        server_child_stopped(pid, status);
                    } else if WIFEXITED(status) || WIFSIGNALED(status) {
                        server_child_exited(pid, status);
                    }
                }
            }
        }
    }
}

/// C `vendor/tmux/server.c:486`: `static void server_child_exited(pid_t pid, int status)`
unsafe fn server_child_exited(pid: pid_t, status: i32) {
    unsafe {
        for w in rb_foreach(&raw mut WINDOWS).map(NonNull::as_ptr) {
            for wp in tailq_foreach::<_, discr_entry>(&raw mut (*w).panes).map(NonNull::as_ptr) {
                if (*wp).pid == pid {
                    (*wp).status = status;
                    (*wp).flags |= window_pane_flags::PANE_STATUSREADY;

                    log_debug!("%%{} exited", (*wp).id);
                    (*wp).flags |= window_pane_flags::PANE_EXITED;

                    if window_pane_destroy_ready(wp) {
                        server_destroy_pane(wp, 1);
                    }
                    break;
                }
            }
        }
        job_check_died(pid, status);
    }
}

/// C `vendor/tmux/server.c:514`: `static void server_child_stopped(pid_t pid, int status)`
unsafe fn server_child_stopped(pid: pid_t, status: i32) {
    unsafe {
        if WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU {
            return;
        }

        for w in rb_foreach(&raw mut WINDOWS).map(NonNull::as_ptr) {
            for wp in tailq_foreach::<_, discr_entry>(&raw mut (*w).panes).map(NonNull::as_ptr) {
                if (*wp).pid == pid && killpg(pid, SIGCONT) != 0 {
                    kill(pid, SIGCONT);
                }
            }
        }
        job_check_died(pid, status);
    }
}

macro_rules! server_add_message {
   ($fmt:literal $(, $args:expr)* $(,)?) => {
        crate::server::server_add_message_(format_args!($fmt $(, $args)*))
    };
}
pub(crate) use server_add_message;
pub unsafe fn server_add_message_(args: std::fmt::Arguments) {
    unsafe {
        let text = crate::cstring_truncating(args.to_string());

        log_debug!("message: {}", _s(text.as_ptr().cast::<u8>()));

        let mut msg_time = std::mem::zeroed();
        gettimeofday(&raw mut msg_time, null_mut());
        MESSAGE_NEXT += 1;
        let msg = Box::into_raw(Box::new(message_entry {
            msg: text,
            msg_num: MESSAGE_NEXT,
            msg_time,
            entry: std::mem::zeroed(),
        }));

        tailq_insert_tail(&raw mut MESSAGE_LOG, msg);

        let limit = options_get_number_(GLOBAL_OPTIONS, "message-limit") as u32;
        for msg in tailq_foreach(&raw mut MESSAGE_LOG).map(NonNull::as_ptr) {
            if (*msg).msg_num + limit >= MESSAGE_NEXT {
                continue;
            }
            tailq_remove(&raw mut MESSAGE_LOG, msg);
            // Reclaim the boxed entry; its owned `msg` CString drops with it.
            drop(Box::from_raw(msg));
        }
    }
}