This is an automated email from the git hooks/post-receive script.

git pushed a commit to branch tymux-12-session-parity
in repository terminology.

View the commit online.

commit b536054994e6356b1e91ec3dcdae8fc4f57b5ba0
Author: Cedric BAIL <[email protected]>
AuthorDate: Sun Nov 22 17:48:08 2026 -0600

    termio: require a per-terminal token for the tymux hand-off
    
    The hand-off escape was only gated by ty_escapes, which is on by
    default, so displaying an untrusted file could replace the terminal's
    shell with a tymux session, open tabs or start a daemon.
    
    Each terminal now gives its shell a random token in
    TERMINOLOGY_HANDOFF, and the escape must carry it. Bytes that are
    merely displayed do not know it. tymux only sends the escape when
    stdin and stdout are terminals, so the token never lands in a
    redirected file, and session shells get no token, so tymux inside a
    session uses its inline proxy.
---
 README.md                    |   9 ++--
 man/tymux.1                  |  15 ++++--
 src/bin/termio.c             |  12 +++--
 src/bin/termpty.c            |  47 ++++++++++++++++
 src/bin/termpty.h            |   9 ++++
 src/bin/termtymux.c          | 124 ++++++++++++++++++++++++++++---------------
 src/bin/termtymux.h          |  29 +++++-----
 src/bin/tymux.c              |  31 +++++++----
 src/bin/tymuxd.c             |   4 ++
 src/bin/tytest_tymux.c       |   1 +
 tests/tymux.py               | 117 ++++++++++++++++++++++++++++++----------
 tests/tymux_attach_escape.sh |  26 ++++-----
 12 files changed, 304 insertions(+), 120 deletions(-)

diff --git a/README.md b/README.md
index ffe2c9fa..f379b7aa 100644
--- a/README.md
+++ b/README.md
@@ -193,15 +193,18 @@ Examples:
   * `ap[on/true/yes/off/false/no]`
     set the terminal alpha state to be on, or off permanently
 
-  * `at;[NAME]`, `ats;[NAME]`, `atr;[NAME]`
+  * `at;TOKEN;NONCE;NAME`, `ats;TOKEN;NONCE;NAME`, `atr;TOKEN;NONCE;NAME`
     native tymux hand-off: replace this terminal's pty with a shadow pty
     mirroring the tymux session `NAME`, as hijack, shared or readonly
     respectively (see `tymux(1)`). Like every other command on this list,
-    it is only recognized when Terminology escapes are enabled. A value
+    it is only recognized when Terminology escapes are enabled, and when
+    `TOKEN` is the 32 hex digits of the secret Terminology exported to the
+    terminal's shell as `TERMINOLOGY_HANDOFF`; `NONCE` is 8 hex digits
+    chosen by the sender. A value
     with no `;` (e.g. `atoff`) is the alpha command above, not a hand-off;
     an unrecognized or malformed hand-off is ignored.
 
-  * `atn;[NAME]`, `atns;[NAME]`, `atnr;[NAME]`
+  * `atn;TOKEN;NONCE;NAME`, `atns;TOKEN;NONCE;NAME`, `atnr;TOKEN;NONCE;NAME`
     native tymux new-tab hand-off: like `at;`/`ats;`/`atr;` above, but
     opens a new tab already attached to `NAME` instead of replacing this
     terminal's pty, which is left running whatever it was running (see
diff --git a/man/tymux.1 b/man/tymux.1
index 0a99d77d..eade9847 100644
--- a/man/tymux.1
+++ b/man/tymux.1
@@ -112,7 +112,7 @@ to their name.
 .B tymux
 warns when attaching from inside one of them.
 .TP
-.B TERMINOLOGY, TMUX, STY, TYMUX_NO_NATIVE
+.B TERMINOLOGY_HANDOFF, TMUX, STY, TYMUX_NO_NATIVE
 Used to decide on native hand-off; see \fBNATIVE HAND\-OFF\fP.
 .SH NATIVE HAND-OFF
 Instead of proxying the session through the inline terminal emulation
@@ -123,8 +123,12 @@ and
 detect when they are run inside a Terminology terminal and ask it to take
 the session over directly.
 .PP
-Detection requires \fBTERMINOLOGY\fP to be set, which Terminology sets in
-the environment of the shells it starts, and neither \fBTMUX\fP nor
+Detection requires \fBTERMINOLOGY_HANDOFF\fP to be set. Terminology gives
+each terminal a random secret and sets it in the environment of the shells it
+starts; the hand-off escape is only accepted when it carries it, so text
+merely displayed in the terminal cannot trigger one. Shells running in a
+session do not have it, and use the inline proxy. Detection also requires
+neither \fBTMUX\fP nor
 \fBSTY\fP to be set, since either would mean the visible terminal is a
 tmux or screen pane multiplexed behind the one Terminology drew, and the
 hand-off escape would not necessarily reach it.
@@ -160,13 +164,14 @@ Since a hand-off targets whatever terminal reads standard output, running
 .B tymux attach
 or
 .B tymux new
-inside Terminology over an SSH connection that forwards \fBTERMINOLOGY\fP
+inside Terminology over an SSH connection that forwards \fBTERMINOLOGY_HANDOFF\fP
 (via \fBSendEnv\fP or \fBAcceptEnv\fP) makes the escape reach the
 .I local
 Terminology window, which then switches to a
 .I local
 tymux session of the same name \(en not the remote one the command was
-meant to operate on. \fBTYMUX_NO_NATIVE\fP avoids this.
+meant to operate on. A remote shell does not have the variable unless it is
+forwarded explicitly; \fBTYMUX_NO_NATIVE\fP avoids this.
 .PP
 A natively attached terminal recognizes
 .B Ctrl+b d
diff --git a/src/bin/termio.c b/src/bin/termio.c
index d4ade2c7..6dcd168e 100644
--- a/src/bin/termio.c
+++ b/src/bin/termio.c
@@ -4562,9 +4562,10 @@ _smart_pty_command(void *data)
      return;
 
 #ifdef HAVE_TYMUX
-   /* at;NAME / ats;NAME / atr;NAME - native tymux hand-off, and its
-    * atn;NAME / atns;NAME / atnr;NAME new-tab variants (open a new tab
-    * attached to NAME instead of switching this terminal), gated by
+   /* at;TOKEN;NONCE;NAME / ats;... / atr;... - native tymux hand-off, and
+    * its atn;... / atns;... / atnr;... new-tab variants (open a new tab
+    * attached to NAME instead of switching this terminal). TOKEN is the
+    * one exported to the shell as TERMINOLOGY_HANDOFF. Gated by
     * ty_escapes like every other private command family below (alpha,
     * images, popmedia, background, sendfile): untrusted output (a `cat`
     * of a file, an ssh MOTD, a CI log) must not be able to switch the
@@ -4582,9 +4583,10 @@ _smart_pty_command(void *data)
         const char *name;
         TermSrvAttachMode mode;
         Eina_Bool new_tab;
+        char nonce[9];
 
-        if (termtymux_attach_escape_parse(&ty->cur_cmd[2], &name, &mode,
-                                          &new_tab))
+        if (termtymux_attach_escape_parse(&ty->cur_cmd[2], ty->handoff_token,
+                                          &name, &mode, &new_tab, nonce))
           {
              if (new_tab)
                _termio_tymux_newtab(obj, sd, name, mode);
diff --git a/src/bin/termpty.c b/src/bin/termpty.c
index a8fd523d..08d1cb9c 100644
--- a/src/bin/termpty.c
+++ b/src/bin/termpty.c
@@ -25,6 +25,9 @@
 #include <sys/types.h>
 #include <signal.h>
 #include <sys/wait.h>
+#ifdef HAVE_TYMUX
+# include <sys/random.h>
+#endif
 #include <sys/stat.h>
 #include <stdlib.h>
 #include <fcntl.h>
@@ -550,6 +553,35 @@ _is_shell_valid(const char *cmd)
    return EINA_TRUE;
 }
 
+static Eina_Bool _handoff_token_enabled = EINA_TRUE;
+
+void
+termpty_handoff_token_enable_set(Eina_Bool enable)
+{
+   _handoff_token_enabled = enable;
+}
+
+/* Leaves token empty, which disables the hand-off, when no randomness is
+ * available, as on platforms without tymux. */
+static void
+_handoff_token_new(char token[TERMPTY_HANDOFF_TOKEN_LEN + 1])
+{
+   token[0] = '\0';
+#ifdef HAVE_TYMUX
+   static const char hex[] = "0123456789abcdef";
+   unsigned char rnd[TERMPTY_HANDOFF_TOKEN_LEN / 2];
+   size_t i;
+
+   if (getrandom(rnd, sizeof(rnd), 0) != (ssize_t)sizeof(rnd)) return;
+   for (i = 0; i < sizeof(rnd); i++)
+     {
+        token[2 * i] = hex[rnd[i] >> 4];
+        token[2 * i + 1] = hex[rnd[i] & 0xf];
+     }
+   token[TERMPTY_HANDOFF_TOKEN_LEN] = '\0';
+#endif
+}
+
 Termpty *
 termpty_new(const char *cmd, Eina_Bool login_shell, const char *cd,
             int w, int h, Config *config, const char *title,
@@ -563,9 +595,15 @@ termpty_new(const char *cmd, Eina_Bool login_shell, const char *cd,
    const char *shell = NULL;
    const char *args[4] = {NULL, NULL, NULL, NULL};
    const char *arg0;
+#ifdef HAVE_TYMUX
+   /* putenv() keeps the pointer: this must outlive the child's setup */
+   char handoff_env[sizeof("TERMINOLOGY_HANDOFF=") +
+                    TERMPTY_HANDOFF_TOKEN_LEN];
+#endif
 
    ty = calloc(1, sizeof(Termpty));
    if (!ty) return NULL;
+   if (_handoff_token_enabled) _handoff_token_new(ty->handoff_token);
    termpty_log_level_refresh();
    ty->config = config;
    ty->w = w;
@@ -817,6 +855,15 @@ termpty_new(const char *cmd, Eina_Bool login_shell, const char *cd,
              snprintf(buf, sizeof(buf), "WINDOWID=%lu", (unsigned long)window_id);
              putenv(buf);
           }
+        unsetenv("TERMINOLOGY_HANDOFF");
+#ifdef HAVE_TYMUX
+        if (ty->handoff_token[0])
+          {
+             snprintf(handoff_env, sizeof(handoff_env),
+                      "TERMINOLOGY_HANDOFF=%s", ty->handoff_token);
+             putenv(handoff_env);
+          }
+#endif
 #if ((EFL_VERSION_MAJOR > 1) || (EFL_VERSION_MINOR >= 24)) || ((EFL_VERSION_MAJOR == 1) && (EFL_VERSION_MINOR == 23) && (EFL_VERSION_MICRO == 99))
         eina_file_close_from(3, NULL);
 #endif
diff --git a/src/bin/termpty.h b/src/bin/termpty.h
index c9fec755..26338886 100644
--- a/src/bin/termpty.h
+++ b/src/bin/termpty.h
@@ -192,6 +192,8 @@ typedef struct tag_Termpty_Kitty_Kbd
    uint8_t depth;
 } Termpty_Kitty_Kbd;
 
+#define TERMPTY_HANDOFF_TOKEN_LEN 32
+
 struct tag_Termpty
 {
    Evas_Object *obj;
@@ -320,6 +322,10 @@ struct tag_Termpty
    int vs16_base_x, vs16_base_y;
    int exit_code;
    pid_t pid;
+   /* Secret the child's programs present to hand the terminal over to a
+    * tymux session (see termtymux_attach_escape_parse()), exported to
+    * them as TERMINOLOGY_HANDOFF. Empty for a shadow pty. */
+   char handoff_token[TERMPTY_HANDOFF_TOKEN_LEN + 1];
    unsigned int altbuf     : 1;
    unsigned int mouse_mode : 3;
    unsigned int mouse_ext  : 2;
@@ -421,6 +427,9 @@ Termpty   *termpty_new(const char *cmd, Eina_Bool login_shell, const char *cd,
                        int w, int h, Config *config, const char *title,
                        Ecore_Window window_id);
 void       termpty_free(Termpty *ty);
+/* Whether termpty_new() gives its children a hand-off token. On by default;
+ * the tymux daemon turns it off, as nothing there can receive a hand-off. */
+void       termpty_handoff_token_enable_set(Eina_Bool enable);
 void       termpty_sync_output_reset(Termpty *ty);
 /* private — called from termptyesc.c _sync_output_end only */
 void       termpty_sync_output_snapshot_free(Termpty *ty);
diff --git a/src/bin/termtymux.c b/src/bin/termtymux.c
index 9dd26bab..b8c9033f 100644
--- a/src/bin/termtymux.c
+++ b/src/bin/termtymux.c
@@ -1113,18 +1113,24 @@ termtymux_title_compose(const char *tymux_name, const char *title)
  * (win.c _cb_command(), values "on"/"true"/"yes"/"off"/"false"/"no")
  * lives: none of those values contain ';', so requiring one right after
  * the optional 'n'/'s'/'r' variant letters is what tells the two apart. Do
- * not relax this without checking that set of alpha values first. */
+ * not relax this without checking that set of alpha values first.
+ *
+ * The token is compared in constant time. */
 Eina_Bool
-termtymux_attach_escape_parse(const char *arg, const char **name,
-                              TermSrvAttachMode *mode, Eina_Bool *new_tab)
+termtymux_attach_escape_parse(const char *arg, const char *token,
+                              const char **name, TermSrvAttachMode *mode,
+                              Eina_Bool *new_tab, char nonce[9])
 {
    TermSrvAttachMode m = TSRV_ATTACH_HIJACK;
    Eina_Bool nt = EINA_FALSE;
+   unsigned char diff = 0;
+   int i;
 
    EINA_SAFETY_ON_NULL_RETURN_VAL(arg, EINA_FALSE);
    EINA_SAFETY_ON_NULL_RETURN_VAL(name, EINA_FALSE);
    EINA_SAFETY_ON_NULL_RETURN_VAL(mode, EINA_FALSE);
    EINA_SAFETY_ON_NULL_RETURN_VAL(new_tab, EINA_FALSE);
+   EINA_SAFETY_ON_NULL_RETURN_VAL(nonce, EINA_FALSE);
 
    if (*arg == 'n') { nt = EINA_TRUE; arg++; }
 
@@ -1133,9 +1139,31 @@ termtymux_attach_escape_parse(const char *arg, const char **name,
 
    if (*arg != ';') return EINA_FALSE;
    arg++;
-   if (termsrv_name_check(arg) < 0) return EINA_FALSE;
 
-   *name = arg;
+   EINA_SAFETY_ON_NULL_RETURN_VAL(token, EINA_FALSE);
+   if (strlen(token) != TERMPTY_HANDOFF_TOKEN_LEN) return EINA_FALSE;
+   for (i = 0; i < TERMPTY_HANDOFF_TOKEN_LEN; i++)
+     {
+        if (!arg[i]) return EINA_FALSE;
+        diff |= (unsigned char)(arg[i] ^ token[i]);
+     }
+   if (diff) return EINA_FALSE;
+   arg += TERMPTY_HANDOFF_TOKEN_LEN;
+   if (*arg != ';') return EINA_FALSE;
+   arg++;
+
+   for (i = 0; i < 8; i++)
+     {
+        if (!(((arg[i] >= '0') && (arg[i] <= '9')) ||
+              ((arg[i] >= 'a') && (arg[i] <= 'f'))))
+          return EINA_FALSE;
+     }
+   if (arg[8] != ';') return EINA_FALSE;
+   if (termsrv_name_check(&arg[9]) < 0) return EINA_FALSE;
+
+   memcpy(nonce, arg, 8);
+   nonce[8] = '\0';
+   *name = &arg[9];
    *mode = m;
    *new_tab = nt;
    return EINA_TRUE;
@@ -1498,71 +1526,83 @@ tytest_termtymux_input_chunks_send(void)
 }
 
 /* Test: the "at"/"ats"/"atr" hand-off escape argument, and its "atn"/
- * "atns"/"atnr" new-tab variants, parse to the right name, mode and
- * new_tab flag, and malformed or invalid variants are rejected. */
+ * "atns"/"atnr" new-tab variants, parse to the right name, mode, new_tab
+ * flag and nonce, and are rejected unless they carry the terminal's token. */
 int
 tytest_termtymux_attach_escape_parse(void)
 {
+#define TOKEN "0123456789abcdef0123456789abcdef"
+#define PARSE(arg, token) \
+   termtymux_attach_escape_parse(arg, token, &name, &mode, &new_tab, nonce)
    const char *name;
    TermSrvAttachMode mode;
    Eina_Bool new_tab;
+   char nonce[9];
 
-   assert(termtymux_attach_escape_parse(";work", &name, &mode, &new_tab));
+   assert(PARSE(";" TOKEN ";0000abcd;work", TOKEN));
    assert(!strcmp(name, "work"));
+   assert(!strcmp(nonce, "0000abcd"));
    assert(mode == TSRV_ATTACH_HIJACK);
    assert(!new_tab);
 
-   assert(termtymux_attach_escape_parse("s;work", &name, &mode, &new_tab));
-   assert(!strcmp(name, "work"));
+   assert(PARSE("s;" TOKEN ";0000abcd;work", TOKEN));
    assert(mode == TSRV_ATTACH_SHARED);
    assert(!new_tab);
 
-   assert(termtymux_attach_escape_parse("r;work", &name, &mode, &new_tab));
-   assert(!strcmp(name, "work"));
+   assert(PARSE("r;" TOKEN ";0000abcd;work", TOKEN));
    assert(mode == TSRV_ATTACH_READONLY);
    assert(!new_tab);
 
-   /* new-tab variants */
-   assert(termtymux_attach_escape_parse("n;work", &name, &mode, &new_tab));
-   assert(!strcmp(name, "work"));
+   assert(PARSE("n;" TOKEN ";0000abcd;work", TOKEN));
    assert(mode == TSRV_ATTACH_HIJACK);
    assert(new_tab);
 
-   assert(termtymux_attach_escape_parse("ns;work", &name, &mode, &new_tab));
-   assert(!strcmp(name, "work"));
+   assert(PARSE("ns;" TOKEN ";0000abcd;a;b", TOKEN));
+   assert(!strcmp(name, "a;b"));
    assert(mode == TSRV_ATTACH_SHARED);
    assert(new_tab);
 
-   assert(termtymux_attach_escape_parse("nr;work", &name, &mode, &new_tab));
-   assert(!strcmp(name, "work"));
+   assert(PARSE("nr;" TOKEN ";0000abcd;work", TOKEN));
    assert(mode == TSRV_ATTACH_READONLY);
    assert(new_tab);
 
-   /* missing ';' */
-   assert(!termtymux_attach_escape_parse("work", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("nwork", &name, &mode, &new_tab));
-   /* empty name */
-   assert(!termtymux_attach_escape_parse(";", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("n;", &name, &mode, &new_tab));
-   /* unknown variant letter */
-   assert(!termtymux_attach_escape_parse("x;work", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("nx;work", &name, &mode, &new_tab));
-   /* invalid name (path traversal) */
-   assert(!termtymux_attach_escape_parse(";../x", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("n;../x", &name, &mode, &new_tab));
+   /* the tokenless form of earlier versions */
+   assert(!PARSE(";work", TOKEN));
+   assert(!PARSE("n;work", TOKEN));
+   /* wrong, truncated or missing token */
+   assert(!PARSE(";ffffffffffffffffffffffffffffffff;0000abcd;work", TOKEN));
+   assert(!PARSE(";0123456789abcdef0123456789abcde;0000abcd;work", TOKEN));
+   assert(!PARSE(";;0000abcd;work", TOKEN));
+   /* a shadow pty has no token and accepts nothing */
+   assert(!PARSE(";" TOKEN ";0000abcd;work", ""));
+   assert(!PARSE(";;0000abcd;work", ""));
+   /* malformed nonce */
+   assert(!PARSE(";" TOKEN ";0000abc;work", TOKEN));
+   assert(!PARSE(";" TOKEN ";0000abcde;work", TOKEN));
+   assert(!PARSE(";" TOKEN ";0000abcg;work", TOKEN));
+   assert(!PARSE(";" TOKEN ";0000ABCD;work", TOKEN));
+   /* missing separators */
+   assert(!PARSE(";" TOKEN "0000abcd;work", TOKEN));
+   assert(!PARSE(";" TOKEN ";0000abcd", TOKEN));
+   /* empty and invalid names */
+   assert(!PARSE(";" TOKEN ";0000abcd;", TOKEN));
+   assert(!PARSE(";" TOKEN ";0000abcd;../x", TOKEN));
+   assert(!PARSE("n;" TOKEN ";0000abcd;../x", TOKEN));
+   /* unknown variant letters */
+   assert(!PARSE("x;" TOKEN ";0000abcd;work", TOKEN));
+   assert(!PARSE("nx;" TOKEN ";0000abcd;work", TOKEN));
 
-   /* the pre-existing 'at[on/true/yes/off/false/no]' alpha command (see
-    * win.c _cb_command()) must never be taken for a hand-off: none of its
-    * values contain ';' */
-   assert(!termtymux_attach_escape_parse("on", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("true", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("yes", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("off", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("false", &name, &mode, &new_tab));
-   assert(!termtymux_attach_escape_parse("no", &name, &mode, &new_tab));
-   /* a bare numeric alpha value, e.g. from a future extension */
-   assert(!termtymux_attach_escape_parse("128", &name, &mode, &new_tab));
+   /* the 'at[on/true/yes/off/false/no]' alpha command is not a hand-off */
+   assert(!PARSE("on", TOKEN));
+   assert(!PARSE("true", TOKEN));
+   assert(!PARSE("yes", TOKEN));
+   assert(!PARSE("off", TOKEN));
+   assert(!PARSE("false", TOKEN));
+   assert(!PARSE("no", TOKEN));
+   assert(!PARSE("128", TOKEN));
 
+#undef PARSE
+#undef TOKEN
    return 0;
 }
 
diff --git a/src/bin/termtymux.h b/src/bin/termtymux.h
index a6bdb167..43e23f53 100644
--- a/src/bin/termtymux.h
+++ b/src/bin/termtymux.h
@@ -128,20 +128,21 @@ Eina_Stringshare *termtymux_title_compose(const char *tymux_name,
                                           const char *title);
 
 /* Parses the argument of Terminology's private native hand-off escape,
- * "\033}at<variant>;NAME\0", where arg points right after "at":
- *   ";NAME"   -> TSRV_ATTACH_HIJACK
- *   "s;NAME"  -> TSRV_ATTACH_SHARED
- *   "r;NAME"  -> TSRV_ATTACH_READONLY
- * "n<variant>;NAME" asks for a new tab attached to NAME instead of
- * switching the current terminal (see tymux.c's --new-tab option):
- *   "n;NAME"  -> TSRV_ATTACH_HIJACK, new_tab
- *   "ns;NAME" -> TSRV_ATTACH_SHARED, new_tab
- *   "nr;NAME" -> TSRV_ATTACH_READONLY, new_tab
- * NAME is validated with termsrv_name_check(). On success, name points
- * into arg (no copy), mode and new_tab are set; returns EINA_FALSE and
- * leaves all three untouched for a malformed variant or an invalid name. */
-Eina_Bool termtymux_attach_escape_parse(const char *arg, const char **name,
+ * "\033}at<variant>;TOKEN;NONCE;NAME\0", where arg points right after "at"
+ * and TOKEN is the 32 hex digits of the terminal's handoff_token:
+ *   ";TOKEN;NONCE;NAME"   -> TSRV_ATTACH_HIJACK
+ *   "s;..."               -> TSRV_ATTACH_SHARED
+ *   "r;..."               -> TSRV_ATTACH_READONLY
+ * "n<variant>;..." asks for a new tab attached to NAME instead of
+ * switching the current terminal (see tymux.c's --new-tab option).
+ * NONCE is 8 lowercase hex digits, copied to nonce. NAME is validated with
+ * termsrv_name_check(). On success, name points into arg (no copy) and
+ * mode and new_tab are set. Returns EINA_FALSE and leaves the outputs
+ * untouched for a malformed variant, nonce or name, or when TOKEN differs
+ * from token. An empty token, as on a shadow pty, never matches. */
+Eina_Bool termtymux_attach_escape_parse(const char *arg, const char *token,
+                                        const char **name,
                                         TermSrvAttachMode *mode,
-                                        Eina_Bool *new_tab);
+                                        Eina_Bool *new_tab, char nonce[9]);
 
 #endif
diff --git a/src/bin/tymux.c b/src/bin/tymux.c
index 3a9556fc..15d15d68 100644
--- a/src/bin/tymux.c
+++ b/src/bin/tymux.c
@@ -13,6 +13,7 @@
 #include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/param.h>
+#include <sys/random.h>
 #include <sys/socket.h>
 #include <sys/time.h>
 #include <Eina.h>
@@ -650,9 +651,11 @@ _proxy_run(int sock)
  * session over natively (see _native_handoff_try()) instead of running
  * the inline proxy below.
  *
- * TERMINOLOGY is set by Terminology in the environment of the shells it
- * spawns, so its presence means our stdout is very likely a Terminology
- * terminal. $TMUX and $STY rule out the cases where that terminal is
+ * TERMINOLOGY_HANDOFF is set by Terminology in the environment of the
+ * shells it spawns, and is the secret the hand-off escape must carry. The
+ * hand-off needs it, and both stdin and stdout to be terminals, so that the
+ * token is never written to a file or a pipe. TERMINOLOGY alone is not
+ * enough: a session inherits it but has no token. $TMUX and $STY rule out the cases where that terminal is
  * multiplexed behind tmux or screen: the escape would only reach
  * whichever pane is currently attached to *that* multiplexer, not
  * necessarily us, and demoting the wrong pane's shell would be a
@@ -662,8 +665,12 @@ _proxy_run(int sock)
 static bool
 _native_handoff_allowed(void)
 {
+   const char *token = getenv("TERMINOLOGY_HANDOFF");
+
    if (getenv("TYMUX_NO_NATIVE")) return false;
-   if (!getenv("TERMINOLOGY")) return false;
+   if (!token || !*token) return false;
+   /* The escape carries the token: never write it to a file or a pipe */
+   if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO)) return false;
    if (getenv("TMUX") || getenv("STY")) return false;
    return true;
 }
@@ -678,25 +685,31 @@ _native_handoff_allowed(void)
 static bool
 _native_handoff_try(const char *name, TermSrvAttachMode mode, bool new_tab)
 {
-   char esc[128];
+   char esc[192];
    const char *variant;
+   const char *token;
+   uint32_t nonce;
    int n;
 
    if (!_native_handoff_allowed()) return false;
+   token = getenv("TERMINOLOGY_HANDOFF");
+   if (getrandom(&nonce, sizeof(nonce), 0) != (ssize_t)sizeof(nonce))
+     return false;
 
    switch (mode)
      {
       case TSRV_ATTACH_SHARED:
-        variant = new_tab ? "atns;" : "ats;";
+        variant = new_tab ? "atns" : "ats";
         break;
       case TSRV_ATTACH_READONLY:
-        variant = new_tab ? "atnr;" : "atr;";
+        variant = new_tab ? "atnr" : "atr";
         break;
       default:
-        variant = new_tab ? "atn;" : "at;";
+        variant = new_tab ? "atn" : "at";
         break;
      }
-   n = snprintf(esc, sizeof(esc), "\033}%s%s", variant, name);
+   n = snprintf(esc, sizeof(esc), "\033}%s;%s;%08x;%s", variant, token,
+                (unsigned)nonce, name);
    if (n <= 0 || (size_t)n >= sizeof(esc)) return false;
 
    /* +1 to also send the NUL that terminates a Terminology escape. */
diff --git a/src/bin/tymuxd.c b/src/bin/tymuxd.c
index 0a963ad2..fa702b32 100644
--- a/src/bin/tymuxd.c
+++ b/src/bin/tymuxd.c
@@ -214,6 +214,10 @@ main(int argc, char **argv)
    if (_listen_fd < 0)
      goto end;
 
+   /* A session never inherits the hand-off token of the terminal that
+    * spawned tymuxd, nor gets one of its own. */
+   unsetenv("TERMINOLOGY_HANDOFF");
+   termpty_handoff_token_enable_set(EINA_FALSE);
    setenv("TYMUX_NAME", name, 1);
    _tymux = termd_tymux_new(name, NULL);
    if (!_tymux)
diff --git a/src/bin/tytest_tymux.c b/src/bin/tytest_tymux.c
index f0b27de3..92a93ffa 100644
--- a/src/bin/tytest_tymux.c
+++ b/src/bin/tytest_tymux.c
@@ -73,6 +73,7 @@ _environment_setup(void)
    unsetenv("WAYLAND_DISPLAY");
    unsetenv("TYMUX_NAME");
    unsetenv("TERMINOLOGY");
+   unsetenv("TERMINOLOGY_HANDOFF");
    unsetenv("TMUX");
    unsetenv("STY");
    unsetenv("TYMUX_NO_NATIVE");
diff --git a/tests/tymux.py b/tests/tymux.py
index bb8b44c6..8ad5a18b 100644
--- a/tests/tymux.py
+++ b/tests/tymux.py
@@ -32,7 +32,8 @@ 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",
-                    "TERMINOLOGY", "TMUX", "STY", "TYMUX_NO_NATIVE")}
+                    "TERMINOLOGY", "TERMINOLOGY_HANDOFF", "TMUX", "STY",
+                    "TYMUX_NO_NATIVE")}
 ENV.update(XDG_RUNTIME_DIR=XDG, XDG_CONFIG_HOME=XDG, SHELL="/bin/sh",
            PS1="$ ", ENV=SHELL_RC, TERM="xterm-256color")
 failures = []
@@ -467,49 +468,87 @@ def main():
     b = Client(["new", NAME2])
     check(b.expect("$ "), "hand-off: second session shell prompt shown")
 
-    term_env = dict(ENV, TERMINOLOGY="1")
-    result = subprocess.run([TYMUX, "attach", NAME2], env=term_env,
-                            capture_output=True, timeout=10)
-    check(result.returncode == 0, "hand-off: attach exits 0")
-    check(result.stdout == b"\033}at;" + NAME2.encode() + b"\0",
-          "hand-off: attach emits the plain (hijack) escape")
+    TOKEN = "0123456789abcdef0123456789abcdef"
+    term_env = dict(ENV, TERMINOLOGY="1", TERMINOLOGY_HANDOFF=TOKEN)
 
-    result = subprocess.run([TYMUX, "attach", "--readonly", NAME2],
-                            env=term_env, capture_output=True, timeout=10)
-    check(result.stdout == b"\033}atr;" + NAME2.encode() + b"\0",
+    def escape_ok(out, variant, name):
+        return re.fullmatch(
+            b"\033}" + variant + b";" + TOKEN.encode() + b";[0-9a-f]{8};" +
+            name.encode() + b"\0", out) is not None
+    def handoff(args):
+        """tymux on a pty, as in a terminal; its status and output"""
+        client = Client(args, env=term_env)
+        client.wait()
+        client.idle(0.2)
+        return client
+
+    result = handoff(["attach", NAME2])
+    check(result.status == 0, "hand-off: attach exits 0")
+    check(escape_ok(result.out, b"at", NAME2),
+          "hand-off: attach emits the plain (hijack) escape with the token")
+
+    result = handoff(["attach", "--readonly", NAME2])
+    check(escape_ok(result.out, b"atr", NAME2),
           "hand-off: --readonly emits the atr; variant")
 
-    result = subprocess.run([TYMUX, "attach", "--shared", NAME2],
-                            env=term_env, capture_output=True, timeout=10)
-    check(result.stdout == b"\033}ats;" + NAME2.encode() + b"\0",
+    result = handoff(["attach", "--shared", NAME2])
+    check(escape_ok(result.out, b"ats", NAME2),
           "hand-off: --shared emits the ats; variant")
 
     NAME3 = "j%d" % os.getpid()
-    result = subprocess.run([TYMUX, "new", NAME3], env=term_env,
-                            capture_output=True, timeout=10)
-    check(result.returncode == 0 and
-          result.stdout == b"\033}at;" + NAME3.encode() + b"\0",
+    result = handoff(["new", NAME3])
+    check(result.status == 0 and
+          escape_ok(result.out, b"at", NAME3),
           "hand-off: 'tymux new' also hands off the freshly created session")
 
     # --new-tab: same variants, with an 'n' inserted right after "at".
-    result = subprocess.run([TYMUX, "attach", "--new-tab", NAME2],
-                            env=term_env, capture_output=True, timeout=10)
-    check(result.returncode == 0 and
-          result.stdout == b"\033}atn;" + NAME2.encode() + b"\0",
+    result = handoff(["attach", "--new-tab", NAME2])
+    check(result.status == 0 and
+          escape_ok(result.out, b"atn", NAME2),
           "hand-off: --new-tab emits the atn; variant")
 
-    result = subprocess.run(
-        [TYMUX, "attach", "--new-tab", "--readonly", NAME2],
-        env=term_env, capture_output=True, timeout=10)
-    check(result.stdout == b"\033}atnr;" + NAME2.encode() + b"\0",
+    result = handoff(["attach", "--new-tab", "--readonly", NAME2])
+    check(escape_ok(result.out, b"atnr", NAME2),
           "hand-off: --new-tab --readonly emits the atnr; variant")
 
-    result = subprocess.run(
-        [TYMUX, "attach", "--new-tab", "--shared", NAME2],
-        env=term_env, capture_output=True, timeout=10)
-    check(result.stdout == b"\033}atns;" + NAME2.encode() + b"\0",
+    result = handoff(["attach", "--new-tab", "--shared", NAME2])
+    check(escape_ok(result.out, b"atns", NAME2),
           "hand-off: --new-tab --shared emits the atns; variant")
 
+    # With either end not a terminal the token must not be written: the
+    # output could be a file that a later cat in the terminal would replay.
+    # Each case keeps the other end on a pty, to test one half of the
+    # condition at a time.
+    def new_tab_with_redirect(redirect_stdout):
+        master, slave = pty.openpty()
+        redirected = os.path.join(XDG, "redirected")
+        try:
+            with open(redirected, "wb") as out:
+                result = subprocess.run(
+                    [TYMUX, "attach", "--new-tab", NAME2], env=term_env,
+                    stdin=slave if redirect_stdout else subprocess.DEVNULL,
+                    stdout=out if redirect_stdout else slave,
+                    stderr=subprocess.PIPE, timeout=10)
+            if redirect_stdout:
+                with open(redirected, "rb") as out:
+                    written = out.read()
+            else:
+                written = os.read(master, 65536) if select.select(
+                    [master], [], [], 0.2)[0] else b""
+        finally:
+            os.close(master)
+            os.close(slave)
+        return result, written
+
+    for redirect_stdout, what in ((True, "stdout"), (False, "stdin")):
+        result, written = new_tab_with_redirect(redirect_stdout)
+        check(TOKEN.encode() not in written and b"\033}" not in written,
+              "hand-off: %s not a terminal gets no escape and no token"
+              % what)
+        check(result.returncode == 1 and b"--new-tab" in result.stderr,
+              "hand-off: %s not a terminal takes the non-hand-off path"
+              % what)
+
     # Outside Terminology, --new-tab cannot work (there is no tab to open
     # into): it must fail loudly instead of silently proxying.
     result = subprocess.run([TYMUX, "attach", "--new-tab", NAME2], env=ENV,
@@ -532,6 +571,26 @@ def main():
     forced.send("\x02d")
     check(forced.wait() == 0, "hand-off: forced proxy detaches normally")
 
+    # Without the token the escape could never be accepted: TERMINOLOGY
+    # alone, as inherited by a session, keeps the inline proxy.
+    tokenless = dict(ENV, TERMINOLOGY="1")
+    proxied = Client(["attach", NAME2], env=tokenless)
+    check(proxied.expect("$ "),
+          "hand-off: TERMINOLOGY without a token runs the inline proxy")
+    proxied.send("\x02d")
+    check(proxied.wait() == 0, "hand-off: tokenless proxy detaches normally")
+
+    # A shell in a session never holds the token of the terminal that
+    # spawned tymuxd.
+    NAME9 = "g%d" % os.getpid()
+    g = Client(["new", NAME9], env=dict(term_env, TYMUX_NO_NATIVE="1"))
+    check(g.expect("$ "), "hand-off: session spawned with a token starts")
+    g.send("echo handoff=${TERMINOLOGY_HANDOFF-unset}\r")
+    check(g.expect("handoff=unset"),
+          "hand-off: a session shell has no TERMINOLOGY_HANDOFF")
+    check(TOKEN.encode() not in g.out,
+          "hand-off: the token does not reach a session shell")
+    tymux("kill", NAME9)
     tymux("kill", NAME2)
     tymux("kill", NAME3)
 
diff --git a/tests/tymux_attach_escape.sh b/tests/tymux_attach_escape.sh
index 586e99fc..f0429abf 100644
--- a/tests/tymux_attach_escape.sh
+++ b/tests/tymux_attach_escape.sh
@@ -3,8 +3,8 @@
 . "$(dirname "$0")/utils.sh"
 
 # Terminology's private native tymux hand-off escape
-# ("\033}at[n][s|r];NAME\0", emitted by 'tymux attach'/'tymux new' when
-# run inside Terminology, see termtymux_attach_escape_parse() and
+# ("\033}at[n][s|r];TOKEN;NONCE;NAME\0", emitted by 'tymux attach'/'tymux new'
+# when run inside Terminology, see termtymux_attach_escape_parse() and
 # _termio_tymux_switch()/_termio_tymux_newtab() in termio.c). The 'n'
 # variants (atn;/atns;/atnr;) ask for a new tab instead of switching the
 # current terminal (see 'tymux attach --new-tab' in tymux(1)).
@@ -20,45 +20,45 @@
 printf '\033[2J\033[0;0H'
 
 # plain (hijack) attach
-printf '\033}at;work\000'
+printf '\033}at;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'A'
 
 # shared attach
-printf '\033}ats;work\000'
+printf '\033}ats;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'B'
 
 # readonly attach
-printf '\033}atr;work\000'
+printf '\033}atr;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'C'
 
 # empty name — rejected by termsrv_name_check(), still a complete escape
-printf '\033}at;\000'
+printf '\033}at;0123456789abcdef0123456789abcdef;0000abcd;\000'
 printf 'D'
 
 # invalid name (path traversal) — rejected by termsrv_name_check()
-printf '\033}at;../x\000'
+printf '\033}at;0123456789abcdef0123456789abcdef;0000abcd;../x\000'
 printf 'E'
 
 # unknown variant letter
-printf '\033}atx;work\000'
+printf '\033}atx;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'F'
 
 # new-tab, hijack
-printf '\033}atn;work\000'
+printf '\033}atn;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'G'
 
 # new-tab, shared
-printf '\033}atns;work\000'
+printf '\033}atns;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'H'
 
 # new-tab, readonly
-printf '\033}atnr;work\000'
+printf '\033}atnr;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'I'
 
 # new-tab, empty name
-printf '\033}atn;\000'
+printf '\033}atn;0123456789abcdef0123456789abcdef;0000abcd;\000'
 printf 'J'
 
 # new-tab, unknown variant letter after 'n'
-printf '\033}atnx;work\000'
+printf '\033}atnx;0123456789abcdef0123456789abcdef;0000abcd;work\000'
 printf 'K'

-- 
To stop receiving notification emails like this one, please contact
the administrator of this repository.

Reply via email to