Merge branches
[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 #define TFTP_PKT_SIZE 516
30
31 static const char *opcode_names[] = {
32         "RRQ", "WRQ", "DATA", "ACK", "ERR"
33 };
34
35 enum tftp_opcode {
36         RRQ  = 1,
37         WRQ  = 2,
38         DATA = 3,
39         ACK  = 4,
40         ERR  = 5
41 };
42
43 static bool is_netascii(const char *str)
44 {
45         uint8_t *p = (uint8_t*)str;
46
47         for (; *p; ++p) {
48                 if (*p < 0x20 || *p > 0x7f) {
49                         return false;
50                 }
51         }
52
53         return true;
54 }
55
56 static inline void pkt_mknum(char *pkt, uint16_t n)
57 {
58         *(uint16_t*)pkt = htons(n);
59 }
60
61 static inline uint16_t pkt_num(char *pkt)
62 {
63         return ntohs(*(uint16_t*)pkt);
64 }
65
66 static void pkt_mkwrq(char *pkt, const char *filename)
67 {
68         size_t len = 2;
69
70         filename = leafname(filename);
71         if (!tftp_is_valid_filename(filename)) {
72                 fprintf(stderr, "Overlong/illegal filename; using 'firmware'.\n");
73                 filename = "firmware";
74         } else if (!strcmp(filename, "-")) {
75                 filename = "firmware";
76         }
77
78         pkt_mknum(pkt, WRQ);
79
80         strcpy(pkt + len, filename);
81         len += strlen(filename) + 1;
82         strcpy(pkt + len, "octet");
83 }
84
85 static inline void pkt_print(char *pkt, FILE *fp)
86 {
87         uint16_t opcode = pkt_num(pkt);
88         if (!opcode || opcode > ERR) {
89                 fprintf(fp, "(%d)", opcode);
90         } else {
91                 fprintf(fp, "%s", opcode_names[opcode - 1]);
92                 if (opcode == ACK || opcode == DATA) {
93                         fprintf(fp, "(%d)", pkt_num(pkt + 2));
94                 } else if (opcode == WRQ || opcode == RRQ) {
95                         fprintf(fp, "(%s, %s)", pkt + 2, pkt + 2 + strlen(pkt + 2) + 1);
96                 }
97         }
98 }
99
100 static ssize_t tftp_recvfrom(int sock, char *pkt, uint16_t* port,
101                 unsigned timeout)
102 {
103         ssize_t len;
104         struct sockaddr_in src;
105 #ifndef NMRPFLASH_WINDOWS
106         socklen_t alen;
107 #else
108         int alen;
109 #endif
110
111         len = select_fd(sock, timeout);
112         if (len < 0) {
113                 return -1;
114         } else if (!len) {
115                 return 0;
116         }
117
118         alen = sizeof(src);
119         len = recvfrom(sock, pkt, TFTP_PKT_SIZE, 0, (struct sockaddr*)&src, &alen);
120         if (len < 0) {
121                 sock_perror("recvfrom");
122                 return -1;
123         }
124
125         *port = ntohs(src.sin_port);
126
127         uint16_t opcode = pkt_num(pkt);
128
129         if (opcode == ERR) {
130                 fprintf(stderr, "Error (%d): %.511s\n", pkt_num(pkt + 2), pkt + 4);
131                 return -1;
132         } else if (isprint(pkt[0])) {
133                 /* In case of a firmware checksum error, the EX2700 I've tested this
134                  * on sends a raw UDP packet containing just an error message starting
135                  * at offset 0. The limit of 32 chars is arbitrary.
136                  */
137                 fprintf(stderr, "Error: %.32s\n", pkt);
138                 return -2;
139         } else if (!opcode || opcode > ERR) {
140                 fprintf(stderr, "Received invalid packet: ");
141                 pkt_print(pkt, stderr);
142                 fprintf(stderr, ".\n");
143                 return -1;
144         }
145
146         if (verbosity > 2) {
147                 printf(">> ");
148                 pkt_print(pkt, stdout);
149                 printf("\n");
150         }
151
152         return len;
153 }
154
155 static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
156                 struct sockaddr_in *dst)
157 {
158         ssize_t sent;
159
160         switch (pkt_num(pkt)) {
161                 case RRQ:
162                 case WRQ:
163                         len = 2 + strlen(pkt + 2) + 1;
164                         len += strlen(pkt + len) + 1;
165                         break;
166                 case DATA:
167                         len += 4;
168                         break;
169                 case ACK:
170                         len = 4;
171                         break;
172                 case ERR:
173                         len = 4 + strlen(pkt + 4);
174                         break;
175                 default:
176                         fprintf(stderr, "Attempted to send invalid packet ");
177                         pkt_print(pkt, stderr);
178                         fprintf(stderr, "; this is a bug!\n");
179                         return -1;
180         }
181
182         if (verbosity > 2) {
183                 printf("<< ");
184                 pkt_print(pkt, stdout);
185                 printf("\n");
186         }
187
188         sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
189         if (sent < 0) {
190                 sock_perror("sendto");
191         }
192
193         return sent;
194 }
195
196 const char *leafname(const char *path)
197 {
198         const char *slash, *bslash;
199
200         slash = strrchr(path, '/');
201         bslash = strrchr(path, '\\');
202
203         if (slash && bslash) {
204                 path = 1 + (slash > bslash ? slash : bslash);
205         } else if (slash) {
206                 path = 1 + slash;
207         } else if (bslash) {
208                 path = 1 + bslash;
209         }
210
211         return path;
212 }
213
214 #ifdef NMRPFLASH_WINDOWS
215 void sock_perror(const char *msg)
216 {
217         win_perror2(msg, WSAGetLastError());
218 }
219 #endif
220
221 inline bool tftp_is_valid_filename(const char *filename)
222 {
223         return strlen(filename) <= 500 && is_netascii(filename);
224 }
225
226 int tftp_put(struct nmrpd_args *args)
227 {
228         struct sockaddr_in addr;
229         uint16_t block, port;
230         ssize_t len, last_len;
231         int fd, sock, ret, timeout, errors, ackblock;
232         char rx[TFTP_PKT_SIZE], tx[TFTP_PKT_SIZE];
233
234         sock = -1;
235         ret = -1;
236
237         if (!strcmp(args->file_local, "-")) {
238                 fd = STDIN_FILENO;
239         } else {
240                 fd = open(args->file_local, O_RDONLY);
241                 if (fd < 0) {
242                         perror("open");
243                         ret = fd;
244                         goto cleanup;
245                 }
246         }
247
248         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
249         if (sock < 0) {
250                 sock_perror("socket");
251                 ret = sock;
252                 goto cleanup;
253         }
254
255         if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
256                 perror("inet_addr");
257                 goto cleanup;
258         }
259
260         addr.sin_family = AF_INET;
261         addr.sin_port = htons(args->port);
262
263         block = 0;
264         last_len = -1;
265         len = 0;
266         errors = 0;
267         /* Not really, but this way the loop sends our WRQ before receiving */
268         timeout = 1;
269
270         pkt_mkwrq(tx, args->file_remote);
271
272         do {
273                 if (!timeout && pkt_num(rx) == ACK) {
274                         ackblock = pkt_num(rx + 2);
275                 } else {
276                         ackblock = -1;
277                 }
278
279                 if (timeout || ackblock == block) {
280                         if (!timeout) {
281                                 ++block;
282                                 pkt_mknum(tx, DATA);
283                                 pkt_mknum(tx + 2, block);
284                                 len = read(fd, tx + 4, 512);
285                                 if (len < 0) {
286                                         perror("read");
287                                         ret = len;
288                                         goto cleanup;
289                                 } else if (!len) {
290                                         if (last_len != 512 && last_len != -1) {
291                                                 break;
292                                         }
293                                 }
294
295                                 last_len = len;
296                         }
297
298                         ret = tftp_sendto(sock, tx, len, &addr);
299                         if (ret < 0) {
300                                 goto cleanup;
301                         }
302                 } else if (pkt_num(rx) != ACK || ackblock > block) {
303                         if (verbosity) {
304                                 fprintf(stderr, "Expected ACK(%d), got ", block);
305                                 pkt_print(rx, stderr);
306                                 fprintf(stderr, ".\n");
307                         }
308
309                         if (ackblock != -1 && ++errors > 5) {
310                                 fprintf(stderr, "Protocol error; bailing out.\n");
311                                 ret = -1;
312                                 goto cleanup;
313                         }
314                 }
315
316                 ret = tftp_recvfrom(sock, rx, &port, args->rx_timeout);
317                 if (ret < 0) {
318                         goto cleanup;
319                 } else if (!ret) {
320                         if (++timeout < 5 || (!block && timeout < 10)) {
321                                 continue;
322                         } else if (block) {
323                                 fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block);
324                         } else {
325                                 fprintf(stderr, "Timeout while waiting for initial reply.\n");
326                         }
327                         ret = -1;
328                         goto cleanup;
329                 } else {
330                         timeout = 0;
331                         ret = 0;
332
333                         if (!block && port != args->port) {
334                                 if (verbosity > 1) {
335                                         printf("Switching to port %d\n", port);
336                                 }
337                                 addr.sin_port = htons(port);
338                         }
339                 }
340         } while(1);
341
342         ret = 0;
343
344 cleanup:
345         if (fd >= 0) {
346                 close(fd);
347         }
348
349         if (sock >= 0) {
350 #ifndef NMRPFLASH_WINDOWS
351                 shutdown(sock, SHUT_RDWR);
352                 close(sock);
353 #else
354                 shutdown(sock, SD_BOTH);
355                 closesocket(sock);
356 #endif
357         }
358
359         return ret;
360 }