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