Sanitize filename (netascii, basename)
[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 char *x_basename(const char *path)
44 {
45         char *slash, *bslash;
46
47         slash = rindex(path, '/');
48         bslash = rindex(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 strdup(path);
59 }
60
61 static const char *sanitize_netascii(char *str)
62 {
63         char *p = str;
64
65         for (; *p; ++p) {
66                 if (*p < 0x20 || *p > 0x7f) {
67                         *p = '_';
68                 }
69         }
70
71         return str;
72 }
73
74 static inline void pkt_mknum(char *pkt, uint16_t n)
75 {
76         *(uint16_t*)pkt = htons(n);
77 }
78
79 static inline uint16_t pkt_num(char *pkt)
80 {
81         return ntohs(*(uint16_t*)pkt);
82 }
83
84 static void pkt_mkwrq(char *pkt, const char *filename, const char *mode)
85 {
86         size_t len = 2;
87
88         pkt_mknum(pkt, WRQ);
89
90         strcpy(pkt + len, filename);
91         len += strlen(filename) + 1;
92         strcpy(pkt + len, mode);
93         len += strlen(mode) + 1;
94 }
95
96 static inline void pkt_print(char *pkt, FILE *fp)
97 {
98         uint16_t opcode = pkt_num(pkt);
99         if (!opcode || opcode > ERR) {
100                 fprintf(fp, "(%d)", opcode);
101         } else {
102                 fprintf(fp, "%s", opcode_names[opcode - 1]);
103                 if (opcode == ACK || opcode == DATA) {
104                         fprintf(fp, "(%d)", pkt_num(pkt + 2));
105                 } else if (opcode == WRQ) {
106                         fprintf(fp, "(%s, %s)", pkt + 2, pkt + 2 + strlen(pkt + 2) + 1);
107                 }
108         }
109 }
110
111 static ssize_t tftp_recvfrom(int sock, char *pkt, struct sockaddr_in *src)
112 {
113         ssize_t len;
114
115         len = recvfrom(sock, pkt, TFTP_PKT_SIZE, 0, NULL, NULL);
116         if (len < 0) {
117                 if (errno != EAGAIN) {
118                         perror("recvfrom");
119                         return -1;
120                 }
121
122                 return -2;
123         }
124
125         uint16_t opcode = pkt_num(pkt);
126
127         if (opcode == ERR) {
128                 fprintf(stderr, "Error (%d): %.511s\n", pkt_num(pkt + 2), pkt + 4);
129                 return -1;
130         } else if (!opcode || opcode > ERR) {
131                 /* The EX2700 I've tested this on sends a raw TFTP packet with no
132                  * opcode, and an error message starting at offset 0.
133                  */
134                 fprintf(stderr, "Error: %.32s\n", pkt);
135                 return -3;
136         }
137
138         return len;
139 }
140
141 static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
142                 struct sockaddr_in *dst)
143 {
144         ssize_t sent;
145
146         switch (pkt_num(pkt)) {
147                 case RRQ:
148                 case WRQ:
149                         len = 2 + strlen(pkt + 2) + 1;
150                         len += strlen(pkt + len) + 1;
151                         break;
152                 case DATA:
153                         len += 4;
154                         break;
155                 case ACK:
156                         len = 4;
157                         break;
158                 case ERR:
159                         len = 4 + strlen(pkt + 4);
160                         break;
161                 default:
162                         fprintf(stderr, "Error: Invalid packet ");
163                         pkt_print(pkt, stderr);
164                         return -1;
165         }
166
167         sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
168         if (sent < 0) {
169                 perror("sendto");
170         }
171
172         return sent;
173 }
174
175 int sock_set_rx_timeout(int fd, unsigned msec)
176 {
177         struct timeval tv;
178
179         if (msec) {
180                 tv.tv_usec = (msec % 1000) * 1000;
181                 tv.tv_sec = msec / 1000;
182                 if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)) < 0) {
183                         perror("setsockopt(SO_RCVTIMEO)");
184                         return 1;
185                 }
186         }
187
188         return 0;
189 }
190
191 int tftp_put(struct nmrpd_args *args)
192 {
193         struct sockaddr_in addr;
194         char *filename;
195         uint16_t block;
196         ssize_t len;
197         int fd, sock, err, timeout, last_len;
198         char rx[TFTP_PKT_SIZE], tx[TFTP_PKT_SIZE];
199
200         sock = -1;
201         filename = NULL;
202
203         fd = open(args->filename, O_RDONLY);
204         if (fd < 0) {
205                 perror("open");
206                 err = fd;
207                 goto cleanup;
208         }
209
210         sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
211         if (sock < 0) {
212                 perror("socket");
213                 err = sock;
214                 goto cleanup;
215         }
216
217         err = sock_set_rx_timeout(sock, args->rx_timeout);
218         if (err) {
219                 goto cleanup;
220         }
221
222         if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
223                 perror("inet_addr");
224                 goto cleanup;
225         }
226
227         addr.sin_family = AF_INET;
228         addr.sin_port = htons(args->port);
229
230         filename = x_basename(args->filename);
231         if (!filename) {
232                 perror("x_basename");
233                 goto cleanup;
234         } else if (strlen(filename) > 256) {
235                 fprintf(stderr, "Filename exceeds maximum of 256 characters.\n");
236                 goto cleanup;
237         }
238
239         sanitize_netascii(filename);
240         if (verbosity > 1) {
241                 printf("%s -> %s\n", args->filename, filename);
242         }
243
244         pkt_mkwrq(tx, filename, "octet");
245
246         len = tftp_sendto(sock, tx, 0, &addr);
247         if (len < 0) {
248                 err = len;
249                 goto cleanup;
250         }
251
252         len = tftp_recvfrom(sock, rx, &addr);
253         if (len < 0) {
254                 err = len;
255                 goto cleanup;
256         }
257
258         timeout = 0;
259         block = 0;
260         last_len = -1;
261
262         do {
263                 if (timeout || (pkt_num(rx) == ACK && pkt_num(rx + 2) == block)) {
264                         if (!timeout) {
265                                 ++block;
266                                 pkt_mknum(tx, DATA);
267                                 pkt_mknum(tx + 2, block);
268                                 len = read(fd, tx + 4, 512);
269                                 if (len < 0) {
270                                         perror("read");
271                                         err = len;
272                                         goto cleanup;
273                                 } else if (!len) {
274                                         if (last_len != 512) {
275                                                 break;
276                                         }
277                                 }
278
279                                 last_len = len;
280                         }
281
282                         err = tftp_sendto(sock, tx, len, &addr);
283                         if (err < 0) {
284                                 goto cleanup;
285                         }
286                 } else if (pkt_num(rx) != ACK) {
287                         fprintf(stderr, "Expected ACK(%d), got ", block);
288                         pkt_print(rx, stderr);
289                         fprintf(stderr, "!\n");
290                 }
291
292                 err = tftp_recvfrom(sock, rx, &addr);
293                 if (err < 0) {
294                         if (err == -2) {
295                                 if (++timeout < 5) {
296                                         continue;
297                                 }
298                                 fprintf(stderr, "Timeout while waiting for ACK(%d)\n.", block);
299                         }
300                         goto cleanup;
301                 } else {
302                         timeout = 0;
303                         err = 0;
304                 }
305         } while(1);
306
307         err = 0;
308
309 cleanup:
310         free(filename);
311
312         if (fd >= 0) {
313                 close(fd);
314         }
315
316         if (sock >= 0) {
317                 close(sock);
318         }
319
320         return err;
321 }