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