+static u_int
+read_mux(Channel *c, u_int need)
+{
+ char buf[CHAN_RBUF];
+ int len;
+ u_int rlen;
+
+ if (buffer_len(&c->input) < need) {
+ rlen = need - buffer_len(&c->input);
+ len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
+ if (len <= 0) {
+ if (errno != EINTR && errno != EAGAIN) {
+ debug2("channel %d: ctl read<=0 rfd %d len %d",
+ c->self, c->rfd, len);
+ chan_read_failed(c);
+ return 0;
+ }
+ } else
+ buffer_append(&c->input, buf, len);
+ }
+ return buffer_len(&c->input);
+}
+
+static void
+channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
+{
+ u_int need;
+ ssize_t len;
+
+ if (!compat20)
+ fatal("%s: entered with !compat20", __func__);
+
+ if (c->rfd != -1 && FD_ISSET(c->rfd, readset) &&
+ (c->istate == CHAN_INPUT_OPEN ||
+ c->istate == CHAN_INPUT_WAIT_DRAIN)) {
+ /*
+ * Don't not read past the precise end of packets to
+ * avoid disrupting fd passing.
+ */
+ if (read_mux(c, 4) < 4) /* read header */
+ return;
+ need = get_u32(buffer_ptr(&c->input));
+#define CHANNEL_MUX_MAX_PACKET (256 * 1024)
+ if (need > CHANNEL_MUX_MAX_PACKET) {
+ debug2("channel %d: packet too big %u > %u",
+ c->self, CHANNEL_MUX_MAX_PACKET, need);
+ chan_rcvd_oclose(c);
+ return;
+ }
+ if (read_mux(c, need + 4) < need + 4) /* read body */
+ return;
+ if (c->mux_rcb(c) != 0) {
+ debug("channel %d: mux_rcb failed", c->self);
+ chan_mark_dead(c);
+ return;
+ }
+ }
+
+ if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
+ buffer_len(&c->output) > 0) {
+ len = write(c->wfd, buffer_ptr(&c->output),
+ buffer_len(&c->output));
+ if (len < 0 && (errno == EINTR || errno == EAGAIN))
+ return;
+ if (len <= 0) {
+ chan_mark_dead(c);
+ return;
+ }
+ buffer_consume(&c->output, len);
+ }
+}
+