Update README.md
[oweals/nmrpflash.git] / tftp.c
1 /**
2  * nmrpflash - Netgear Unbrick Utility
3  * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
4  *
5  * nmrpflash is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * nmrpflash is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with nmrpflash.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  */
19
20 #include <string.h>
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <ctype.h>
27 #include "nmrpd.h"
28
29 #ifndef O_BINARY
30 #define O_BINARY 0
31 #endif
32
33 #define TFTP_BLKSIZE 1456
34
35 static const char *opcode_names[] = {
36         "RRQ", "WRQ", "DATA", "ACK", "ERR", "OACK"
37 };
38
39 enum tftp_opcode {
40         RRQ  = 1,
41         WRQ  = 2,
42         DATA = 3,
43         ACK  = 4,
44         ERR  = 5,
45         OACK = 6
46 };
47
48 static bool is_netascii(const char *str)
49 {
50         uint8_t *p = (uint8_t*)str;
51
52         for (; *p; ++p) {
53                 if (*p < 0x20 || *p > 0x7f) {
54                         return false;
55                 }
56         }
57
58         return true;
59 }
60
61 static inline char *pkt_mknum(char *pkt, uint16_t n)
62 {
63         *(uint16_t*)pkt = htons(n);
64         return pkt + 2;
65 }
66
67 static inline uint16_t pkt_num(char *pkt)
68 {
69         return ntohs(*(uint16_t*)pkt);
70 }
71
72 static char *pkt_mkopt(char *pkt, const char *opt, const char* val)
73 {
74         strcpy(pkt, opt);
75         pkt += strlen(opt) + 1;
76         strcpy(pkt, val);
77         pkt += strlen(val) + 1;
78         return pkt;
79 }
80
81 static bool pkt_nextstr(char **pkt, char **str, size_t *rem)
82 {
83         size_t len;
84
85         if (!isprint(**pkt) || !(len = strnlen(*pkt, *rem))) {
86                 return false;
87         } else if (str) {
88                 *str = *pkt;
89         }
90
91         *pkt += len + 1;
92
93         if (*rem > 1) {
94                 *rem -= len + 1;
95         } else {
96                 *rem = 0;
97         }
98
99         return true;
100 }
101
102 static bool pkt_nextopt(char **pkt, char **opt, char **val, size_t *rem)
103 {
104         return pkt_nextstr(pkt, opt, rem) && pkt_nextstr(pkt, val, rem);
105 }
106
107 static char *pkt_optval(char* pkt, const char* name)
108 {
109         size_t rem = 512;
110         char *opt, *val;
111         pkt += 2;
112
113         while (pkt_nextopt(&pkt, &opt, &val, &rem)) {
114                 if (!strcasecmp(name, opt)) {
115                         return val;
116                 }
117         }
118
119         return NULL;
120 }
121
122 static size_t pkt_xrqlen(char *pkt)
123 {
124         size_t rem = 512;
125
126         pkt += 2;
127         while (pkt_nextopt(&pkt, NULL, NULL, &rem)) {
128                 ;
129         }
130
131         return 514 - rem;
132 }
133
134 static void pkt_mkwrq(char *pkt, const char *filename, unsigned blksize)
135 {
136         filename = leafname(filename);
137         if (!tftp_is_valid_filename(filename)) {
138                 fprintf(stderr, "Overlong/illegal filename; using 'firmware'.\n");
139                 filename = "firmware";
140         } else if (!strcmp(filename, "-")) {
141                 filename = "firmware";
142         }
143
144         pkt = pkt_mknum(pkt, WRQ);
145         pkt = pkt_mkopt(pkt, filename, "octet");
146
147         if (blksize && blksize != 512) {
148                 pkt = pkt_mkopt(pkt, "blksize", lltostr(blksize, 10));
149         }
150 }
151
152 static inline void pkt_print(char *pkt, FILE *fp)
153 {
154         uint16_t opcode = pkt_num(pkt);
155         size_t rem;
156         char *opt, *val;
157
158         if (!opcode || opcode > OACK) {
159                 fprintf(fp, "(%d)", opcode);
160         } else {
161                 fprintf(fp, "%s", opcode_names[opcode - 1]);
162                 if (opcode == ACK || opcode == DATA) {
163                         fprintf(fp, "(%d)", pkt_num(pkt + 2));
164                 } else if (opcode == WRQ || opcode == RRQ) {
165                         fprintf(fp, "(%s, %s)", pkt + 2, pkt + 2 + strlen(pkt + 2) + 1);
166                 } else if (opcode == OACK) {
167                                 fprintf(fp, "(");
168                                 rem = 512;
169                                 pkt += 2;
170                                 while (pkt_nextopt(&pkt, &opt, &val, &rem)) {
171                                         fprintf(fp, " %s=%s ", opt, val);
172                                 }
173                                 fprintf(fp, ")");
174                 }
175         }
176 }
177
178 static ssize_t tftp_recvfrom(int sock, char *pkt, uint16_t* port,
179                 unsigned timeout, size_t pktlen)
180 {
181         ssize_t len;
182         struct sockaddr_in src;
183 #ifndef NMRPFLASH_WINDOWS
184         socklen_t alen;
185 #else
186         int alen;
187 #endif
188
189         len = select_fd(sock, timeout);
190         if (len < 0) {
191                 return -1;
192         } else if (!len) {
193                 return 0;
194         }
195
196         alen = sizeof(src);
197         len = recvfrom(sock, pkt, pktlen, 0, (struct sockaddr*)&src, &alen);
198         if (len < 0) {
199                 sock_perror("recvfrom");
200                 return -1;
201         }
202
203         *port = ntohs(src.sin_port);
204
205         uint16_t opcode = pkt_num(pkt);
206
207         if (opcode == ERR) {
208                 fprintf(stderr, "Error (%d): %.511s\n", pkt_num(pkt + 2), pkt + 4);
209                 return -1;
210         } else if (isprint(pkt[0])) {
211                 /* In case of a firmware checksum error, the EX2700 I've tested this
212                  * on sends a raw UDP packet containing just an error message starting
213                  * at offset 0. The limit of 32 chars is arbitrary.
214                  */
215                 fprintf(stderr, "Error: %.32s\n", pkt);
216                 return -2;
217         } else if (!opcode || opcode > OACK) {
218                 fprintf(stderr, "Received invalid packet: ");
219                 pkt_print(pkt, stderr);
220                 fprintf(stderr, ".\n");
221                 return -1;
222         }
223
224         if (verbosity > 2) {
225                 printf(">> ");
226                 pkt_print(pkt, stdout);
227                 printf("\n");
228         }
229
230         return len;
231 }
232
233 static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
234                 struct sockaddr_in *dst)
235 {
236         ssize_t sent;
237
238         switch (pkt_num(pkt)) {
239                 case RRQ:
240                 case WRQ:
241                 case OACK:
242                         len = pkt_xrqlen(pkt);
243                         break;
244                 case DATA:
245                         len += 4;
246                         break;
247                 case ACK:
248                         len = 4;
249                         break;
250                 case ERR:
251                         len = 4 + strlen(pkt + 4);
252                         break;
253                 default:
254                         fprintf(stderr, "Attempted to send invalid packet ");
255                         pkt_print(pkt, stderr);
256                         fprintf(stderr, "; this is a bug!\n");
257                         return -1;
258         }
259
260         if (verbosity > 2) {
261                 printf("<< ");
262                 pkt_print(pkt, stdout);
263                 printf("\n");
264         }
265
266         sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
267         if (sent < 0) {
268                 sock_perror("sendto");
269         }
270
271         return sent;
272 }
273
274 const char *leafname(const char *path)
275 {
276         if (!path) {
277                 return NULL;
278         }
279
280         const char *slash, *bslash;
281
282         slash = strrchr(path, '/');
283         bslash = strrchr(path, '\\');
284
285         if (slash && bslash) {
286                 path = 1 + (slash > bslash ? slash : bslash);
287         } else if (slash) {
288                 path = 1 + slash;
289         } else if (bslash) {
290                 path = 1 + bslash;
291         }
292
293         return path;
294 }
295
296 #ifdef NMRPFLASH_WINDOWS
297 void sock_perror(const char *msg)
298 {
299         win_perror2(msg, WSAGetLastError());
300 }
301 #endif
302
303 inline bool tftp_is_valid_filename(const char *filename)
304 {
305         return strlen(filename) <= 255 && is_netascii(filename);
306 }
307
308 static const char *spinner = "\\|/-";
309
310 int tftp_put(struct nmrpd_args *args)
311 {
312         struct sockaddr_in addr;
313         uint16_t block, port, op, blksize;
314         ssize_t len, last_len;
315         int fd, sock, ret, timeouts, errors, ackblock;
316         char rx[2048], tx[2048];
317         const char *file_remote = args->file_remote;
318         char *val, *end;
319         bool rollover;
320         const unsigned rx_timeout = MAX(args->rx_timeout / (args->blind ? 50 : 5), 2000);
321         const unsigned max_timeouts = args->blind ? 3 : 5;
322
323         sock = -1;
324         ret = -1;
325         fd = -1;
326
327         if (g_interrupted) {
328                 goto cleanup;
329         }
330
331         if (!strcmp(args->file_local, "-")) {
332                 fd = STDIN_FILENO;
333                 if (!file_remote) {
334                         file_remote = "firmware";
335                 }
336         } else {
337                 fd = open(args->file_local, O_RDONLY | O_BINARY);
338                 if (fd < 0) {
339                         xperror("open");
340                         ret = fd;
341                         goto cleanup;
342                 } else if (!file_remote) {
343                         file_remote = args->file_local;
344                 }
345         }
346
347         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
348         if (sock < 0) {
349                 sock_perror("socket");
350                 ret = sock;
351                 goto cleanup;
352         }
353
354         memset(&addr, 0, sizeof(addr));
355
356         addr.sin_family = AF_INET;
357
358         if (args->ipaddr_intf) {
359                 if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr_intf)) == INADDR_NONE) {
360                         xperror("inet_addr");
361                         goto cleanup;
362                 }
363
364                 if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
365                         sock_perror("bind");
366                         goto cleanup;
367                 }
368         }
369
370         if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
371                 xperror("inet_addr");
372                 goto cleanup;
373         }
374
375         addr.sin_port = htons(args->port);
376
377         blksize = 512;
378         block = 0;
379         last_len = -1;
380         len = 0;
381         errors = 0;
382         rollover = false;
383         /* Not really, but this way the loop sends our WRQ before receiving */
384         timeouts = 1;
385
386         pkt_mkwrq(tx, file_remote, TFTP_BLKSIZE);
387
388         while (!g_interrupted) {
389                 ackblock = -1;
390                 op = pkt_num(rx);
391
392                 if (!timeouts) {
393                         if (op == ACK) {
394                                 ackblock = pkt_num(rx + 2);
395                         } else if (op == OACK) {
396                                 ackblock = 0;
397                                 if ((val = pkt_optval(rx, "blksize"))) {
398                                         blksize = strtol(val, &end, 10);
399                                         if (*end != '\0' || blksize < 8 || blksize > TFTP_BLKSIZE) {
400                                                 fprintf(stderr, "Error: invalid blksize in OACK: %s\n", val);
401                                                 ret = -1;
402                                                 goto cleanup;
403                                         }
404
405                                         if (verbosity) {
406                                                 printf("Remote accepted blksize option: %d b\n", blksize);
407                                         }
408                                 }
409                         }
410                 }
411
412                 if (timeouts || ackblock == block) {
413                         if (!timeouts) {
414                                 if (++block == 0) {
415                                         if (!rollover) {
416                                                 printf("Warning: TFTP block rollover. Upload might fail!\n");
417                                                 rollover = true;
418                                         }
419                                 }
420
421                                 printf("%c ", spinner[block & 3]);
422                                 fflush(stdout);
423                                 printf("\b\b");
424
425                                 pkt_mknum(tx, DATA);
426                                 pkt_mknum(tx + 2, block);
427                                 len = read(fd, tx + 4, blksize);
428                                 if (len < 0) {
429                                         xperror("read");
430                                         ret = len;
431                                         goto cleanup;
432                                 } else if (!len) {
433                                         if (last_len != blksize && last_len != -1) {
434                                                 break;
435                                         }
436                                 }
437
438                                 last_len = len;
439                         }
440
441                         ret = tftp_sendto(sock, tx, len, &addr);
442                         if (ret < 0) {
443                                 goto cleanup;
444                         }
445                 } else if ((op != OACK && op != ACK) || ackblock > block) {
446                         if (verbosity) {
447                                 fprintf(stderr, "Expected ACK(%d), got ", block);
448                                 pkt_print(rx, stderr);
449                                 fprintf(stderr, ".\n");
450                         }
451
452                         if (ackblock != -1 && ++errors > 5) {
453                                 fprintf(stderr, "Protocol error; bailing out.\n");
454                                 ret = -1;
455                                 goto cleanup;
456                         }
457                 }
458
459                 ret = tftp_recvfrom(sock, rx, &port, rx_timeout, blksize + 4);
460                 if (ret < 0) {
461                         goto cleanup;
462                 } else if (!ret) {
463                         if (++timeouts < max_timeouts || (!block && timeouts < (max_timeouts * 4))) {
464                                 continue;
465                         } else if (args->blind) {
466                                 timeouts = 0;
467                                 // fake an ACK packet
468                                 pkt_mknum(rx, ACK);
469                                 pkt_mknum(rx + 2, block);
470                                 continue;
471                         } else if (block) {
472                                 fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block);
473                         } else {
474                                 fprintf(stderr, "Timeout while waiting for ACK(0)/OACK.\n");
475                         }
476                         ret = -1;
477                         goto cleanup;
478                 } else {
479                         timeouts = 0;
480                         ret = 0;
481
482                         if (!block && port != args->port) {
483                                 if (verbosity > 1) {
484                                         printf("Switching to port %d\n", port);
485                                 }
486                                 addr.sin_port = htons(port);
487                         }
488                 }
489         }
490
491         ret = !g_interrupted ? 0 : -1;
492
493 cleanup:
494         if (fd >= 0) {
495                 close(fd);
496         }
497
498         if (sock >= 0) {
499 #ifndef NMRPFLASH_WINDOWS
500                 shutdown(sock, SHUT_RDWR);
501                 close(sock);
502 #else
503                 shutdown(sock, SD_BOTH);
504                 closesocket(sock);
505 #endif
506         }
507
508         return ret;
509 }