Update README.md
[oweals/nmrpflash.git] / tftp.c
diff --git a/tftp.c b/tftp.c
index 84050887eedaeb71609985e99ba7aeabb4960f7a..da76dc97158e75947ab2e9e23d3a9cc1862dcd62 100644 (file)
--- a/tftp.c
+++ b/tftp.c
@@ -1,19 +1,19 @@
 /**
- * nmrp-flash - Netgear Unbrick Utility
+ * nmrpflash - Netgear Unbrick Utility
  * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
  *
- * nmrp-flash is free software: you can redistribute it and/or modify
+ * nmrpflash is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
- * nmrp-flash is distributed in the hope that it will be useful,
+ * nmrpflash is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
- * along with nmrp-flash.  If not, see <http://www.gnu.org/licenses/>.
+ * along with nmrpflash.  If not, see <http://www.gnu.org/licenses/>.
  *
  */
 
@@ -40,28 +40,12 @@ enum tftp_opcode {
        ERR  = 5
 };
 
-static const char *x_basename(const char *path)
-{
-       const char *slash, *bslash;
-
-       slash = strrchr(path, '/');
-       bslash = strrchr(path, '\\');
-
-       if (slash && bslash) {
-               path = 1 + (slash > bslash ? slash : bslash);
-       } else if (slash) {
-               path = 1 + slash;
-       } else if (bslash) {
-               path = 1 + bslash;
-       }
-
-       return path;
-}
-
 static bool is_netascii(const char *str)
 {
-       for (; *str; ++str) {
-               if (*str < 0x20 || *str > 0x7f) {
+       uint8_t *p = (uint8_t*)str;
+
+       for (; *p; ++p) {
+               if (*p < 0x20 || *p > 0x7f) {
                        return false;
                }
        }
@@ -83,10 +67,12 @@ static void pkt_mkwrq(char *pkt, const char *filename)
 {
        size_t len = 2;
 
-       filename = x_basename(filename);
-       if (!is_netascii(filename) || strlen(filename) > 500) {
-               fprintf(stderr, "Overlong/illegal filename; using 'firmware.bin'.");
-               filename = "firmware.bin";
+       filename = leafname(filename);
+       if (!tftp_is_valid_filename(filename)) {
+               fprintf(stderr, "Overlong/illegal filename; using 'firmware'.\n");
+               filename = "firmware";
+       } else if (!strcmp(filename, "-")) {
+               filename = "firmware";
        }
 
        pkt_mknum(pkt, WRQ);
@@ -111,20 +97,33 @@ static inline void pkt_print(char *pkt, FILE *fp)
        }
 }
 
-static ssize_t tftp_recvfrom(int sock, char *pkt, struct sockaddr_in *src)
+static ssize_t tftp_recvfrom(int sock, char *pkt, uint16_t* port,
+               unsigned timeout)
 {
        ssize_t len;
+       struct sockaddr_in src;
+#ifndef NMRPFLASH_WINDOWS
+       socklen_t alen;
+#else
+       int alen;
+#endif
 
-       len = recvfrom(sock, pkt, TFTP_PKT_SIZE, 0, NULL, NULL);
+       len = select_fd(sock, timeout);
        if (len < 0) {
-               if (errno != EAGAIN) {
-                       perror("recvfrom");
-                       return -1;
-               }
+               return -1;
+       } else if (!len) {
+               return 0;
+       }
 
-               return -2;
+       alen = sizeof(src);
+       len = recvfrom(sock, pkt, TFTP_PKT_SIZE, 0, (struct sockaddr*)&src, &alen);
+       if (len < 0) {
+               sock_perror("recvfrom");
+               return -1;
        }
 
+       *port = ntohs(src.sin_port);
+
        uint16_t opcode = pkt_num(pkt);
 
        if (opcode == ERR) {
@@ -136,12 +135,18 @@ static ssize_t tftp_recvfrom(int sock, char *pkt, struct sockaddr_in *src)
                 * at offset 0. The limit of 32 chars is arbitrary.
                 */
                fprintf(stderr, "Error: %.32s\n", pkt);
-               return -3;
-       } else {
+               return -2;
+       } else if (!opcode || opcode > ERR) {
                fprintf(stderr, "Received invalid packet: ");
                pkt_print(pkt, stderr);
                fprintf(stderr, ".\n");
-               return -2;
+               return -1;
+       }
+
+       if (verbosity > 2) {
+               printf(">> ");
+               pkt_print(pkt, stdout);
+               printf("\n");
        }
 
        return len;
@@ -174,56 +179,76 @@ static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
                        return -1;
        }
 
+       if (verbosity > 2) {
+               printf("<< ");
+               pkt_print(pkt, stdout);
+               printf("\n");
+       }
+
        sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
        if (sent < 0) {
-               perror("sendto");
+               sock_perror("sendto");
        }
 
        return sent;
 }
 
-static int sock_set_rx_timeout(int fd, unsigned msec)
+const char *leafname(const char *path)
 {
-       struct timeval tv;
-
-       if (msec) {
-               tv.tv_usec = (msec % 1000) * 1000;
-               tv.tv_sec = msec / 1000;
-               if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)) < 0) {
-                       perror("setsockopt(SO_RCVTIMEO)");
-                       return 1;
-               }
+       const char *slash, *bslash;
+
+       slash = strrchr(path, '/');
+       bslash = strrchr(path, '\\');
+
+       if (slash && bslash) {
+               path = 1 + (slash > bslash ? slash : bslash);
+       } else if (slash) {
+               path = 1 + slash;
+       } else if (bslash) {
+               path = 1 + bslash;
        }
 
-       return 0;
+       return path;
+}
+
+#ifdef NMRPFLASH_WINDOWS
+void sock_perror(const char *msg)
+{
+       win_perror2(msg, WSAGetLastError());
+}
+#endif
+
+inline bool tftp_is_valid_filename(const char *filename)
+{
+       return strlen(filename) <= 500 && is_netascii(filename);
 }
 
 int tftp_put(struct nmrpd_args *args)
 {
        struct sockaddr_in addr;
-       uint16_t block;
-       ssize_t len;
-       int fd, sock, err, timeout, last_len;
+       uint16_t block, port;
+       ssize_t len, last_len;
+       int fd, sock, ret, timeout, errors, ackblock;
        char rx[TFTP_PKT_SIZE], tx[TFTP_PKT_SIZE];
 
        sock = -1;
+       ret = -1;
 
-       fd = open(args->filename, O_RDONLY);
-       if (fd < 0) {
-               perror("open");
-               err = fd;
-               goto cleanup;
+       if (!strcmp(args->file_local, "-")) {
+               fd = STDIN_FILENO;
+       } else {
+               fd = open(args->file_local, O_RDONLY);
+               if (fd < 0) {
+                       perror("open");
+                       ret = fd;
+                       goto cleanup;
+               }
        }
 
        sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (sock < 0) {
-               perror("socket");
-               err = sock;
-               goto cleanup;
-       }
-
-       err = sock_set_rx_timeout(sock, args->rx_timeout);
-       if (err) {
+               sock_perror("socket");
+               ret = sock;
                goto cleanup;
        }
 
@@ -238,13 +263,20 @@ int tftp_put(struct nmrpd_args *args)
        block = 0;
        last_len = -1;
        len = 0;
+       errors = 0;
        /* Not really, but this way the loop sends our WRQ before receiving */
        timeout = 1;
 
-       pkt_mkwrq(tx, args->filename);
+       pkt_mkwrq(tx, args->file_remote);
 
        do {
-               if (timeout || (pkt_num(rx) == ACK && pkt_num(rx + 2) == block)) {
+               if (!timeout && pkt_num(rx) == ACK) {
+                       ackblock = pkt_num(rx + 2);
+               } else {
+                       ackblock = -1;
+               }
+
+               if (timeout || ackblock == block) {
                        if (!timeout) {
                                ++block;
                                pkt_mknum(tx, DATA);
@@ -252,10 +284,10 @@ int tftp_put(struct nmrpd_args *args)
                                len = read(fd, tx + 4, 512);
                                if (len < 0) {
                                        perror("read");
-                                       err = len;
+                                       ret = len;
                                        goto cleanup;
                                } else if (!len) {
-                                       if (last_len != 512) {
+                                       if (last_len != 512 && last_len != -1) {
                                                break;
                                        }
                                }
@@ -263,32 +295,51 @@ int tftp_put(struct nmrpd_args *args)
                                last_len = len;
                        }
 
-                       err = tftp_sendto(sock, tx, len, &addr);
-                       if (err < 0) {
+                       ret = tftp_sendto(sock, tx, len, &addr);
+                       if (ret < 0) {
+                               goto cleanup;
+                       }
+               } else if (pkt_num(rx) != ACK || ackblock > block) {
+                       if (verbosity) {
+                               fprintf(stderr, "Expected ACK(%d), got ", block);
+                               pkt_print(rx, stderr);
+                               fprintf(stderr, ".\n");
+                       }
+
+                       if (ackblock != -1 && ++errors > 5) {
+                               fprintf(stderr, "Protocol error; bailing out.\n");
+                               ret = -1;
                                goto cleanup;
                        }
-               } else if (pkt_num(rx) != ACK) {
-                       fprintf(stderr, "Expected ACK(%d), got ", block);
-                       pkt_print(rx, stderr);
-                       fprintf(stderr, "!\n");
                }
 
-               err = tftp_recvfrom(sock, rx, &addr);
-               if (err < 0) {
-                       if (err == -2) {
-                               if (++timeout < 5) {
-                                       continue;
-                               }
+               ret = tftp_recvfrom(sock, rx, &port, args->rx_timeout);
+               if (ret < 0) {
+                       goto cleanup;
+               } else if (!ret) {
+                       if (++timeout < 5 || (!block && timeout < 10)) {
+                               continue;
+                       } else if (block) {
                                fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block);
+                       } else {
+                               fprintf(stderr, "Timeout while waiting for initial reply.\n");
                        }
+                       ret = -1;
                        goto cleanup;
                } else {
                        timeout = 0;
-                       err = 0;
+                       ret = 0;
+
+                       if (!block && port != args->port) {
+                               if (verbosity > 1) {
+                                       printf("Switching to port %d\n", port);
+                               }
+                               addr.sin_port = htons(port);
+                       }
                }
        } while(1);
 
-       err = 0;
+       ret = 0;
 
 cleanup:
        if (fd >= 0) {
@@ -296,13 +347,14 @@ cleanup:
        }
 
        if (sock >= 0) {
-               shutdown(sock, SHUT_RDWR);
 #ifndef NMRPFLASH_WINDOWS
+               shutdown(sock, SHUT_RDWR);
                close(sock);
 #else
+               shutdown(sock, SD_BOTH);
                closesocket(sock);
 #endif
        }
 
-       return err;
+       return ret;
 }