Blame SOURCES/tftp-rfc7440-windowsize.patch

361352
commit e46782908e7026f27ef92de52e47ec3720116125
361352
Author: Jan Synacek <jsynacek@redhat.com>
361352
Date:   Tue Nov 7 08:26:54 2017 +0100
361352
361352
    implement rfc7440
361352
361352
diff --git a/common/Makefile b/common/Makefile
361352
index a825213..d1e97b5 100644
361352
--- a/common/Makefile
361352
+++ b/common/Makefile
361352
@@ -4,7 +4,7 @@ VERSION = $(shell cat ../version)
361352
 -include ../MCONFIG
361352
 include ../MRULES
361352
 
361352
-OBJS = tftpsubs.$(O)
361352
+OBJS = tftpsubs.$(O) common.$(O)
361352
 LIB  = libcommon.a
361352
 
361352
 all: $(LIB)
361352
@@ -14,7 +14,7 @@ $(LIB): $(OBJS)
361352
 	$(AR) $(LIB) $(OBJS)
361352
 	$(RANLIB) $(LIB)
361352
 
361352
-$(OBJS): tftpsubs.h
361352
+$(OBJS): tftpsubs.h common.h
361352
 
361352
 install:
361352
 
361352
diff --git a/common/common.c b/common/common.c
361352
new file mode 100644
361352
index 0000000..a4e2fef
361352
--- /dev/null
361352
+++ b/common/common.c
361352
@@ -0,0 +1,433 @@
361352
+/*
361352
+ * Copyright (c) 2017 Jan Synáček
361352
+ * All rights reserved.
361352
+ *
361352
+ * Redistribution and use in source and binary forms, with or without
361352
+ * modification, are permitted provided that the following conditions
361352
+ * are met:
361352
+ * 1. Redistributions of source code must retain the above copyright
361352
+ *    notice, this list of conditions and the following disclaimer.
361352
+ * 2. Redistributions in binary form must reproduce the above copyright
361352
+ *    notice, this list of conditions and the following disclaimer in the
361352
+ *    documentation and/or other materials provided with the distribution.
361352
+ * 3. All advertising materials mentioning features or use of this software
361352
+ *    must display the following acknowledgement:
361352
+ *	This product includes software developed by the University of
361352
+ *	California, Berkeley and its contributors.
361352
+ * 4. Neither the name of the University nor the names of its contributors
361352
+ *    may be used to endorse or promote products derived from this software
361352
+ *    without specific prior written permission.
361352
+ *
361352
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
361352
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
361352
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
361352
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
361352
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
361352
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
361352
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
361352
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
361352
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
361352
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
361352
+ * SUCH DAMAGE.
361352
+ */
361352
+
361352
+#include <poll.h>
361352
+#include <stdarg.h>
361352
+#include <syslog.h>
361352
+#include "common.h"
361352
+
361352
+static char *pktbuf;
361352
+static int verbose;
361352
+
361352
+const int SYNC_TIMEOUT = 50; /* ms */
361352
+
361352
+static void die(const char *fmt, ...)
361352
+{
361352
+    va_list ap;
361352
+
361352
+    va_start(ap, fmt);
361352
+    fprintf(stderr, "fatal: ");
361352
+    vfprintf(stderr, fmt, ap);
361352
+    printf("\n");
361352
+    va_end(ap);
361352
+    exit(1);
361352
+}
361352
+
361352
+int format_error(struct tftphdr *tp, char *error)
361352
+{
361352
+    int r = 0;
361352
+
361352
+    if (error)
361352
+        r = snprintf(error, ERROR_MAXLEN, "Error code %d: %s", ntohs(tp->th_code), tp->th_msg);
361352
+    return r;
361352
+}
361352
+
361352
+void die_on_error(struct tftphdr *tp)
361352
+{
361352
+    char error[ERROR_MAXLEN];
361352
+
361352
+    snprintf(error, ERROR_MAXLEN, "Error code %d: %s", ntohs(tp->th_code), tp->th_msg);
361352
+    fprintf(stderr, "%s\n", error);
361352
+    exit(1);
361352
+}
361352
+
361352
+void send_error(int sockfd, union sock_addr *to, const char *msg)
361352
+{
361352
+    char buf[516];
361352
+    struct tftphdr *out = (struct tftphdr *)buf;
361352
+    int len;
361352
+
361352
+    out->th_opcode = htons(ERROR);
361352
+    out->th_code = htons(EUNDEF);
361352
+
361352
+    len = strlen(msg) + 1;
361352
+    memset(buf, 0, 516);
361352
+    memcpy(out->th_msg, msg, len > 511 ? 511 : len);
361352
+    len += 4;
361352
+
361352
+    if (to) {
361352
+        if (sendto(sockfd, out, len, 0, &to->sa, SOCKLEN(to)) != len)
361352
+            die("send_error: sendto: %s", strerror(-errno));
361352
+    } else {
361352
+        if (send(sockfd, out, len, 0) != len)
361352
+            die("send_error: send: %s", strerror(-errno));
361352
+    }
361352
+}
361352
+
361352
+static void _send_ack(int sockfd, union sock_addr *to, unsigned short block, int check_errors)
361352
+{
361352
+    struct tftphdr out;
361352
+    out.th_opcode = htons(ACK);
361352
+    out.th_block  = htons(block);
361352
+
361352
+    if (to) {
361352
+        if (sendto(sockfd, &out, 4, 0, &to->sa, SOCKLEN(to)) != 4 && check_errors)
361352
+            die("send_ack: sendto: %m");
361352
+    } else {
361352
+        if (send(sockfd, &out, 4, 0) != 4 && check_errors)
361352
+            die("send_ack: send: %m");
361352
+    }
361352
+}
361352
+
361352
+void send_ack(int sockfd, union sock_addr *to, unsigned short block)
361352
+{
361352
+    _send_ack(sockfd, to, block, 1);
361352
+}
361352
+
361352
+
361352
+static size_t read_data(FILE *fp,
361352
+                        int blocksize,
361352
+                        unsigned short block,
361352
+                        int seek,
361352
+                        struct tftphdr *out)
361352
+{
361352
+    out->th_opcode = htons(DATA);
361352
+    out->th_block  = htons(block);
361352
+    if (seek)
361352
+        (void) fseek(fp, seek, SEEK_CUR);
361352
+    return fread(pktbuf + 4, 1, blocksize, fp);
361352
+}
361352
+
361352
+static size_t write_data(FILE *fp, char *buf, size_t count, int convert)
361352
+{
361352
+    char wbuf[count];
361352
+    size_t i = 0, cnt = 0;
361352
+    static int was_cr = 0;
361352
+
361352
+    /* TODO: jsynacek: I don't think any conversion should take place...
361352
+     * RFC 1350 says: "A host which receives netascii mode data must translate
361352
+     * the data to its own format."
361352
+     * That basically means nothing. What does "own format" even mean?
361352
+     * The original implementation translated \r\n to \n and skipped \0 bytes,
361352
+     * which aren't even legal in the netascii format.
361352
+     * However, I believe that the file should remain as is before and after
361352
+     * the transfer.
361352
+     */
361352
+    convert = 0;
361352
+
361352
+    if (convert == 0)
361352
+        return fwrite(buf, 1, count, fp);
361352
+
361352
+    /* Working conversion. Leave it as dead code for now. */
361352
+    if (was_cr && buf[0] == '\n') {
361352
+        wbuf[cnt++] = '\n';
361352
+        i = 1;
361352
+        (void) fseek(fp, -1, SEEK_CUR);
361352
+    }
361352
+
361352
+    while(i < count) {
361352
+        if (buf[i] == '\r' && buf[i + 1] == '\n') {
361352
+            wbuf[cnt++] = '\n';
361352
+            ++i;
361352
+        } else if (buf[i] == '\0') {
361352
+            /* Skip it */
361352
+        } else {
361352
+            wbuf[cnt++] = buf[i];
361352
+        }
361352
+        ++i;
361352
+    }
361352
+    /* Preserve state between data chunks */
361352
+    was_cr = buf[i - 1] == '\r';
361352
+
361352
+    if (fwrite(wbuf, 1, cnt, fp) == 0)
361352
+        return 0;
361352
+
361352
+    return count;
361352
+}
361352
+
361352
+void set_verbose(int v)
361352
+{
361352
+    verbose = v;
361352
+}
361352
+
361352
+int recv_with_timeout(int s, void *in, int len, int timeout)
361352
+{
361352
+    return recvfrom_flags_with_timeout(s, in, len, NULL, timeout, 0);
361352
+}
361352
+
361352
+int recvfrom_with_timeout(int s,
361352
+                          void *in,
361352
+                          size_t len,
361352
+                          union sock_addr *from,
361352
+                          int timeout)
361352
+{
361352
+    return recvfrom_flags_with_timeout(s, in, len, from, timeout, 0);
361352
+}
361352
+
361352
+int recvfrom_flags_with_timeout(int s,
361352
+                                void *in,
361352
+                                size_t len,
361352
+                                union sock_addr *from,
361352
+                                int timeout,
361352
+                                int flags)
361352
+{
361352
+    socklen_t fromlen = sizeof(from);
361352
+    struct pollfd pfd;
361352
+    int r;
361352
+
361352
+    pfd.fd = s;
361352
+    pfd.events = POLLIN;
361352
+    pfd.revents = 0;
361352
+
361352
+    r = poll(&pfd, 1, timeout);
361352
+    if (r > 0) {
361352
+        if (from) {
361352
+            r = recvfrom(s, in, len, flags, &from->sa, &fromlen);
361352
+            if (r < 0)
361352
+                die("recvfrom_flags_with_timeout: recvfrom: %m");
361352
+        } else {
361352
+            r = recv(s, in, len, flags);
361352
+            if (r < 0)
361352
+                die("recvfrom_flags_with_timeout: recv: %m");
361352
+        }
361352
+    }
361352
+
361352
+    return r;
361352
+}
361352
+
361352
+int receiver(int sockfd,
361352
+             union sock_addr *server,
361352
+             int blocksize,
361352
+             int windowsize,
361352
+             int timeout,
361352
+             FILE *fp,
361352
+             unsigned long *received,
361352
+             char *error)
361352
+{
361352
+    struct tftphdr *tp;
361352
+    unsigned short tp_opcode, tp_block;
361352
+    unsigned short block = 1;
361352
+    unsigned long amount = 0;
361352
+    int pktsize = blocksize + 4;
361352
+    int window = 1;
361352
+    size_t size;
361352
+    int retries;
361352
+    int n, r = 0;
361352
+
361352
+    pktbuf = calloc(pktsize, 1);
361352
+    if (!pktbuf)
361352
+        die("Out of memory!");
361352
+    tp = (struct tftphdr *)pktbuf;
361352
+
361352
+    retries = RETRIES;
361352
+    do {
361352
+        n = recvfrom_with_timeout(sockfd, tp, pktsize, server, timeout);
361352
+        if (n == 0) {
361352
+            if (--retries <= 0) {
361352
+                r = E_TIMED_OUT;
361352
+                goto abort;
361352
+            }
361352
+            continue;
361352
+        }
361352
+        retries = RETRIES;
361352
+
361352
+        tp_opcode = ntohs(tp->th_opcode);
361352
+        tp_block  = ntohs(tp->th_block);
361352
+
361352
+        if (tp_opcode == DATA) {
361352
+            if (tp_block == block) {
361352
+                size = write_data(fp, tp->th_data, n - 4, 0);
361352
+                if (size == 0 && ferror(fp)) {
361352
+                    send_error(sockfd, server, "Failed to write data");
361352
+                    r = E_FAILED_TO_WRITE;
361352
+                    goto abort;
361352
+                }
361352
+                amount += size;
361352
+
361352
+                if (window++ >= windowsize || size != blocksize) {
361352
+                    send_ack(sockfd, server, block);
361352
+                    window = 1;
361352
+                }
361352
+
361352
+                ++block;
361352
+            } else {
361352
+                do {
361352
+                    n = recvfrom_with_timeout(sockfd, pktbuf, pktsize, server, SYNC_TIMEOUT);
361352
+                } while (n > 0);
361352
+                if (windowsize > 0) {
361352
+                    send_ack(sockfd, server, block - 1);
361352
+                }
361352
+                window = 1;
361352
+                n = 0;
361352
+            }
361352
+        } else if (tp_opcode == ERROR) {
361352
+            format_error(tp, error);
361352
+            r = E_RECEIVED_ERROR;
361352
+            goto abort;
361352
+        } else {
361352
+            r = E_UNEXPECTED_PACKET;
361352
+            goto abort;
361352
+        }
361352
+    } while (size == blocksize || n == 0);
361352
+
361352
+    /* Last ack can get lost, let's try and resend it twice
361352
+     * to make it more likely that the ack gets to the sender.
361352
+     */
361352
+    --block;
361352
+    for (n = 0; n < 2; ++n) {
361352
+        usleep(SYNC_TIMEOUT * 1000);
361352
+        _send_ack(sockfd, server, block, 0);
361352
+    }
361352
+
361352
+    if (received)
361352
+        *received = amount;
361352
+abort:
361352
+    free(pktbuf);
361352
+    return r;
361352
+}
361352
+
361352
+int sender(int sockfd,
361352
+           union sock_addr *server,
361352
+           int blocksize,
361352
+           int windowsize,
361352
+           int timeout,
361352
+           int rollover,
361352
+           FILE *fp,
361352
+           unsigned long *sent)
361352
+{
361352
+    struct tftphdr *tp;
361352
+    unsigned short tp_opcode, tp_block;
361352
+    unsigned short block = 1;
361352
+    unsigned long amount = 0;
361352
+    int l_timeout = timeout;
361352
+    int pktsize = blocksize + 4;
361352
+    int window = 1;
361352
+    int seek = 0;
361352
+    int retries;
361352
+    size_t size;
361352
+    int done = 0;
361352
+    int n, r = 0;
361352
+
361352
+    pktbuf = calloc(pktsize, 1);
361352
+    if (!pktbuf)
361352
+        die("Out of memory!");
361352
+    tp = (struct tftphdr *)pktbuf;
361352
+
361352
+    retries = RETRIES;
361352
+    do {
361352
+        size = read_data(fp, blocksize, block, seek, tp);
361352
+        if (size == 0 && ferror(fp)) {
361352
+            send_error(sockfd, server, "Error while reading the file");
361352
+            r = E_FAILED_TO_READ;
361352
+            goto abort;
361352
+        }
361352
+        amount += size;
361352
+        seek = 0;
361352
+
361352
+        if (server)
361352
+            n = sendto(sockfd, tp, size + 4, 0, &server->sa, SOCKLEN(server));
361352
+        else
361352
+            n = send(sockfd, tp, size + 4, 0);
361352
+        if (n != size + 4) {
361352
+            syslog(LOG_WARNING, "tftpd: send: %m");
361352
+            r = E_SYSTEM_ERROR;
361352
+            goto abort;
361352
+        }
361352
+
361352
+        if (window++ < windowsize) {
361352
+            /* Even if the entire window is not sent, the server should check for incoming packets
361352
+             * and react to out of order ACKs, or ERRORs.
361352
+             */
361352
+            l_timeout = 0;
361352
+        } else {
361352
+            l_timeout = timeout;
361352
+            window = 1;
361352
+        }
361352
+        done = size != blocksize;
361352
+        if (done) {
361352
+            l_timeout = timeout;
361352
+            window = 1;
361352
+        }
361352
+
361352
+        n = recvfrom_with_timeout(sockfd, pktbuf, pktsize, server, l_timeout);
361352
+        if (n < 0) {
361352
+            syslog(LOG_WARNING, "tftpd: recv: %m");
361352
+            r = E_SYSTEM_ERROR;
361352
+            goto abort;
361352
+        } else if (l_timeout > 0 && n == 0) {
361352
+            seek = -size;
361352
+            if (--retries <= 0) {
361352
+                r = E_TIMED_OUT;
361352
+                goto abort;
361352
+            }
361352
+            done = 0;
361352
+            continue;
361352
+        }
361352
+
361352
+        if (++block == 0)
361352
+            block = rollover;
361352
+
361352
+        tp_opcode = ntohs(tp->th_opcode);
361352
+        tp_block  = ntohs(tp->th_block);
361352
+
361352
+        if (tp_opcode == ACK) {
361352
+            if (tp_block != (unsigned short)(block - 1)) {
361352
+                int offset = tp_block;
361352
+
361352
+                done = 0;
361352
+                do {
361352
+                    n = recvfrom_with_timeout(sockfd, pktbuf, pktsize, server, SYNC_TIMEOUT);
361352
+                } while (n > 0);
361352
+                /* This is a bit of a hack. Mismatched packets that are "over the edge" of the unsigned short
361352
+                 * have to be handled and a correct seek has to be issued. In theory, overflowing block number
361352
+                 * should not even be supported, as it is impossible to distinguish correctly if more than 2^16
361352
+                 * packets are sent, but the first ones are received later than the last ones.
361352
+                 */
361352
+                if (tp_block > 65000 && tp_block > (unsigned short)(block - 1))
361352
+                    offset -= 65535;
361352
+                seek = (offset - block + 2) * blocksize - size;
361352
+            }
361352
+            block = tp_block + 1;
361352
+            retries = RETRIES;
361352
+        } else if (tp_opcode == ERROR) {
361352
+            r = E_RECEIVED_ERROR;
361352
+            goto abort;
361352
+        }
361352
+    } while (!done);
361352
+
361352
+    if (sent)
361352
+        *sent = amount;
361352
+abort:
361352
+    free(pktbuf);
361352
+    return r;
361352
+}
361352
diff --git a/common/common.h b/common/common.h
361352
new file mode 100644
361352
index 0000000..31c1b7c
361352
--- /dev/null
361352
+++ b/common/common.h
361352
@@ -0,0 +1,97 @@
361352
+/*
361352
+ * Copyright (c) 2017 Jan Synáček
361352
+ * All rights reserved.
361352
+ *
361352
+ * Redistribution and use in source and binary forms, with or without
361352
+ * modification, are permitted provided that the following conditions
361352
+ * are met:
361352
+ * 1. Redistributions of source code must retain the above copyright
361352
+ *    notice, this list of conditions and the following disclaimer.
361352
+ * 2. Redistributions in binary form must reproduce the above copyright
361352
+ *    notice, this list of conditions and the following disclaimer in the
361352
+ *    documentation and/or other materials provided with the distribution.
361352
+ * 3. All advertising materials mentioning features or use of this software
361352
+ *    must display the following acknowledgement:
361352
+ *	This product includes software developed by the University of
361352
+ *	California, Berkeley and its contributors.
361352
+ * 4. Neither the name of the University nor the names of its contributors
361352
+ *    may be used to endorse or promote products derived from this software
361352
+ *    without specific prior written permission.
361352
+ *
361352
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
361352
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
361352
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
361352
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
361352
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
361352
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
361352
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
361352
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
361352
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
361352
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
361352
+ * SUCH DAMAGE.
361352
+ */
361352
+
361352
+#ifndef _COMMON_H
361352
+#define _COMMON_H
361352
+
361352
+#include <netinet/in.h>
361352
+#include "config.h"
361352
+
361352
+#define TIMEOUT 1000 /* ms */
361352
+#define RETRIES 6
361352
+
361352
+#define E_TIMED_OUT -1
361352
+#define E_RECEIVED_ERROR -2
361352
+#define E_UNEXPECTED_PACKET -3
361352
+#define E_FAILED_TO_READ -4
361352
+#define E_FAILED_TO_WRITE -5
361352
+#define E_SYSTEM_ERROR -6
361352
+#define ERROR_MAXLEN 511
361352
+
361352
+union sock_addr {
361352
+    struct sockaddr     sa;
361352
+    struct sockaddr_in  si;
361352
+#ifdef HAVE_IPV6
361352
+    struct sockaddr_in6 s6;
361352
+#endif
361352
+};
361352
+
361352
+#define SOCKLEN(sock) \
361352
+    (((union sock_addr*)sock)->sa.sa_family == AF_INET ? \
361352
+    (sizeof(struct sockaddr_in)) : \
361352
+    (sizeof(union sock_addr)))
361352
+
361352
+const char *opcode_to_str(unsigned short opcode);
361352
+int str_equal(const char *s1, const char *s2);
361352
+void set_verbose(int v);
361352
+
361352
+int format_error(struct tftphdr *tp, char *error);
361352
+void die_on_error(struct tftphdr *tp);
361352
+void send_error(int sockfd, union sock_addr *to, const char *msg);
361352
+void send_ack(int sockfd, union sock_addr *to, unsigned short block);
361352
+int recv_with_timeout(int s, void *in, int len, int timeout);
361352
+int recvfrom_with_timeout(int s, void *in, size_t len, union sock_addr *from, int timeout);
361352
+int recvfrom_flags_with_timeout(int s,
361352
+                                void *in,
361352
+                                size_t len,
361352
+                                union sock_addr *from,
361352
+                                int timeout,
361352
+                                int flags);
361352
+int receiver(int sockfd,
361352
+             union sock_addr *server,
361352
+             int blocksize,
361352
+             int windowsize,
361352
+             int timeout,
361352
+             FILE *fp,
361352
+             unsigned long *received,
361352
+             char *error);
361352
+
361352
+int sender(int sockfd,
361352
+           union sock_addr *server,
361352
+           int blocksize,
361352
+           int windowsize,
361352
+           int timeout,
361352
+           int rollover,
361352
+           FILE *fp,
361352
+           unsigned long *sent);
361352
+#endif
361352
diff --git a/common/tftpsubs.c b/common/tftpsubs.c
361352
index 8c999f6..6033e9b 100644
361352
--- a/common/tftpsubs.c
361352
+++ b/common/tftpsubs.c
361352
@@ -404,3 +404,23 @@ char *strip_address(char *addr)
361352
     return addr;
361352
 }
361352
 #endif
361352
+
361352
+
361352
+int str_equal(const char *s1, const char *s2)
361352
+{
361352
+    return !strcmp(s1, s2);
361352
+}
361352
+
361352
+
361352
+const char *opcode_to_str(unsigned short opcode)
361352
+{
361352
+    switch(opcode) {
361352
+        case RRQ:   return "RRQ";
361352
+        case WRQ:   return "WRQ";
361352
+        case DATA:  return "DATA";
361352
+        case ACK:   return "ACK";
361352
+        case ERROR: return "ERROR";
361352
+        case OACK:  return "OACK";
361352
+    }
361352
+    return "UNKNOWN";
361352
+}
361352
diff --git a/common/tftpsubs.h b/common/tftpsubs.h
361352
index b3a3bf3..311b141 100644
361352
--- a/common/tftpsubs.h
361352
+++ b/common/tftpsubs.h
361352
@@ -38,21 +38,9 @@
361352
 #ifndef TFTPSUBS_H
361352
 #define TFTPSUBS_H
361352
 
361352
+#include "common.h"
361352
 #include "config.h"
361352
 
361352
-union sock_addr {
361352
-    struct sockaddr     sa;
361352
-    struct sockaddr_in  si;
361352
-#ifdef HAVE_IPV6
361352
-    struct sockaddr_in6 s6;
361352
-#endif
361352
-};
361352
-
361352
-#define SOCKLEN(sock) \
361352
-    (((union sock_addr*)sock)->sa.sa_family == AF_INET ? \
361352
-    (sizeof(struct sockaddr_in)) : \
361352
-    (sizeof(union sock_addr)))
361352
-
361352
 #ifdef HAVE_IPV6
361352
 #define SOCKPORT(sock) \
361352
     (((union sock_addr*)sock)->sa.sa_family == AF_INET ? \
361352
diff --git a/tftp/extern.h b/tftp/extern.h
361352
index 78474fc..dd0523f 100644
361352
--- a/tftp/extern.h
361352
+++ b/tftp/extern.h
361352
@@ -34,7 +34,7 @@
361352
 #ifndef RECVFILE_H
361352
 #define RECVFILE_H
361352
 
361352
-void tftp_recvfile(int, const char *, const char *);
361352
-void tftp_sendfile(int, const char *, const char *);
361352
+void tftp_recvfile(int, const char *, const char *, int);
361352
+void tftp_sendfile(int, const char *, const char *, int);
361352
 
361352
 #endif
361352
diff --git a/tftp/main.c b/tftp/main.c
361352
index fcf5a25..5a7d3a6 100644
361352
--- a/tftp/main.c
361352
+++ b/tftp/main.c
361352
@@ -49,7 +49,7 @@
361352
 
361352
 #include "extern.h"
361352
 
361352
-#define	TIMEOUT		5       /* secs between rexmt's */
361352
+#define	RTIMEOUT	5       /* secs between rexmt's */
361352
 #define	LBUFLEN		200     /* size of input buffer */
361352
 
361352
 struct modes {
361352
@@ -82,7 +82,7 @@ int ai_fam_sock = AF_INET;
361352
 union sock_addr peeraddr;
361352
 int f = -1;
361352
 u_short port;
361352
-int trace;
361352
+int trace_opt;
361352
 int verbose;
361352
 int literal;
361352
 int connected;
361352
@@ -104,6 +104,7 @@ struct servent *sp;
361352
 int portrange = 0;
361352
 unsigned int portrange_from = 0;
361352
 unsigned int portrange_to = 0;
361352
+int windowsize = -1;
361352
 
361352
 void get(int, char **);
361352
 void help(int, char **);
361352
@@ -191,14 +192,14 @@ char *xstrdup(const char *);
361352
 
361352
 const char *program;
361352
 
361352
-static inline void usage(int errcode)
361352
+static void usage(int errcode)
361352
 {
361352
     fprintf(stderr,
361352
 #ifdef HAVE_IPV6
361352
-            "Usage: %s [-4][-6][-v][-V][-l][-m mode] [-R port:port] "
361352
+            "Usage: %s [-4][-6][-v][-V][-l][-m mode][-w size] [-R port:port] "
361352
 			"[host [port]] [-c command]\n",
361352
 #else
361352
-            "Usage: %s [-v][-V][-l][-m mode] [-R port:port] "
361352
+            "Usage: %s [-v][-V][-l][-m mode][-w size] [-R port:port] "
361352
 			"[host [port]] [-c command]\n",
361352
 #endif
361352
             program);
361352
@@ -279,6 +280,15 @@ int main(int argc, char *argv[])
361352
                     }
361352
                     portrange = 1;
361352
                     break;
361352
+                case 'w':
361352
+                    if (++arg >= argc)
361352
+                        usage(EX_USAGE);
361352
+                    windowsize = atoi(argv[arg]);
361352
+                    if (windowsize <= 0 || windowsize > 64) {
361352
+                        fprintf(stderr, "Bad window size: %s (1-64)\n", argv[arg]);
361352
+                        exit(EX_USAGE);
361352
+                    }
361352
+                    break;
361352
                 case 'h':
361352
                 default:
361352
                     usage(*optx == 'h' ? 0 : EX_USAGE);
361352
@@ -593,7 +603,7 @@ void put(int argc, char *argv[])
361352
             printf("putting %s to %s:%s [%s]\n",
361352
                    cp, hostname, targ, mode->m_mode);
361352
         sa_set_port(&peeraddr, port);
361352
-        tftp_sendfile(fd, targ, mode->m_mode);
361352
+        tftp_sendfile(fd, targ, mode->m_mode, windowsize);
361352
         return;
361352
     }
361352
     /* this assumes the target is a directory */
361352
@@ -625,7 +635,7 @@ void put(int argc, char *argv[])
361352
             printf("putting %s to %s:%s [%s]\n",
361352
                    argv[n], hostname, remote_pth, mode->m_mode);
361352
         sa_set_port(&peeraddr, port);
361352
-        tftp_sendfile(fd, remote_pth, mode->m_mode);
361352
+        tftp_sendfile(fd, remote_pth, mode->m_mode, windowsize);
361352
     }
361352
 }
361352
 
361352
@@ -693,7 +703,7 @@ void get(int argc, char *argv[])
361352
                 printf("getting from %s:%s to %s [%s]\n",
361352
                        hostname, src, cp, mode->m_mode);
361352
             sa_set_port(&peeraddr, port);
361352
-            tftp_recvfile(fd, src, mode->m_mode);
361352
+            tftp_recvfile(fd, src, mode->m_mode, windowsize);
361352
             break;
361352
         }
361352
         cp = tail(src);         /* new .. jdg */
361352
@@ -708,7 +718,7 @@ void get(int argc, char *argv[])
361352
             printf("getting from %s:%s to %s [%s]\n",
361352
                    hostname, src, cp, mode->m_mode);
361352
         sa_set_port(&peeraddr, port);
361352
-        tftp_recvfile(fd, src, mode->m_mode);
361352
+        tftp_recvfile(fd, src, mode->m_mode, windowsize);
361352
     }
361352
 }
361352
 
361352
@@ -718,7 +728,7 @@ static void getusage(char *s)
361352
     printf("       %s file file ... file if connected\n", s);
361352
 }
361352
 
361352
-int rexmtval = TIMEOUT;
361352
+int rexmtval = RTIMEOUT;
361352
 
361352
 void setrexmt(int argc, char *argv[])
361352
 {
361352
@@ -741,7 +751,7 @@ void setrexmt(int argc, char *argv[])
361352
         rexmtval = t;
361352
 }
361352
 
361352
-int maxtimeout = 5 * TIMEOUT;
361352
+int maxtimeout = 5 * RTIMEOUT;
361352
 
361352
 void settimeout(int argc, char *argv[])
361352
 {
361352
@@ -781,7 +791,7 @@ void status(int argc, char *argv[])
361352
     else
361352
         printf("Not connected.\n");
361352
     printf("Mode: %s Verbose: %s Tracing: %s Literal: %s\n", mode->m_mode,
361352
-           verbose ? "on" : "off", trace ? "on" : "off",
361352
+           verbose ? "on" : "off", trace_opt ? "on" : "off",
361352
            literal ? "on" : "off");
361352
     printf("Rexmt-interval: %d seconds, Max-timeout: %d seconds\n",
361352
            rexmtval, maxtimeout);
361352
@@ -969,8 +979,8 @@ void settrace(int argc, char *argv[])
361352
     (void)argc;
361352
     (void)argv;                 /* Quiet unused warning */
361352
 
361352
-    trace = !trace;
361352
-    printf("Packet tracing %s.\n", trace ? "on" : "off");
361352
+    trace_opt = !trace_opt;
361352
+    printf("Packet tracing %s.\n", trace_opt ? "on" : "off");
361352
 }
361352
 
361352
 void setverbose(int argc, char *argv[])
361352
diff --git a/tftp/tftp.1.in b/tftp/tftp.1.in
361352
index b41f7b5..1779a43 100644
361352
--- a/tftp/tftp.1.in
361352
+++ b/tftp/tftp.1.in
361352
@@ -82,6 +82,9 @@ Default to verbose mode.
361352
 .B \-V
361352
 Print the version number and configuration to standard output, then
361352
 exit gracefully.
361352
+.TP
361352
+.B \-w\fP \fIwindow-size\fP
361352
+Set the "windowsize" TFTP option (RFC 7440) to the specified value.
361352
 .SH COMMANDS
361352
 Once
361352
 .B tftp
361352
diff --git a/tftp/tftp.c b/tftp/tftp.c
361352
index 9d15022..58ea597 100644
361352
--- a/tftp/tftp.c
361352
+++ b/tftp/tftp.c
361352
@@ -31,355 +31,307 @@
361352
  * SUCH DAMAGE.
361352
  */
361352
 
361352
+#include <poll.h>
361352
+#include <stdarg.h>
361352
 #include "common/tftpsubs.h"
361352
-
361352
-/*
361352
- * TFTP User Program -- Protocol Machines
361352
- */
361352
 #include "extern.h"
361352
 
361352
+/* TODO: This 'peeraddr' global should be removed. */
361352
 extern union sock_addr peeraddr; /* filled in by main */
361352
 extern int f;                    /* the opened socket */
361352
-extern int trace;
361352
+extern int trace_opt;
361352
 extern int verbose;
361352
-extern int rexmtval;
361352
-extern int maxtimeout;
361352
-
361352
+/* TODO: Adjust when blocksize is implemented. */
361352
 #define PKTSIZE    SEGSIZE+4
361352
-char ackbuf[PKTSIZE];
361352
-int timeout;
361352
-sigjmp_buf toplevel;
361352
-sigjmp_buf timeoutbuf;
361352
+static char pktbuf[PKTSIZE];
361352
 
361352
-static void nak(int, const char *);
361352
-static int makerequest(int, const char *, struct tftphdr *, const char *);
361352
 static void printstats(const char *, unsigned long);
361352
 static void startclock(void);
361352
 static void stopclock(void);
361352
-static void timer(int);
361352
-static void tpacket(const char *, struct tftphdr *, int);
361352
+static void timed_out(void)
361352
+{
361352
+    printf("client: timed out");
361352
+    exit(1);
361352
+}
361352
+
361352
+static void die(const char *fmt, ...)
361352
+{
361352
+    va_list ap;
361352
+
361352
+    va_start(ap, fmt);
361352
+    fprintf(stderr, "fatal: client: ");
361352
+    vfprintf(stderr, fmt, ap);
361352
+    printf("\n");
361352
+    va_end(ap);
361352
+    exit(1);
361352
+}
361352
+
361352
+static size_t make_request(unsigned short opcode,
361352
+                           const char *name,
361352
+                           const char *mode,
361352
+                           int blocksize,
361352
+                           int windowsize,
361352
+                           struct tftphdr *out)
361352
+{
361352
+    char *cp, buf[16];
361352
+    size_t len;
361352
+
361352
+    cp = (char *)&(out->th_stuff);
361352
+
361352
+    out->th_opcode = htons(opcode);
361352
+
361352
+    len = strlen(name) + 1;
361352
+    memcpy(cp, name, len);
361352
+    cp += len;
361352
+
361352
+    len = strlen(mode) + 1;
361352
+    memcpy(cp, mode, len);
361352
+    cp += len;
361352
+
361352
+    /* Don't include options with default values. */
361352
+
361352
+    /* TODO: TBI in a separate patch. */
361352
+    (void) blocksize;
361352
+    /*if (blocksize != SEGSIZE) {
361352
+        len = strlen("blksize") + 1;
361352
+        memcpy(cp, "blksize", len);
361352
+        cp += len;
361352
+        if (snprintf(buf, 16, "%u", blocksize) < 0)
361352
+            die("out of memory");
361352
+        len = strlen(buf) + 1;
361352
+        memcpy(cp, buf, len);
361352
+        cp += len;
361352
+    }*/
361352
+
361352
+    if (windowsize > 0) {
361352
+        len = strlen("windowsize") + 1;
361352
+        memcpy(cp, "windowsize", len);
361352
+        cp += len;
361352
+        if (snprintf(buf, 16, "%u", windowsize) < 0)
361352
+            die("out of memory");
361352
+        len = strlen(buf) + 1;
361352
+        memcpy(cp, buf, len);
361352
+        cp += len;
361352
+    }
361352
+
361352
+    return (cp - (char *)out);
361352
+}
361352
+
361352
+static void send_request(int sock,
361352
+                         union sock_addr *to,
361352
+                         short request,
361352
+                         const char *name,
361352
+                         const char *mode,
361352
+                         unsigned blocksize,
361352
+                         unsigned windowsize)
361352
+{
361352
+    struct tftphdr *out;
361352
+    size_t size;
361352
+
361352
+    out = (struct tftphdr *)pktbuf;
361352
+    size = make_request(request, name, mode, blocksize, windowsize, out);
361352
+
361352
+    if (sendto(sock, out, size, 0, &to->sa, SOCKLEN(to)) != (unsigned)size)
361352
+        die("send_request: sendto: %m");
361352
+}
361352
+
361352
+static int wait_for_oack(int sock, union sock_addr *from, char **options, int *optlen)
361352
+{
361352
+    unsigned short in_opcode;
361352
+    struct tftphdr *in;
361352
+    int r;
361352
+
361352
+    r = recvfrom_with_timeout(sock, pktbuf, sizeof(pktbuf), from, TIMEOUT);
361352
+    if (r == 0)
361352
+        return r;
361352
+
361352
+    in = (struct tftphdr *)pktbuf;
361352
+    in_opcode = ntohs(in->th_opcode);
361352
+
361352
+    if (in_opcode == ERROR)
361352
+        die_on_error(in);
361352
+    if (in_opcode != OACK)
361352
+        return -in_opcode;
361352
+
361352
+    *options = pktbuf + 2;
361352
+    *optlen = r - 2;
361352
+
361352
+    return 1;
361352
+}
361352
 
361352
 /*
361352
  * Send the requested file.
361352
  */
361352
-void tftp_sendfile(int fd, const char *name, const char *mode)
361352
+void tftp_sendfile(int fd, const char *name, const char *mode, int windowsize)
361352
 {
361352
-    struct tftphdr *ap;         /* data and ack packets */
361352
-    struct tftphdr *dp;
361352
-    int n;
361352
-    volatile int is_request;
361352
-    volatile u_short block;
361352
-    volatile int size, convert;
361352
-    volatile off_t amount;
361352
-    union sock_addr from;
361352
-    socklen_t fromlen;
361352
-    FILE *file;
361352
-    u_short ap_opcode, ap_block;
361352
-
361352
-    startclock();               /* start stat's clock */
361352
-    dp = r_init();              /* reset fillbuf/read-ahead code */
361352
-    ap = (struct tftphdr *)ackbuf;
361352
-    convert = !strcmp(mode, "netascii");
361352
-    file = fdopen(fd, convert ? "rt" : "rb");
361352
-    block = 0;
361352
-    is_request = 1;             /* First packet is the actual WRQ */
361352
-    amount = 0;
361352
-
361352
-    bsd_signal(SIGALRM, timer);
361352
+    union sock_addr server = peeraddr;
361352
+    unsigned long amount = 0;
361352
+    int blocksize = SEGSIZE;
361352
+    char *options;
361352
+    int optlen;
361352
+    int retries;
361352
+    FILE *fp;
361352
+    int n, r;
361352
+
361352
+    set_verbose(trace_opt + verbose);
361352
+
361352
+    startclock();
361352
+    send_request(f, &server, WRQ, name, mode, blocksize, windowsize);
361352
+
361352
+    /* If no windowsize was specified on the command line,
361352
+     * don't bother with options.
361352
+     * When blocksize is supported, this should actually only be called
361352
+     * if no options were sent in the RRQ.
361352
+     */
361352
+    if (windowsize < 0)
361352
+        goto no_options;
361352
+    retries = RETRIES;
361352
     do {
361352
-        if (is_request) {
361352
-            size = makerequest(WRQ, name, dp, mode) - 4;
361352
-        } else {
361352
-            /*      size = read(fd, dp->th_data, SEGSIZE);   */
361352
-            size = readit(file, &dp, convert);
361352
-            if (size < 0) {
361352
-                nak(errno + 100, NULL);
361352
-                break;
361352
-            }
361352
-            dp->th_opcode = htons((u_short) DATA);
361352
-            dp->th_block = htons((u_short) block);
361352
+        r = wait_for_oack(f, &server, &options, &optlen);
361352
+        if (r < 0) {
361352
+            return;
361352
         }
361352
-        timeout = 0;
361352
-        (void)sigsetjmp(timeoutbuf, 1);
361352
-
361352
-        if (trace)
361352
-            tpacket("sent", dp, size + 4);
361352
-        n = sendto(f, dp, size + 4, 0,
361352
-                   &peeraddr.sa, SOCKLEN(&peeraddr));
361352
-        if (n != size + 4) {
361352
-            perror("tftp: sendto");
361352
-            goto abort;
361352
-        }
361352
-        read_ahead(file, convert);
361352
-        for (;;) {
361352
-            alarm(rexmtval);
361352
-            do {
361352
-                fromlen = sizeof(from);
361352
-                n = recvfrom(f, ackbuf, sizeof(ackbuf), 0,
361352
-                             &from.sa, &fromlen);
361352
-            } while (n <= 0);
361352
-            alarm(0);
361352
-            if (n < 0) {
361352
-                perror("tftp: recvfrom");
361352
-                goto abort;
361352
-            }
361352
-            sa_set_port(&peeraddr, SOCKPORT(&from));  /* added */
361352
-            if (trace)
361352
-                tpacket("received", ap, n);
361352
-            /* should verify packet came from server */
361352
-            ap_opcode = ntohs((u_short) ap->th_opcode);
361352
-            ap_block = ntohs((u_short) ap->th_block);
361352
-            if (ap_opcode == ERROR) {
361352
-                printf("Error code %d: %s\n", ap_block, ap->th_msg);
361352
-                goto abort;
361352
-            }
361352
-            if (ap_opcode == ACK) {
361352
-                int j;
361352
 
361352
-                if (ap_block == block) {
361352
-                    break;
361352
+        /* Parse returned options. */
361352
+        n = 0;
361352
+        if (r != 0) {
361352
+            char *opt, *val;
361352
+            int got_ws = 0;
361352
+            int v;
361352
+
361352
+            while (n < optlen) {
361352
+                opt = options + n;
361352
+                n += strlen(opt) + 1;
361352
+                val = options + n;
361352
+                if (str_equal(opt, "windowsize") && windowsize != 1) {
361352
+                    v = atoi(val);
361352
+                    if (v != windowsize)
361352
+                        printf("client: server negotiated different windowsize: %d", v);
361352
+                    /* Assumes v > 0, it probably shouldn't. */
361352
+                    windowsize = v;
361352
+                    got_ws = 1;
361352
                 }
361352
-                /* On an error, try to synchronize
361352
-                 * both sides.
361352
-                 */
361352
-                j = synchnet(f);
361352
-                if (j && trace) {
361352
-                    printf("discarded %d packets\n", j);
361352
-                }
361352
-                /*
361352
-                 * RFC1129/RFC1350: We MUST NOT re-send the DATA
361352
-                 * packet in response to an invalid ACK.  Doing so
361352
-                 * would cause the Sorcerer's Apprentice bug.
361352
-                 */
361352
+                n += strlen(val) + 1;
361352
+            }
361352
+
361352
+            if (got_ws == 0 && windowsize != 1) {
361352
+                windowsize = 1;
361352
+                printf("client: server didn't negotiate windowsize, continuing with windowsize=1");
361352
             }
361352
         }
361352
-        if (!is_request)
361352
-            amount += size;
361352
-        is_request = 0;
361352
-        block++;
361352
-    } while (size == SEGSIZE || block == 1);
361352
-  abort:
361352
-    fclose(file);
361352
+    } while (r == 0 && --retries > 0);
361352
+    if (retries <= 0)
361352
+        timed_out();
361352
+
361352
+no_options:
361352
+    if (windowsize < 0) {
361352
+        struct tftphdr *tp = (struct tftphdr *)pktbuf;
361352
+
361352
+        retries = RETRIES;
361352
+        do {
361352
+            r = recvfrom_with_timeout(f, pktbuf, PKTSIZE, &server, TIMEOUT);
361352
+            if (r == 0) {
361352
+                /* Timed out. */
361352
+                continue;
361352
+            }
361352
+            if (ntohs(tp->th_opcode) == ACK && ntohs(tp->th_block) == 0) {
361352
+                break;
361352
+            } else if (ntohs(tp->th_opcode) == ERROR) {
361352
+                die_on_error(tp);
361352
+            }
361352
+        } while (r == 0 && --retries > 0);
361352
+        if (retries <= 0)
361352
+            timed_out();
361352
+    }
361352
+    fp = fdopen(fd, "r");
361352
+    r = sender(f, &server, blocksize, windowsize, TIMEOUT, 0, fp, &amount);
361352
+    if (r < 0)
361352
+        exit(1);
361352
+
361352
     stopclock();
361352
     if (amount > 0)
361352
         printstats("Sent", amount);
361352
 }
361352
 
361352
+
361352
 /*
361352
  * Receive a file.
361352
  */
361352
-void tftp_recvfile(int fd, const char *name, const char *mode)
361352
+void tftp_recvfile(int fd, const char *name, const char *mode, int windowsize)
361352
 {
361352
-    struct tftphdr *ap;
361352
-    struct tftphdr *dp;
361352
-    int n;
361352
-    volatile u_short block;
361352
-    volatile int size, firsttrip;
361352
-    volatile unsigned long amount;
361352
-    union sock_addr from;
361352
-    socklen_t fromlen;
361352
-    FILE *file;
361352
-    volatile int convert;       /* true if converting crlf -> lf */
361352
-    u_short dp_opcode, dp_block;
361352
+    union sock_addr server = peeraddr;
361352
+    unsigned long amount = 0;
361352
+    int blocksize = SEGSIZE;
361352
+    char *options, error[ERROR_MAXLEN];
361352
+    int optlen;
361352
+    int retries;
361352
+    FILE *fp;
361352
+    int n, r;
361352
+
361352
+    set_verbose(trace_opt + verbose);
361352
 
361352
     startclock();
361352
-    dp = w_init();
361352
-    ap = (struct tftphdr *)ackbuf;
361352
-    convert = !strcmp(mode, "netascii");
361352
-    file = fdopen(fd, convert ? "wt" : "wb");
361352
-    block = 1;
361352
-    firsttrip = 1;
361352
-    amount = 0;
361352
-
361352
-    bsd_signal(SIGALRM, timer);
361352
+
361352
+    send_request(f, &server, RRQ, name, mode, blocksize, windowsize);
361352
+    /* If no windowsize was specified on the command line,
361352
+     * don't bother with options.
361352
+     * When blocksize is supported, this should actually only be called
361352
+     * if no options were sent in the RRQ.
361352
+     */
361352
+    if (windowsize < 0)
361352
+        goto no_options;
361352
+    retries = RETRIES;
361352
     do {
361352
-        if (firsttrip) {
361352
-            size = makerequest(RRQ, name, ap, mode);
361352
-            firsttrip = 0;
361352
-        } else {
361352
-            ap->th_opcode = htons((u_short) ACK);
361352
-            ap->th_block = htons((u_short) block);
361352
-            size = 4;
361352
-            block++;
361352
-        }
361352
-        timeout = 0;
361352
-        (void)sigsetjmp(timeoutbuf, 1);
361352
-      send_ack:
361352
-        if (trace)
361352
-            tpacket("sent", ap, size);
361352
-        if (sendto(f, ackbuf, size, 0, &peeraddr.sa,
361352
-                   SOCKLEN(&peeraddr)) != size) {
361352
-            alarm(0);
361352
-            perror("tftp: sendto");
361352
-            goto abort;
361352
+        r = wait_for_oack(f, &server, &options, &optlen);
361352
+        if (r < 0) {
361352
+            return;
361352
         }
361352
-        write_behind(file, convert);
361352
-        for (;;) {
361352
-            alarm(rexmtval);
361352
-            do {
361352
-                fromlen = sizeof(from);
361352
-                n = recvfrom(f, dp, PKTSIZE, 0,
361352
-                             &from.sa, &fromlen);
361352
-            } while (n <= 0);
361352
-            alarm(0);
361352
-            if (n < 0) {
361352
-                perror("tftp: recvfrom");
361352
-                goto abort;
361352
-            }
361352
-            sa_set_port(&peeraddr, SOCKPORT(&from));  /* added */
361352
-            if (trace)
361352
-                tpacket("received", dp, n);
361352
-            /* should verify client address */
361352
-            dp_opcode = ntohs((u_short) dp->th_opcode);
361352
-            dp_block = ntohs((u_short) dp->th_block);
361352
-            if (dp_opcode == ERROR) {
361352
-                printf("Error code %d: %s\n", dp_block, dp->th_msg);
361352
-                goto abort;
361352
-            }
361352
-            if (dp_opcode == DATA) {
361352
-                int j;
361352
 
361352
-                if (dp_block == block) {
361352
-                    break;      /* have next packet */
361352
-                }
361352
-                /* On an error, try to synchronize
361352
-                 * both sides.
361352
-                 */
361352
-                j = synchnet(f);
361352
-                if (j && trace) {
361352
-                    printf("discarded %d packets\n", j);
361352
-                }
361352
-                if (dp_block == (block - 1)) {
361352
-                    goto send_ack;      /* resend ack */
361352
+        /* Parse returned options. */
361352
+        n = 0;
361352
+        if (r != 0) {
361352
+            char *opt, *val;
361352
+            int got_ws = 0;
361352
+            int v;
361352
+
361352
+            while (n < optlen) {
361352
+                opt = options + n;
361352
+                n += strlen(opt) + 1;
361352
+                val = options + n;
361352
+                if (str_equal(opt, "windowsize") && windowsize != 1) {
361352
+                    v = atoi(val);
361352
+                    if (v != windowsize)
361352
+                        printf("client: server negotiated different windowsize: %d", v);
361352
+                    /* Assumes v > 0, it probably shouldn't. */
361352
+                    windowsize = v;
361352
+                    got_ws = 1;
361352
                 }
361352
+                n += strlen(val) + 1;
361352
+            }
361352
+
361352
+            if (got_ws == 0 && windowsize != 1) {
361352
+                windowsize = 1;
361352
+                printf("client: server didn't negotiate windowsize, continuing with windowsize=1");
361352
             }
361352
         }
361352
-        /*      size = write(fd, dp->th_data, n - 4); */
361352
-        size = writeit(file, &dp, n - 4, convert);
361352
-        if (size < 0) {
361352
-            nak(errno + 100, NULL);
361352
-            break;
361352
-        }
361352
-        amount += size;
361352
-    } while (size == SEGSIZE);
361352
-  abort:                       /* ok to ack, since user */
361352
-    ap->th_opcode = htons((u_short) ACK);       /* has seen err msg */
361352
-    ap->th_block = htons((u_short) block);
361352
-    (void)sendto(f, ackbuf, 4, 0, (struct sockaddr *)&peeraddr,
361352
-                 SOCKLEN(&peeraddr));
361352
-    write_behind(file, convert);        /* flush last buffer */
361352
-    fclose(file);
361352
+    } while (r == 0 && --retries > 0);
361352
+    if (retries <= 0)
361352
+        timed_out();
361352
+
361352
+    send_ack(f, &server, 0);
361352
+
361352
+no_options:
361352
+    fp = fdopen(fd, "w");
361352
+    r = receiver(f, &server, blocksize, windowsize, TIMEOUT, fp, &amount, error);
361352
+    if (r < 0) {
361352
+        fprintf(stderr, "%s\n", error);
361352
+        exit(1);
361352
+    }
361352
+
361352
     stopclock();
361352
     if (amount > 0)
361352
         printstats("Received", amount);
361352
-}
361352
-
361352
-static int
361352
-makerequest(int request, const char *name,
361352
-            struct tftphdr *tp, const char *mode)
361352
-{
361352
-    char *cp;
361352
-    size_t len;
361352
-
361352
-    tp->th_opcode = htons((u_short) request);
361352
-    cp = (char *)&(tp->th_stuff);
361352
-    len = strlen(name) + 1;
361352
-    memcpy(cp, name, len);
361352
-    cp += len;
361352
-    len = strlen(mode) + 1;
361352
-    memcpy(cp, mode, len);
361352
-    cp += len;
361352
-    return (cp - (char *)tp);
361352
-}
361352
-
361352
-static const char *const errmsgs[] = {
361352
-    "Undefined error code",     /* 0 - EUNDEF */
361352
-    "File not found",           /* 1 - ENOTFOUND */
361352
-    "Access denied",            /* 2 - EACCESS */
361352
-    "Disk full or allocation exceeded", /* 3 - ENOSPACE */
361352
-    "Illegal TFTP operation",   /* 4 - EBADOP */
361352
-    "Unknown transfer ID",      /* 5 - EBADID */
361352
-    "File already exists",      /* 6 - EEXISTS */
361352
-    "No such user",             /* 7 - ENOUSER */
361352
-    "Failure to negotiate RFC2347 options"      /* 8 - EOPTNEG */
361352
-};
361352
-
361352
-#define ERR_CNT (sizeof(errmsgs)/sizeof(const char *))
361352
-
361352
-/*
361352
- * Send a nak packet (error message).
361352
- * Error code passed in is one of the
361352
- * standard TFTP codes, or a UNIX errno
361352
- * offset by 100.
361352
- */
361352
-static void nak(int error, const char *msg)
361352
-{
361352
-    struct tftphdr *tp;
361352
-    int length;
361352
-
361352
-    tp = (struct tftphdr *)ackbuf;
361352
-    tp->th_opcode = htons((u_short) ERROR);
361352
-    tp->th_code = htons((u_short) error);
361352
-
361352
-    if (error >= 100) {
361352
-        /* This is a Unix errno+100 */
361352
-        if (!msg)
361352
-            msg = strerror(error - 100);
361352
-        error = EUNDEF;
361352
-    } else {
361352
-        if ((unsigned)error >= ERR_CNT)
361352
-            error = EUNDEF;
361352
-
361352
-        if (!msg)
361352
-            msg = errmsgs[error];
361352
-    }
361352
-
361352
-    tp->th_code = htons((u_short) error);
361352
-
361352
-    length = strlen(msg) + 1;
361352
-    memcpy(tp->th_msg, msg, length);
361352
-    length += 4;                /* Add space for header */
361352
-
361352
-    if (trace)
361352
-        tpacket("sent", tp, length);
361352
-    if (sendto(f, ackbuf, length, 0, &peeraddr.sa,
361352
-               SOCKLEN(&peeraddr)) != length)
361352
-        perror("nak");
361352
-}
361352
-
361352
-static void tpacket(const char *s, struct tftphdr *tp, int n)
361352
-{
361352
-    static const char *opcodes[] =
361352
-        { "#0", "RRQ", "WRQ", "DATA", "ACK", "ERROR", "OACK" };
361352
-    char *cp, *file;
361352
-    u_short op = ntohs((u_short) tp->th_opcode);
361352
-
361352
-    if (op < RRQ || op > ERROR)
361352
-        printf("%s opcode=%x ", s, op);
361352
-    else
361352
-        printf("%s %s ", s, opcodes[op]);
361352
-    switch (op) {
361352
-
361352
-    case RRQ:
361352
-    case WRQ:
361352
-        n -= 2;
361352
-        file = cp = (char *)&(tp->th_stuff);
361352
-        cp = strchr(cp, '\0');
361352
-        printf("<file=%s, mode=%s>\n", file, cp + 1);
361352
-        break;
361352
-
361352
-    case DATA:
361352
-        printf("<block=%d, %d bytes>\n", ntohs(tp->th_block), n - 4);
361352
-        break;
361352
-
361352
-    case ACK:
361352
-        printf("<block=%d>\n", ntohs(tp->th_block));
361352
-        break;
361352
-
361352
-    case ERROR:
361352
-        printf("<code=%d, msg=%s>\n", ntohs(tp->th_code), tp->th_msg);
361352
-        break;
361352
-    }
361352
+    fclose(fp);
361352
 }
361352
 
361352
 struct timeval tstart;
361352
@@ -404,23 +356,9 @@ static void printstats(const char *direction, unsigned long amount)
361352
         (tstart.tv_sec + (tstart.tv_usec / 1000000.0));
361352
     if (verbose) {
361352
         printf("%s %lu bytes in %.1f seconds", direction, amount, delta);
361352
+        /* TODO: Change the statistics in a separate patch (bits???)! */
361352
         printf(" [%.0f bit/s]", (amount * 8.) / delta);
361352
         putchar('\n');
361352
     }
361352
 }
361352
 
361352
-static void timer(int sig)
361352
-{
361352
-    int save_errno = errno;
361352
-
361352
-    (void)sig;                  /* Shut up unused warning */
361352
-
361352
-    timeout += rexmtval;
361352
-    if (timeout >= maxtimeout) {
361352
-        printf("Transfer timed out.\n");
361352
-        errno = save_errno;
361352
-        siglongjmp(toplevel, -1);
361352
-    }
361352
-    errno = save_errno;
361352
-    siglongjmp(timeoutbuf, 1);
361352
-}
361352
diff --git a/tftpd/tftpd.8.in b/tftpd/tftpd.8.in
361352
index 321b8c6..46384d6 100644
361352
--- a/tftpd/tftpd.8.in
361352
+++ b/tftpd/tftpd.8.in
361352
@@ -227,6 +227,11 @@ Set the time before the server retransmits a packet, in microseconds.
361352
 \fBrollover\fP (nonstandard)
361352
 Set the block number to resume at after a block number rollover.  The
361352
 default and recommended value is zero.
361352
+.TP
361352
+\fBwindowsize\fP (RFC 7440)
361352
+Set the windowsize to a number of blocks that should be sent before
361352
+expecting an ack. The default is 1, which means the same functionality
361352
+as if windowsize wasn't used. Maximum is 64.
361352
 .PP
361352
 The
361352
 .B \-\-refuse
361352
@@ -408,6 +413,9 @@ RFC 2348,
361352
 .br
361352
 RFC 2349,
361352
 .IR "TFTP Timeout Interval and Transfer Size Options" .
361352
+.br
361352
+RFC 7440,
361352
+.IR "TFTP Windowsize Option" .
361352
 .SH "AUTHOR"
361352
 This version of
361352
 .B tftpd
361352
diff --git a/tftpd/tftpd.c b/tftpd/tftpd.c
361352
index b7a5a95..98adbc1 100644
361352
--- a/tftpd/tftpd.c
361352
+++ b/tftpd/tftpd.c
361352
@@ -48,6 +48,8 @@
361352
 #include <pwd.h>
361352
 #include <limits.h>
361352
 #include <syslog.h>
361352
+#include <poll.h>
361352
+#include <stdarg.h>
361352
 
361352
 #include "common/tftpsubs.h"
361352
 #include "recvfrom.h"
361352
@@ -72,23 +74,16 @@ static int ai_fam = AF_UNSPEC;
361352
 static int ai_fam = AF_INET;
361352
 #endif
361352
 
361352
-#define	TIMEOUT 1000000         /* Default timeout (us) */
361352
-#define TRIES   6               /* Number of attempts to send each packet */
361352
-#define TIMEOUT_LIMIT ((1 << TRIES)-1)
361352
-
361352
 const char *__progname;
361352
 static int peer;
361352
-static unsigned long timeout  = TIMEOUT;        /* Current timeout value */
361352
-static unsigned long rexmtval = TIMEOUT;       /* Basic timeout value */
361352
-static unsigned long maxtimeout = TIMEOUT_LIMIT * TIMEOUT;
361352
-static int timeout_quit = 0;
361352
-static sigjmp_buf timeoutbuf;
361352
 static uint16_t rollover_val = 0;
361352
+static int windowsize = 1;
361352
 
361352
 #define	PKTSIZE	MAX_SEGSIZE+4
361352
 static char buf[PKTSIZE];
361352
-static char ackbuf[PKTSIZE];
361352
+static char pktbuf[PKTSIZE];
361352
 static unsigned int max_blksize = MAX_SEGSIZE;
361352
+#define MAX_WINDOWSIZE 64
361352
 
361352
 static char tmpbuf[INET6_ADDRSTRLEN], *tmp_p;
361352
 
361352
@@ -113,8 +108,7 @@ static struct rule *rewrite_rules = NULL;
361352
 #endif
361352
 
361352
 int tftp(struct tftphdr *, int);
361352
-static void nak(int, const char *);
361352
-static void timer(int);
361352
+static void nak(int error, const char *msg);
361352
 static void do_opt(const char *, const char *, char **);
361352
 
361352
 static int set_blksize(uintmax_t *);
361352
@@ -123,6 +117,9 @@ static int set_tsize(uintmax_t *);
361352
 static int set_timeout(uintmax_t *);
361352
 static int set_utimeout(uintmax_t *);
361352
 static int set_rollover(uintmax_t *);
361352
+static int set_windowsize(uintmax_t *);
361352
+
361352
+int g_timeout = 1000; /* ms */
361352
 
361352
 struct options {
361352
     const char *o_opt;
361352
@@ -134,6 +131,7 @@ struct options {
361352
     {"timeout",  set_timeout},
361352
     {"utimeout", set_utimeout},
361352
     {"rollover", set_rollover},
361352
+    {"windowsize", set_windowsize},
361352
     {NULL, NULL}
361352
 };
361352
 
361352
@@ -152,16 +150,6 @@ static void handle_exit(int sig)
361352
     exit_signal = sig;
361352
 }
361352
 
361352
-/* Handle timeout signal or timeout event */
361352
-void timer(int sig)
361352
-{
361352
-    (void)sig;                  /* Suppress unused warning */
361352
-    timeout <<= 1;
361352
-    if (timeout >= maxtimeout || timeout_quit)
361352
-        exit(0);
361352
-    siglongjmp(timeoutbuf, 1);
361352
-}
361352
-
361352
 #ifdef WITH_REGEX
361352
 static struct rule *read_remap_rules(const char *file)
361352
 {
361352
@@ -229,64 +217,6 @@ static void pmtu_discovery_off(int fd)
361352
 #endif
361352
 }
361352
 
361352
-/*
361352
- * Receive packet with synchronous timeout; timeout is adjusted
361352
- * to account for time spent waiting.
361352
- */
361352
-static int recv_time(int s, void *rbuf, int len, unsigned int flags,
361352
-                     unsigned long *timeout_us_p)
361352
-{
361352
-    fd_set fdset;
361352
-    struct timeval tmv, t0, t1;
361352
-    int rv, err;
361352
-    unsigned long timeout_us = *timeout_us_p;
361352
-    unsigned long timeout_left, dt;
361352
-
361352
-    gettimeofday(&t0, NULL);
361352
-    timeout_left = timeout_us;
361352
-
361352
-    for (;;) {
361352
-        FD_ZERO(&fdset);
361352
-        FD_SET(s, &fdset);
361352
-
361352
-        do {
361352
-            tmv.tv_sec = timeout_left / 1000000;
361352
-            tmv.tv_usec = timeout_left % 1000000;
361352
-
361352
-            rv = select(s + 1, &fdset, NULL, NULL, &tmv);
361352
-            err = errno;
361352
-
361352
-            gettimeofday(&t1, NULL);
361352
-
361352
-            dt = (t1.tv_sec - t0.tv_sec) * 1000000 +
361352
-		 (t1.tv_usec - t0.tv_usec);
361352
-            *timeout_us_p = timeout_left =
361352
-                (dt >= timeout_us) ? 1 : (timeout_us - dt);
361352
-        } while (rv == -1 && err == EINTR);
361352
-
361352
-        if (rv == 0) {
361352
-            timer(0);           /* Should not return */
361352
-            return -1;
361352
-        }
361352
-
361352
-        set_socket_nonblock(s, 1);
361352
-        rv = recv(s, rbuf, len, flags);
361352
-        err = errno;
361352
-        set_socket_nonblock(s, 0);
361352
-
361352
-        if (rv < 0) {
361352
-            if (E_WOULD_BLOCK(err) || err == EINTR) {
361352
-                continue;       /* Once again, with feeling... */
361352
-            } else {
361352
-                errno = err;
361352
-                return rv;
361352
-            }
361352
-        } else {
361352
-            return rv;
361352
-        }
361352
-    }
361352
-}
361352
-
361352
 static int split_port(char **ap, char **pp)
361352
 {
361352
     char *a, *p;
361352
@@ -325,7 +255,7 @@ static int split_port(char **ap, char **pp)
361352
 enum long_only_options {
361352
     OPT_VERBOSITY	= 256,
361352
 };
361352
-    
361352
+
361352
 static struct option long_options[] = {
361352
     { "ipv4",        0, NULL, '4' },
361352
     { "ipv6",        0, NULL, '6' },
361352
@@ -389,7 +319,7 @@ int main(int argc, char **argv)
361352
     char envtz[10];
361352
     my_time = time(NULL);
361352
     p_tm = localtime(&my_time);
361352
-    snprintf(envtz, sizeof(envtz) - 1, "UTC%+d", (p_tm->tm_gmtoff * -1)/3600);
361352
+    snprintf(envtz, sizeof(envtz) - 1, "UTC%+ld", (p_tm->tm_gmtoff * -1)/3600);
361352
     setenv("TZ", envtz, 0);
361352
 
361352
     /* basename() is way too much of a pain from a portability standpoint */
361352
@@ -455,8 +385,7 @@ int main(int argc, char **argv)
361352
                     syslog(LOG_ERR, "Bad timeout value: %s", optarg);
361352
                     exit(EX_USAGE);
361352
                 }
361352
-                rexmtval = timeout = tov;
361352
-                maxtimeout = rexmtval * TIMEOUT_LIMIT;
361352
+                g_timeout = tov;
361352
             }
361352
             break;
361352
         case 'R':
361352
@@ -1090,9 +1019,9 @@ int tftp(struct tftphdr *tp, int size)
361352
     u_short tp_opcode = ntohs(tp->th_opcode);
361352
 
361352
     char *val = NULL, *opt = NULL;
361352
-    char *ap = ackbuf + 2;
361352
+    char *ap = pktbuf + 2;
361352
 
361352
-    ((struct tftphdr *)ackbuf)->th_opcode = htons(OACK);
361352
+    ((struct tftphdr *)pktbuf)->th_opcode = htons(OACK);
361352
 
361352
     origfilename = cp = (char *)&(tp->th_stuff);
361352
     argn = 0;
361352
@@ -1176,11 +1105,11 @@ int tftp(struct tftphdr *tp, int size)
361352
         exit(0);
361352
     }
361352
 
361352
-    if (ap != (ackbuf + 2)) {
361352
+    if (ap != (pktbuf + 2)) {
361352
         if (tp_opcode == WRQ)
361352
-            (*pf->f_recv) (pf, (struct tftphdr *)ackbuf, ap - ackbuf);
361352
+            (*pf->f_recv) (pf, (struct tftphdr *)pktbuf, ap - pktbuf);
361352
         else
361352
-            (*pf->f_send) (pf, (struct tftphdr *)ackbuf, ap - ackbuf, origfilename);
361352
+            (*pf->f_send) (pf, (struct tftphdr *)pktbuf, ap - pktbuf, origfilename);
361352
     } else {
361352
         if (tp_opcode == WRQ)
361352
             (*pf->f_recv) (pf, NULL, 0);
361352
@@ -1248,7 +1177,7 @@ static int set_blksize2(uintmax_t *vp)
361352
 static int set_rollover(uintmax_t *vp)
361352
 {
361352
     uintmax_t ro = *vp;
361352
-    
361352
+
361352
     if (ro > 65535)
361352
 	return 0;
361352
 
361352
@@ -1287,8 +1216,7 @@ static int set_timeout(uintmax_t *vp)
361352
     if (to < 1 || to > 255)
361352
         return 0;
361352
 
361352
-    rexmtval = timeout = to * 1000000UL;
361352
-    maxtimeout = rexmtval * TIMEOUT_LIMIT;
361352
+    g_timeout = to * 1000;
361352
 
361352
     return 1;
361352
 }
361352
@@ -1301,8 +1229,20 @@ static int set_utimeout(uintmax_t *vp)
361352
     if (to < 10000UL || to > 255000000UL)
361352
         return 0;
361352
 
361352
-    rexmtval = timeout = to;
361352
-    maxtimeout = rexmtval * TIMEOUT_LIMIT;
361352
+    g_timeout = to / 1000;
361352
+
361352
+    return 1;
361352
+}
361352
+
361352
+/*
361352
+ * Set window size (c.f. RFC7440)
361352
+ */
361352
+static int set_windowsize(uintmax_t *vp)
361352
+{
361352
+    if (*vp < 1 || *vp > MAX_WINDOWSIZE)
361352
+        return 0;
361352
+
361352
+    windowsize = *vp;
361352
 
361352
     return 1;
361352
 }
361352
@@ -1343,11 +1283,11 @@ static void do_opt(const char *opt, const char *val, char **ap)
361352
 		optlen = strlen(opt);
361352
 		retlen = sprintf(retbuf, "%"PRIuMAX, v);
361352
 
361352
-                if (p + optlen + retlen + 2 >= ackbuf + sizeof(ackbuf)) {
361352
+                if (p + optlen + retlen + 2 >= pktbuf + sizeof(pktbuf)) {
361352
                     nak(EOPTNEG, "Insufficient space for options");
361352
                     exit(0);
361352
                 }
361352
-		
361352
+
361352
 		memcpy(p, opt, optlen+1);
361352
 		p += optlen+1;
361352
 		memcpy(p, retbuf, retlen+1);
361352
@@ -1568,104 +1508,63 @@ static int validate_access(char *filename, int mode,
361352
  */
361352
 static void tftp_sendfile(const struct formats *pf, struct tftphdr *oap, int oacklen, char *filename)
361352
 {
361352
-    struct tftphdr *dp;
361352
-    struct tftphdr *ap;         /* ack packet */
361352
-    static u_short block = 1;   /* Static to avoid longjmp funnies */
361352
-    u_short ap_opcode, ap_block;
361352
-    unsigned long r_timeout;
361352
-    int size, n;
361352
-
361352
+    struct tftphdr *tp = (struct tftphdr *)pktbuf;
361352
+    unsigned short tp_opcode, tp_block;
361352
+    int retries = RETRIES;
361352
+    int timed_out = 0;
361352
+    int n, r = 0;
361352
+    (void) pf;
361352
+
361352
+    set_verbose(verbosity);
361352
     if (oap) {
361352
-        timeout = rexmtval;
361352
-        (void)sigsetjmp(timeoutbuf, 1);
361352
-      oack:
361352
-        r_timeout = timeout;
361352
-        if (send(peer, oap, oacklen, 0) != oacklen) {
361352
-            syslog(LOG_WARNING, "tftpd: oack: %m\n");
361352
-            goto abort;
361352
-        }
361352
-        for (;;) {
361352
-            n = recv_time(peer, ackbuf, sizeof(ackbuf), 0, &r_timeout);
361352
-            if (n < 0) {
361352
-                syslog(LOG_WARNING, "tftpd: read: %m\n");
361352
-                goto abort;
361352
-            }
361352
-            ap = (struct tftphdr *)ackbuf;
361352
-            ap_opcode = ntohs((u_short) ap->th_opcode);
361352
-            ap_block = ntohs((u_short) ap->th_block);
361352
-
361352
-            if (ap_opcode == ERROR) {
361352
-                syslog(LOG_WARNING,
361352
-                       "tftp: client does not accept options\n");
361352
+        do {
361352
+            if (send(peer, oap, oacklen, 0) != oacklen) {
361352
+                syslog(LOG_WARNING, "tftpd: oack: %m\n");
361352
                 goto abort;
361352
             }
361352
-            if (ap_opcode == ACK) {
361352
-                if (ap_block == 0)
361352
-                    break;
361352
-                /* Resynchronize with the other side */
361352
-                (void)synchnet(peer);
361352
-                goto oack;
361352
-            }
361352
-        }
361352
-    }
361352
 
361352
-    dp = r_init();
361352
-    do {
361352
-        size = readit(file, &dp, pf->f_convert);
361352
-        if (size < 0) {
361352
-            nak(errno + 100, NULL);
361352
-            goto abort;
361352
-        }
361352
-        dp->th_opcode = htons((u_short) DATA);
361352
-        dp->th_block = htons((u_short) block);
361352
-        timeout = rexmtval;
361352
-        (void)sigsetjmp(timeoutbuf, 1);
361352
-
361352
-        r_timeout = timeout;
361352
-        if (send(peer, dp, size + 4, 0) != size + 4) {
361352
-            syslog(LOG_WARNING, "tftpd: write: %m");
361352
-            goto abort;
361352
-        }
361352
-        read_ahead(file, pf->f_convert);
361352
-        for (;;) {
361352
-            n = recv_time(peer, ackbuf, sizeof(ackbuf), 0, &r_timeout);
361352
+            n = recv_with_timeout(peer, pktbuf, sizeof(pktbuf), g_timeout);
361352
             if (n < 0) {
361352
-                syslog(LOG_WARNING, "tftpd: read(ack): %m");
361352
+                syslog(LOG_WARNING, "tftpd: recv: %m");
361352
                 goto abort;
361352
+            } else if (n == 0) {
361352
+                if (--retries <= 0) {
361352
+                    timed_out = 1;
361352
+                    goto abort;
361352
+                }
361352
+                continue;
361352
             }
361352
-            ap = (struct tftphdr *)ackbuf;
361352
-            ap_opcode = ntohs((u_short) ap->th_opcode);
361352
-            ap_block = ntohs((u_short) ap->th_block);
361352
 
361352
-            if (ap_opcode == ERROR)
361352
-                goto abort;
361352
+            tp_opcode = ntohs(tp->th_opcode);
361352
+            tp_block  = ntohs(tp->th_block);
361352
 
361352
-            if (ap_opcode == ACK) {
361352
-                if (ap_block == block) {
361352
-                    break;
361352
-                }
361352
-                /* Re-synchronize with the other side */
361352
-                (void)synchnet(peer);
361352
-                /*
361352
-                 * RFC1129/RFC1350: We MUST NOT re-send the DATA
361352
-                 * packet in response to an invalid ACK.  Doing so
361352
-                 * would cause the Sorcerer's Apprentice bug.
361352
-                 */
361352
+            if (tp_opcode == ERROR) {
361352
+                char error[ERROR_MAXLEN];
361352
+
361352
+                format_error(tp, error);
361352
+                syslog(LOG_WARNING, "%s", error);
361352
+                goto abort;
361352
+            } else if (!(tp_opcode == ACK && tp_block == 0)) {
361352
+                syslog(LOG_WARNING, "unexpected packet %s block=%u", opcode_to_str(tp_opcode), tp_block);
361352
+                send_error(peer, NULL, "Unexpected packet");
361352
+                exit(1);
361352
             }
361352
+        } while (n == 0);
361352
+    }
361352
+
361352
+    r = sender(peer, NULL, segsize, windowsize, TIMEOUT, rollover_val, file, NULL);
361352
 
361352
-        }
361352
-	if (!++block)
361352
-	  block = rollover_val;
361352
-    } while (size == segsize);
361352
     tmp_p = (char *)inet_ntop(from.sa.sa_family, SOCKADDR_P(&from),
361352
-                                          tmpbuf, INET6_ADDRSTRLEN);
361352
+                              tmpbuf, INET6_ADDRSTRLEN);
361352
     if (!tmp_p) {
361352
             tmp_p = tmpbuf;
361352
             strcpy(tmpbuf, "???");
361352
     }
361352
-    syslog(LOG_NOTICE, "Client %s finished %s",tmp_p,filename);
361352
-  abort:
361352
-    (void)fclose(file);
361352
+    syslog(LOG_NOTICE, "Client %s finished %s", tmp_p, filename);
361352
+abort:
361352
+    if (timed_out || r == E_TIMED_OUT)
361352
+        syslog(LOG_NOTICE, "Client %s timed out", tmp_p);
361352
+    fclose(file);
361352
 }
361352
 
361352
 /*
361352
@@ -1673,90 +1572,44 @@ static void tftp_sendfile(const struct formats *pf, struct tftphdr *oap, int oac
361352
  */
361352
 static void tftp_recvfile(const struct formats *pf, struct tftphdr *oap, int oacklen)
361352
 {
361352
-    struct tftphdr *dp;
361352
-    int n, size;
361352
-    /* These are "static" to avoid longjmp funnies */
361352
-    static struct tftphdr *ap;  /* ack buffer */
361352
-    static u_short block = 0;
361352
-    static int acksize;
361352
-    u_short dp_opcode, dp_block;
361352
-    unsigned long r_timeout;
361352
-
361352
-    dp = w_init();
361352
-    do {
361352
-        timeout = rexmtval;
361352
-
361352
-        if (!block && oap) {
361352
-            ap = (struct tftphdr *)ackbuf;
361352
-            acksize = oacklen;
361352
-        } else {
361352
-            ap = (struct tftphdr *)ackbuf;
361352
-            ap->th_opcode = htons((u_short) ACK);
361352
-            ap->th_block = htons((u_short) block);
361352
-            acksize = 4;
361352
-            /* If we're sending a regular ACK, that means we have successfully
361352
-             * sent the OACK. Clear oap so that we won't try to send another
361352
-             * OACK when the block number wraps back to 0. */
361352
-            oap = NULL;
361352
-        }
361352
-        if (!++block)
361352
-	  block = rollover_val;
361352
-        (void)sigsetjmp(timeoutbuf, 1);
361352
-      send_ack:
361352
-        r_timeout = timeout;
361352
-        if (send(peer, ackbuf, acksize, 0) != acksize) {
361352
-            syslog(LOG_WARNING, "tftpd: write(ack): %m");
361352
-            goto abort;
361352
-        }
361352
-        write_behind(file, pf->f_convert);
361352
-        for (;;) {
361352
-            n = recv_time(peer, dp, PKTSIZE, 0, &r_timeout);
361352
-            if (n < 0) {        /* really? */
361352
-                syslog(LOG_WARNING, "tftpd: read: %m");
361352
+    int retries = RETRIES;
361352
+    int timed_out = 0;
361352
+    int r;
361352
+    (void) pf;
361352
+
361352
+    set_verbose(verbosity);
361352
+    if (oap) {
361352
+        do {
361352
+            if (send(peer, oap, oacklen, 0) != oacklen) {
361352
+                syslog(LOG_WARNING, "tftpd: oack: %m\n");
361352
                 goto abort;
361352
             }
361352
-            dp_opcode = ntohs((u_short) dp->th_opcode);
361352
-            dp_block = ntohs((u_short) dp->th_block);
361352
-            if (dp_opcode == ERROR)
361352
-                goto abort;
361352
-            if (dp_opcode == DATA) {
361352
-                if (dp_block == block) {
361352
-                    break;      /* normal */
361352
+            r = recvfrom_flags_with_timeout(peer, pktbuf, sizeof(pktbuf), NULL, TIMEOUT, MSG_PEEK);
361352
+            if (r == 0) {
361352
+                if (--retries <= 0) {
361352
+                    timed_out = 1;
361352
+                    goto abort;
361352
                 }
361352
-                /* Re-synchronize with the other side */
361352
-                (void)synchnet(peer);
361352
-                if (dp_block == (block - 1))
361352
-                    goto send_ack;      /* rexmit */
361352
             }
361352
-        }
361352
-        /*  size = write(file, dp->th_data, n - 4); */
361352
-        size = writeit(file, &dp, n - 4, pf->f_convert);
361352
-        if (size != (n - 4)) {  /* ahem */
361352
-            if (size < 0)
361352
-                nak(errno + 100, NULL);
361352
-            else
361352
-                nak(ENOSPACE, NULL);
361352
-            goto abort;
361352
-        }
361352
-    } while (size == segsize);
361352
-    write_behind(file, pf->f_convert);
361352
-    (void)fclose(file);         /* close data file */
361352
-
361352
-    ap->th_opcode = htons((u_short) ACK);       /* send the "final" ack */
361352
-    ap->th_block = htons((u_short) (block));
361352
-    (void)send(peer, ackbuf, 4, 0);
361352
-
361352
-    timeout_quit = 1;           /* just quit on timeout */
361352
-    n = recv_time(peer, buf, sizeof(buf), 0, &timeout); /* normally times out and quits */
361352
-    timeout_quit = 0;
361352
-
361352
-    if (n >= 4 &&               /* if read some data */
361352
-        dp_opcode == DATA &&    /* and got a data block */
361352
-        block == dp_block) {    /* then my last ack was lost */
361352
-        (void)send(peer, ackbuf, 4, 0); /* resend final ack */
361352
+        } while (r == 0);
361352
+    } else {
361352
+        do {
361352
+            send_ack(peer, NULL, 0);
361352
+            r = recvfrom_flags_with_timeout(peer, pktbuf, sizeof(pktbuf), NULL, TIMEOUT, MSG_PEEK);
361352
+            if (r == 0) {
361352
+                if (--retries <= 0) {
361352
+                    timed_out = 1;
361352
+                    goto abort;
361352
+                }
361352
+            }
361352
+        } while (r == 0);
361352
     }
361352
-  abort:
361352
-    return;
361352
+
361352
+    r = receiver(peer, NULL, segsize, windowsize, TIMEOUT, file, NULL, NULL);
361352
+abort:
361352
+    if (timed_out || r == E_TIMED_OUT)
361352
+        syslog(LOG_NOTICE, "Client %s timed out", tmp_p);
361352
+    fclose(file);
361352
 }
361352
 
361352
 static const char *const errmsgs[] = {