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