Update readme
[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_HDR_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 3
35
36 #define NMRP_OPT_NEXT(x) ((struct nmrp_opt*)(((char*)x) + x->len))
37
38 #define ETH_P_NMRP 0x0912
39 #define IP_LEN 4
40 #define MAX_LOOP_RECV 1024
41
42 #ifndef PACKED
43 #define PACKED __attribute__((__packed__))
44 #endif
45
46 enum nmrp_code {
47         NMRP_C_NONE = 0,
48         NMRP_C_ADVERTISE = 1,
49         NMRP_C_CONF_REQ = 2,
50         NMRP_C_CONF_ACK = 3,
51         NMRP_C_CLOSE_REQ = 4,
52         NMRP_C_CLOSE_ACK = 5,
53         NMRP_C_KEEP_ALIVE_REQ = 6,
54         NMRP_C_KEEP_ALIVE_ACK = 7,
55         NMRP_C_TFTP_UL_REQ = 16
56 };
57
58 enum nmrp_opt_type {
59         NMRP_O_MAGIC_NO = 0x0001,
60         NMRP_O_DEV_IP = 0x0002,
61         NMRP_O_DEV_REGION = 0x0004,
62         NMRP_O_FW_UP = 0x0101,
63         NMRP_O_ST_UP = 0x0102,
64         NMRP_O_FILE_NAME = 0x0181
65 };
66
67 struct nmrp_opt {
68         uint16_t type;
69         uint16_t len;
70         union {
71                 uint8_t magic[4];
72                 uint16_t region;
73                 struct {
74                         uint8_t addr[4];
75                         uint8_t mask[4];
76                 } ip;
77         } val;
78 } PACKED;
79
80 struct nmrp_msg {
81         uint16_t reserved;
82         uint8_t code;
83         uint8_t id;
84         uint16_t len;
85         /* only opts[0] is valid! think of this as a char* */
86         struct nmrp_opt opts[NMRP_MAX_OPT_NUM];
87         /* this is NOT part of the transmitted packet */
88         uint32_t num_opts;
89 } PACKED;
90
91 struct eth_hdr {
92         uint8_t ether_dhost[6];
93         uint8_t ether_shost[6];
94         uint16_t ether_type;
95 } PACKED;
96
97 struct nmrp_pkt {
98         struct eth_hdr eh;
99         struct nmrp_msg msg;
100 } PACKED;
101
102 static const char *msg_code_str(uint16_t code)
103 {
104 #define CASE_CODE(x) case NMRP_C_ ## x: return #x
105         static char buf[16];
106
107         switch (code) {
108                 CASE_CODE(ADVERTISE);
109                 CASE_CODE(CONF_REQ);
110                 CASE_CODE(CONF_ACK);
111                 CASE_CODE(CLOSE_REQ);
112                 CASE_CODE(CLOSE_ACK);
113                 CASE_CODE(KEEP_ALIVE_REQ);
114                 CASE_CODE(KEEP_ALIVE_ACK);
115                 CASE_CODE(TFTP_UL_REQ);
116                 default:
117                         snprintf(buf, sizeof(buf), "%04x", code);
118                         return buf;
119         }
120 #undef CASE_CODE
121 }
122
123 static uint16_t to_region_code(const char *region)
124 {
125 #define REGION_CODE(r, c) if (!strcasecmp(region, r)) return c
126         REGION_CODE("NA", 0x0001);
127         REGION_CODE("WW", 0x0002);
128         REGION_CODE("GR", 0x0003);
129         REGION_CODE("PR", 0x0004);
130         REGION_CODE("RU", 0x0005);
131         REGION_CODE("BZ", 0x0006);
132         REGION_CODE("IN", 0x0007);
133         REGION_CODE("KO", 0x0008);
134         REGION_CODE("JP", 0x0009);
135 #undef REGION_CODE
136         return 0;
137 }
138
139 static void msg_dump(struct nmrp_msg *msg, int dump_opts)
140 {
141         struct nmrp_opt *opt;
142         int remain_len, len, i;
143
144         fprintf(stderr, "res=0x%04x, code=0x%02x, id=0x%02x, len=%u",
145                         msg->reserved, msg->code, msg->id, msg->len);
146
147         remain_len = msg->len - NMRP_HDR_LEN;
148         fprintf(stderr, "%s\n", remain_len ? "" : " (no opts)");
149
150         if (dump_opts) {
151                 opt = msg->opts;
152
153                 while (remain_len > 0) {
154                         len = opt->len;
155                         fprintf(stderr, "  opt type=%u, len=%u", opt->type, len);
156                         if (len) {
157                                 for (i = 0; i != len - NMRP_OPT_HDR_LEN; ++i) {
158                                         if (!(i % 16)) {
159                                                 fprintf(stderr, "\n  ");
160                                         }
161
162                                         fprintf(stderr, "%02x ", ((char*)&opt->val)[i] & 0xff);
163                                 }
164                                 fprintf(stderr, "\n");
165                         }
166                         remain_len -= len;
167                         opt = NMRP_OPT_NEXT(opt);
168                 }
169         }
170 }
171
172 static void msg_hton(struct nmrp_msg *msg)
173 {
174         uint32_t i = 0;
175         struct nmrp_opt *opt = msg->opts, *next;
176
177         msg->reserved = htons(msg->reserved);
178         msg->len = htons(msg->len);
179
180         for (; i != msg->num_opts; ++i) {
181                 next = NMRP_OPT_NEXT(opt);
182                 opt->len = htons(opt->len);
183                 opt->type = htons(opt->type);
184                 opt = next;
185         }
186 }
187
188 static void msg_hdr_ntoh(struct nmrp_msg *msg)
189 {
190         msg->reserved = ntohs(msg->reserved);
191         msg->len = ntohs(msg->len);
192 }
193
194 static int msg_ntoh(struct nmrp_msg *msg)
195 {
196         struct nmrp_opt *opt = msg->opts;
197         int remaining;
198
199         remaining = msg->len - NMRP_HDR_LEN;
200
201         // FIXME maximum of two options supported, maximum option
202         // size is 12
203         if (remaining < NMRP_MAX_OPT_NUM * NMRP_MAX_OPT_SIZE) {
204                 while (remaining > 0) {
205                         if (remaining < NMRP_OPT_HDR_LEN) {
206                                 break;
207                         }
208
209                         opt->type = ntohs(opt->type);
210                         opt->len = ntohs(opt->len);
211
212                         if (opt->len > NMRP_MAX_OPT_SIZE) {
213                                 break;
214                         }
215
216                         remaining -= opt->len;
217                         opt = NMRP_OPT_NEXT(opt);
218                 }
219
220                 if (!remaining) {
221                         return 0;
222                 }
223         }
224
225         fprintf(stderr, "Unexpected message format.\n");
226         msg_dump(msg, 0);
227         return 1;
228 }
229
230 static void *msg_opt_data(struct nmrp_msg *msg, uint16_t type, uint16_t *len)
231 {
232         static char buf[128];
233         struct nmrp_opt *opt = msg->opts;
234         int remaining = msg->len - NMRP_HDR_LEN;
235
236         memset(buf, 0, sizeof(buf));
237
238         while (remaining > 0) {
239                 if (opt->type == type) {
240                         if (opt->len == NMRP_OPT_HDR_LEN) {
241                                 return NULL;
242                         }
243                         *len = opt->len - NMRP_OPT_HDR_LEN;
244                         memcpy(buf, &opt->val, MIN(*len, sizeof(buf)-1));
245                         return buf;
246                 }
247
248                 remaining -= opt->len;
249                 opt = NMRP_OPT_NEXT(opt);
250         }
251
252         return NULL;
253 }
254
255 static void msg_opt_add(struct nmrp_msg *msg, uint16_t type, void *data,
256                 uint16_t len)
257 {
258         uint32_t i = 0;
259         struct nmrp_opt *opt = msg->opts;
260
261         if (len + NMRP_OPT_HDR_LEN > NMRP_MAX_OPT_SIZE
262                         || msg->num_opts == NMRP_MAX_OPT_NUM) {
263                 fprintf(stderr, "Invalid option - this is a bug.\n");
264         }
265
266         for (; i <= msg->num_opts; ++i) {
267                 opt = NMRP_OPT_NEXT(opt);
268         }
269
270         opt->len = NMRP_OPT_HDR_LEN + len;
271         opt->type = type;
272
273         if (len) {
274                 memcpy(&opt->val, data, len);
275         }
276
277         msg->len += opt->len;
278         ++msg->num_opts;
279 }
280
281 static inline void msg_init(struct nmrp_msg *msg, uint16_t code)
282 {
283         memset(msg, 0, sizeof(*msg));
284         msg->len = NMRP_HDR_LEN;
285         msg->code = code;
286 }
287
288 static int pkt_send(struct ethsock *sock, struct nmrp_pkt *pkt)
289 {
290         size_t len = ntohs(pkt->msg.len) + sizeof(pkt->eh);
291         return ethsock_send(sock, pkt, len);
292 }
293
294 static int pkt_recv(struct ethsock *sock, struct nmrp_pkt *pkt)
295 {
296         ssize_t bytes, len;
297
298         memset(pkt, 0, sizeof(*pkt));
299         bytes = ethsock_recv(sock, pkt, sizeof(*pkt));
300         if (bytes < 0) {
301                 return 1;
302         } else if (!bytes) {
303                 return 2;
304         } else if (bytes < NMRP_MIN_PKT_LEN) {
305                 fprintf(stderr, "Short packet (%d bytes)\n", (int)bytes);
306                 return 1;
307         }
308
309         msg_hdr_ntoh(&pkt->msg);
310         len = pkt->msg.len + sizeof(pkt->eh);
311
312         if (bytes < len) {
313                 fprintf(stderr, "Short packet (expected %d, got %d).\n",
314                                 (int)len, (int)bytes);
315                 return 1;
316         }
317
318         return msg_ntoh(&pkt->msg);
319 }
320
321 static int mac_parse(const char *str, uint8_t *hwaddr)
322 {
323         int i;
324         unsigned data[6];
325
326         sscanf(str, "%02x:%02x:%02x:%02x:%02x:%02x%n",
327                         data, data + 1, data + 2, data + 3, data + 4, data + 5, &i);
328
329         if (i == strlen(str)) {
330                 for (i = 0; i != 6; ++i) {
331                         if (data[i] > 255) {
332                                 break;
333                         }
334
335                         hwaddr[i] = data[i] & 0xff;
336                 }
337
338                 if (i == 6) {
339                         return 1;
340                 }
341         }
342         return 0;
343 }
344
345 struct is_valid_ip_arg
346 {
347         struct in_addr *ipaddr;
348         struct in_addr *ipmask;
349         int result;
350 };
351
352 static int is_valid_ip_cb(struct ethsock_ip_callback_args *args)
353 {
354 #define SUBNET(x) ((x)->ipaddr->s_addr & (x)->ipmask->s_addr)
355         struct is_valid_ip_arg *arg = args->arg;
356         if (SUBNET(args) == SUBNET(arg)) {
357                 arg->result = args->ipaddr->s_addr != arg->ipaddr->s_addr;
358                 return 0;
359         }
360
361         return 1;
362 #undef SUBNET
363 }
364
365 static int is_valid_ip(struct ethsock *sock, struct in_addr *ipaddr,
366                 struct in_addr *ipmask)
367 {
368         int status;
369         struct is_valid_ip_arg arg = {
370                 .ipaddr = ipaddr,
371                 .ipmask = ipmask,
372                 .result = 0
373         };
374
375         status = ethsock_for_each_ip(sock, is_valid_ip_cb, &arg);
376         return status < 0 ? status : arg.result;
377 }
378
379 static struct ethsock *gsock = NULL;
380 static int garp = 0;
381 static struct in_addr arpip = { 0 };
382 static uint8_t arpmac[6] = { 0 };
383
384 static void sigh(int sig)
385 {
386         printf("\n");
387         if (gsock) {
388                 if (garp) {
389                         ethsock_arp_del(gsock, arpmac, &arpip);
390                 }
391                 ethsock_close(gsock);
392                 gsock = NULL;
393         }
394
395         exit(1);
396 }
397
398 static const char *spinner = "\\|/-";
399
400 int nmrp_do(struct nmrpd_args *args)
401 {
402         struct nmrp_pkt tx, rx;
403         uint8_t *src, dest[6];
404         uint16_t len, region;
405         char *filename;
406         time_t beg;
407         int i, status, ulreqs, expect, upload_ok;
408         struct ethsock *sock;
409         void (*sigh_orig)(int);
410         struct {
411                 struct in_addr addr;
412                 struct in_addr mask;
413         } PACKED ipconf;
414
415         if (args->op != NMRP_UPLOAD_FW) {
416                 fprintf(stderr, "Operation not implemented.\n");
417                 return 1;
418         }
419
420         if (!mac_parse(args->mac, dest)) {
421                 fprintf(stderr, "Invalid MAC address '%s'.\n", args->mac);
422                 return 1;
423         }
424
425         if ((ipconf.addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
426                 fprintf(stderr, "Invalid IP address '%s'.\n", args->ipaddr);
427                 return 1;
428         }
429
430         if ((ipconf.mask.s_addr = inet_addr(args->ipmask)) == INADDR_NONE) {
431                 fprintf(stderr, "Invalid subnet mask '%s'.\n", args->ipmask);
432                 return 1;
433         }
434
435         if (args->file_local && strcmp(args->file_local, "-") && access(args->file_local, R_OK) == -1) {
436                 fprintf(stderr, "Error accessing file '%s'.\n", args->file_local);
437                 return 1;
438         }
439
440         if (args->file_remote) {
441                 if (!tftp_is_valid_filename(args->file_remote)) {
442                         fprintf(stderr, "Invalid remote filename '%s'.\n",
443                                         args->file_remote);
444                         return 1;
445                 }
446         }
447
448         if (args->region) {
449                 region = htons(to_region_code(args->region));
450                 if (!region) {
451                         fprintf(stderr, "Invalid region code '%s'.\n", args->region);
452                         return 1;
453                 }
454         } else {
455                 region = 0;
456         }
457
458         status = 1;
459
460         sock = ethsock_create(args->intf, ETH_P_NMRP);
461         if (!sock) {
462                 return 1;
463         }
464
465         gsock = sock;
466         garp = 0;
467         sigh_orig = signal(SIGINT, sigh);
468
469         status = is_valid_ip(sock, &ipconf.addr, &ipconf.mask);
470         if (status <= 0) {
471                 if (!status) {
472                         fprintf(stderr, "Address %s/%s cannot be used on interface %s.\n",
473                                         args->ipaddr, args->ipmask, args->intf);
474                 }
475                 goto out;
476         }
477
478         if (ethsock_set_timeout(sock, args->rx_timeout)) {
479                 goto out;
480         }
481
482         src = ethsock_get_hwaddr(sock);
483         if (!src) {
484                 goto out;
485         }
486
487         memcpy(tx.eh.ether_shost, src, 6);
488         memcpy(tx.eh.ether_dhost, dest, 6);
489         tx.eh.ether_type = htons(ETH_P_NMRP);
490
491         msg_init(&tx.msg, NMRP_C_ADVERTISE);
492         msg_opt_add(&tx.msg, NMRP_O_MAGIC_NO, "NTGR", 4);
493         msg_hton(&tx.msg);
494
495         i = 0;
496         upload_ok = 0;
497         beg = time(NULL);
498
499         while (1) {
500                 printf("\rAdvertising NMRP server on %s ... %c",
501                                 args->intf, spinner[i]);
502                 fflush(stdout);
503                 i = (i + 1) & 3;
504
505                 if (pkt_send(sock, &tx) < 0) {
506                         perror("sendto");
507                         goto out;
508                 }
509
510                 status = pkt_recv(sock, &rx);
511                 if (status == 0 && memcmp(rx.eh.ether_dhost, src, 6) == 0) {
512                         break;
513                 } else if (status == 1) {
514                         goto out;
515                 } else {
516                         if ((time(NULL) - beg) >= 60) {
517                                 printf("\nNo response after 60 seconds. Bailing out.\n");
518                                 goto out;
519                         }
520                 }
521         }
522
523         printf("\n");
524
525         expect = NMRP_C_CONF_REQ;
526         ulreqs = 0;
527
528         do {
529                 if (expect != NMRP_C_NONE && rx.msg.code != expect) {
530                         fprintf(stderr, "Received %s while waiting for %s!\n",
531                                         msg_code_str(rx.msg.code), msg_code_str(expect));
532                 }
533
534                 msg_init(&tx.msg, NMRP_C_NONE);
535
536                 status = 1;
537
538                 switch (rx.msg.code) {
539                         case NMRP_C_ADVERTISE:
540                                 printf("Received NMRP advertisement from %s.\n",
541                                                 mac_to_str(rx.eh.ether_shost));
542                                 status = 1;
543                                 goto out;
544                         case NMRP_C_CONF_REQ:
545                                 tx.msg.code = NMRP_C_CONF_ACK;
546
547                                 msg_opt_add(&tx.msg, NMRP_O_DEV_IP, &ipconf, 8);
548                                 msg_opt_add(&tx.msg, NMRP_O_FW_UP, NULL, 0);
549
550 #ifdef NMRPFLASH_SET_REGION
551                                 if (region) {
552                                         msg_opt_add(&tx.msg, NMRP_O_DEV_REGION, &region, 2);
553                                 }
554 #endif
555
556                                 expect = NMRP_C_TFTP_UL_REQ;
557
558                                 printf("Received configuration request from %s.\n",
559                                                 mac_to_str(rx.eh.ether_shost));
560
561                                 memcpy(tx.eh.ether_dhost, rx.eh.ether_shost, 6);
562
563                                 printf("Sending configuration: ip %s, mask %s.\n",
564                                                 args->ipaddr, args->ipmask);
565
566                                 memcpy(arpmac, rx.eh.ether_shost, 6);
567                                 memcpy(&arpip, &ipconf.addr, sizeof(ipconf.addr));
568
569                                 if (ethsock_arp_add(sock, arpmac, &arpip) != 0) {
570                                         goto out;
571                                 }
572
573                                 garp = 1;
574
575                                 break;
576                         case NMRP_C_TFTP_UL_REQ:
577                                 if (!upload_ok) {
578                                         if (++ulreqs > 5) {
579                                                 printf("Bailing out after %d upload requests.\n",
580                                                                 ulreqs);
581                                                 tx.msg.code = NMRP_C_CLOSE_REQ;
582                                                 break;
583                                         }
584                                 } else {
585                                         if (verbosity) {
586                                                 printf("Ignoring extra upload request.\n");
587                                         }
588                                         ethsock_set_timeout(sock, args->ul_timeout);
589                                         tx.msg.code = NMRP_C_KEEP_ALIVE_REQ;
590                                         break;
591                                 }
592
593                                 len = 0;
594                                 filename = msg_opt_data(&rx.msg, NMRP_O_FILE_NAME, &len);
595                                 if (filename) {
596                                         if (!args->file_remote) {
597                                                 args->file_remote = filename;
598                                         }
599                                         printf("Received upload request: filename '%.*s'.\n",
600                                                         len, filename);
601                                 } else if (!args->file_remote) {
602                                         args->file_remote = args->file_local;
603                                         printf("Received upload request with empty filename.\n");
604                                 }
605
606                                 status = 0;
607
608                                 if (args->tftpcmd) {
609                                         printf("Executing '%s' ... ", args->tftpcmd);
610                                         fflush(stdout);
611                                         status = system(args->tftpcmd);
612                                         if (!status) {
613                                                 printf("OK\n");
614                                         } else {
615                                                 printf("ERR\n");
616                                         }
617                                 }
618
619                                 if (!status && args->file_local) {
620                                         status = is_valid_ip(sock, &ipconf.addr, &ipconf.mask);
621                                         if (status < 0) {
622                                                 goto out;
623                                         } else if (!status) {
624                                                 printf("IP address of %s has changed. Please assign a "
625                                                                 "static ip to the interface.\n", args->intf);
626                                                 tx.msg.code = NMRP_C_CLOSE_REQ;
627                                                 break;
628                                         }
629
630                                         if (verbosity) {
631                                                 printf("Using remote filename '%s'.\n",
632                                                                 args->file_remote);
633                                         }
634
635                                         if (!strcmp(args->file_local, "-")) {
636                                                 printf("Uploading from stdin ... ");
637                                         } else {
638                                                 printf("Uploading %s ... ", leafname(args->file_local));
639                                         }
640                                         fflush(stdout);
641                                         status = tftp_put(args);
642                                 }
643
644                                 if (!status) {
645                                         printf("OK\nWaiting for remote to respond.\n");
646                                         upload_ok = 1;
647                                         ethsock_set_timeout(sock, args->ul_timeout);
648                                         tx.msg.code = NMRP_C_KEEP_ALIVE_REQ;
649                                         expect = NMRP_C_NONE;
650                                 } else if (status == -2) {
651                                         expect = NMRP_C_TFTP_UL_REQ;
652                                 } else {
653                                         goto out;
654                                 }
655
656                                 break;
657                         case NMRP_C_KEEP_ALIVE_REQ:
658                                 tx.msg.code = NMRP_C_KEEP_ALIVE_ACK;
659                                 ethsock_set_timeout(sock, 15000);
660                                 printf("Received keep-alive request.\n");
661                                 break;
662                         case NMRP_C_CLOSE_REQ:
663                                 tx.msg.code = NMRP_C_CLOSE_ACK;
664                                 break;
665                         case NMRP_C_CLOSE_ACK:
666                                 status = 0;
667                                 goto out;
668                         default:
669                                 fprintf(stderr, "Unknown message code 0x%02x!\n",
670                                                 rx.msg.code);
671                                 msg_dump(&rx.msg, 0);
672                 }
673
674                 if (tx.msg.code != NMRP_C_NONE) {
675                         msg_hton(&tx.msg);
676
677                         if (pkt_send(sock, &tx) < 0) {
678                                 perror("sendto");
679                                 goto out;
680                         }
681
682                         if (tx.msg.code == NMRP_C_CLOSE_REQ) {
683                                 goto out;
684                         }
685                 }
686
687                 if (rx.msg.code == NMRP_C_CLOSE_REQ) {
688                         printf("Remote finished. Closing connection.\n");
689                         break;
690                 }
691
692                 status = pkt_recv(sock, &rx);
693                 if (status) {
694                         if (status == 2) {
695                                 fprintf(stderr, "Timeout while waiting for %s.\n",
696                                                 msg_code_str(expect));
697                         }
698                         goto out;
699                 }
700
701                 ethsock_set_timeout(sock, args->rx_timeout);
702
703         } while (1);
704
705         status = 0;
706
707         if (ulreqs) {
708                 printf("Reboot your device now.\n");
709         } else {
710                 printf("No upload request received.\n");
711         }
712
713 out:
714         signal(SIGINT, sigh_orig);
715         gsock = NULL;
716         ethsock_arp_del(sock, arpmac, &arpip);
717         ethsock_close(sock);
718         return status;
719 }