Open firmware images in binary mode on Windows
[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
238         sock = -1;
239         ret = -1;
240
241         if (!strcmp(args->file_local, "-")) {
242                 fd = STDIN_FILENO;
243         } else {
244                 fd = open(args->file_local, O_RDONLY | O_BINARY);
245                 if (fd < 0) {
246                         perror("open");
247                         ret = fd;
248                         goto cleanup;
249                 }
250         }
251
252         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
253         if (sock < 0) {
254                 sock_perror("socket");
255                 ret = sock;
256                 goto cleanup;
257         }
258
259         if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
260                 perror("inet_addr");
261                 goto cleanup;
262         }
263
264         addr.sin_family = AF_INET;
265         addr.sin_port = htons(args->port);
266
267         block = 0;
268         last_len = -1;
269         len = 0;
270         errors = 0;
271         /* Not really, but this way the loop sends our WRQ before receiving */
272         timeout = 1;
273
274         pkt_mkwrq(tx, args->file_remote);
275
276         do {
277                 if (!timeout && pkt_num(rx) == ACK) {
278                         ackblock = pkt_num(rx + 2);
279                 } else {
280                         ackblock = -1;
281                 }
282
283                 if (timeout || ackblock == block) {
284                         if (!timeout) {
285                                 ++block;
286                                 pkt_mknum(tx, DATA);
287                                 pkt_mknum(tx + 2, block);
288                                 len = read(fd, tx + 4, 512);
289                                 if (len < 0) {
290                                         perror("read");
291                                         ret = len;
292                                         goto cleanup;
293                                 } else if (!len) {
294                                         if (last_len != 512 && last_len != -1) {
295                                                 break;
296                                         }
297                                 }
298
299                                 last_len = len;
300                         }
301
302                         ret = tftp_sendto(sock, tx, len, &addr);
303                         if (ret < 0) {
304                                 goto cleanup;
305                         }
306                 } else if (pkt_num(rx) != ACK || ackblock > block) {
307                         if (verbosity) {
308                                 fprintf(stderr, "Expected ACK(%d), got ", block);
309                                 pkt_print(rx, stderr);
310                                 fprintf(stderr, ".\n");
311                         }
312
313                         if (ackblock != -1 && ++errors > 5) {
314                                 fprintf(stderr, "Protocol error; bailing out.\n");
315                                 ret = -1;
316                                 goto cleanup;
317                         }
318                 }
319
320                 ret = tftp_recvfrom(sock, rx, &port, args->rx_timeout);
321                 if (ret < 0) {
322                         goto cleanup;
323                 } else if (!ret) {
324                         if (++timeout < 5 || (!block && timeout < 10)) {
325                                 continue;
326                         } else if (block) {
327                                 fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block);
328                         } else {
329                                 fprintf(stderr, "Timeout while waiting for initial reply.\n");
330                         }
331                         ret = -1;
332                         goto cleanup;
333                 } else {
334                         timeout = 0;
335                         ret = 0;
336
337                         if (!block && port != args->port) {
338                                 if (verbosity > 1) {
339                                         printf("Switching to port %d\n", port);
340                                 }
341                                 addr.sin_port = htons(port);
342                         }
343                 }
344         } while(1);
345
346         ret = 0;
347
348 cleanup:
349         if (fd >= 0) {
350                 close(fd);
351         }
352
353         if (sock >= 0) {
354 #ifndef NMRPFLASH_WINDOWS
355                 shutdown(sock, SHUT_RDWR);
356                 close(sock);
357 #else
358                 shutdown(sock, SD_BOTH);
359                 closesocket(sock);
360 #endif
361         }
362
363         return ret;
364 }