This is an automated email from the git hooks/post-receive script.
git pushed a commit to branch master
in repository terminology.
View the commit online.
commit 0b73c62994e74cda67644d0431cb6872a7970adc
Author: [email protected] <[email protected]>
AuthorDate: Fri Sep 25 17:23:34 2026 -0600
tymux: add a command line client
tymux creates, lists, attaches to and kills sessions from any terminal,
over ssh included. Attaching runs an inline proxy: it copies each frame
out of shared memory and redraws in the outer terminal only the cells
that changed since the previous one. Ctrl+b d detaches, as in tmux.
Like the rest of Terminology it runs on the Ecore main loop and builds
its output in an Eina_Strbuf. Ecore has no SIGWINCH event, so the
signal handler only wakes the loop through a pipe. It does not load
Ecore's system modules: a proxy has no use for their power and locale
events, and they would open a D-Bus connection on every attach.
tests/tymux.py drives tymux and tymuxd through pseudo terminals: new,
detach, list, attach again, hijack with pause and resume, shared and
read-only clients, resize, wide characters, true colour and kill. It
also checks that a client which stops reading, or stalls in the middle
of a message, neither blocks the daemon nor makes it spin.
Not supported yet: the input modes set by the application (application
cursor keys, mouse reporting, bracketed paste) are not forwarded to the
outer terminal, there is no scrollback, and only the primary client can
resize the session.
---
DESIGN.md | 1 +
meson.build | 5 +
src/bin/meson.build | 5 +
src/bin/tymux.c | 877 ++++++++++++++++++++++++++++++++++++++++++++++++++++
tests/meson.build | 9 +
tests/tymux.py | 340 ++++++++++++++++++++
6 files changed, 1237 insertions(+)
diff --git a/DESIGN.md b/DESIGN.md
index d6f38d1f..90a71c35 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -42,6 +42,7 @@ A simple documentation to navigate through the C files:
* `src/bin/tybg.c`: the `tybg` tool
* `src/bin/tycat.c`: the `tycat` tool
* `src/bin/tyls.c`: the `tyls` tool
+* `src/bin/tymux.c`: the `tymux` tool, a command line client to attach to a `tymuxd`
* `src/bin/tymuxd.c`: the `tymuxd` daemon, keeps a terminal running in the background
* `src/bin/tymuxd_stubs.c`: stands in for the `termio` functions `tymuxd` has no widget for
* `src/bin/typop.c`: the `typop` tool
diff --git a/meson.build b/meson.build
index b41222a5..2bafc5f2 100644
--- a/meson.build
+++ b/meson.build
@@ -91,6 +91,11 @@ foreach efl_dep: efl_deps
if efl_dep == 'evas'
evas_dep = dep
endif
+ # kept aside for tymux and tybenchd, which link Eina and Ecore only, not
+ # the rest of EFL.
+ if efl_dep == 'ecore'
+ ecore_dep = dep
+ endif
endforeach
if cc.has_function('evas_object_textgrid_ligatures_set', dependencies: evas_dep)
diff --git a/src/bin/meson.build b/src/bin/meson.build
index ecf436fa..93c9763a 100644
--- a/src/bin/meson.build
+++ b/src/bin/meson.build
@@ -232,6 +232,11 @@ if host_os == 'linux'
install: true,
include_directories: config_dir,
dependencies: terminology_dependencies)
+ tymux = executable('tymux',
+ ['tymux.c', 'termsrv.c', 'termsrv.h'],
+ install: true,
+ include_directories: config_dir,
+ dependencies: [eina_dep, ecore_dep])
endif
if fuzzing
diff --git a/src/bin/tymux.c b/src/bin/tymux.c
new file mode 100644
index 00000000..9f08eb95
--- /dev/null
+++ b/src/bin/tymux.c
@@ -0,0 +1,877 @@
+#include "private.h"
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <termios.h>
+#include <time.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <Eina.h>
+#include <Ecore.h>
+#include "termsrv.h"
+
+/* Ctrl+b d, as in tmux */
+#define DETACH_PREFIX 0x02
+#define DETACH_KEY 'd'
+
+typedef struct
+{
+ int sock;
+ const TermSrvShmHeader *shm;
+ /* copy of the screen being drawn, and of the last one drawn to only
+ * send what changed, each with room for cells_cap cells */
+ TermSrvCell *cur, *prev;
+ size_t cells_cap;
+ bool prev_valid;
+ uint32_t prev_cols, prev_rows;
+ bool prefix_pending;
+ bool paused;
+ bool running;
+ TermSrvReader reader;
+ int exit_code;
+ Ecore_Fd_Handler *fdh_stdin, *fdh_sock, *fdh_winch;
+ Ecore_Event_Handler *eh_exit, *eh_hup;
+ int winch_pipe[2];
+} Proxy;
+
+/* The attributes the terminal draws with */
+typedef struct
+{
+ TermSrvAtt att;
+ bool valid;
+} Pen;
+
+static struct termios _orig_termios;
+static bool _raw_mode = false;
+/* the only fd handler allowed to touch: SIGWINCH has no Ecore event, so its
+ * handler only wakes the main loop through this self-pipe */
+static int _winch_pipe_write_fd = -1;
+
+static void
+_raw_mode_enter(void)
+{
+ struct termios t;
+
+ if (tcgetattr(STDIN_FILENO, &_orig_termios) < 0)
+ return;
+ t = _orig_termios;
+ cfmakeraw(&t);
+ if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &t) == 0)
+ _raw_mode = true;
+}
+
+static void
+_raw_mode_leave(void)
+{
+ if (!_raw_mode)
+ return;
+ tcsetattr(STDIN_FILENO, TCSAFLUSH, &_orig_termios);
+ _raw_mode = false;
+}
+
+/* async-signal-safe: only writes one byte to the self-pipe an Ecore_Fd_Handler
+ * watches, to have the resize handled from the main loop like everything
+ * else. */
+static void
+_cb_sigwinch(int sig __attribute__((unused)))
+{
+ if (_winch_pipe_write_fd >= 0)
+ (void)!write(_winch_pipe_write_fd, "", 1);
+}
+
+static void
+_write_all(const char *buf, size_t len)
+{
+ while (len > 0)
+ {
+ ssize_t n = write(STDOUT_FILENO, buf, len);
+
+ if (n < 0)
+ {
+ if (errno == EINTR)
+ continue;
+ return;
+ }
+ buf += n;
+ len -= (size_t)n;
+ }
+}
+
+static void
+_write_str(const char *s)
+{
+ _write_all(s, strlen(s));
+}
+
+static void
+_out_flush(Eina_Strbuf *out)
+{
+ _write_all(eina_strbuf_string_get(out), eina_strbuf_length_get(out));
+ eina_strbuf_reset(out);
+}
+
+static void
+_out_printf(Eina_Strbuf *out, const char *fmt, ...)
+ __attribute__((format(printf, 2, 3)));
+
+static void
+_out_printf(Eina_Strbuf *out, const char *fmt, ...)
+{
+ va_list args;
+
+ va_start(args, fmt);
+ eina_strbuf_append_vprintf(out, fmt, args);
+ va_end(args);
+}
+
+static void
+_out_codepoint(Eina_Strbuf *out, uint32_t cp)
+{
+ char utf8[5] = { 0 };
+
+ if (cp < 0x80)
+ utf8[0] = cp;
+ else if (cp < 0x800)
+ {
+ utf8[0] = 0xc0 | (cp >> 6);
+ utf8[1] = 0x80 | (cp & 0x3f);
+ }
+ else if (cp < 0x10000)
+ {
+ utf8[0] = 0xe0 | (cp >> 12);
+ utf8[1] = 0x80 | ((cp >> 6) & 0x3f);
+ utf8[2] = 0x80 | (cp & 0x3f);
+ }
+ else
+ {
+ utf8[0] = 0xf0 | (cp >> 18);
+ utf8[1] = 0x80 | ((cp >> 12) & 0x3f);
+ utf8[2] = 0x80 | ((cp >> 6) & 0x3f);
+ utf8[3] = 0x80 | (cp & 0x3f);
+ }
+ _out_printf(out, "%s", utf8);
+}
+
+/* color is 0xRRGGBB when is_rgb is set, otherwise it follows termpty's COL_*
+ * numbering, or is an index in the 256 color palette when is256 is set. */
+static void
+_out_color(Eina_Strbuf *out, unsigned int color, bool is_rgb, bool is256,
+ bool intense, bool is_bg)
+{
+ if (is_rgb)
+ _out_printf(out, "\033[%d;2;%u;%u;%um", is_bg ? 48 : 38,
+ (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff);
+ else if (is256)
+ _out_printf(out, "\033[%d;5;%um", is_bg ? 48 : 38, color);
+ else if (color >= 1 && color <= 8)
+ _out_printf(out, "\033[%um",
+ (is_bg ? (intense ? 100 : 40) : (intense ? 90 : 30))
+ + color - 1);
+ else
+ _out_printf(out, "\033[%dm", is_bg ? 49 : 39);
+}
+
+static void
+_out_att(Eina_Strbuf *out, Pen *pen, const TermSrvAtt *att)
+{
+ const TermSrvAtt *p = pen->valid ? &pen->att : NULL;
+
+ if (!p ||
+ att->bold != p->bold || att->faint != p->faint ||
+ att->italic != p->italic || att->underline != p->underline ||
+ att->blink != p->blink || att->blink2 != p->blink2 ||
+ att->inverse != p->inverse || att->invisible != p->invisible ||
+ att->strike != p->strike || att->fraktur != p->fraktur ||
+ att->framed != p->framed || att->encircled != p->encircled ||
+ att->overlined != p->overlined)
+ {
+ _out_printf(out, "\033[0%s%s%s%s%s%s%s%s%s%s%s%s%sm",
+ att->bold ? ";1" : "",
+ att->faint ? ";2" : "",
+ att->italic ? ";3" : "",
+ att->underline ? ";4" : "",
+ att->blink ? ";5" : "",
+ att->blink2 ? ";6" : "",
+ att->inverse ? ";7" : "",
+ att->invisible ? ";8" : "",
+ att->strike ? ";9" : "",
+ att->fraktur ? ";20" : "",
+ att->framed ? ";51" : "",
+ att->encircled ? ";52" : "",
+ att->overlined ? ";53" : "");
+ p = NULL;
+ }
+ if (!p || att->fg != p->fg || att->fgrgb != p->fgrgb ||
+ att->fg256 != p->fg256 || att->fgintense != p->fgintense)
+ _out_color(out, att->fg, att->fgrgb, att->fg256, att->fgintense, false);
+ if (!p || att->bg != p->bg || att->bgrgb != p->bgrgb ||
+ att->bg256 != p->bg256 || att->bgintense != p->bgintense)
+ _out_color(out, att->bg, att->bgrgb, att->bg256, att->bgintense, true);
+ pen->att = *att;
+ pen->valid = true;
+}
+
+/* The right half of a double width character, drawn along with its left
+ * half */
+static bool
+_cell_is_dblwidth_tail(const TermSrvCell *row, uint32_t x)
+{
+ return x > 0 && row[x].codepoint == 0 && row[x].att.dblwidth &&
+ row[x - 1].codepoint != 0 && row[x - 1].att.dblwidth;
+}
+
+static void
+_out_cell(Eina_Strbuf *out, Pen *pen, const TermSrvCell *cell)
+{
+ _out_att(out, pen, &cell->att);
+ if (cell->codepoint < ' ' || cell->codepoint == 0x7f)
+ _out_printf(out, " ");
+ else
+ _out_codepoint(out, cell->codepoint);
+}
+
+static bool
+_cells_grow(Proxy *proxy, size_t cells)
+{
+ TermSrvCell *cur = realloc(proxy->cur, cells * sizeof(TermSrvCell));
+ TermSrvCell *prev;
+
+ if (!cur)
+ return false;
+ proxy->cur = cur;
+ prev = realloc(proxy->prev, cells * sizeof(TermSrvCell));
+ if (!prev)
+ return false;
+ proxy->prev = prev;
+ proxy->cells_cap = cells;
+ return true;
+}
+
+/* Draw the screen of the tymux, only the cells that changed since the last
+ * frame unless full is set. What does not fit in the terminal is left out. */
+static void
+_screen_draw(Proxy *proxy, bool full)
+{
+ Pen pen = { .valid = false };
+ TermSrvFrame frame;
+ TermSrvCell *swap;
+ uint32_t cols, rows, vis_cols, vis_rows, x, y;
+ int32_t pen_x = -1, pen_y = -1;
+ int res;
+ struct winsize ws;
+ Eina_Strbuf *out;
+
+ /* a frame missed now is drawn fully with the next one */
+ if (full)
+ proxy->prev_valid = false;
+ /* the daemon may resize again before the frame is read */
+ while ((res = termsrv_shm_read(proxy->shm, &frame, proxy->cur,
+ proxy->cells_cap)) > 0)
+ {
+ if (!_cells_grow(proxy, (size_t)frame.cols * frame.rows))
+ return;
+ }
+ if (res < 0)
+ return;
+ out = eina_strbuf_new();
+ EINA_SAFETY_ON_NULL_RETURN(out);
+ cols = frame.cols;
+ rows = frame.rows;
+ vis_cols = cols;
+ vis_rows = rows;
+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 &&
+ ws.ws_col > 0 && ws.ws_row > 0)
+ {
+ vis_cols = MIN(cols, ws.ws_col);
+ vis_rows = MIN(rows, ws.ws_row);
+ }
+ if (!proxy->prev_valid ||
+ cols != proxy->prev_cols || rows != proxy->prev_rows)
+ full = true;
+
+ /* Synchronized Output (mode 2026): the terminal shows the frame at once
+ * instead of while it is being drawn. Terminals without it ignore it. */
+ _out_printf(out, "\033[?2026h\033[?25l");
+ if (full)
+ _out_printf(out, "\033[0m\033[2J");
+
+ for (y = 0; y < vis_rows; y++)
+ {
+ const TermSrvCell *row = proxy->cur + y * cols;
+ const TermSrvCell *prev_row = proxy->prev + y * cols;
+
+ for (x = 0; x < vis_cols; x++)
+ {
+ bool changed = full ||
+ memcmp(&row[x], &prev_row[x], sizeof(TermSrvCell));
+
+ if (!changed && row[x].att.dblwidth && x + 1 < cols)
+ changed = memcmp(&row[x + 1], &prev_row[x + 1],
+ sizeof(TermSrvCell));
+ if (!changed || _cell_is_dblwidth_tail(row, x))
+ continue;
+ if (pen_x != (int32_t)x || pen_y != (int32_t)y)
+ _out_printf(out, "\033[%u;%uH", y + 1, x + 1);
+ _out_cell(out, &pen, &row[x]);
+ pen_y = y;
+ pen_x = x + ((row[x].att.dblwidth && row[x].codepoint) ? 2 : 1);
+ }
+ }
+ swap = proxy->prev;
+ proxy->prev = proxy->cur;
+ proxy->cur = swap;
+ proxy->prev_valid = true;
+ proxy->prev_cols = cols;
+ proxy->prev_rows = rows;
+
+ _out_printf(out, "\033[0m");
+ if (frame.cursor_visible &&
+ frame.cursor_x < vis_cols && frame.cursor_y < vis_rows)
+ _out_printf(out, "\033[%u;%uH\033[?25h",
+ frame.cursor_y + 1, frame.cursor_x + 1);
+ _out_printf(out, "\033[?2026l");
+ _out_flush(out);
+ eina_strbuf_free(out);
+}
+
+static void
+_paused_draw(void)
+{
+ struct winsize ws = { .ws_col = 80, .ws_row = 24 };
+ int x, y;
+ char buf[64];
+
+ ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
+ y = ws.ws_row / 2;
+ x = (ws.ws_col - (int)strlen(" PAUSED ")) / 2 + 1;
+ snprintf(buf, sizeof(buf), "\033[0m\033[2J\033[%d;%dH\033[7m PAUSED \033[0m",
+ MAX(y, 1), MAX(x, 1));
+ _write_str(buf);
+}
+
+static void
+_resize_send(Proxy *proxy)
+{
+ struct winsize ws;
+ TermSrvMsgResize resize;
+
+ if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0 ||
+ ws.ws_col == 0 || ws.ws_row == 0)
+ return;
+ resize.cols = MIN(ws.ws_col, TERMSRV_MAX_COLS);
+ resize.rows = MIN(ws.ws_row, TERMSRV_MAX_ROWS);
+ if (termsrv_msg_send(proxy->sock, TSRV_MSG_RESIZE,
+ &resize, sizeof(resize)) < 0)
+ proxy->running = false;
+}
+
+static void
+_detach(Proxy *proxy)
+{
+ termsrv_msg_send(proxy->sock, TSRV_MSG_DETACH, NULL, 0);
+ proxy->running = false;
+}
+
+/* Forward what was typed, minus the detach chord: a prefix not followed by
+ * the detach key is sent along with that key. While paused, only the chord
+ * is honored. */
+static void
+_input_handle(Proxy *proxy)
+{
+ char in[4096], out[sizeof(in) + 1];
+ size_t out_len = 0;
+ ssize_t n, i;
+
+ n = read(STDIN_FILENO, in, sizeof(in));
+ if (n < 0 && errno == EINTR)
+ return;
+ if (n <= 0)
+ {
+ _detach(proxy);
+ return;
+ }
+ for (i = 0; i < n; i++)
+ {
+ if (proxy->prefix_pending)
+ {
+ proxy->prefix_pending = false;
+ if (in[i] == DETACH_KEY)
+ {
+ _detach(proxy);
+ return;
+ }
+ out[out_len++] = DETACH_PREFIX;
+ out[out_len++] = in[i];
+ }
+ else if (in[i] == DETACH_PREFIX)
+ proxy->prefix_pending = true;
+ else
+ out[out_len++] = in[i];
+ }
+ if (out_len > 0 && !proxy->paused &&
+ termsrv_msg_send(proxy->sock, TSRV_MSG_INPUT, out, out_len) < 0)
+ proxy->running = false;
+}
+
+static void
+_title_set(const char *title, uint32_t size)
+{
+ uint32_t i;
+
+ for (i = 0; i < size && title[i]; i++)
+ {
+ /* would end the sequence early */
+ if ((unsigned char)title[i] < ' ' || title[i] == 0x7f)
+ return;
+ }
+ _write_str("\033]2;");
+ _write_all(title, i);
+ _write_str("\a");
+}
+
+/* Returns true if the screen changed */
+static bool
+_msg_handle(Proxy *proxy, int type, void *payload, uint32_t size)
+{
+ switch (type)
+ {
+ case TSRV_MSG_NOTIFY:
+ return true;
+ case TSRV_MSG_TITLE:
+ _title_set(payload, size);
+ break;
+ case TSRV_MSG_BELL:
+ _write_str("\a");
+ break;
+ case TSRV_MSG_EXIT:
+ if (size == sizeof(TermSrvMsgExit))
+ proxy->exit_code = ((TermSrvMsgExit *)payload)->exit_code;
+ proxy->running = false;
+ break;
+ case TSRV_MSG_PAUSE:
+ proxy->paused = true;
+ _paused_draw();
+ break;
+ case TSRV_MSG_RESUME:
+ proxy->paused = false;
+ _resize_send(proxy);
+ _screen_draw(proxy, true);
+ break;
+ default:
+ break;
+ }
+ return false;
+}
+
+/* Handle all the messages that arrived, drawing the screen once for them */
+static void
+_msgs_handle(Proxy *proxy)
+{
+ bool changed = false;
+ void *payload;
+ uint32_t size;
+ int type = 0;
+
+ if (termsrv_reader_fill(&proxy->reader, proxy->sock) < 0)
+ proxy->running = false;
+ while (proxy->running &&
+ (type = termsrv_reader_next(&proxy->reader, &payload, &size)) > 0)
+ {
+ changed |= _msg_handle(proxy, type, payload, size);
+ free(payload);
+ }
+ if (type < 0 || proxy->reader.eof)
+ proxy->running = false;
+ if (changed && proxy->running && !proxy->paused)
+ _screen_draw(proxy, false);
+}
+
+static void
+_winch_handler_set(void (*handler)(int))
+{
+ struct sigaction sa;
+
+ memset(&sa, 0, sizeof(sa));
+ sigemptyset(&sa.sa_mask);
+ sa.sa_handler = handler;
+ sigaction(SIGWINCH, &sa, NULL);
+}
+
+static Eina_Bool
+_cb_fd_stdin(void *data, Ecore_Fd_Handler *fdh __attribute__((unused)))
+{
+ Proxy *proxy = data;
+
+ _input_handle(proxy);
+ if (!proxy->running)
+ ecore_main_loop_quit();
+ return ECORE_CALLBACK_RENEW;
+}
+
+static Eina_Bool
+_cb_fd_sock(void *data, Ecore_Fd_Handler *fdh __attribute__((unused)))
+{
+ Proxy *proxy = data;
+
+ _msgs_handle(proxy);
+ if (!proxy->running)
+ ecore_main_loop_quit();
+ return ECORE_CALLBACK_RENEW;
+}
+
+static Eina_Bool
+_cb_fd_winch(void *data, Ecore_Fd_Handler *fdh)
+{
+ Proxy *proxy = data;
+ char drain[64];
+ int fd = ecore_main_fd_handler_fd_get(fdh);
+ ssize_t n;
+
+ /* the pipe is non-blocking: this drains it down to EAGAIN, not to a
+ * literal 0-byte read, since the write end is never closed */
+ do
+ n = read(fd, drain, sizeof(drain));
+ while (n > 0 || (n < 0 && errno == EINTR));
+ if (!proxy->paused)
+ {
+ _resize_send(proxy);
+ _screen_draw(proxy, true);
+ if (!proxy->running)
+ ecore_main_loop_quit();
+ }
+ return ECORE_CALLBACK_RENEW;
+}
+
+static Eina_Bool
+_cb_sig_exit(void *data, int type __attribute__((unused)),
+ void *event __attribute__((unused)))
+{
+ Proxy *proxy = data;
+
+ _detach(proxy);
+ ecore_main_loop_quit();
+ return ECORE_CALLBACK_DONE;
+}
+
+/* Take over the terminal to show the tymux until detached or until its
+ * shell exits. Returns the exit code of the shell. */
+static int
+_proxy_run(int sock)
+{
+ Proxy proxy = { .sock = sock, .running = true };
+ TermSrvMsgAttached attached;
+ void *shm;
+ int shm_fd;
+ struct timeval timeout = { .tv_sec = 5, .tv_usec = 0 };
+
+ /* do not hang on a daemon that does not answer */
+ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
+ if (termsrv_recv_attached(sock, &shm_fd, &attached) < 0)
+ {
+ fprintf(stderr, "tymux: no valid answer from tymuxd\n");
+ return 1;
+ }
+ timeout.tv_sec = 0;
+ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
+ shm = mmap(NULL, TERMSRV_SHM_TOTAL_SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
+ close(shm_fd);
+ if (shm == MAP_FAILED)
+ {
+ perror("tymux: mmap");
+ return 1;
+ }
+ proxy.shm = shm;
+ if (proxy.shm->magic != TERMSRV_SHM_MAGIC ||
+ proxy.shm->version != TERMSRV_SHM_VERSION)
+ {
+ fprintf(stderr, "tymux: tymuxd speaks another protocol version\n");
+ munmap(shm, TERMSRV_SHM_TOTAL_SIZE);
+ return 1;
+ }
+
+ if (pipe2(proxy.winch_pipe, O_CLOEXEC | O_NONBLOCK) < 0)
+ {
+ perror("tymux: pipe");
+ free(proxy.cur);
+ free(proxy.prev);
+ munmap(shm, TERMSRV_SHM_TOTAL_SIZE);
+ return 1;
+ }
+ _winch_pipe_write_fd = proxy.winch_pipe[1];
+
+ signal(SIGPIPE, SIG_IGN);
+ _winch_handler_set(_cb_sigwinch);
+ proxy.eh_exit = ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT,
+ _cb_sig_exit, &proxy);
+ proxy.eh_hup = ecore_event_handler_add(ECORE_EVENT_SIGNAL_HUP,
+ _cb_sig_exit, &proxy);
+ proxy.fdh_stdin = ecore_main_fd_handler_add(STDIN_FILENO,
+ ECORE_FD_READ | ECORE_FD_ERROR,
+ _cb_fd_stdin, &proxy,
+ NULL, NULL);
+ proxy.fdh_sock = ecore_main_fd_handler_add(sock,
+ ECORE_FD_READ | ECORE_FD_ERROR,
+ _cb_fd_sock, &proxy,
+ NULL, NULL);
+ proxy.fdh_winch = ecore_main_fd_handler_add(proxy.winch_pipe[0],
+ ECORE_FD_READ,
+ _cb_fd_winch, &proxy,
+ NULL, NULL);
+ _raw_mode_enter();
+ _resize_send(&proxy);
+ _screen_draw(&proxy, true);
+
+ if (proxy.running)
+ ecore_main_loop_begin();
+
+ _raw_mode_leave();
+ _winch_handler_set(SIG_DFL);
+ _winch_pipe_write_fd = -1;
+ if (proxy.fdh_stdin) ecore_main_fd_handler_del(proxy.fdh_stdin);
+ if (proxy.fdh_sock) ecore_main_fd_handler_del(proxy.fdh_sock);
+ if (proxy.fdh_winch) ecore_main_fd_handler_del(proxy.fdh_winch);
+ if (proxy.eh_exit) ecore_event_handler_del(proxy.eh_exit);
+ if (proxy.eh_hup) ecore_event_handler_del(proxy.eh_hup);
+ close(proxy.winch_pipe[0]);
+ close(proxy.winch_pipe[1]);
+ _write_str("\033[0m\033[?25h\r\n");
+ free(proxy.cur);
+ free(proxy.prev);
+ termsrv_reader_clear(&proxy.reader);
+ munmap(shm, TERMSRV_SHM_TOTAL_SIZE);
+ return proxy.exit_code;
+}
+
+static int
+_attach(const char *name, TermSrvAttachMode mode)
+{
+ const char *current = getenv("TYMUX_NAME");
+ uint8_t mode_byte = mode;
+ int sock, ret;
+
+ if (current)
+ fprintf(stderr, "tymux: warning: already inside tymux '%s'\n", current);
+ sock = termsrv_connect(name);
+ if (sock < 0)
+ {
+ fprintf(stderr, "tymux: no tymux named '%s'\n", name);
+ return 1;
+ }
+ if (termsrv_msg_send(sock, TSRV_MSG_ATTACH, &mode_byte, 1) < 0)
+ {
+ perror("tymux: send");
+ close(sock);
+ return 1;
+ }
+ /* no use for power/timezone/D-Bus system monitoring in a terminal proxy,
+ * and it would open a D-Bus connection on every attach */
+ ecore_app_no_system_modules();
+ ecore_init();
+ ret = _proxy_run(sock);
+ ecore_shutdown();
+ close(sock);
+ return ret;
+}
+
+static int
+_cmd_attach(int argc, char **argv)
+{
+ TermSrvAttachMode mode = TSRV_ATTACH_HIJACK;
+ const char *name = NULL;
+ int i;
+
+ for (i = 2; i < argc; i++)
+ {
+ if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--shared"))
+ mode = TSRV_ATTACH_SHARED;
+ else if (!strcmp(argv[i], "-r") || !strcmp(argv[i], "--readonly"))
+ mode = TSRV_ATTACH_READONLY;
+ else if (argv[i][0] == '-' || name)
+ {
+ fprintf(stderr, "tymux attach: unexpected argument '%s'\n",
+ argv[i]);
+ return 1;
+ }
+ else
+ name = argv[i];
+ }
+ if (!name)
+ {
+ fprintf(stderr, "Usage: tymux attach [--shared|--readonly] NAME\n");
+ return 1;
+ }
+ return _attach(name, mode);
+}
+
+static int
+_cmd_new(int argc, char **argv)
+{
+ const char *name = (argc > 2) ? argv[2] : "default";
+ int sock;
+
+ if (argc > 3 || termsrv_name_check(name) < 0)
+ {
+ fprintf(stderr, "Usage: tymux new [NAME]\n"
+ "NAME must not start with '-', contain '/' or be longer"
+ " than %d bytes\n", TERMSRV_NAME_MAX);
+ return 1;
+ }
+ sock = termsrv_connect(name);
+ if (sock >= 0)
+ {
+ close(sock);
+ fprintf(stderr, "tymux: '%s' is already running, use:"
+ " tymux attach %s\n", name, name);
+ return 1;
+ }
+ if (termsrv_daemon_spawn(name) < 0)
+ {
+ fprintf(stderr, "tymux: could not start tymuxd for '%s'\n", name);
+ return 1;
+ }
+ return _attach(name, TSRV_ATTACH_HIJACK);
+}
+
+static int
+_cmd_list(void)
+{
+ const size_t suffix_len = strlen(".sock");
+ char dir_path[4096];
+ Eina_Iterator *it;
+ const Eina_File_Direct_Info *info;
+
+ if (termsrv_tymux_dir(dir_path, sizeof(dir_path)) < 0)
+ return 1;
+ it = eina_file_direct_ls(dir_path);
+ if (!it)
+ return 0;
+ EINA_ITERATOR_FOREACH(it, info)
+ {
+ const char *base = info->path + info->name_start;
+ char name[TERMSRV_NAME_MAX + 1];
+ size_t len = info->name_length;
+ int sock;
+
+ if (len <= suffix_len || len - suffix_len > TERMSRV_NAME_MAX ||
+ strcmp(base + len - suffix_len, ".sock"))
+ continue;
+ memcpy(name, base, len - suffix_len);
+ name[len - suffix_len] = '\0';
+ sock = termsrv_connect(name);
+ if (sock < 0)
+ continue;
+ close(sock);
+ printf("%s\n", name);
+ }
+ eina_iterator_free(it);
+ return 0;
+}
+
+static int
+_cmd_kill(int argc, char **argv)
+{
+ const struct timespec delay = { .tv_sec = 0, .tv_nsec = 10 * 1000 * 1000 };
+ struct ucred cred;
+ socklen_t cred_len = sizeof(cred);
+ int sock, i;
+
+ if (argc != 3)
+ {
+ fprintf(stderr, "Usage: tymux kill NAME\n");
+ return 1;
+ }
+ sock = termsrv_connect(argv[2]);
+ if (sock < 0)
+ {
+ fprintf(stderr, "tymux: no tymux named '%s'\n", argv[2]);
+ return 1;
+ }
+ /* identifies the process that listens: tymuxd */
+ if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) < 0 ||
+ cred.uid != getuid() || kill(cred.pid, SIGTERM) < 0)
+ {
+ perror("tymux: kill");
+ close(sock);
+ return 1;
+ }
+ close(sock);
+ for (i = 0; i < 300; i++)
+ {
+ nanosleep(&delay, NULL);
+ sock = termsrv_connect(argv[2]);
+ if (sock < 0)
+ return 0;
+ close(sock);
+ }
+ fprintf(stderr, "tymux: '%s' did not exit\n", argv[2]);
+ return 1;
+}
+
+static void
+_usage(const char *argv0)
+{
+ printf("Usage: %s COMMAND [ARGS]\n"
+ "Keep shells running in the background and use them from any\n"
+ "terminal.\n"
+ "\n"
+ "Commands:\n"
+ " new [NAME] Start a shell called NAME (\"default\")\n"
+ " and attach to it\n"
+ " attach [-s|-r] NAME Show NAME in this terminal, pausing the\n"
+ " terminal it was attached to\n"
+ " -s, --shared Type along with the other terminals\n"
+ " -r, --readonly Only watch\n"
+ " list List the running shells\n"
+ " kill NAME Hang up the shell called NAME\n"
+ "\n"
+ "Detach with Ctrl+b d. See tymux(1).\n",
+ argv0);
+}
+
+static int
+_run(int argc, char **argv)
+{
+ const char *cmd = (argc > 1) ? argv[1] : NULL;
+
+ if (!cmd)
+ {
+ _usage(argv[0]);
+ return 1;
+ }
+ if (!strcmp(cmd, "new"))
+ return _cmd_new(argc, argv);
+ if (!strcmp(cmd, "attach"))
+ return _cmd_attach(argc, argv);
+ if (!strcmp(cmd, "list"))
+ return _cmd_list();
+ if (!strcmp(cmd, "kill"))
+ return _cmd_kill(argc, argv);
+ if (!strcmp(cmd, "-h") || !strcmp(cmd, "--help"))
+ {
+ _usage(argv[0]);
+ return 0;
+ }
+ fprintf(stderr, "tymux: unknown command '%s'\n", cmd);
+ _usage(argv[0]);
+ return 1;
+}
+
+int
+main(int argc, char **argv)
+{
+ int ret;
+
+ eina_init();
+ ret = _run(argc, argv);
+ eina_shutdown();
+ return ret;
+}
diff --git a/tests/meson.build b/tests/meson.build
index 12fab8a0..354d7cc9 100644
--- a/tests/meson.build
+++ b/tests/meson.build
@@ -89,6 +89,15 @@ if tests
meson.project_source_root() / 'data' / 'terminfo' / 'terminology.terminfo',
meson.project_source_root() / 'src' / 'bin' / 'termptytcap.h'])
endif
+
+ if host_os == 'linux'
+ # Starts tymuxd with a shell and drives tymux through pseudo terminals.
+ test('tymux',
+ find_program('python3'),
+ args: [files('tymux.py'), tymux.full_path()],
+ depends: [tymux, tymuxd],
+ timeout: 120)
+ endif
endif
if benchmarks
diff --git a/tests/tymux.py b/tests/tymux.py
new file mode 100644
index 00000000..a7345d95
--- /dev/null
+++ b/tests/tymux.py
@@ -0,0 +1,340 @@
+#!/usr/bin/env python3
+"""Drive tymux and tymuxd through pseudo terminals.
+
+Usage: tymux.py PATH_TO_TYMUX
+
+tymuxd is expected next to tymux. Each check prints PASS or FAIL; the exit
+status is the number of failures.
+"""
+import atexit
+import fcntl
+import os
+import pty
+import re
+import select
+import shutil
+import signal
+import socket
+import struct
+import subprocess
+import sys
+import tempfile
+import termios
+import time
+
+TYMUX = os.path.abspath(sys.argv[1])
+XDG = tempfile.mkdtemp(prefix="tymux-test-")
+NAME = "t%d" % os.getpid()
+# interactive POSIX shells read $ENV: switch line editing off so that
+# readline does not eat the control characters typed in the tests
+SHELL_RC = os.path.join(XDG, "shellrc")
+with open(SHELL_RC, "w") as f:
+ f.write("set +o emacs 2>/dev/null; set +o vi 2>/dev/null\n")
+ENV = {k: v for k, v in os.environ.items()
+ if k not in ("DISPLAY", "WAYLAND_DISPLAY", "TYMUX_NAME")}
+ENV.update(XDG_RUNTIME_DIR=XDG, SHELL="/bin/sh", PS1="$ ", ENV=SHELL_RC,
+ TERM="xterm-256color")
+failures = []
+stopped = []
+
+
+def _tymuxd_pids_for_xdg():
+ """pids of every tymuxd that has our XDG_RUNTIME_DIR in its environment,
+ however it was named (a test may create several sessions -- NAME,
+ NAME2, ... -- and a scenario that raises before its own 'tymux kill'
+ would otherwise leak that daemon)."""
+ needle = ("XDG_RUNTIME_DIR=" + XDG).encode()
+ pids = []
+ for entry in os.listdir("/proc"):
+ if not entry.isdigit():
+ continue
+ try:
+ with open("/proc/%s/comm" % entry) as f:
+ if f.read().strip() != "tymuxd":
+ continue
+ with open("/proc/%s/environ" % entry, "rb") as f:
+ environ = f.read()
+ except OSError:
+ continue
+ if needle in environ.split(b"\0"):
+ pids.append(int(entry))
+ return pids
+
+
+def _cleanup():
+ """Run on every exit path (normal return, an uncaught exception, or a
+ signal) so a scenario that raises before reaching its own 'tymux kill'
+ never leaves a tymuxd running against this run's XDG_RUNTIME_DIR."""
+ for client in list(stopped):
+ try:
+ os.kill(client.pid, signal.SIGCONT)
+ except OSError:
+ pass
+ stopped.clear()
+ for pid in _tymuxd_pids_for_xdg():
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(XDG, ignore_errors=True)
+
+
+_cleanup_done = False
+
+
+def _cleanup_once():
+ global _cleanup_done
+ if _cleanup_done:
+ return
+ _cleanup_done = True
+ _cleanup()
+
+
+atexit.register(_cleanup_once)
+
+
+def _handle_signal(signum, _frame):
+ _cleanup_once()
+ signal.signal(signum, signal.SIG_DFL)
+ os.kill(os.getpid(), signum)
+
+
+for _sig in (signal.SIGINT, signal.SIGTERM):
+ signal.signal(_sig, _handle_signal)
+
+
+def check(cond, what):
+ print(("PASS " if cond else "FAIL ") + what, flush=True)
+ if not cond:
+ failures.append(what)
+
+
+class Client:
+ """tymux running in a pseudo terminal of rows x cols"""
+
+ def __init__(self, args, rows=24, cols=80):
+ self.pid, self.fd = pty.fork()
+ if self.pid == 0:
+ os.execve(TYMUX, [TYMUX] + args, ENV)
+ self.resize(rows, cols)
+ self.out = b""
+ self.status = None
+
+ def resize(self, rows, cols):
+ fcntl.ioctl(self.fd, termios.TIOCSWINSZ,
+ struct.pack("HHHH", rows, cols, 0, 0))
+
+ def _read(self, timeout):
+ ready, _, _ = select.select([self.fd], [], [], timeout)
+ if not ready:
+ return
+ try:
+ self.out += os.read(self.fd, 65536)
+ except OSError:
+ time.sleep(timeout)
+
+ def expect(self, text, timeout=5):
+ text = text.encode("utf-8") if isinstance(text, str) else text
+ end = time.time() + timeout
+ while text not in self.out and time.time() < end:
+ self._read(0.05)
+ return text in self.out
+
+ def idle(self, duration=0.5):
+ end = time.time() + duration
+ while time.time() < end:
+ self._read(0.05)
+
+ def send(self, text):
+ os.write(self.fd, text.encode("utf-8"))
+
+ def wait(self, timeout=5):
+ end = time.time() + timeout
+ while time.time() < end:
+ self._read(0.05)
+ pid, status = os.waitpid(self.pid, os.WNOHANG)
+ if pid:
+ self.status = os.waitstatus_to_exitcode(status)
+ return self.status
+ return None
+
+
+def tymux(*args):
+ return subprocess.run([TYMUX] + list(args), env=ENV, capture_output=True,
+ text=True, timeout=10)
+
+
+def daemons():
+ return subprocess.run(["pgrep", "-x", "-f", "tymuxd " + NAME],
+ capture_output=True, text=True).stdout.split()
+
+
+def cpu_time(pid):
+ """user + system CPU time of pid, in seconds"""
+ with open("/proc/%d/stat" % pid) as f:
+ fields = f.read().rsplit(")", 1)[1].split()
+ return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK")
+
+
+def main():
+ a = Client(["new", NAME])
+ check(a.expect("$ "), "new: the shell prompt is shown")
+ a.send("echo hello-$((6*7))\r")
+ check(a.expect("hello-42"), "new: output is drawn")
+ check(a.expect("\033[?2026l"), "frames are synchronized updates")
+ a.send("\x02d")
+ check(a.wait() == 0, "Ctrl+b d detaches")
+ check(tymux("list").stdout.split() == [NAME], "list shows the tymux")
+ check(len(daemons()) == 1, "tymuxd keeps running once detached")
+
+ a = Client(["attach", NAME])
+ check(a.expect("hello-42"), "attach: the screen is drawn again")
+
+ readonly = Client(["attach", "--readonly", NAME])
+ check(readonly.expect("hello-42"), "readonly: the screen is drawn")
+ readonly.send("echo readonly-$((2+2))\r")
+ a.idle()
+ check(b"readonly-4" not in a.out, "readonly: input is dropped")
+
+ shared = Client(["attach", "--shared", NAME])
+ check(shared.expect("hello-42"), "shared: the screen is drawn")
+ shared.send("echo shared-$((1+1))\r")
+ check(a.expect("shared-2") and readonly.expect("shared-2"),
+ "shared: input is written to the shell")
+ a.send("echo primary-$((3+4))\r")
+ check(shared.expect("primary-7"), "primary: input still works")
+
+ hijack = Client(["attach", NAME])
+ check(hijack.expect("primary-7"), "hijack: the screen is drawn")
+ check(a.expect("PAUSED"), "hijack: the previous primary is paused")
+ a.send("echo paused-$((4+4))\r")
+ hijack.idle()
+ check(b"paused-8" not in hijack.out, "paused: input is dropped")
+ hijack.send("echo hijack-$((5+5))\r")
+ check(hijack.expect("hijack-10"), "hijack: input is written")
+ hijack.send("\x02d")
+ check(hijack.wait() == 0, "hijack: detaches")
+ check(a.expect("hijack-10"), "resume: the screen is drawn again")
+ a.send("echo resumed-$((8+1))\r")
+ check(a.expect("resumed-9"), "resume: input works again")
+
+ a.send("echo p\x02q | od -An -c\r")
+ check(a.expect("002"), "Ctrl+b followed by another key is forwarded")
+
+ a.send("printf '\\346\\274\\242X|\\n'\r")
+ check(a.expect("漢X|"), "double width characters are not padded")
+
+ a.send("printf '\\033[38;2;255;0;0mRED\\033[0m\\n'\r")
+ a.expect("RED\033")
+ check(re.search(rb"38;2;255;0;0m(\033\[[0-9;]*m)*RED", a.out) is not None,
+ "true foreground colors are drawn as is")
+
+ a.send("printf '\\033[48;2;18;52;86mBLU\\033[0m\\n'\r")
+ a.expect("BLU\033")
+ check(re.search(rb"48;2;18;52;86m(\033\[[0-9;]*m)*BLU", a.out) is not None,
+ "true background colors are drawn as is")
+
+ # fraktur and encircled turn letters into other characters: use
+ # characters they leave alone
+ for code, word, name in ((5, "BLK", "blink"), (6, "RPD", "rapid blink"),
+ (8, "INV", "invisible"), (20, "123", "fraktur"),
+ (51, "FRM", "framed"), (52, "-_-", "encircled"),
+ (53, "OVR", "overlined")):
+ a.send("printf '\\033[%dm%s\\033[0m\\n'\r" % (code, word))
+ a.expect(word + "\033")
+ check(re.search(rb"\033\[0(;[0-9]+)*;%dm(\033\[[0-9;]*m)*%s"
+ % (code, re.escape(word.encode())), a.out) is not None,
+ "%s text keeps its attribute" % name)
+
+ a.resize(30, 100)
+ os.kill(a.pid, signal.SIGWINCH)
+ a.idle(0.3)
+ a.send("stty size\r")
+ check(a.expect("30 100"), "the size of the terminal reaches the shell")
+
+ a.resize(30, 600)
+ os.kill(a.pid, signal.SIGWINCH)
+ a.idle(0.3)
+ a.send("stty size\r")
+ check(a.expect("30 600"), "a wide terminal gets a session of its width")
+
+ for rows, cols in ((10, 40), (35, 130)):
+ a.resize(rows, cols)
+ os.kill(a.pid, signal.SIGWINCH)
+ a.idle(0.3)
+ a.send("stty size\r")
+ check(a.expect("%d %d" % (rows, cols)),
+ "the screen is drawn after a resize to %dx%d" % (cols, rows))
+
+ a.send("echo name=$TYMUX_NAME\r")
+ check(a.expect("name=" + NAME), "TYMUX_NAME is set in the shell")
+
+ result = tymux("kill", NAME)
+ check(result.returncode == 0, "kill succeeds")
+ for client in (a, readonly, shared):
+ check(client.wait() is not None, "kill detaches every client")
+ check(tymux("list").stdout == "", "list is empty after kill")
+ check(not daemons(), "kill stops tymuxd")
+ check(not os.path.exists(os.path.join(XDG, "terminology", "tymux",
+ NAME + ".sock")),
+ "kill removes the socket")
+
+ a = Client(["new", NAME])
+ check(a.expect("$ "), "new after kill")
+ a.send("exit 3\r")
+ check(a.wait() == 3, "the exit status of the shell is returned")
+ check(not daemons(), "tymuxd exits with its shell")
+
+ # a client that stops reading is dropped instead of blocking tymuxd
+ a = Client(["new", NAME])
+ check(a.expect("$ "), "new for the stuck client test")
+ stuck = Client(["attach", "--readonly", NAME])
+ check(stuck.expect("$ "), "stuck: attached")
+ os.kill(stuck.pid, signal.SIGSTOP)
+ stopped.append(stuck)
+ a.send("i=0; while [ $i -lt 3000 ]; do printf '\\033]2;%0500d\\007' $i;"
+ " i=$((i+1)); done; echo flood-$((9*9))\r")
+ check(a.expect("flood-81", timeout=30),
+ "a stopped client does not block the others")
+ os.kill(stuck.pid, signal.SIGCONT)
+ stopped.remove(stuck)
+ check(stuck.wait(10) is not None, "the stopped client was dropped")
+ a.send("echo alive-$((6+6))\r")
+ check(a.expect("alive-12"), "the primary still works")
+
+ # a client stalling in the middle of a message costs tymuxd nothing
+ path = os.path.join(XDG, "terminology", "tymux", NAME + ".sock")
+ pending = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ pending.connect(path)
+ pending.send(struct.pack("=II", 1, 1)[:3])
+ attached = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ attached.connect(path)
+ attached.send(struct.pack("=IIB", 1, 1, 2))
+ _, fds, _, _ = socket.recv_fds(attached, 20, 1)
+ for fd in fds:
+ os.close(fd)
+ attached.send(struct.pack("=II", 5, 8)[:3])
+ daemon = int(daemons()[0])
+ before = cpu_time(daemon)
+ a.send("echo stall-$((7+7))\r")
+ check(a.expect("stall-14"), "the primary works while a client stalls")
+ a.idle(2)
+ used = cpu_time(daemon) - before
+ check(used < 0.2, "a stalled client does not make tymuxd spin"
+ " (%.2f s of CPU in 2 s)" % used)
+ pending.close()
+ attached.close()
+ a.send("exit\r")
+ check(a.wait() == 0, "exit after the stuck client test")
+
+ result = tymux("attach", NAME)
+ check(result.returncode == 1 and "no tymux" in result.stderr,
+ "attach to a missing tymux fails")
+ check(tymux("new", "a/b").returncode == 1, "invalid names are refused")
+
+
+try:
+ main()
+finally:
+ _cleanup_once()
+sys.exit(len(failures))
--
To stop receiving notification emails like this one, please contact
the administrator of this repository.