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