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