Check if ip address is valid for given interface
[oweals/nmrpflash.git] / nmrp.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 <signal.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <stdio.h>
26 #include <time.h>
27 #include "nmrpd.h"
28
29 #define NMRP_HDR_LEN 6
30 #define NMRP_OPT_LEN 4
31 #define NMRP_MIN_PKT_LEN (sizeof(struct eth_hdr) +  NMRP_HDR_LEN)
32
33 #define NMRP_MAX_OPT_SIZE 12
34 #define NMRP_MAX_OPT_NUM 2
35
36 #define ETH_P_NMRP 0x0912
37 #define IP_LEN 4
38 #define MAX_LOOP_RECV 1024
39
40 #ifndef PACKED
41 #define PACKED __attribute__((__packed__))
42 #endif
43
44 enum nmrp_code {
45         NMRP_C_NONE = 0,
46         NMRP_C_ADVERTISE = 1,
47         NMRP_C_CONF_REQ = 2,
48         NMRP_C_CONF_ACK = 3,
49         NMRP_C_CLOSE_REQ = 4,
50         NMRP_C_CLOSE_ACK = 5,
51         NMRP_C_KEEP_ALIVE_REQ = 6,
52         NMRP_C_KEEP_ALIVE_ACK = 7,
53         NMRP_C_TFTP_UL_REQ = 16
54 };
55
56 enum nmrp_opt_type {
57         NMRP_O_MAGIC_NO = 0x0001,
58         NMRP_O_DEV_IP = 0x0002,
59         NMRP_O_DEV_REGION = 0x0004,
60         NMRP_O_FW_UP = 0x0101,
61         NMRP_O_ST_UP = 0x0102,
62         NMRP_O_FILE_NAME = 0x0181
63 };
64
65 struct nmrp_opt {
66         uint16_t type;
67         uint16_t len;
68         union {
69                 uint8_t magic[4];
70                 uint16_t region;
71                 struct {
72                         uint8_t addr[4];
73                         uint8_t mask[4];
74                 } ip;
75         } val;
76 } PACKED;
77
78 struct nmrp_msg {
79         uint16_t reserved;
80         uint8_t code;
81         uint8_t id;
82         uint16_t len;
83         struct nmrp_opt opts[2];
84         uint32_t num_opts;
85 } PACKED;
86
87 struct eth_hdr {
88         uint8_t ether_dhost[6];
89         uint8_t ether_shost[6];
90         uint16_t ether_type;
91 } PACKED;
92
93 struct nmrp_pkt {
94         struct eth_hdr eh;
95         struct nmrp_msg msg;
96 } PACKED;
97
98 static void msg_update_len(struct nmrp_msg *msg)
99 {
100         uint32_t i = 0;
101         msg->len = NMRP_HDR_LEN;
102         for (; i != msg->num_opts; ++i) {
103                 msg->len += msg->opts[i].len;
104         }
105 }
106
107 static void msg_dump(struct nmrp_msg *msg, int dump_opts)
108 {
109         struct nmrp_opt *opt;
110         int remain_len, len, i;
111
112         fprintf(stderr, "res=0x%04x, code=0x%02x, id=0x%02x, len=%u",
113                         msg->reserved, msg->code, msg->id, msg->len);
114
115         remain_len = msg->len - NMRP_HDR_LEN;
116         fprintf(stderr, "%s\n", remain_len ? "" : " (no opts)");
117
118         if (dump_opts) {
119                 opt = msg->opts;
120
121                 while (remain_len > 0) {
122                         len = opt->len;
123                         fprintf(stderr, "  opt type=%u, len=%u", opt->type, len);
124                         for (i = 0; i != len - NMRP_OPT_LEN; ++i) {
125                                 if (!(i % 16)) {
126                                         fprintf(stderr, "\n  ");
127                                 }
128
129                                 fprintf(stderr, "%02x ", ((char*)&opt->val)[i] & 0xff);
130                         }
131                         fprintf(stderr, "\n");
132                         remain_len -= len;
133                         opt = (struct nmrp_opt*)(((char*)opt) + len);
134                 }
135         }
136 }
137
138 static void msg_hton(struct nmrp_msg *msg)
139 {
140         uint32_t i = 0;
141
142         msg->reserved = htons(msg->reserved);
143         msg->len = htons(msg->len);
144
145         for (; i != msg->num_opts; ++i) {
146                 msg->opts[i].len = htons(msg->opts[i].len);
147                 msg->opts[i].type = htons(msg->opts[i].type);
148         }
149 }
150
151 static void msg_hdr_ntoh(struct nmrp_msg *msg)
152 {
153         msg->reserved = ntohs(msg->reserved);
154         msg->len = ntohs(msg->len);
155 }
156
157 static int msg_ntoh(struct nmrp_msg *msg)
158 {
159         struct nmrp_opt *opt = msg->opts;
160         int remaining;
161
162         remaining = msg->len - NMRP_HDR_LEN;
163
164         // FIXME maximum of two options supported, maximum option
165         // size is 12
166         if (remaining < NMRP_MAX_OPT_NUM * NMRP_MAX_OPT_SIZE) {
167                 while (remaining > 0) {
168                         if (remaining < NMRP_OPT_LEN) {
169                                 break;
170                         }
171
172                         opt->type = ntohs(opt->type);
173                         opt->len = ntohs(opt->len);
174
175                         if (opt->len > NMRP_MAX_OPT_SIZE) {
176                                 break;
177                         }
178
179                         remaining -= opt->len;
180                         ++opt;
181                 }
182
183                 if (!remaining) {
184                         return 0;
185                 }
186         }
187
188         fprintf(stderr, "Unexpected message format.\n");
189         msg_dump(msg, 0);
190         return 1;
191 }
192
193 static void *msg_opt_data(struct nmrp_msg *msg, int type, uint16_t *len)
194 {
195         struct nmrp_opt *opt = msg->opts;
196         int remaining = msg->len - NMRP_HDR_LEN;
197
198         while (remaining > 0) {
199                 if (opt->type == type) {
200                         *len = opt->len - NMRP_OPT_LEN;
201                         return (char*)&opt->val;
202                 }
203
204                 remaining -= opt->len;
205                 opt = (struct nmrp_opt*)((char*)opt) + opt->len;
206         }
207
208         return NULL;
209 }
210
211 static int pkt_send(struct ethsock *sock, struct nmrp_pkt *pkt)
212 {
213         size_t len = ntohs(pkt->msg.len) + sizeof(pkt->eh);
214         return ethsock_send(sock, pkt, len);
215 }
216
217 static int pkt_recv(struct ethsock *sock, struct nmrp_pkt *pkt)
218 {
219         ssize_t bytes, len;
220
221         memset(pkt, 0, sizeof(*pkt));
222         bytes = ethsock_recv(sock, pkt, sizeof(*pkt));
223         if (bytes < 0) {
224                 return 1;
225         } else if (!bytes) {
226                 return 2;
227         } else if (bytes < NMRP_MIN_PKT_LEN) {
228                 fprintf(stderr, "Short packet (%d bytes)\n", (int)bytes);
229                 return 1;
230         }
231
232         msg_hdr_ntoh(&pkt->msg);
233         len = pkt->msg.len + sizeof(pkt->eh);
234
235         if (bytes < len) {
236                 fprintf(stderr, "Short packet (expected %d, got %d).\n",
237                                 (int)len, (int)bytes);
238                 return 1;
239         }
240
241         return msg_ntoh(&pkt->msg);
242 }
243
244 static int mac_parse(const char *str, uint8_t *hwaddr)
245 {
246         int i;
247         unsigned data[6];
248
249         sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x%n",
250                         data, data + 1, data + 2, data + 3, data + 4, data + 5, &i);
251
252         if (i == strlen(str)) {
253                 for (i = 0; i != 6; ++i) {
254                         if (data[i] > 255) {
255                                 break;
256                         }
257
258                         hwaddr[i] = data[i] & 0xff;
259                 }
260
261                 if (i == 6) {
262                         return 1;
263                 }
264         }
265         return 0;
266 }
267
268 static struct ethsock *gsock = NULL;
269
270 static void sigh(int sig)
271 {
272         printf("\n");
273         if (gsock) {
274                 ethsock_close(gsock);
275         }
276
277         exit(1);
278 }
279
280 static const char *spinner = "\\|/-";
281
282 int nmrp_do(struct nmrpd_args *args)
283 {
284         struct nmrp_pkt tx, rx;
285         uint8_t *src, dest[6];
286         uint16_t len;
287         char *filename;
288         struct in_addr ipaddr, ipmask;
289         time_t beg;
290         int i, status, ulreqs, expect;
291         struct ethsock *sock;
292         void (*sigh_orig)(int);
293
294         if (args->op != NMRP_UPLOAD_FW) {
295                 fprintf(stderr, "Operation not implemented.\n");
296                 return 1;
297         }
298
299         if (!mac_parse(args->mac, dest)) {
300                 fprintf(stderr, "Invalid MAC address '%s'.\n", args->mac);
301                 return 1;
302         }
303
304         if ((ipaddr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
305                 fprintf(stderr, "Invalid IP address '%s'.\n", args->ipaddr);
306                 return 1;
307         }
308
309         if ((ipmask.s_addr = inet_addr(args->ipmask)) == INADDR_NONE) {
310                 fprintf(stderr, "Invalid subnet mask '%s'.\n", args->ipmask);
311                 return 1;
312         }
313
314         if (strcmp(args->file_local, "-") && access(args->file_local, R_OK) == -1) {
315                 fprintf(stderr, "Error accessing file '%s'.\n", args->file_local);
316                 return 1;
317         }
318
319         if (args->file_remote) {
320                 if (!tftp_is_valid_filename(args->file_remote)) {
321                         fprintf(stderr, "Invalid remote filename '%s'.\n",
322                                         args->file_remote);
323                         return 1;
324                 }
325         }
326
327         status = 1;
328
329         sock = ethsock_create(args->intf, ETH_P_NMRP);
330         if (!sock) {
331                 return 1;
332         }
333
334         status = ethsock_is_same_subnet(sock, &ipaddr, &ipmask);
335         if (status <= 0) {
336                 if (!status) {
337                         fprintf(stderr, "Address %s/%s invalid for interface %s.\n",
338                                         args->ipaddr, args->ipmask, args->intf);
339                 }
340                 return 1;
341         }
342
343         gsock = sock;
344         sigh_orig = signal(SIGINT, sigh);
345
346         if (ethsock_set_timeout(sock, args->rx_timeout)) {
347                 goto out;
348         }
349
350         src = ethsock_get_hwaddr(sock);
351         if (!src) {
352                 goto out;
353         }
354
355         memcpy(tx.eh.ether_shost, src, 6);
356         memcpy(tx.eh.ether_dhost, dest, 6);
357         tx.eh.ether_type = htons(ETH_P_NMRP);
358
359         tx.msg.reserved = 0;
360         tx.msg.code = NMRP_C_ADVERTISE;
361         tx.msg.id = 0;
362         tx.msg.num_opts = 1;
363         tx.msg.opts[0].type = NMRP_O_MAGIC_NO;
364         tx.msg.opts[0].len = NMRP_OPT_LEN + 4;
365         tx.msg.opts[0].val.magic[0] = 'N';
366         tx.msg.opts[0].val.magic[1] = 'T';
367         tx.msg.opts[0].val.magic[2] = 'G';
368         tx.msg.opts[0].val.magic[3] = 'R';
369
370         msg_update_len(&tx.msg);
371         msg_hton(&tx.msg);
372
373         i = 0;
374         beg = time(NULL);
375
376         while (1) {
377                 printf("\rAdvertising NMRP server on %s ... %c",
378                                 args->intf, spinner[i]);
379                 fflush(stdout);
380                 i = (i + 1) & 3;
381
382                 if (pkt_send(sock, &tx) < 0) {
383                         perror("sendto");
384                         goto out;
385                 }
386
387                 status = pkt_recv(sock, &rx);
388                 if (status == 0 && memcmp(rx.eh.ether_dhost, src, 6) == 0) {
389                         break;
390                 } else if (status == 1) {
391                         printf("ERR\n");
392                         goto out;
393                 } else {
394                         if ((time(NULL) - beg) >= 60) {
395                                 printf("\nNo response after 60 seconds. Bailing out.\n");
396                                 goto out;
397                         }
398                 }
399         }
400
401         printf("\n");
402
403         expect = NMRP_C_CONF_REQ;
404         ulreqs = 0;
405
406         do {
407                 if (expect != NMRP_C_NONE && rx.msg.code != expect) {
408                         fprintf(stderr, "Received code 0x%02x while waiting for 0x%02x!\n",
409                                         rx.msg.code, expect);
410                 }
411
412                 tx.msg.code = NMRP_C_NONE;
413                 tx.msg.reserved = 0;
414                 tx.msg.id = 0;
415                 tx.msg.num_opts = 0;
416                 tx.msg.len = 0;
417
418                 status = 1;
419
420                 switch (rx.msg.code) {
421                         case NMRP_C_ADVERTISE:
422                                 printf("Received NMRP advertisement from %s.\n",
423                                                 mac_to_str(rx.eh.ether_shost));
424                                 status = 1;
425                                 goto out;
426                         case NMRP_C_CONF_REQ:
427                                 tx.msg.code = NMRP_C_CONF_ACK;
428                                 tx.msg.num_opts = 2;
429
430                                 tx.msg.opts[0].type = NMRP_O_DEV_IP;
431                                 tx.msg.opts[0].len = NMRP_OPT_LEN + 2 * 4;
432
433                                 memcpy(tx.msg.opts[0].val.ip.addr, &ipaddr, 4);
434                                 memcpy(tx.msg.opts[0].val.ip.mask, &ipmask, 4);
435
436                                 tx.msg.opts[1].type = NMRP_O_FW_UP;
437                                 tx.msg.opts[1].len = NMRP_OPT_LEN;
438
439 #ifdef NMRPFLASH_SET_REGION
440                                 tx.msg.num_opts = 3;
441
442                                 tx.msg.opts[2].type = NMRP_O_DEV_REGION;
443                                 tx.msg.opts[2].len = NMRP_OPT_LEN + 2;
444                                 tx.msg.opts[2].val.region = args->region;
445 #endif
446
447                                 expect = NMRP_C_TFTP_UL_REQ;
448
449                                 printf("Received configuration request from %s.\n",
450                                                 mac_to_str(rx.eh.ether_shost));
451
452                                 memcpy(tx.eh.ether_dhost, rx.eh.ether_shost, 6);
453
454                                 printf("Sending configuration: ip %s, mask %s.\n",
455                                                 args->ipaddr, args->ipmask);
456
457                                 break;
458                         case NMRP_C_TFTP_UL_REQ:
459                                 if (++ulreqs > 5) {
460                                         fprintf(stderr, "Device re-requested file upload %d "
461                                                         "times; aborting.\n", ulreqs);
462                                         tx.msg.code = NMRP_C_CLOSE_REQ;
463                                         break;
464                                 }
465
466                                 len = 0;
467                                 filename = msg_opt_data(&rx.msg, NMRP_O_FILE_NAME, &len);
468                                 if (filename) {
469                                         if (!args->file_remote) {
470                                                 args->file_remote = filename;
471                                         }
472                                         printf("Received upload request: filename '%.*s'.\n",
473                                                         len, filename);
474                                 } else if (!args->file_remote) {
475                                         if (tftp_is_valid_filename(args->file_local)) {
476                                                 args->file_remote = args->file_local;
477                                         } else {
478                                                 args->file_remote = "firmware";
479                                         }
480                                         printf("Received upload request with empty filename.");
481                                 }
482
483                                 status = 0;
484
485                                 if (args->tftpcmd) {
486                                         printf("Executing '%s' ... ", args->tftpcmd);
487                                         fflush(stdout);
488                                         status = system(args->tftpcmd);
489                                         if (!status) {
490                                                 printf("OK\n");
491                                         } else {
492                                                 printf("ERR\n");
493                                         }
494                                 }
495
496                                 if (!status && args->file_local) {
497                                         if (verbosity) {
498                                                 printf("Using remote filename '%s'.\n",
499                                                                 args->file_remote);
500                                         }
501
502                                         if (!strcmp(args->file_local, "-")) {
503                                                 printf("Uploading from stdin ... ");
504                                         } else {
505                                                 printf("Uploading %s ... ", args->file_local);
506                                         }
507                                         fflush(stdout);
508                                         status = tftp_put(args);
509                                 }
510
511                                 if (!status) {
512                                         printf("OK\nWaiting for remote to respond.\n");
513                                         ethsock_set_timeout(sock, args->ul_timeout);
514                                         expect = NMRP_C_CLOSE_REQ;
515                                 } else if (status == -2) {
516                                         expect = NMRP_C_TFTP_UL_REQ;
517                                 } else {
518                                         goto out;
519                                 }
520
521                                 break;
522                         case NMRP_C_KEEP_ALIVE_REQ:
523                                 tx.msg.code = NMRP_C_KEEP_ALIVE_ACK;
524                                 break;
525                         case NMRP_C_CLOSE_REQ:
526                                 tx.msg.code = NMRP_C_CLOSE_ACK;
527                                 break;
528                         case NMRP_C_CLOSE_ACK:
529                                 status = 0;
530                                 goto out;
531                         default:
532                                 fprintf(stderr, "Unknown message code 0x%02x!\n",
533                                                 rx.msg.code);
534                                 msg_dump(&rx.msg, 0);
535                 }
536
537                 if (tx.msg.code != NMRP_C_NONE) {
538                         msg_update_len(&tx.msg);
539                         msg_hton(&tx.msg);
540
541                         if (pkt_send(sock, &tx) < 0) {
542                                 perror("sendto");
543                                 goto out;
544                         }
545                 }
546
547                 if (rx.msg.code == NMRP_C_CLOSE_REQ) {
548                         printf("Remote finished. Closing connection.\n");
549                         break;
550                 }
551
552                 status = pkt_recv(sock, &rx);
553                 if (status) {
554                         if (status == 2) {
555                                 fprintf(stderr, "Timeout while waiting for 0x%02x.\n", expect);
556                         }
557                         goto out;
558                 }
559
560                 ethsock_set_timeout(sock, args->rx_timeout);
561
562         } while (1);
563
564         status = 0;
565
566         printf("Reboot your device now.\n");
567
568 out:
569         signal(SIGINT, sigh_orig);
570         gsock = NULL;
571         ethsock_close(sock);
572         return status;
573 }