Fix winsock shutdown call
[oweals/nmrpflash.git] / tftp.c
1 /**
2  * nmrp-flash - Netgear Unbrick Utility
3  * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
4  *
5  * nmrp-flash 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  * nmrp-flash 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 nmrp-flash.  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'.");
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, struct sockaddr_in *src)
115 {
116         ssize_t len;
117
118         len = recvfrom(sock, pkt, TFTP_PKT_SIZE, 0, NULL, NULL);
119         if (len < 0) {
120                 if (errno != EAGAIN) {
121                         perror("recvfrom");
122                         return -1;
123                 }
124
125                 return -2;
126         }
127
128         uint16_t opcode = pkt_num(pkt);
129
130         if (opcode == ERR) {
131                 fprintf(stderr, "Error (%d): %.511s\n", pkt_num(pkt + 2), pkt + 4);
132                 return -1;
133         } else if (isprint(pkt[0])) {
134                 /* In case of a firmware checksum error, the EX2700 I've tested this
135                  * on sends a raw UDP packet containing just an error message starting
136                  * at offset 0. The limit of 32 chars is arbitrary.
137                  */
138                 fprintf(stderr, "Error: %.32s\n", pkt);
139                 return -3;
140         } else {
141                 fprintf(stderr, "Received invalid packet: ");
142                 pkt_print(pkt, stderr);
143                 fprintf(stderr, ".\n");
144                 return -2;
145         }
146
147         return len;
148 }
149
150 static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
151                 struct sockaddr_in *dst)
152 {
153         ssize_t sent;
154
155         switch (pkt_num(pkt)) {
156                 case RRQ:
157                 case WRQ:
158                         len = 2 + strlen(pkt + 2) + 1;
159                         len += strlen(pkt + len) + 1;
160                         break;
161                 case DATA:
162                         len += 4;
163                         break;
164                 case ACK:
165                         len = 4;
166                         break;
167                 case ERR:
168                         len = 4 + strlen(pkt + 4);
169                         break;
170                 default:
171                         fprintf(stderr, "Attempted to send invalid packet ");
172                         pkt_print(pkt, stderr);
173                         fprintf(stderr, "; this is a bug!\n");
174                         return -1;
175         }
176
177         sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
178         if (sent < 0) {
179                 perror("sendto");
180         }
181
182         return sent;
183 }
184
185 static int sock_set_rx_timeout(int fd, unsigned msec)
186 {
187         struct timeval tv;
188
189         if (msec) {
190                 tv.tv_usec = (msec % 1000) * 1000;
191                 tv.tv_sec = msec / 1000;
192                 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)) < 0) {
193                         perror("setsockopt(SO_RCVTIMEO)");
194                         return 1;
195                 }
196         }
197
198         return 0;
199 }
200
201 int tftp_put(struct nmrpd_args *args)
202 {
203         struct sockaddr_in addr;
204         uint16_t block;
205         ssize_t len;
206         int fd, sock, err, timeout, last_len;
207         char rx[TFTP_PKT_SIZE], tx[TFTP_PKT_SIZE];
208
209         sock = -1;
210
211         fd = open(args->filename, O_RDONLY);
212         if (fd < 0) {
213                 perror("open");
214                 err = fd;
215                 goto cleanup;
216         }
217
218         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
219         if (sock < 0) {
220                 perror("socket");
221                 err = sock;
222                 goto cleanup;
223         }
224
225         err = sock_set_rx_timeout(sock, args->rx_timeout);
226         if (err) {
227                 goto cleanup;
228         }
229
230         if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
231                 perror("inet_addr");
232                 goto cleanup;
233         }
234
235         addr.sin_family = AF_INET;
236         addr.sin_port = htons(args->port);
237
238         block = 0;
239         last_len = -1;
240         len = 0;
241         /* Not really, but this way the loop sends our WRQ before receiving */
242         timeout = 1;
243
244         pkt_mkwrq(tx, args->filename);
245
246         do {
247                 if (timeout || (pkt_num(rx) == ACK && pkt_num(rx + 2) == block)) {
248                         if (!timeout) {
249                                 ++block;
250                                 pkt_mknum(tx, DATA);
251                                 pkt_mknum(tx + 2, block);
252                                 len = read(fd, tx + 4, 512);
253                                 if (len < 0) {
254                                         perror("read");
255                                         err = len;
256                                         goto cleanup;
257                                 } else if (!len) {
258                                         if (last_len != 512) {
259                                                 break;
260                                         }
261                                 }
262
263                                 last_len = len;
264                         }
265
266                         err = tftp_sendto(sock, tx, len, &addr);
267                         if (err < 0) {
268                                 goto cleanup;
269                         }
270                 } else if (pkt_num(rx) != ACK) {
271                         fprintf(stderr, "Expected ACK(%d), got ", block);
272                         pkt_print(rx, stderr);
273                         fprintf(stderr, "!\n");
274                 }
275
276                 err = tftp_recvfrom(sock, rx, &addr);
277                 if (err < 0) {
278                         if (err == -2) {
279                                 if (++timeout < 5) {
280                                         continue;
281                                 }
282                                 fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block);
283                         }
284                         goto cleanup;
285                 } else {
286                         timeout = 0;
287                         err = 0;
288                 }
289         } while(1);
290
291         err = 0;
292
293 cleanup:
294         if (fd >= 0) {
295                 close(fd);
296         }
297
298         if (sock >= 0) {
299 #ifndef NMRPFLASH_WINDOWS
300                 shutdown(sock, SHUT_RDWR);
301                 close(sock);
302 #else
303                 shutdown(sock, SD_BOTH);
304                 closesocket(sock);
305 #endif
306         }
307
308         return err;
309 }