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

git pushed a commit to branch tymux-10-quiet-head
in repository terminology.

View the commit online.

commit 4dc994436f1cddf47eb2f231085dc94a6166f0bf
Author: Cedric BAIL <[email protected]>
AuthorDate: Wed Nov 18 21:56:35 2026 -0600

    termsrv: add the backlog page format and messages
    
    The daemon streams the backlog line by line over the socket, which makes
    every attach copy it all. Backlog pages are memfds the client maps
    instead. Add the page layout, messages 14-18 (page request, page with
    its memfd, release, and the map of entry widths), and the plumbing
    they need. Nothing sends them yet.
    
    TermSrvReader used to let the kernel close any descriptor passed along.
    It now keeps one per message, handed over with termsrv_reader_next_fd(),
    and still closes it for termsrv_reader_next().
    
    ATTACHED and NOTIFY grow by first_page_id and page_count, which the
    daemon leaves at zero until it has pages. The sizes grow from 12 to 20
    and from 16 to 24 bytes, so tests/tymux.py reads the larger ATTACHED.
    
    tests/tybenchd_reset.py: its stand-in sends the longer ATTACHED.
---
 src/bin/termd_tymux.c   |   2 +-
 src/bin/termsrv.c       | 502 ++++++++++++++++++++++++++++++++++++++++++++----
 src/bin/termsrv.h       | 120 +++++++++++-
 src/bin/tytest.c        |   2 +
 src/bin/unit_tests.h    |   2 +
 tests/tybenchd_reset.py |   2 +-
 tests/tymux.py          |  20 +-
 7 files changed, 594 insertions(+), 56 deletions(-)

diff --git a/src/bin/termd_tymux.c b/src/bin/termd_tymux.c
index de2532d9..ca6860ca 100644
--- a/src/bin/termd_tymux.c
+++ b/src/bin/termd_tymux.c
@@ -571,7 +571,7 @@ _client_attach(Client *client, TermSrvAttachMode mode)
    Client *other;
 
    if (termsrv_send_attached(client->fd, td->shm_fd, ty->w, ty->h,
-                             ty->pid > 0 ? ty->pid : -1) < 0)
+                             ty->pid > 0 ? ty->pid : -1, 0, 0) < 0)
      {
         _client_del(client);
         return;
diff --git a/src/bin/termsrv.c b/src/bin/termsrv.c
index 568a1dbd..84faa1ef 100644
--- a/src/bin/termsrv.c
+++ b/src/bin/termsrv.c
@@ -417,19 +417,43 @@ _recv_all(int fd, void *buf, size_t len)
 }
 
 int
-termsrv_msg_send(int fd, TermSrvMsgType type,
-                 const void *payload, uint32_t size)
+termsrv_msg_send_fd(int fd, TermSrvMsgType type,
+                    const void *payload, uint32_t size, int pass_fd)
 {
    TermSrvMsgHdr hdr = { .type = type, .size = payload ? size : 0 };
    struct iovec iov[2] = {
         { .iov_base = &hdr, .iov_len = sizeof(hdr) },
         { .iov_base = (void *)payload, .iov_len = hdr.size },
    };
+   union {
+      char buf[CMSG_SPACE(sizeof(int))];
+      struct cmsghdr align;
+   } control;
    struct msghdr msg = { .msg_iov = iov, .msg_iovlen = hdr.size ? 2 : 1 };
 
+   if (pass_fd >= 0)
+     {
+        struct cmsghdr *cm;
+
+        memset(&control, 0, sizeof(control));
+        msg.msg_control = control.buf;
+        msg.msg_controllen = sizeof(control.buf);
+        cm = CMSG_FIRSTHDR(&msg);
+        cm->cmsg_level = SOL_SOCKET;
+        cm->cmsg_type = SCM_RIGHTS;
+        cm->cmsg_len = CMSG_LEN(sizeof(int));
+        memcpy(CMSG_DATA(cm), &pass_fd, sizeof(int));
+     }
    return _sendmsg_all(fd, &msg);
 }
 
+int
+termsrv_msg_send(int fd, TermSrvMsgType type,
+                 const void *payload, uint32_t size)
+{
+   return termsrv_msg_send_fd(fd, type, payload, size, -1);
+}
+
 int
 termsrv_backlog_line_append(void *buf, uint32_t bufsz, uint32_t *off,
                             uint32_t cols, const TermSrvCell *cells)
@@ -468,10 +492,120 @@ termsrv_backlog_line_next(const void *payload, uint32_t size,
    return 1;
 }
 
+int
+termsrv_backlog_map_page_append(void *buf, uint32_t bufsz, uint32_t *off,
+                                uint32_t page_id, uint32_t num_entries,
+                                const _Atomic uint32_t *widths)
+{
+   uint64_t need = 2 * sizeof(uint32_t) +
+      (uint64_t)num_entries * sizeof(uint32_t);
+   unsigned char *out = buf;
+   uint32_t i;
+
+   if (num_entries > TERMSRV_BACKLOG_PAGE_ENTRIES ||
+       *off > bufsz || need > (uint64_t)(bufsz - *off))
+     return -1;
+   memcpy(out + *off, &page_id, sizeof(page_id));
+   memcpy(out + *off + sizeof(page_id), &num_entries, sizeof(num_entries));
+   *off += 2 * sizeof(uint32_t);
+   for (i = 0; i < num_entries; i++)
+     {
+        uint32_t w = atomic_load_explicit(&widths[i], memory_order_relaxed);
+
+        memcpy(out + *off, &w, sizeof(w));
+        *off += sizeof(w);
+     }
+   return 0;
+}
+
+int
+termsrv_backlog_map_page_next(const void *payload, uint32_t size,
+                              uint32_t *off, uint32_t *page_id,
+                              uint32_t *num_entries, const uint32_t **widths)
+{
+   const unsigned char *in = payload;
+   uint32_t count;
+
+   if (*off == size)
+     return 0;
+   if (*off > size || size - *off < 2 * sizeof(uint32_t))
+     return -1;
+   memcpy(&count, in + *off + sizeof(uint32_t), sizeof(count));
+   if (count > TERMSRV_BACKLOG_PAGE_ENTRIES ||
+       (uint64_t)count * sizeof(uint32_t) >
+       (uint64_t)(size - *off - 2 * sizeof(uint32_t)))
+     return -1;
+   memcpy(page_id, in + *off, sizeof(*page_id));
+   *num_entries = count;
+   *widths = (const uint32_t *)(in + *off + 2 * sizeof(uint32_t));
+   *off += 2 * sizeof(uint32_t) + count * (uint32_t)sizeof(uint32_t);
+   return 1;
+}
+
 /* What one call reads at most, so that a fast peer cannot keep the other
  * end busy */
 #define READER_FILL_MAX (4 * (TERMSRV_MAX_MSG_PAYLOAD + sizeof(TermSrvMsgHdr)))
 
+/* Queue the file descriptor that came with a read ending at stream offset
+ * end. Returns -1 if it was not exactly one descriptor, or on allocation
+ * failure. */
+static int
+_reader_fd_queue(TermSrvReader *reader, struct msghdr *msg, uint64_t end)
+{
+   struct cmsghdr *cm;
+   int fd = -1;
+   int ret = 0;
+
+   for (cm = CMSG_FIRSTHDR(msg); cm; cm = CMSG_NXTHDR(msg, cm))
+     {
+        size_t i, count;
+        unsigned char *data = ""
+
+        if (cm->cmsg_level != SOL_SOCKET || cm->cmsg_type != SCM_RIGHTS)
+          continue;
+        count = (cm->cmsg_len - CMSG_LEN(0)) / sizeof(int);
+        for (i = 0; i < count; i++)
+          {
+             int got;
+
+             memcpy(&got, data + i * sizeof(int), sizeof(int));
+             if (fd < 0)
+               fd = got;
+             else
+               {
+                  close(got);
+                  ret = -1;
+               }
+          }
+     }
+   if (msg->msg_flags & MSG_CTRUNC)
+     ret = -1;
+   if (fd < 0)
+     return ret;
+   if (ret < 0 || reader->fds_count >= TERMSRV_READER_FDS_MAX)
+     {
+        close(fd);
+        return -1;
+     }
+   if (reader->fds_count == reader->fds_cap)
+     {
+        unsigned int cap = reader->fds_cap ? reader->fds_cap * 2 : 4;
+        void *fds = realloc(reader->fds, cap * sizeof(*reader->fds));
+
+        if (!fds)
+          {
+             close(fd);
+             return -1;
+          }
+        reader->fds = fds;
+        reader->fds_cap = cap;
+     }
+   reader->fds[reader->fds_count].fd = fd;
+   reader->fds[reader->fds_count].end = end;
+   reader->fds_count++;
+   return 0;
+}
+
 int
 termsrv_reader_fill(TermSrvReader *reader, int fd)
 {
@@ -487,16 +621,30 @@ termsrv_reader_fill(TermSrvReader *reader, int fd)
    if (reader->start > 0)
      {
         eina_binbuf_remove(buf, 0, reader->start);
+        reader->base += reader->start;
         reader->start = 0;
      }
    while (got < READER_FILL_MAX)
      {
         unsigned char chunk[4096];
+        struct iovec iov = { .iov_base = chunk, .iov_len = sizeof(chunk) };
+        union {
+           char buf[CMSG_SPACE(sizeof(int))];
+           struct cmsghdr align;
+        } control;
+        struct msghdr msg = {
+             .msg_iov = &iov,
+             .msg_iovlen = 1,
+             .msg_control = control.buf,
+             .msg_controllen = sizeof(control.buf),
+        };
         ssize_t n;
 
-        /* without a control buffer, the kernel closes any file descriptor
-         * passed along */
-        n = recv(fd, chunk, sizeof(chunk), MSG_DONTWAIT);
+        /* leave the rest in the socket until the caller has consumed the
+         * messages that own these descriptors */
+        if (reader->fds_count >= TERMSRV_READER_FDS_MAX)
+          return 0;
+        n = recvmsg(fd, &msg, MSG_DONTWAIT | MSG_CMSG_CLOEXEC);
         if (n == 0)
           {
              reader->eof = 1;
@@ -513,13 +661,19 @@ termsrv_reader_fill(TermSrvReader *reader, int fd)
         if (!eina_binbuf_append_length(buf, chunk, (size_t)n))
           return -1;
         got += (size_t)n;
+        /* the descriptor goes with the message that has the last header
+         * starting before the end of this read */
+        if (msg.msg_controllen > 0 &&
+            _reader_fd_queue(reader, &msg,
+                             reader->base + eina_binbuf_length_get(buf)) < 0)
+          return -1;
      }
    return 0;
 }
 
 int
-termsrv_reader_next(TermSrvReader *reader,
-                    void **payload_out, uint32_t *size_out)
+termsrv_reader_next_fd(TermSrvReader *reader,
+                       void **payload_out, uint32_t *size_out, int *fd_out)
 {
    Eina_Binbuf *buf = reader->buf;
    size_t len = buf ? eina_binbuf_length_get(buf) : 0;
@@ -527,18 +681,24 @@ termsrv_reader_next(TermSrvReader *reader,
    const unsigned char *data;
    TermSrvMsgHdr hdr;
    void *payload = NULL;
+   uint64_t msg_start, msg_end;
+   unsigned int taken = 0;
 
    *payload_out = NULL;
    *size_out = 0;
+   *fd_out = -1;
+   /* A full queue with no whole message to take descriptors from can only
+    * come from a peer passing more than one per message: fill() would
+    * never read again, so end the connection rather than stall. */
    if (avail < sizeof(hdr))
-     return 0;
+     return reader->fds_count >= TERMSRV_READER_FDS_MAX ? -1 : 0;
    data = ""
    memcpy(&hdr, data + reader->start, sizeof(hdr));
    if (hdr.type == 0 || hdr.type > TSRV_MSG_LAST ||
        hdr.size > TERMSRV_MAX_MSG_PAYLOAD)
      return -1;
    if (avail < sizeof(hdr) + hdr.size)
-     return 0;
+     return reader->fds_count >= TERMSRV_READER_FDS_MAX ? -1 : 0;
    if (hdr.size > 0)
      {
         payload = malloc(hdr.size);
@@ -546,56 +706,64 @@ termsrv_reader_next(TermSrvReader *reader,
           return -1;
         memcpy(payload, data + reader->start + sizeof(hdr), hdr.size);
      }
+   msg_start = reader->base + reader->start;
+   msg_end = msg_start + sizeof(hdr) + hdr.size;
+   /* a descriptor read before this message starts has no owner left */
+   while (taken < reader->fds_count && reader->fds[taken].end <= msg_start)
+     close(reader->fds[taken++].fd);
+   if (taken < reader->fds_count && reader->fds[taken].end <= msg_end)
+     *fd_out = reader->fds[taken++].fd;
+   if (taken > 0)
+     {
+        reader->fds_count -= taken;
+        memmove(reader->fds, reader->fds + taken,
+                reader->fds_count * sizeof(*reader->fds));
+     }
    reader->start += sizeof(hdr) + hdr.size;
    *payload_out = payload;
    *size_out = hdr.size;
    return (int)hdr.type;
 }
 
+int
+termsrv_reader_next(TermSrvReader *reader,
+                    void **payload_out, uint32_t *size_out)
+{
+   int fd;
+   int type = termsrv_reader_next_fd(reader, payload_out, size_out, &fd);
+
+   if (fd >= 0)
+     close(fd);
+   return type;
+}
+
 void
 termsrv_reader_clear(TermSrvReader *reader)
 {
+   unsigned int i;
+
+   for (i = 0; i < reader->fds_count; i++)
+     close(reader->fds[i].fd);
+   free(reader->fds);
    eina_binbuf_free(reader->buf);
    memset(reader, 0, sizeof(*reader));
 }
 
 int
 termsrv_send_attached(int fd, int shm_fd,
-                      uint32_t cols, uint32_t rows, int32_t shell_pid)
+                      uint32_t cols, uint32_t rows, int32_t shell_pid,
+                      uint32_t first_page_id, uint32_t page_count)
 {
-   TermSrvMsgHdr hdr = {
-        .type = TSRV_MSG_ATTACHED,
-        .size = sizeof(TermSrvMsgAttached),
-   };
    TermSrvMsgAttached attached = {
         .cols = cols,
         .rows = rows,
         .shell_pid = shell_pid,
+        .first_page_id = first_page_id,
+        .page_count = page_count,
    };
-   struct iovec iov[2] = {
-        { .iov_base = &hdr, .iov_len = sizeof(hdr) },
-        { .iov_base = &attached, .iov_len = sizeof(attached) },
-   };
-   union {
-      char buf[CMSG_SPACE(sizeof(int))];
-      struct cmsghdr align;
-   } control;
-   struct msghdr msg = {
-        .msg_iov = iov,
-        .msg_iovlen = 2,
-        .msg_control = control.buf,
-        .msg_controllen = sizeof(control.buf),
-   };
-   struct cmsghdr *cm;
 
-   memset(&control, 0, sizeof(control));
-   cm = CMSG_FIRSTHDR(&msg);
-   cm->cmsg_level = SOL_SOCKET;
-   cm->cmsg_type = SCM_RIGHTS;
-   cm->cmsg_len = CMSG_LEN(sizeof(int));
-   memcpy(CMSG_DATA(cm), &shm_fd, sizeof(int));
-
-   return _sendmsg_all(fd, &msg);
+   return termsrv_msg_send_fd(fd, TSRV_MSG_ATTACHED,
+                              &attached, sizeof(attached), shm_fd);
 }
 
 int
@@ -698,6 +866,7 @@ termsrv_chord_flush(TermSrvChord *chord, Eina_Binbuf *out)
 #include <fcntl.h>
 #include <poll.h>
 #include <pthread.h>
+#include <sys/mman.h>
 #include <Elementary.h>
 #include "termpty.h"
 
@@ -1250,18 +1419,20 @@ tytest_termsrv_attached(void)
    assert(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
    assert(pipe(pipefd) == 0);
 
-   assert(termsrv_send_attached(sv[0], pipefd[0], 132, 43, 4242) == 0);
+   assert(termsrv_send_attached(sv[0], pipefd[0], 132, 43, 4242,
+                                   17, 3) == 0);
    assert(termsrv_recv_attached(sv[1], &shm_fd, &attached) == 0);
    assert(shm_fd >= 0 && shm_fd != pipefd[0]);
    assert(fcntl(shm_fd, F_GETFD) & FD_CLOEXEC);
    assert(attached.cols == 132 && attached.rows == 43);
    assert(attached.shell_pid == 4242);
+   assert(attached.first_page_id == 17 && attached.page_count == 3);
    assert(write(pipefd[1], "ty", 3) == 3);
    assert(read(shm_fd, buf, 3) == 3 && strcmp(buf, "ty") == 0);
    close(shm_fd);
 
    /* the message after ATTACHED is left to the reader */
-   assert(termsrv_send_attached(sv[0], pipefd[0], 80, 24, -1) == 0);
+   assert(termsrv_send_attached(sv[0], pipefd[0], 80, 24, -1, 0, 0) == 0);
    assert(termsrv_msg_send(sv[0], TSRV_MSG_BELL, NULL, 0) == 0);
    assert(termsrv_recv_attached(sv[1], &shm_fd, &attached) == 0);
    assert(shm_fd >= 0 && attached.cols == 80 && attached.shell_pid == -1);
@@ -1500,4 +1671,257 @@ tytest_termsrv_backlog_line(void)
 
    return 0;
 }
+
+int
+tytest_termsrv_backlog_page_fd(void)
+{
+   TermSrvReader reader = { 0 };
+   TermSrvMsgBacklogPageId id = { .page_id = 42 }, *got;
+   void *payload;
+   uint32_t size;
+   char buf[4];
+   int sv[2], mem_fd, page_fd = -1, i;
+
+   assert(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
+   mem_fd = memfd_create("test-page", MFD_CLOEXEC);
+   assert(mem_fd >= 0);
+   assert(write(mem_fd, "TMBP", 4) == 4);
+
+   assert(termsrv_msg_send_fd(sv[0], TSRV_MSG_BACKLOG_PAGE,
+                              &id, sizeof(id), mem_fd) == 0);
+   id.page_id = 43;
+   assert(termsrv_msg_send(sv[0], TSRV_MSG_BACKLOG_PAGE_REQ,
+                           &id, sizeof(id)) == 0);
+
+   assert(termsrv_reader_fill(&reader, sv[1]) == 0);
+   assert(termsrv_reader_next_fd(&reader, &payload, &size, &page_fd) ==
+          TSRV_MSG_BACKLOG_PAGE);
+   got = payload;
+   assert(size == sizeof(*got) && got->page_id == 42);
+   free(payload);
+   assert(page_fd >= 0 && page_fd != mem_fd);
+   assert(fcntl(page_fd, F_GETFD) & FD_CLOEXEC);
+   assert(pread(page_fd, buf, 4, 0) == 4 && !memcmp(buf, "TMBP", 4));
+   close(page_fd);
+
+   page_fd = 123;
+   assert(termsrv_reader_next_fd(&reader, &payload, &size, &page_fd) ==
+          TSRV_MSG_BACKLOG_PAGE_REQ);
+   got = payload;
+   assert(got->page_id == 43 && page_fd == -1);
+   free(payload);
+
+   /* termsrv_reader_next() closes the fd it is not asked for */
+   assert(termsrv_msg_send_fd(sv[0], TSRV_MSG_BACKLOG_PAGE,
+                              &id, sizeof(id), mem_fd) == 0);
+   assert(_msg_recv(&reader, sv[1], &payload, &size) ==
+          TSRV_MSG_BACKLOG_PAGE);
+   free(payload);
+
+   /* an fd arriving in the same read as plain messages before and after
+    * it stays with its own message */
+   assert(termsrv_msg_send(sv[0], TSRV_MSG_BELL, NULL, 0) == 0);
+   assert(termsrv_msg_send_fd(sv[0], TSRV_MSG_BACKLOG_PAGE,
+                              &id, sizeof(id), mem_fd) == 0);
+   assert(termsrv_msg_send(sv[0], TSRV_MSG_BELL, NULL, 0) == 0);
+   assert(termsrv_reader_fill(&reader, sv[1]) == 0);
+   assert(termsrv_reader_next_fd(&reader, &payload, &size, &page_fd) ==
+          TSRV_MSG_BELL && page_fd == -1);
+   assert(termsrv_reader_next_fd(&reader, &payload, &size, &page_fd) ==
+          TSRV_MSG_BACKLOG_PAGE && page_fd >= 0);
+   free(payload);
+   close(page_fd);
+   assert(termsrv_reader_next_fd(&reader, &payload, &size, &page_fd) ==
+          TSRV_MSG_BELL && page_fd == -1);
+
+   /* more fd messages than the reader queues in one fill: it stops early
+    * and the rest is read once the earlier messages are consumed */
+   {
+      int mem[100], received = 0;
+
+      for (i = 0; i < 100; i++)
+        {
+           char tag = (char)i;
+
+           mem[i] = memfd_create("test-page", MFD_CLOEXEC);
+           assert(mem[i] >= 0 && write(mem[i], &tag, 1) == 1);
+           id.page_id = (uint32_t)i;
+           assert(termsrv_msg_send_fd(sv[0], TSRV_MSG_BACKLOG_PAGE,
+                                      &id, sizeof(id), mem[i]) == 0);
+        }
+      while (received < 100)
+        {
+           int type;
+
+           assert(termsrv_reader_fill(&reader, sv[1]) == 0);
+           while ((type = termsrv_reader_next_fd(&reader, &payload, &size,
+                                                 &page_fd)) > 0)
+             {
+                char tag;
+
+                got = payload;
+                assert(type == TSRV_MSG_BACKLOG_PAGE &&
+                       got->page_id == (uint32_t)received);
+                assert(page_fd >= 0 &&
+                       pread(page_fd, &tag, 1, 0) == 1 &&
+                       tag == (char)received);
+                free(payload);
+                close(page_fd);
+                received++;
+             }
+           assert(type == 0);
+        }
+      assert(!_readable(sv[1]));
+      for (i = 0; i < 100; i++)
+        close(mem[i]);
+   }
+
+   /* a peer that keeps passing descriptors inside one unfinished message
+    * ends the stream instead of leaving the reader stalled */
+   {
+      TermSrvReader stuck = { 0 };
+      TermSrvMsgHdr hdr = { TSRV_MSG_INPUT, TERMSRV_MAX_MSG_PAYLOAD };
+      int pair[2], type;
+
+      assert(socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == 0);
+      assert(write(pair[0], &hdr, sizeof(hdr)) == (ssize_t)sizeof(hdr));
+      for (i = 0; i < TERMSRV_READER_FDS_MAX + 1; i++)
+        {
+           struct iovec iov = { "x", 1 };
+           union {
+              char buf[CMSG_SPACE(sizeof(int))];
+              struct cmsghdr align;
+           } control;
+           struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1,
+                                 .msg_control = control.buf,
+                                 .msg_controllen = sizeof(control.buf) };
+           struct cmsghdr *cm;
+
+           memset(&control, 0, sizeof(control));
+           cm = CMSG_FIRSTHDR(&msg);
+           cm->cmsg_level = SOL_SOCKET;
+           cm->cmsg_type = SCM_RIGHTS;
+           cm->cmsg_len = CMSG_LEN(sizeof(int));
+           memcpy(CMSG_DATA(cm), &mem_fd, sizeof(int));
+           assert(sendmsg(pair[0], &msg, MSG_NOSIGNAL) == 1);
+        }
+      assert(termsrv_reader_fill(&stuck, pair[1]) == 0);
+      type = termsrv_reader_next(&stuck, &payload, &size);
+      assert(type < 0);
+      termsrv_reader_clear(&stuck);
+      close(pair[0]);
+      close(pair[1]);
+   }
+
+   /* two descriptors in one message are refused */
+   {
+      struct {
+         TermSrvMsgHdr hdr;
+         TermSrvMsgBacklogPageId id;
+      } msg_buf = { .hdr = { TSRV_MSG_BACKLOG_PAGE, sizeof(id) } };
+      struct iovec iov = { &msg_buf, sizeof(msg_buf) };
+      union {
+         char buf[CMSG_SPACE(2 * sizeof(int))];
+         struct cmsghdr align;
+      } control;
+      struct msghdr msg = { .msg_iov = &iov, .msg_iovlen = 1,
+                            .msg_control = control.buf,
+                            .msg_controllen = sizeof(control.buf) };
+      struct cmsghdr *cm;
+      int two[2] = { mem_fd, mem_fd };
+
+      memset(&control, 0, sizeof(control));
+      cm = CMSG_FIRSTHDR(&msg);
+      cm->cmsg_level = SOL_SOCKET;
+      cm->cmsg_type = SCM_RIGHTS;
+      cm->cmsg_len = CMSG_LEN(sizeof(two));
+      memcpy(CMSG_DATA(cm), two, sizeof(two));
+      assert(sendmsg(sv[0], &msg, MSG_NOSIGNAL) == (ssize_t)sizeof(msg_buf));
+      assert(termsrv_reader_fill(&reader, sv[1]) < 0);
+   }
+
+   /* fds still queued when the reader is cleared are closed: ASan's
+    * leak checker reports them otherwise */
+   for (i = 0; i < 4; i++)
+     assert(termsrv_msg_send_fd(sv[0], TSRV_MSG_BACKLOG_PAGE,
+                                &id, sizeof(id), mem_fd) == 0);
+   assert(termsrv_reader_fill(&reader, sv[1]) == 0);
+   termsrv_reader_clear(&reader);
+
+   close(mem_fd);
+   close(sv[0]);
+   close(sv[1]);
+   return 0;
+}
+
+int
+tytest_termsrv_backlog_map(void)
+{
+   _Alignas(uint32_t) unsigned char buf[2048];
+   _Atomic uint32_t widths[TERMSRV_BACKLOG_PAGE_ENTRIES];
+   const uint32_t *got;
+   uint32_t off = 0, end, page_id, num_entries, bad;
+
+   memset(widths, 0, sizeof(widths));
+   atomic_store(&widths[0], 1);
+   atomic_store(&widths[1], 2);
+   atomic_store(&widths[2], 3);
+
+   assert(termsrv_backlog_map_page_append(buf, sizeof(buf), &off,
+                                          7, 3, widths) == 0);
+   assert(termsrv_backlog_map_page_append(buf, sizeof(buf), &off,
+                                          8, 0, widths) == 0);
+   assert(off == 2 * 2 * sizeof(uint32_t) + 3 * sizeof(uint32_t));
+   end = off;
+
+   off = 0;
+   assert(termsrv_backlog_map_page_next(buf, end, &off, &page_id,
+                                        &num_entries, &got) == 1);
+   assert(page_id == 7 && num_entries == 3);
+   assert(got[0] == 1 && got[1] == 2 && got[2] == 3);
+   assert(termsrv_backlog_map_page_next(buf, end, &off, &page_id,
+                                        &num_entries, &got) == 1);
+   assert(page_id == 8 && num_entries == 0);
+   assert(termsrv_backlog_map_page_next(buf, end, &off, &page_id,
+                                        &num_entries, &got) == 0);
+
+   /* truncated in the middle of the widths, or of the page header */
+   off = 0;
+   assert(termsrv_backlog_map_page_next(buf, 2 * sizeof(uint32_t) + 4, &off,
+                                        &page_id, &num_entries, &got) < 0);
+   off = 0;
+   assert(termsrv_backlog_map_page_next(buf, 4, &off, &page_id,
+                                        &num_entries, &got) < 0);
+
+   /* more entries than a page holds */
+   bad = TERMSRV_BACKLOG_PAGE_ENTRIES + 1;
+   memcpy(buf, &(uint32_t){ 9 }, sizeof(uint32_t));
+   memcpy(buf + sizeof(uint32_t), &bad, sizeof(bad));
+   memset(buf + 2 * sizeof(uint32_t), 0, bad * sizeof(uint32_t));
+   off = 0;
+   assert(termsrv_backlog_map_page_next(buf, sizeof(buf), &off, &page_id,
+                                        &num_entries, &got) < 0);
+   assert(termsrv_backlog_map_page_append(buf, sizeof(buf), &(uint32_t){ 0 },
+                                          9, bad, widths) < 0);
+
+   /* a full page that does not fit, and one that fits exactly */
+   off = 0;
+   assert(termsrv_backlog_map_page_append(buf, 2 * sizeof(uint32_t) + 8,
+                                          &off, 1, 3, widths) < 0);
+   assert(off == 0);
+   assert(termsrv_backlog_map_page_append(buf, 2 * sizeof(uint32_t) + 8,
+                                          &off, 1, 2, widths) == 0);
+   assert(off == 2 * sizeof(uint32_t) + 8);
+
+   /* after the echoed range of a TermSrvMsgBacklogMapReq */
+   off = sizeof(TermSrvMsgBacklogMapReq);
+   assert(termsrv_backlog_map_page_append(buf, sizeof(buf), &off,
+                                          5, 1, widths) == 0);
+   end = off;
+   off = sizeof(TermSrvMsgBacklogMapReq);
+   assert(termsrv_backlog_map_page_next(buf, end, &off, &page_id,
+                                        &num_entries, &got) == 1);
+   assert(page_id == 5 && num_entries == 1 && got[0] == 1);
+   return 0;
+}
 #endif
diff --git a/src/bin/termsrv.h b/src/bin/termsrv.h
index c132b656..7eeab01c 100644
--- a/src/bin/termsrv.h
+++ b/src/bin/termsrv.h
@@ -92,6 +92,36 @@ typedef struct
 #define TERMSRV_SHM_CELLS(shm) \
    ((TermSrvCell *)((uint8_t *)(shm) + TERMSRV_SHM_HEADER_SIZE))
 
+/* A backlog page is a memfd: a TERMSRV_BACKLOG_HEADER_SIZE header, then the
+ * cells of its entries packed with no gap, entry_off[] in cells. A page takes
+ * no new entry once it holds TERMSRV_BACKLOG_PAGE_ENTRIES entries or
+ * TERMSRV_BACKLOG_PAGE_SEAL_CELLS cells. The entry in progress may still
+ * grow to TERMSRV_BACKLOG_ENTRY_MAX_CELLS, so it always fits. The memfd is
+ * sparse: only the cells actually written take memory. */
+#define TERMSRV_BACKLOG_MAGIC              0x544D4250u /* "TMBP" */
+#define TERMSRV_BACKLOG_VERSION            1u
+#define TERMSRV_BACKLOG_PAGE_ENTRIES       256u
+#define TERMSRV_BACKLOG_PAGE_SEAL_CELLS    (1u << 20)
+#define TERMSRV_BACKLOG_ENTRY_MAX_CELLS    ((1u << 22) - 1) /* Termsave.w */
+#define TERMSRV_BACKLOG_HEADER_SIZE        4096u
+#define TERMSRV_BACKLOG_PAGE_SIZE \
+   (TERMSRV_BACKLOG_HEADER_SIZE + \
+    ((size_t)TERMSRV_BACKLOG_PAGE_SEAL_CELLS + \
+     TERMSRV_BACKLOG_ENTRY_MAX_CELLS) * sizeof(TermSrvCell))
+
+typedef struct
+{
+   uint32_t         magic;
+   uint32_t         version;
+   uint32_t         page_id;
+   _Atomic uint32_t num_entries;     /* release-stored after the entry */
+   uint32_t         entry_off[TERMSRV_BACKLOG_PAGE_ENTRIES]; /* in cells */
+   _Atomic uint32_t entry_w[TERMSRV_BACKLOG_PAGE_ENTRIES];   /* only grows */
+} TermSrvBacklogPage;
+
+_Static_assert(sizeof(TermSrvBacklogPage) <= TERMSRV_BACKLOG_HEADER_SIZE,
+               "the backlog page header must fit its header area");
+
 typedef enum
 {
    TSRV_MSG_ATTACH   = 1,  /* client: TermSrvAttachMode as one byte, optional */
@@ -117,7 +147,19 @@ typedef enum
     * or more TSRV_MSG_BACKLOG messages, is applied. NOTIFY and screen
     * updates were not affected and need no such reset. */
    TSRV_MSG_BACKLOG_RESET = 13,
-   TSRV_MSG_LAST     = TSRV_MSG_BACKLOG_RESET
+   /* client: ask for a backlog page, TermSrvMsgBacklogPageId. An unknown
+    * or evicted page gets no reply. */
+   TSRV_MSG_BACKLOG_PAGE_REQ = 14,
+   /* daemon: TermSrvMsgBacklogPageId + the page memfd (SCM_RIGHTS) */
+   TSRV_MSG_BACKLOG_PAGE = 15,
+   /* client: done with a page, TermSrvMsgBacklogPageId */
+   TSRV_MSG_BACKLOG_PAGE_RELEASE = 16,
+   /* client: TermSrvMsgBacklogMapReq */
+   TSRV_MSG_BACKLOG_MAP_REQ = 17,
+   /* daemon: a TermSrvMsgBacklogMapReq echoing the range covered, then per
+    * page what termsrv_backlog_map_page_append() packs */
+   TSRV_MSG_BACKLOG_MAP = 18,
+   TSRV_MSG_LAST     = TSRV_MSG_BACKLOG_MAP
 } TermSrvMsgType;
 
 typedef enum
@@ -141,6 +183,9 @@ typedef struct
    uint32_t cols;
    uint32_t rows;
    int32_t  shell_pid; /* -1 if unknown */
+   uint32_t first_page_id; /* backlog pages held, the last one is the head */
+   uint32_t page_count; /* 0: an empty store with no head, as after a reset
+                         * until rows are saved: nothing to ask for */
 } TermSrvMsgAttached;
 
 typedef struct
@@ -162,6 +207,9 @@ typedef struct
    uint8_t  bracketed_paste;
    uint8_t  focus_reporting;
    uint8_t  reserved[2];
+   uint32_t first_page_id; /* backlog pages held, the last one is the head */
+   uint32_t page_count; /* 0: an empty store with no head, as after a reset
+                         * until rows are saved: nothing to ask for */
 } TermSrvMsgNotify;
 
 typedef struct
@@ -169,6 +217,17 @@ typedef struct
    int32_t exit_code;
 } TermSrvMsgExit;
 
+typedef struct
+{
+   uint32_t page_id;
+} TermSrvMsgBacklogPageId;
+
+typedef struct
+{
+   uint32_t first_page_id;
+   uint32_t count;
+} TermSrvMsgBacklogMapReq;
+
 /* A frame read from the shared memory with termsrv_shm_read() */
 typedef struct
 {
@@ -284,6 +343,11 @@ int termsrv_attach_mode_parse(const void *payload, uint32_t size,
 int termsrv_msg_send(int fd, TermSrvMsgType type,
                      const void *payload, uint32_t size);
 
+/* Like termsrv_msg_send(), passing pass_fd along (SCM_RIGHTS) unless it is
+ * negative. The caller keeps its own copy of pass_fd. */
+int termsrv_msg_send_fd(int fd, TermSrvMsgType type,
+                        const void *payload, uint32_t size, int pass_fd);
+
 /* Gathers the bytes of a connection until they make whole messages.
  * Zero it before use. */
 typedef struct
@@ -291,25 +355,51 @@ typedef struct
    Eina_Binbuf *buf;
    size_t       start; /* first byte of buf not yet consumed */
    int          eof;   /* the peer will send nothing more */
+   uint64_t     base;  /* stream offset of the first byte of buf */
+   /* file descriptors received and not yet handed over, each with the
+    * stream offset where the read that brought it ended */
+   struct {
+      int      fd;
+      uint64_t end;
+   }           *fds;
+   unsigned int fds_count;
+   unsigned int fds_cap;
 } TermSrvReader;
 
+/* How many passed descriptors a reader queues before it stops reading */
+#define TERMSRV_READER_FDS_MAX 64
+
 /* Read what fd has available, without blocking, so that it is not reported
  * readable again for the same bytes. A file descriptor passed along is
- * closed. Returns 0, or -1 on error (end of file sets reader->eof). */
+ * kept, close-on-exec, for termsrv_reader_next_fd(). Returns 0, or -1 on
+ * error (end of file sets reader->eof). It stops reading, leaving the rest
+ * in the socket, once TERMSRV_READER_FDS_MAX descriptors are queued, so the
+ * caller must take the messages out with termsrv_reader_next*() after every
+ * fill, until they return 0: that frees the queue, and a level-triggered
+ * handler fires again for what is left. */
 int termsrv_reader_fill(TermSrvReader *reader, int fd);
 
 /* Take the next whole message out of reader. On success returns its type
  * and sets *payload_out to a malloc'd copy of the payload (NULL if empty)
- * that the caller frees. Returns 0 if no whole message is there, -1 if the
- * stream is invalid. */
+ * that the caller frees. A file descriptor that came with the message is
+ * closed. Returns 0 if no whole message is there, -1 if the stream is
+ * invalid. */
 int termsrv_reader_next(TermSrvReader *reader,
                         void **payload_out, uint32_t *size_out);
 
+/* Like termsrv_reader_next(), and *fd_out is the file descriptor that came
+ * with the message, owned by the caller, or -1 if it had none. */
+int termsrv_reader_next_fd(TermSrvReader *reader,
+                           void **payload_out, uint32_t *size_out,
+                           int *fd_out);
+
+/* Frees the reader, closing the file descriptors not handed over. */
 void termsrv_reader_clear(TermSrvReader *reader);
 
 /* Send ATTACHED with the screen memfd. Returns 0 on success, -1 on error. */
 int termsrv_send_attached(int fd, int shm_fd,
-                          uint32_t cols, uint32_t rows, int32_t shell_pid);
+                          uint32_t cols, uint32_t rows, int32_t shell_pid,
+                          uint32_t first_page_id, uint32_t page_count);
 
 /* Receive ATTACHED, blocking, before any other message: it must not go
  * through a TermSrvReader, which would lose the file descriptor that comes
@@ -337,4 +427,24 @@ int termsrv_backlog_line_next(const void *payload, uint32_t size,
                               uint32_t *off, uint32_t *cols_out,
                               const TermSrvCell **cells_out);
 
+/* The payload of TSRV_MSG_BACKLOG_MAP is a TermSrvMsgBacklogMapReq, then per
+ * page its page_id and num_entries as uint32_t, followed by num_entries
+ * uint32_t widths in cells.
+ *
+ * Append one page to buf (of bufsz bytes, *off already used, at least
+ * sizeof(TermSrvMsgBacklogMapReq) once the echoed range is written). widths
+ * is TermSrvBacklogPage.entry_w of the page. Returns 0 on success, -1 if it
+ * does not fit or has more than TERMSRV_BACKLOG_PAGE_ENTRIES entries. */
+int termsrv_backlog_map_page_append(void *buf, uint32_t bufsz, uint32_t *off,
+                                    uint32_t page_id, uint32_t num_entries,
+                                    const _Atomic uint32_t *widths);
+
+/* Read the page at *off in payload, and advance *off. *widths points into
+ * payload, aligned for uint32_t if payload is. Returns 1 for a
+ * page, 0 at the end of the payload, -1 if it is malformed. */
+int termsrv_backlog_map_page_next(const void *payload, uint32_t size,
+                                  uint32_t *off, uint32_t *page_id,
+                                  uint32_t *num_entries,
+                                  const uint32_t **widths);
+
 #endif
diff --git a/src/bin/tytest.c b/src/bin/tytest.c
index e764905b..0f1b1735 100644
--- a/src/bin/tytest.c
+++ b/src/bin/tytest.c
@@ -176,6 +176,8 @@ static struct {
        { "termsrv_attached", tytest_termsrv_attached},
        { "termsrv_cell_layout", tytest_termsrv_cell_layout},
        { "termsrv_backlog_line", tytest_termsrv_backlog_line},
+       { "termsrv_backlog_page_fd", tytest_termsrv_backlog_page_fd},
+       { "termsrv_backlog_map", tytest_termsrv_backlog_map},
        { "termtymux_frame_apply_same_size", tytest_termtymux_frame_apply_same_size},
        { "termtymux_frame_apply_resize", tytest_termtymux_frame_apply_resize},
        { "termtymux_frame_apply_shrink_grow", tytest_termtymux_frame_apply_shrink_grow},
diff --git a/src/bin/unit_tests.h b/src/bin/unit_tests.h
index ac72191c..9ba5f5ee 100644
--- a/src/bin/unit_tests.h
+++ b/src/bin/unit_tests.h
@@ -131,6 +131,8 @@ int tytest_termsrv_shm_seqlock(void);
 int tytest_termsrv_attached(void);
 int tytest_termsrv_cell_layout(void);
 int tytest_termsrv_backlog_line(void);
+int tytest_termsrv_backlog_page_fd(void);
+int tytest_termsrv_backlog_map(void);
 int tytest_termtymux_frame_apply_same_size(void);
 int tytest_termtymux_frame_apply_resize(void);
 int tytest_termtymux_frame_apply_shrink_grow(void);
diff --git a/tests/tybenchd_reset.py b/tests/tybenchd_reset.py
index cd139f24..3ecf036b 100644
--- a/tests/tybenchd_reset.py
+++ b/tests/tybenchd_reset.py
@@ -34,7 +34,7 @@ srv.listen(8)
 with open(os.environ["PIDFILE"], "w") as f:
     f.write(str(os.getpid()))
 TSRV_MSG_ATTACHED = 2
-attached = struct.pack("=IIi", 80, 24, -1)
+attached = struct.pack("=IIiII", 80, 24, -1, 0, 0)
 while True:
     conn, _ = srv.accept()
     # tybenchd checks whether a daemon runs before it attaches
diff --git a/tests/tymux.py b/tests/tymux.py
index aef18d39..dd8bc336 100644
--- a/tests/tymux.py
+++ b/tests/tymux.py
@@ -361,10 +361,10 @@ def main():
     raw = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     raw.connect(path4)
     raw.send(struct.pack("=IIB", 1, 1, 2))  # ATTACH, readonly
-    msg, fds, _, _ = socket.recv_fds(raw, 20, 1)
+    msg, fds, _, _ = socket.recv_fds(raw, 28, 1)
     for fd in fds:
         os.close(fd)
-    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+    check(len(msg) == 28 and struct.unpack_from("=II", msg)[0] == 2,
           "backlog: ATTACHED is received")
 
     def recv_msg(sock, buf, timeout=5):
@@ -464,7 +464,7 @@ def main():
         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
         sock.connect(os.path.join(XDG, "terminology", "tymux", name + ".sock"))
         sock.send(struct.pack("=IIB", 1, 1, 2))
-        msg, fds, _, _ = socket.recv_fds(sock, 20, 1)
+        msg, fds, _, _ = socket.recv_fds(sock, 28, 1)
         for fd in fds:
             os.close(fd)
         return sock
@@ -610,10 +610,10 @@ def main():
     raw2.connect(path5)
     raw2.send(struct.pack("=IIB", 1, 1, 2))  # ATTACH, readonly, no idle:
     # racing the flood is the point of this test.
-    msg, fds, _, _ = socket.recv_fds(raw2, 20, 1)
+    msg, fds, _, _ = socket.recv_fds(raw2, 28, 1)
     for fd in fds:
         os.close(fd)
-    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+    check(len(msg) == 28 and struct.unpack_from("=II", msg)[0] == 2,
           "dup: ATTACHED is received during a flood")
 
     # A resync (see the slow-reader test below) legitimately re-sends a
@@ -663,10 +663,10 @@ def main():
     raw3 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     raw3.connect(path6)
     raw3.send(struct.pack("=IIB", 1, 1, 2))
-    msg, fds, _, _ = socket.recv_fds(raw3, 20, 1)
+    msg, fds, _, _ = socket.recv_fds(raw3, 28, 1)
     for fd in fds:
         os.close(fd)
-    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+    check(len(msg) == 28 and struct.unpack_from("=II", msg)[0] == 2,
           "slow: ATTACHED is received")
 
     resets = 0
@@ -739,7 +739,7 @@ def main():
     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)
+    _, fds, _, _ = socket.recv_fds(attached, 28, 1)
     for fd in fds:
         os.close(fd)
     attached.send(struct.pack("=II", 5, 8)[:3])
@@ -877,10 +877,10 @@ def main():
     raw4 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     raw4.connect(path8)
     raw4.send(struct.pack("=IIB", 1, 1, 2))  # ATTACH, readonly
-    msg, fds, _, _ = socket.recv_fds(raw4, 20, 1)
+    msg, fds, _, _ = socket.recv_fds(raw4, 28, 1)
     for fd in fds:
         os.close(fd)
-    check(len(msg) == 20 and struct.unpack_from("=II", msg)[0] == 2,
+    check(len(msg) == 28 and struct.unpack_from("=II", msg)[0] == 2,
           "kill-exit: ATTACHED is received")
 
     result = tymux("kill", NAME8)

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

Reply via email to