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