Use strrchr instead of rindex
[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 #define _BSD_SOURCE
21 #include <string.h>
22 #include <unistd.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <fcntl.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 *x_basename(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 = x_basename(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) {
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 (!opcode || opcode > ERR) {
134                 /* The EX2700 I've tested this on sends a raw TFTP packet with no
135                  * opcode, and an error message starting at offset 0.
136                  */
137                 fprintf(stderr, "Error: %.32s\n", pkt);
138                 return -3;
139         }
140
141         return len;
142 }
143
144 static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
145                 struct sockaddr_in *dst)
146 {
147         ssize_t sent;
148
149         switch (pkt_num(pkt)) {
150                 case RRQ:
151                 case WRQ:
152                         len = 2 + strlen(pkt + 2) + 1;
153                         len += strlen(pkt + len) + 1;
154                         break;
155                 case DATA:
156                         len += 4;
157                         break;
158                 case ACK:
159                         len = 4;
160                         break;
161                 case ERR:
162                         len = 4 + strlen(pkt + 4);
163                         break;
164                 default:
165                         fprintf(stderr, "Error: Invalid packet ");
166                         pkt_print(pkt, stderr);
167                         return -1;
168         }
169
170         sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
171         if (sent < 0) {
172                 perror("sendto");
173         }
174
175         return sent;
176 }
177
178 int sock_set_rx_timeout(int fd, unsigned msec)
179 {
180         struct timeval tv;
181
182         if (msec) {
183                 tv.tv_usec = (msec % 1000) * 1000;
184                 tv.tv_sec = msec / 1000;
185                 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)) < 0) {
186                         perror("setsockopt(SO_RCVTIMEO)");
187                         return 1;
188                 }
189         }
190
191         return 0;
192 }
193
194 int tftp_put(struct nmrpd_args *args)
195 {
196         struct sockaddr_in addr;
197         uint16_t block;
198         ssize_t len;
199         int fd, sock, err, timeout, last_len;
200         char rx[TFTP_PKT_SIZE], tx[TFTP_PKT_SIZE];
201
202         sock = -1;
203
204         fd = open(args->filename, O_RDONLY);
205         if (fd < 0) {
206                 perror("open");
207                 err = fd;
208                 goto cleanup;
209         }
210
211         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
212         if (sock < 0) {
213                 perror("socket");
214                 err = sock;
215                 goto cleanup;
216         }
217
218         err = sock_set_rx_timeout(sock, args->rx_timeout);
219         if (err) {
220                 goto cleanup;
221         }
222
223         if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
224                 perror("inet_addr");
225                 goto cleanup;
226         }
227
228         addr.sin_family = AF_INET;
229         addr.sin_port = htons(args->port);
230
231         pkt_mkwrq(tx, args->filename);
232
233         len = tftp_sendto(sock, tx, 0, &addr);
234         if (len < 0) {
235                 err = len;
236                 goto cleanup;
237         }
238
239         len = tftp_recvfrom(sock, rx, &addr);
240         if (len < 0) {
241                 err = len;
242                 goto cleanup;
243         }
244
245         timeout = 0;
246         block = 0;
247         last_len = -1;
248
249         do {
250                 if (timeout || (pkt_num(rx) == ACK && pkt_num(rx + 2) == block)) {
251                         if (!timeout) {
252                                 ++block;
253                                 pkt_mknum(tx, DATA);
254                                 pkt_mknum(tx + 2, block);
255                                 len = read(fd, tx + 4, 512);
256                                 if (len < 0) {
257                                         perror("read");
258                                         err = len;
259                                         goto cleanup;
260                                 } else if (!len) {
261                                         if (last_len != 512) {
262                                                 break;
263                                         }
264                                 }
265
266                                 last_len = len;
267                         }
268
269                         err = tftp_sendto(sock, tx, len, &addr);
270                         if (err < 0) {
271                                 goto cleanup;
272                         }
273                 } else if (pkt_num(rx) != ACK) {
274                         fprintf(stderr, "Expected ACK(%d), got ", block);
275                         pkt_print(rx, stderr);
276                         fprintf(stderr, "!\n");
277                 }
278
279                 err = tftp_recvfrom(sock, rx, &addr);
280                 if (err < 0) {
281                         if (err == -2) {
282                                 if (++timeout < 5) {
283                                         continue;
284                                 }
285                                 fprintf(stderr, "Timeout while waiting for ACK(%d)\n.", block);
286                         }
287                         goto cleanup;
288                 } else {
289                         timeout = 0;
290                         err = 0;
291                 }
292         } while(1);
293
294         err = 0;
295
296 cleanup:
297         if (fd >= 0) {
298                 close(fd);
299         }
300
301         if (sock >= 0) {
302                 shutdown(sock, SHUT_RDWR);
303 #ifndef NMRPFLASH_WINDOWS
304                 close(sock);
305 #else
306                 closesocket(sock);
307 #endif
308         }
309
310         return err;
311 }