+ * Receive a block of data from the SSH link. Block until all data
+ * is available.
+ *
+ * To do this, we repeatedly call the SSH protocol module, with our
+ * own trap in term_out() to catch the data that comes back. We do
+ * this until we have enough data.
+ */
+static unsigned char *outptr; /* where to put the data */
+static unsigned outlen; /* how much data required */
+static unsigned char *pending = NULL; /* any spare data */
+static unsigned pendlen=0, pendsize=0; /* length and phys. size of buffer */
+void term_out(void) {
+ /*
+ * Here we must deal with a block of data, in `inbuf', size
+ * `inbuf_head'.
+ */
+ unsigned char *p = inbuf;
+ unsigned len = inbuf_head;
+
+ inbuf_head = 0;
+
+ /*
+ * If this is before the real session begins, just return.
+ */
+ if (!outptr)
+ return;
+
+ if (outlen > 0) {
+ unsigned used = outlen;
+ if (used > len) used = len;
+ memcpy(outptr, p, used);
+ outptr += used; outlen -= used;
+ p += used; len -= used;
+ }
+
+ if (len > 0) {
+ if (pendsize < pendlen + len) {
+ pendsize = pendlen + len + 4096;
+ pending = (pending ? realloc(pending, pendsize) :
+ malloc(pendsize));
+ if (!pending)
+ fatalbox("Out of memory");
+ }
+ memcpy(pending+pendlen, p, len);
+ pendlen += len;
+ }
+}
+static int ssh_scp_recv(unsigned char *buf, int len) {
+ SOCKET s;
+
+ outptr = buf;
+ outlen = len;
+
+ /*
+ * See if the pending-input block contains some of what we
+ * need.
+ */
+ if (pendlen > 0) {
+ unsigned pendused = pendlen;
+ if (pendused > outlen)
+ pendused = outlen;
+ memcpy(outptr, pending, pendused);
+ memmove(pending, pending+pendused, pendlen-pendused);
+ outptr += pendused;
+ outlen -= pendused;
+ pendlen -= pendused;
+ if (pendlen == 0) {
+ pendsize = 0;
+ free(pending);
+ pending = NULL;
+ }
+ if (outlen == 0)
+ return len;
+ }
+
+ while (outlen > 0) {
+ fd_set readfds;
+ s = back->socket();
+ if (s == INVALID_SOCKET) {
+ connection_open = FALSE;
+ return 0;
+ }
+ FD_ZERO(&readfds);
+ FD_SET(s, &readfds);
+ if (select(1, &readfds, NULL, NULL, NULL) < 0)
+ return 0; /* doom */
+ back->msg(0, FD_READ);
+ term_out();
+ }
+
+ return len;
+}
+
+/*
+ * Loop through the ssh connection and authentication process.
+ */
+static void ssh_scp_init(void) {
+ SOCKET s;
+
+ s = back->socket();
+ if (s == INVALID_SOCKET)
+ return;
+ while (!back->sendok()) {
+ fd_set readfds;
+ FD_ZERO(&readfds);
+ FD_SET(s, &readfds);
+ if (select(1, &readfds, NULL, NULL, NULL) < 0)
+ return; /* doom */
+ back->msg(0, FD_READ);
+ term_out();
+ }
+}
+
+/*