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
// Copyright (c) 2009 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::{closefrom, fdforkpty::fdforkpty};
use crate::libc::{
    AF_UNIX, O_RDWR, PF_UNSPEC, SHUT_WR, SIG_BLOCK, SIG_SETMASK, SIGCONT, SIGTERM, SIGTTIN,
    SIGTTOU, SOCK_STREAM, STDERR_FILENO, STDIN_FILENO, STDOUT_FILENO, TIOCSWINSZ, WIFSTOPPED,
    WSTOPSIG, chdir, close, dup2, execl, execvp, fork, ioctl, kill, killpg, memset, open, setenv,
    shutdown, sigfillset, sigprocmask, sigset_t, socketpair, winsize,
};
use crate::*;
use crate::options_::{options, options_get_string_};

pub type job_update_cb = Option<unsafe fn(*mut job)>;
pub type job_complete_cb = Option<unsafe fn(*mut job)>;
pub type job_free_cb = Option<unsafe fn(*mut c_void)>;

#[derive(Default, Eq, PartialEq)]
#[repr(i32)]
pub enum job_state {
    #[default]
    JOB_RUNNING = 0,
    JOB_DEAD = 1,
    JOB_CLOSED = 2,
}

#[repr(C)]
#[derive(Default)]
pub struct job {
    pub state: job_state,

    pub flags: job_flag,

    pub cmd: *mut u8,
    pub pid: pid_t,
    pub tty: [u8; TTY_NAME_MAX],
    pub status: i32,

    pub fd: c_int,
    pub event: *mut bufferevent,

    pub updatecb: job_update_cb,
    pub completecb: job_complete_cb,
    pub freecb: job_free_cb,
    pub data: *mut c_void,

    pub entry: list_entry<job>,
}
impl ListEntry<job, ()> for job {
    unsafe fn field(this: *mut Self) -> *mut list_entry<job> {
        unsafe { &raw mut (*this).entry }
    }
}

type joblist = list_head<job>;
static mut ALL_JOBS: joblist = list_head_initializer();

/// C `vendor/tmux/job.c:72`: `struct job *job_run(const char *cmd, int argc, char **argv, struct environ *e, struct session *s, const char *cwd, job_update_cb updatecb, job_complete_cb completecb, job_free_cb freecb, void *data, int flags, int sx, int sy)`
pub unsafe fn job_run(
    cmd: *const u8,
    argc: c_int,
    argv: *mut *mut u8,
    e: *mut environ,
    s: *mut session,
    cwd: *const u8,
    updatecb: job_update_cb,
    completecb: job_complete_cb,
    freecb: job_free_cb,
    data: *mut c_void,
    flags: job_flag,
    sx: c_int,
    sy: c_int,
) -> *mut job {
    let __func__ = "job_run";
    unsafe {
        let job: *mut job;
        let env: *mut environ;
        let pid: pid_t;
        let nullfd: i32;
        let mut out: [i32; 2] = [0; 2];
        let mut master: i32 = 0;
        let mut shell: *const u8;
        let mut set = MaybeUninit::<sigset_t>::uninit();
        let mut oldset = MaybeUninit::<sigset_t>::uninit();
        let mut ws = MaybeUninit::<winsize>::uninit();
        // Copied argv for the child's execvp; allocated in the parent before
        // fork and freed in the parent afterwards (null when cmd is set).
        let mut argvp: *mut *mut u8 = null_mut();
        // let mut tty = MaybeUninit::<[c_char; TTY_NAME_MAX]>::uninit();
        let mut tty = [0i8; 64];
        let argv0: *mut u8;
        let oo: *mut options;

        'fail: {
            env = environ_for_session(s, !CFG_FINISHED.load(atomic::Ordering::Acquire) as i32);
            if !e.is_null() {
                environ_copy(e, env);
            }

            if !flags.intersects(job_flag::JOB_DEFAULTSHELL) {
                shell = _PATH_BSHELL;
            } else {
                if !s.is_null() {
                    oo = (*s).options;
                } else {
                    oo = GLOBAL_S_OPTIONS;
                }
                shell = options_get_string_(oo, "default-shell");
                if !checkshell_(shell) {
                    shell = _PATH_BSHELL;
                }
            }
            argv0 = shell_argv0(shell, 0);

            // Resolve everything the forked child needs *before* fork, so the
            // child only calls async-signal-safe libc functions before exec.
            // find_home() reads $HOME under std's ENV_LOCK (not fork-safe) and
            // cmd_copy_argv allocates; doing both here keeps the child clean.
            let home: *const u8 = find_home().map_or(null(), |h| h.as_ptr().cast());
            if cmd.is_null() {
                argvp = cmd_copy_argv(argc, argv);
            }

            sigfillset(set.as_mut_ptr());
            sigprocmask(SIG_BLOCK, set.as_mut_ptr(), oldset.as_mut_ptr());

            if flags.intersects(job_flag::JOB_PTY) {
                memset(ws.as_mut_ptr().cast(), 0, size_of::<winsize>());
                (*ws.as_mut_ptr()).ws_col = sx as u16;
                (*ws.as_mut_ptr()).ws_row = sy as u16;
                pid = fdforkpty(
                    PTM_FD,
                    &raw mut master,
                    (&raw mut tty) as *mut u8,
                    null_mut(),
                    ws.as_mut_ptr(),
                );
            } else {
                if socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, &raw mut out as *mut c_int) != 0 {
                    break 'fail;
                }
                pid = fork();
            }

            if cmd.is_null() {
                cmd_log_argv!(argc, argv, "{__func__}");
                log_debug!(
                    "{} cwd={} shell={}",
                    __func__,
                    _s(if cwd.is_null() { c!("") } else { cwd }),
                    _s(shell),
                );
            } else {
                log_debug!(
                    "{} cmd={} cwd={} shell={}",
                    __func__,
                    _s(cmd),
                    _s(if cwd.is_null() { c!("") } else { cwd }),
                    _s(shell),
                );
            }

            match pid {
                -1 => {
                    if !flags.intersects(job_flag::JOB_PTY) {
                        close(out[0]);
                        close(out[1]);
                    }
                    break 'fail;
                }
                0 => {
                    proc_clear_signals(SERVER_PROC, 1);
                    sigprocmask(SIG_SETMASK, oldset.as_mut_ptr(), null_mut());

                    // Async-signal-safe chdir only: libc chdir, not
                    // std::env::set_current_dir (which allocates a CString). The
                    // home path was resolved in the parent above.
                    if (cwd.is_null() || chdir(cwd.cast()) != 0)
                        && (home.is_null() || chdir(home.cast()) != 0)
                        && chdir(c!("/").cast()) != 0
                    {
                        fatal("chdir failed");
                    }

                    // environ_push uses libc setenv; do not environ_free() here -
                    // the child is about to exec, so freeing the tree would be a
                    // pointless (and non-fork-safe) run of free() calls. The
                    // parent frees env after fork.
                    environ_push(env);

                    if !flags.intersects(job_flag::JOB_PTY) {
                        if dup2(out[1], STDIN_FILENO) == -1 {
                            fatal("dup2 failed");
                        }
                        if dup2(out[1], STDOUT_FILENO) == -1 {
                            fatal("dup2 failed");
                        }
                        if out[1] != STDIN_FILENO && out[1] != STDOUT_FILENO {
                            close(out[1]);
                        }
                        close(out[0]);

                        nullfd = open(_PATH_DEVNULL, O_RDWR, 0);
                        if nullfd == -1 {
                            fatal("open failed");
                        }
                        if dup2(nullfd, STDERR_FILENO) == -1 {
                            fatal("dup2 failed");
                        }
                        if nullfd != STDERR_FILENO {
                            close(nullfd);
                        }
                    }
                    closefrom(STDERR_FILENO + 1);

                    if !cmd.is_null() {
                        setenv(c!("SHELL").cast(), shell.cast(), 1);
                        execl(
                            shell.cast(),
                            argv0.cast(),
                            c!("-c"),
                            cmd,
                            null_mut::<c_void>(),
                        );
                        fatal("execl failed");
                    } else {
                        // argvp was copied in the parent (see above).
                        execvp((*argvp).cast(), argvp.cast());
                        fatal("execvp failed");
                    }
                }
                _ => (),
            }

            sigprocmask(SIG_SETMASK, oldset.as_ptr(), null_mut());
            environ_free(env);
            free_(argv0);
            if !argvp.is_null() {
                cmd_free_argv(argc, argvp);
            }

            job = Box::leak(Box::new(job {
                state: job_state::JOB_RUNNING,
                flags,
                cmd: if !cmd.is_null() {
                    xstrdup(cmd).as_ptr()
                } else {
                    CString::new(cmd_stringify_argv(argc, argv))
                        .unwrap()
                        .into_raw()
                        .cast()
                },
                pid,
                status: 0,
                ..Default::default()
            }));

            strlcpy((*job).tty.as_mut_ptr(), tty.as_ptr().cast(), TTY_NAME_MAX);

            list_insert_head(&raw mut ALL_JOBS, job);

            (*job).updatecb = updatecb;
            (*job).completecb = completecb;
            (*job).freecb = freecb;
            (*job).data = data;

            if !flags.intersects(job_flag::JOB_PTY) {
                close(out[1]);
                (*job).fd = out[0];
            } else {
                (*job).fd = master;
            }
            setblocking((*job).fd, 0);

            (*job).event = bufferevent_new(
                (*job).fd,
                Some(job_read_callback),
                Some(job_write_callback),
                Some(job_error_callback),
                job as *mut c_void,
            );
            if (*job).event.is_null() {
                fatalx("out of memory");
            }
            bufferevent_enable((*job).event, EV_READ | EV_WRITE);

            log_debug!("run job {:p}: {} pid {}", job, _s((*job).cmd), (*job).pid);
            return job;
        }

        sigprocmask(SIG_SETMASK, oldset.as_ptr(), null_mut());
        environ_free(env);
        free_(argv0);
        if !argvp.is_null() {
            cmd_free_argv(argc, argvp);
        }
        null_mut()
    }
}

/// C `vendor/tmux/job.c:243`: `int job_transfer(struct job *job, pid_t *pid, char *tty, size_t ttylen)`
pub unsafe fn job_transfer(job: *mut job, pid: *mut pid_t, tty: *mut u8, ttylen: usize) -> c_int {
    unsafe {
        let fd = (*job).fd;

        log_debug!("transfer job {:p}: {}", job, _s((*job).cmd));

        if !pid.is_null() {
            *pid = (*job).pid;
        }
        if !tty.is_null() {
            strlcpy(tty, ((*job).tty).as_mut_ptr(), ttylen);
        }

        list_remove(job);
        free_((*job).cmd);

        if let Some(freecb) = (*job).freecb
            && !(*job).data.is_null()
        {
            freecb((*job).data);
        }

        if !(*job).event.is_null() {
            bufferevent_free((*job).event);
        }

        free_(job);
        fd
    }
}

/// C `vendor/tmux/job.c:269`: `void job_free(struct job *job)`
pub unsafe fn job_free(job: *mut job) {
    unsafe {
        log_debug!("free job {:p}: {}", job, _s((*job).cmd));

        list_remove(job);
        free_((*job).cmd);

        if let Some(freecb) = (*job).freecb
            && !((*job).data).is_null()
        {
            freecb((*job).data);
        }
        if (*job).pid != -1 {
            kill((*job).pid, SIGTERM);
        }
        if !((*job).event).is_null() {
            bufferevent_free((*job).event);
        }
        if (*job).fd != -1 {
            close((*job).fd);
        }
        free_(job);
    }
}

/// C `vendor/tmux/job.c:291`: `void job_resize(struct job *job, u_int sx, u_int sy)`
pub unsafe fn job_resize(job: *mut job, sx: c_uint, sy: c_uint) {
    let mut ws = MaybeUninit::<winsize>::uninit();

    unsafe {
        let ws = ws.as_mut_ptr();
        if (*job).fd == -1 || !(*job).flags.intersects(job_flag::JOB_PTY) {
            return;
        }
        log_debug!("resize job {:p}: {}x{}", job, sx, sy);
        (*ws).ws_col = sx as u16;
        (*ws).ws_row = sy as u16;

        if ioctl((*job).fd, TIOCSWINSZ, ws) == -1 {
            fatal("ioctl failed");
        }
    }
}

/// C `vendor/tmux/job.c:309`: `static void job_read_callback(__unused struct bufferevent *bufev, void *data)`
unsafe extern "C-unwind" fn job_read_callback(_bufev: *mut bufferevent, data: *mut c_void) {
    let job = data as *mut job;

    unsafe {
        if let Some(updatecb) = (*job).updatecb {
            updatecb(job);
        }
    }
}
/// C `vendor/tmux/job.c:323`: `static void job_write_callback(__unused struct bufferevent *bufev, void *data)`
unsafe extern "C-unwind" fn job_write_callback(_bufev: *mut bufferevent, data: *mut c_void) {
    unsafe {
        let job = data as *mut job;
        let len = EVBUFFER_LENGTH(EVBUFFER_OUTPUT((*job).event));

        log_debug!(
            "job write {:p}: {}, pid {}, output left {}",
            job,
            _s((*job).cmd),
            (*job).pid,
            len,
        );

        if len == 0 && !(*job).flags.intersects(job_flag::JOB_KEEPWRITE) {
            shutdown((*job).fd, SHUT_WR);
            bufferevent_disable((*job).event, EV_WRITE);
        }
    }
}

/// C `vendor/tmux/job.c:339`: `static void job_error_callback(__unused struct bufferevent *bufev, __unused short events, void *data)`
unsafe extern "C-unwind" fn job_error_callback(
    _bufev: *mut bufferevent,
    _events: libc::c_short,
    data: *mut c_void,
) {
    let job: *mut job = data.cast();

    unsafe {
        log_debug!(
            "job error {:p}: {}, pid {}",
            job,
            _s((*job).cmd),
            (*job).pid
        );
        if (*job).state == job_state::JOB_DEAD {
            if let Some(completecb) = (*job).completecb {
                completecb(job);
            }
            job_free(job);
        } else {
            bufferevent_disable((*job).event, EV_READ);
            (*job).state = job_state::JOB_CLOSED;
        }
    }
}

/// C `vendor/tmux/job.c:358`: `void job_check_died(pid_t pid, int status)`
pub unsafe fn job_check_died(pid: pid_t, status: i32) {
    unsafe {
        let Some(job) = list_foreach(&raw mut ALL_JOBS).find(|job| pid == (*job.as_ptr()).pid)
        else {
            return;
        };
        let job = job.as_ptr();

        if WIFSTOPPED(status) {
            if WSTOPSIG(status) == SIGTTIN || WSTOPSIG(status) == SIGTTOU {
                return;
            }
            killpg((*job).pid, SIGCONT);
            return;
        }
        log_debug!(
            "job died {:p}: {} pid {}",
            job,
            _s((*job).cmd),
            (*job).pid as c_long
        );

        (*job).status = status;

        if (*job).state == job_state::JOB_CLOSED {
            if let Some(completecb) = (*job).completecb {
                completecb(job);
            }
            job_free(job);
        } else {
            (*job).pid = -1;
            (*job).state = job_state::JOB_DEAD;
        }
    }
}

/// C `vendor/tmux/job.c:390`: `int job_get_status(struct job *job)`
pub unsafe fn job_get_status(job: *mut job) -> i32 {
    unsafe { (*job).status }
}

/// C `vendor/tmux/job.c:397`: `void *job_get_data(struct job *job)`
pub unsafe fn job_get_data(job: *mut job) -> *mut c_void {
    unsafe { (*job).data }
}

/// C `vendor/tmux/job.c:404`: `struct bufferevent *job_get_event(struct job *job)`
pub unsafe fn job_get_event(job: *mut job) -> *mut bufferevent {
    unsafe { (*job).event }
}

/// C `vendor/tmux/job.c:411`: `void job_kill_all(void)`
pub unsafe fn job_kill_all() {
    unsafe {
        for job in list_foreach(&raw mut ALL_JOBS).map(NonNull::as_ptr) {
            if (*job).pid != -1 {
                kill((*job).pid, SIGTERM);
            }
        }
    }
}

/// C `vendor/tmux/job.c:423`: `int job_still_running(void)`
pub unsafe fn job_still_running() -> bool {
    unsafe {
        list_foreach(&raw mut ALL_JOBS)
            .map(NonNull::as_ptr)
            .any(|job| {
                !(*job).flags.intersects(job_flag::JOB_NOWAIT)
                    && (*job).state == job_state::JOB_RUNNING
            })
    }
}

/// C `vendor/tmux/job.c:436`: `void job_print_summary(struct cmdq_item *item, int blank)`
pub unsafe fn job_print_summary(item: *mut cmdq_item, mut blank: i32) {
    unsafe {
        for (n, job) in list_foreach(&raw mut ALL_JOBS)
            .map(NonNull::as_ptr)
            .enumerate()
        {
            if blank != 0 {
                cmdq_print!(item, "");
                blank = 0;
            }
            cmdq_print!(
                item,
                "Job {}: {} [fd={}, pid={}, status={}]",
                n,
                _s((*job).cmd),
                (*job).fd,
                (*job).pid,
                (*job).status,
            );
        }
    }
}