a29be2c1e733830c787e7680ac3faeba2e25eb4f
[project/relayd.git] / main.c
1 /*
2  *   Copyright (C) 2010 Felix Fietkau <nbd@openwrt.org>
3  *
4  *   This program is free software; you can redistribute it and/or modify
5  *   it under the terms of the GNU General Public License v2 as published by
6  *   the Free Software Foundation.
7  *
8  *   This program is distributed in the hope that it will be useful,
9  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
10  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  *   GNU General Public License for more details.
12  *
13  *   You should have received a copy of the GNU General Public License
14  *   along with this program; if not, write to the Free Software
15  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
16  *
17  */
18 #include <sys/ioctl.h>
19
20 #include <arpa/inet.h>
21 #include <net/if.h>
22 #include <net/ethernet.h>
23 #include <netinet/if_ether.h>
24 #include <netinet/ip.h>
25 #include <netinet/udp.h>
26
27 #include <linux/if_packet.h>
28 #include <linux/rtnetlink.h>
29 #include <linux/neighbour.h>
30
31 #include <stdio.h>
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <stddef.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <stdint.h>
38 #include <stdbool.h>
39 #include <errno.h>
40 #include <signal.h>
41
42 #include "uloop.h"
43 #include "list.h"
44
45 #define DEBUG
46 #ifdef DEBUG
47 #define DPRINTF(level, ...) if (debug >= level) fprintf(stderr, __VA_ARGS__);
48 #else
49 #define DPRINTF(...) do {} while(0)
50 #endif
51
52 #ifndef __packed
53 #define __packed __attribute__((packed))
54 #endif
55
56 #define __uc(c) ((unsigned char *)(c))
57
58 #define MAC_FMT "%02x:%02x:%02x:%02x:%02x:%02x"
59 #define MAC_BUF(_c) __uc(_c)[0], __uc(_c)[1], __uc(_c)[2], __uc(_c)[3], __uc(_c)[4], __uc(_c)[5]
60
61 #define IP_FMT  "%d.%d.%d.%d"
62 #define IP_BUF(_c) __uc(_c)[0], __uc(_c)[1], __uc(_c)[2], __uc(_c)[3]
63
64 #define DUMMY_IP ((uint8_t *) "\x01\x01\x01\x01")
65
66 #define DHCP_FLAG_BROADCAST     (1 << 15)
67
68 struct relayd_interface {
69         struct list_head list;
70         struct uloop_fd fd;
71         struct uloop_fd bcast_fd;
72         struct sockaddr_ll sll;
73         struct sockaddr_ll bcast_sll;
74         char ifname[IFNAMSIZ];
75         struct list_head hosts;
76         uint8_t src_ip[4];
77         bool managed;
78 };
79
80 struct relayd_host {
81         struct list_head list;
82         struct relayd_interface *rif;
83         uint8_t lladdr[ETH_ALEN];
84         uint8_t ipaddr[4];
85         struct uloop_timeout timeout;
86         int cleanup_pending;
87 };
88
89 struct arp_packet {
90         struct ether_header eth;
91         struct ether_arp arp;
92 } __packed;
93
94 struct ip_packet {
95         struct ether_header eth;
96         struct iphdr iph;
97 } __packed;
98
99 struct dhcp_header {
100         uint8_t op, htype, hlen, hops;
101         uint32_t xit;
102         uint16_t secs, flags;
103         struct in_addr ciaddr, yiaddr, siaddr, giaddr;
104         unsigned char chaddr[16];
105         unsigned char sname[64];
106         unsigned char file[128];
107 } __packed;
108
109 struct rtnl_req {
110         struct nlmsghdr nl;
111         struct rtmsg rt;
112 };
113
114 static int debug;
115 static LIST_HEAD(interfaces);
116 static int host_timeout;
117 static int inet_sock;
118 static int forward_bcast;
119 static int forward_dhcp;
120 static struct uloop_fd rtnl_sock;
121 static unsigned int rtnl_seq, rtnl_dump_seq;
122
123 static struct relayd_host *find_host_by_ipaddr(struct relayd_interface *rif, const uint8_t *ipaddr)
124 {
125         struct relayd_host *host;
126
127         if (!rif) {
128                 list_for_each_entry(rif, &interfaces, list) {
129                         host = find_host_by_ipaddr(rif, ipaddr);
130                         if (!host)
131                                 continue;
132
133                         return host;
134                 }
135                 return NULL;
136         }
137
138         list_for_each_entry(host, &rif->hosts, list) {
139                 if (memcmp(ipaddr, host->ipaddr, sizeof(host->ipaddr)) != 0)
140                         continue;
141
142                 return host;
143         }
144         return NULL;
145 }
146
147 static void add_arp(struct relayd_host *host)
148 {
149         struct sockaddr_in *sin;
150         struct arpreq arp;
151
152         strncpy(arp.arp_dev, host->rif->ifname, sizeof(arp.arp_dev));
153         arp.arp_flags = ATF_COM;
154
155         arp.arp_ha.sa_family = ARPHRD_ETHER;
156         memcpy(arp.arp_ha.sa_data, host->lladdr, ETH_ALEN);
157
158         sin = (struct sockaddr_in *) &arp.arp_pa;
159         sin->sin_family = AF_INET;
160         memcpy(&sin->sin_addr, host->ipaddr, sizeof(host->ipaddr));
161
162         ioctl(inet_sock, SIOCSARP, &arp);
163 }
164
165 static void rtnl_route_set(struct relayd_host *host, bool add)
166 {
167         static struct {
168                 struct nlmsghdr nl;
169                 struct rtmsg rt;
170                 struct {
171                         struct rtattr rta;
172                         uint8_t ipaddr[4];
173                 } __packed dst;
174                 struct {
175                         struct rtattr rta;
176                         int ifindex;
177                 } __packed dev;
178         } __packed req;
179
180         memset(&req, 0, sizeof(req));
181
182         req.nl.nlmsg_len = sizeof(req);
183         req.rt.rtm_family = AF_INET;
184         req.rt.rtm_dst_len = 32;
185
186         req.dst.rta.rta_type = RTA_DST;
187         req.dst.rta.rta_len = sizeof(req.dst);
188         memcpy(req.dst.ipaddr, host->ipaddr, sizeof(req.dst.ipaddr));
189
190         req.dev.rta.rta_type = RTA_OIF;
191         req.dev.rta.rta_len = sizeof(req.dev);
192         req.dev.ifindex = host->rif->sll.sll_ifindex;
193
194         req.nl.nlmsg_flags = NLM_F_REQUEST;
195         req.rt.rtm_table = RT_TABLE_MAIN;
196         if (add) {
197                 req.nl.nlmsg_type = RTM_NEWROUTE;
198                 req.nl.nlmsg_flags |= NLM_F_CREATE | NLM_F_REPLACE;
199
200                 req.rt.rtm_protocol = RTPROT_BOOT;
201                 req.rt.rtm_scope = RT_SCOPE_LINK;
202                 req.rt.rtm_type = RTN_UNICAST;
203         } else {
204                 req.nl.nlmsg_type = RTM_DELROUTE;
205                 req.rt.rtm_scope = RT_SCOPE_NOWHERE;
206         }
207
208         send(rtnl_sock.fd, &req, sizeof(req), 0);
209 }
210
211 static void add_route(struct relayd_host *host)
212 {
213         rtnl_route_set(host, true);
214 }
215
216 static void del_route(struct relayd_host *host)
217 {
218         rtnl_route_set(host, false);
219 }
220
221 static void del_host(struct relayd_host *host)
222 {
223         DPRINTF(1, "%s: deleting host "IP_FMT" ("MAC_FMT")\n", host->rif->ifname,
224                 IP_BUF(host->ipaddr), MAC_BUF(host->lladdr));
225
226         if (host->rif->managed)
227                 del_route(host);
228         list_del(&host->list);
229         free(host);
230 }
231
232 static void fill_arp_request(struct arp_packet *pkt, struct relayd_interface *rif,
233                              uint8_t spa[4], uint8_t tpa[4])
234 {
235         memset(pkt, 0, sizeof(*pkt));
236
237         pkt->eth.ether_type = htons(ETHERTYPE_ARP);
238         memcpy(pkt->eth.ether_shost, rif->sll.sll_addr, ETH_ALEN);
239
240         memcpy(pkt->arp.arp_sha, rif->sll.sll_addr, ETH_ALEN);
241         memcpy(pkt->arp.arp_spa, spa, 4);
242         memcpy(pkt->arp.arp_tpa, tpa, 4);
243
244         pkt->arp.arp_hrd = htons(ARPHRD_ETHER);
245         pkt->arp.arp_pro = htons(ETH_P_IP);
246         pkt->arp.arp_hln = ETH_ALEN;
247         pkt->arp.arp_pln = 4;
248 }
249
250 static void send_arp_request(struct relayd_host *host)
251 {
252         struct relayd_interface *rif = host->rif;
253         struct arp_packet pkt;
254
255         fill_arp_request(&pkt, host->rif, host->rif->src_ip, host->ipaddr);
256
257         pkt.arp.arp_op = htons(ARPOP_REQUEST);
258         memcpy(pkt.arp.arp_spa, rif->src_ip, ETH_ALEN);
259         memset(pkt.arp.arp_tha, 0, ETH_ALEN);
260         memset(pkt.eth.ether_dhost, 0xff, ETH_ALEN);
261
262         DPRINTF(2, "%s: sending ARP who-has "IP_FMT", tell "IP_FMT" ("MAC_FMT")\n",
263                 rif->ifname, IP_BUF(pkt.arp.arp_tpa),
264                 IP_BUF(pkt.arp.arp_spa), MAC_BUF(pkt.eth.ether_shost));
265
266         sendto(rif->fd.fd, &pkt, sizeof(pkt), 0,
267                 (struct sockaddr *) &rif->sll, sizeof(rif->sll));
268 }
269
270 static void send_arp_reply(struct relayd_interface *rif, uint8_t spa[4],
271                            uint8_t tha[ETH_ALEN], uint8_t tpa[4])
272 {
273         struct arp_packet pkt;
274
275         fill_arp_request(&pkt, rif, spa, tpa);
276
277         pkt.arp.arp_op = htons(ARPOP_REPLY);
278         memcpy(pkt.eth.ether_dhost, tha, ETH_ALEN);
279         memcpy(pkt.arp.arp_tha, tha, ETH_ALEN);
280
281         DPRINTF(2, "%s: sending ARP reply to "IP_FMT", "IP_FMT" is at ("MAC_FMT")\n",
282                 rif->ifname, IP_BUF(pkt.arp.arp_tpa),
283                 IP_BUF(pkt.arp.arp_spa), MAC_BUF(pkt.eth.ether_shost));
284
285         sendto(rif->fd.fd, &pkt, sizeof(pkt), 0,
286                 (struct sockaddr *) &rif->sll, sizeof(rif->sll));
287 }
288
289 static void host_entry_timeout(struct uloop_timeout *timeout)
290 {
291         struct relayd_host *host = container_of(timeout, struct relayd_host, timeout);
292
293         /*
294          * When a host is behind a managed interface, we must not expire its host
295          * entry prematurely, as this will cause routes to the node to expire,
296          * leading to loss of connectivity from the other side.
297          * When the timeout is reached, try pinging the host a few times before
298          * giving up on it.
299          */
300         if (host->rif->managed && host->cleanup_pending < 2) {
301                 send_arp_request(host);
302                 host->cleanup_pending++;
303                 uloop_timeout_set(&host->timeout, 1000);
304                 return;
305         }
306         del_host(host);
307 }
308
309 static struct relayd_host *add_host(struct relayd_interface *rif, const uint8_t *lladdr, const uint8_t *ipaddr)
310 {
311         struct relayd_host *host;
312
313         DPRINTF(1, "%s: adding host "IP_FMT" ("MAC_FMT")\n", rif->ifname,
314                         IP_BUF(ipaddr), MAC_BUF(lladdr));
315
316         host = calloc(1, sizeof(*host));
317         host->rif = rif;
318         memcpy(host->ipaddr, ipaddr, sizeof(host->ipaddr));
319         memcpy(host->lladdr, lladdr, sizeof(host->lladdr));
320         list_add(&host->list, &rif->hosts);
321         host->timeout.cb = host_entry_timeout;
322         uloop_timeout_set(&host->timeout, host_timeout * 1000);
323
324         add_arp(host);
325         if (rif->managed)
326                 add_route(host);
327
328         return host;
329 }
330
331 static struct relayd_host *refresh_host(struct relayd_interface *rif, const uint8_t *lladdr, const uint8_t *ipaddr)
332 {
333         struct relayd_host *host;
334
335         host = find_host_by_ipaddr(rif, ipaddr);
336         if (!host) {
337                 host = find_host_by_ipaddr(NULL, ipaddr);
338
339                 /* 
340                  * When we suddenly see the host appearing on a different interface,
341                  * reduce the timeout to make the old entry expire faster, in case the
342                  * host has moved.
343                  * If the old entry is behind a managed interface, it will be pinged
344                  * before we expire it
345                  */
346                 if (host && !host->cleanup_pending)
347                         uloop_timeout_set(&host->timeout, 1);
348
349                 host = add_host(rif, lladdr, ipaddr);
350         } else {
351                 host->cleanup_pending = false;
352                 uloop_timeout_set(&host->timeout, host_timeout * 1000);
353         }
354
355         return host;
356 }
357
358 static void relay_arp_request(struct relayd_interface *from_rif, struct arp_packet *pkt)
359 {
360         struct relayd_interface *rif;
361         struct arp_packet reqpkt;
362
363         memcpy(&reqpkt, pkt, sizeof(reqpkt));
364         list_for_each_entry(rif, &interfaces, list) {
365                 if (rif == from_rif)
366                         continue;
367
368                 memcpy(reqpkt.eth.ether_shost, rif->sll.sll_addr, ETH_ALEN);
369                 memcpy(reqpkt.arp.arp_sha, rif->sll.sll_addr, ETH_ALEN);
370
371                 DPRINTF(2, "%s: sending ARP who-has "IP_FMT", tell "IP_FMT" ("MAC_FMT")\n",
372                         rif->ifname, IP_BUF(reqpkt.arp.arp_tpa),
373                         IP_BUF(reqpkt.arp.arp_spa), MAC_BUF(reqpkt.eth.ether_shost));
374
375                 sendto(rif->fd.fd, &reqpkt, sizeof(reqpkt), 0,
376                         (struct sockaddr *) &rif->sll, sizeof(rif->sll));
377         }
378 }
379
380 static void recv_arp_request(struct relayd_interface *rif, struct arp_packet *pkt)
381 {
382         struct relayd_host *host;
383
384         DPRINTF(2, "%s: ARP who-has "IP_FMT", tell "IP_FMT" ("MAC_FMT")\n",
385                 rif->ifname,
386                 IP_BUF(pkt->arp.arp_tpa),
387                 IP_BUF(pkt->arp.arp_spa),
388                 MAC_BUF(pkt->eth.ether_shost));
389
390         if (!memcmp(pkt->arp.arp_spa, "\x00\x00\x00\x00", 4))
391                 return;
392
393         refresh_host(rif, pkt->eth.ether_shost, pkt->arp.arp_spa);
394
395         host = find_host_by_ipaddr(NULL, pkt->arp.arp_tpa);
396
397         /*
398          * If a host is being pinged because of a timeout, do not use the cached
399          * entry here. That way we can avoid giving out stale data in case the node
400          * has moved. We shouldn't relay requests here either, as we might miss our
401          * chance to create a host route.
402          */
403         if (host && host->cleanup_pending)
404                 return;
405
406         relay_arp_request(rif, pkt);
407 }
408
409
410 static void recv_arp_reply(struct relayd_interface *rif, struct arp_packet *pkt)
411 {
412         struct relayd_host *host;
413
414         DPRINTF(2, "%s: received ARP reply for "IP_FMT" from "MAC_FMT", deliver to "IP_FMT"\n",
415                 rif->ifname,
416                 IP_BUF(pkt->arp.arp_spa),
417                 MAC_BUF(pkt->eth.ether_shost),
418                 IP_BUF(pkt->arp.arp_tpa));
419
420         refresh_host(rif, pkt->arp.arp_sha, pkt->arp.arp_spa);
421
422         if (!memcmp(pkt->arp.arp_tpa, rif->src_ip, 4))
423                 return;
424
425         host = find_host_by_ipaddr(NULL, pkt->arp.arp_tpa);
426         if (!host)
427                 return;
428
429         send_arp_reply(host->rif, pkt->arp.arp_spa, host->lladdr, host->ipaddr);
430 }
431
432 static void recv_packet(struct uloop_fd *fd, unsigned int events)
433 {
434         struct relayd_interface *rif = container_of(fd, struct relayd_interface, fd);
435         struct arp_packet *pkt;
436         static char pktbuf[4096];
437         int pktlen;
438
439         do {
440                 if (rif->fd.error)
441                         uloop_end();
442
443                 pktlen = recv(rif->fd.fd, pktbuf, sizeof(pktbuf), 0);
444                 if (pktlen < 0) {
445                         if (errno == EINTR)
446                                 continue;
447
448                         break;
449                 }
450
451                 if (!pktlen)
452                         break;
453
454                 pkt = (void *)pktbuf;
455                 if (pkt->arp.arp_op == htons(ARPOP_REPLY))
456                         recv_arp_reply(rif, pkt);
457                 else if (pkt->arp.arp_op == htons(ARPOP_REQUEST))
458                         recv_arp_request(rif, pkt);
459                 else
460                         DPRINTF(1, "received unknown packet type: %04x\n", ntohs(pkt->arp.arp_op));
461
462         } while (1);
463 }
464
465 static void forward_bcast_packet(struct relayd_interface *from_rif, void *packet, int len)
466 {
467         struct relayd_interface *rif;
468         struct ether_header *eth = packet;
469
470         list_for_each_entry(rif, &interfaces, list) {
471                 if (rif == from_rif)
472                         continue;
473
474                 DPRINTF(3, "%s: forwarding broadcast packet to %s\n", from_rif->ifname, rif->ifname);
475                 memcpy(eth->ether_shost, rif->sll.sll_addr, ETH_ALEN);
476                 send(rif->bcast_fd.fd, packet, len, 0);
477         }
478 }
479
480 static uint16_t
481 chksum(uint16_t sum, const uint8_t *data, uint16_t len)
482 {
483         const uint8_t *last;
484         uint16_t t;
485
486         last = data + len - 1;
487
488         while(data < last) {
489                 t = (data[0] << 8) + data[1];
490                 sum += t;
491                 if(sum < t)
492                         sum++;
493                 data += 2;
494         }
495
496         if(data == last) {
497                 t = (data[0] << 8) + 0;
498                 sum += t;
499                 if(sum < t)
500                         sum++;
501         }
502
503         return sum;
504 }
505
506 static bool forward_dhcp_packet(struct relayd_interface *rif, void *data, int len)
507 {
508         struct ip_packet *pkt = data;
509         struct udphdr *udp;
510         struct dhcp_header *dhcp;
511         int udplen;
512         uint16_t sum;
513
514         if (pkt->eth.ether_type != htons(ETH_P_IP))
515                 return false;
516
517         if (pkt->iph.version != 4)
518                 return false;
519
520         if (pkt->iph.protocol != IPPROTO_UDP)
521                 return false;
522
523         udp = (void *) ((char *) &pkt->iph + (pkt->iph.ihl << 2));
524         dhcp = (void *) (udp + 1);
525
526         udplen = ntohs(udp->len);
527         if (udplen > len - ((char *) udp - (char *) data))
528                 return false;
529
530         if (udp->dest != htons(67) && udp->source != htons(67))
531                 return false;
532
533         if (dhcp->op != 1 && dhcp->op != 2)
534                 return false;
535
536         if (!forward_dhcp)
537                 return true;
538
539         if (dhcp->op == 2)
540                 refresh_host(rif, pkt->eth.ether_shost, (void *) &pkt->iph.saddr);
541
542         DPRINTF(2, "%s: handling DHCP %s\n", rif->ifname, (dhcp->op == 1 ? "request" : "response"));
543
544         dhcp->flags |= htons(DHCP_FLAG_BROADCAST);
545
546         udp->check = 0;
547         sum = udplen + IPPROTO_UDP;
548         sum = chksum(sum, (void *) &pkt->iph.saddr, 8);
549         sum = chksum(sum, (void *) udp, udplen);
550         if (sum == 0)
551                 sum = 0xffff;
552
553         udp->check = htons(~sum);
554
555         forward_bcast_packet(rif, data, len);
556
557         return true;
558 }
559
560 static void recv_bcast_packet(struct uloop_fd *fd, unsigned int events)
561 {
562         struct relayd_interface *rif = container_of(fd, struct relayd_interface, bcast_fd);
563         static char pktbuf[4096];
564         int pktlen;
565
566         do {
567                 if (rif->fd.error)
568                         uloop_end();
569
570                 pktlen = recv(rif->bcast_fd.fd, pktbuf, sizeof(pktbuf), 0);
571                 if (pktlen < 0) {
572                         if (errno == EINTR)
573                                 continue;
574
575                         break;
576                 }
577
578                 if (!pktlen)
579                         break;
580
581                 if (!forward_bcast && !forward_dhcp)
582                         continue;
583
584                 if (forward_dhcp_packet(rif, pktbuf, pktlen))
585                         continue;
586
587                 if (forward_bcast)
588                         forward_bcast_packet(rif, pktbuf, pktlen);
589         } while (1);
590 }
591
592
593 static int init_interface(struct relayd_interface *rif)
594 {
595         struct sockaddr_ll *sll = &rif->sll;
596         struct sockaddr_in *sin;
597         struct ifreq ifr;
598         int fd = rif->fd.fd;
599 #ifdef PACKET_RECV_TYPE
600         unsigned int pkt_type;
601 #endif
602
603         fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
604         if (fd < 0)
605                 return -1;
606
607         rif->fd.fd = fd;
608
609         memset(&ifr, 0, sizeof(ifr));
610         strcpy(ifr.ifr_name, rif->ifname);
611
612         if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
613                 perror("ioctl(SIOCGIFHWADDR)");
614                 return -1;
615         }
616
617         memcpy(sll->sll_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
618         sll->sll_family = AF_PACKET;
619         sll->sll_protocol = htons(ETH_P_ARP);
620         sll->sll_pkttype = PACKET_BROADCAST;
621         sll->sll_hatype = ARPHRD_ETHER;
622         sll->sll_halen = ETH_ALEN;
623
624         if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
625                 perror("ioctl(SIOCGIFINDEX)");
626                 return -1;
627         }
628
629         sll->sll_ifindex = ifr.ifr_ifindex;
630
631         if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) {
632                 memcpy(rif->src_ip, DUMMY_IP, sizeof(rif->src_ip));
633         } else {
634                 sin = (struct sockaddr_in *) &ifr.ifr_addr;
635                 memcpy(rif->src_ip, &sin->sin_addr.s_addr, sizeof(rif->src_ip));
636         }
637
638         if (bind(fd, (struct sockaddr *)sll, sizeof(struct sockaddr_ll)) < 0) {
639                 perror("bind(ETH_P_ARP)");
640                 return -1;
641         }
642
643         rif->fd.cb = recv_packet;
644         uloop_fd_add(&rif->fd, ULOOP_READ | ULOOP_EDGE_TRIGGER);
645
646         if (!forward_bcast && !forward_dhcp)
647                 return 0;
648
649         fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
650         if (fd < 0)
651                 return 0;
652
653         rif->bcast_fd.fd = fd;
654         rif->bcast_fd.cb = recv_bcast_packet;
655
656         memcpy(&rif->bcast_sll, &rif->sll, sizeof(rif->bcast_sll));
657         sll = &rif->bcast_sll;
658         sll->sll_protocol = htons(ETH_P_IP);
659
660         if (bind(fd, (struct sockaddr *)sll, sizeof(struct sockaddr_ll)) < 0) {
661                 perror("bind(ETH_P_IP)");
662                 return 0;
663         }
664
665 #ifdef PACKET_RECV_TYPE
666         pkt_type = (1 << PACKET_BROADCAST);
667         setsockopt(fd, SOL_PACKET, PACKET_RECV_TYPE, &pkt_type, sizeof(pkt_type));
668 #endif
669
670         uloop_fd_add(&rif->bcast_fd, ULOOP_READ | ULOOP_EDGE_TRIGGER);
671         return 0;
672 }
673
674 static int init_interfaces(void)
675 {
676         struct relayd_interface *rif;
677         int ret;
678
679         list_for_each_entry(rif, &interfaces, list) {
680                 ret = init_interface(rif);
681                 if (ret < 0)
682                         return ret;
683         }
684
685         return 0;
686 }
687
688 static void del_interface(struct relayd_interface *rif)
689 {
690         struct relayd_host *host, *htmp;
691
692         list_for_each_entry_safe(host, htmp, &rif->hosts, list) {
693                 del_host(host);
694         }
695         free(rif);
696 }
697
698 static void cleanup_interfaces(void)
699 {
700         struct relayd_interface *rif, *rtmp;
701
702         list_for_each_entry_safe(rif, rtmp, &interfaces, list) {
703                 del_interface(rif);
704         }
705 }
706
707 static int alloc_interface(const char *ifname, bool managed)
708 {
709         struct relayd_interface *rif;
710
711         if (strlen(ifname) >= IFNAMSIZ)
712                 return -1;
713
714         rif = calloc(1, sizeof(*rif));
715         if (!rif)
716                 return -1;
717
718         INIT_LIST_HEAD(&rif->list);
719         INIT_LIST_HEAD(&rif->hosts);
720         strcpy(rif->ifname, ifname);
721         list_add(&rif->list, &interfaces);
722         rif->managed = managed;
723
724         return 0;
725 }
726
727 #ifndef NDA_RTA
728 #define NDA_RTA(r) \
729     ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ndmsg))))
730 #endif
731
732 static void rtnl_parse_newneigh(struct nlmsghdr *h)
733 {
734         struct relayd_interface *rif = NULL;
735         struct ndmsg *r = NLMSG_DATA(h);
736         const uint8_t *lladdr = NULL;
737         const uint8_t *ipaddr = NULL;
738         struct rtattr *rta;
739         int len;
740
741         if (r->ndm_family != AF_INET)
742                 return;
743
744         list_for_each_entry(rif, &interfaces, list) {
745                 if (rif->sll.sll_ifindex == r->ndm_ifindex)
746                         goto found_interface;
747         }
748         return;
749
750 found_interface:
751         len = h->nlmsg_len - NLMSG_LENGTH(sizeof(*r));
752         for (rta = NDA_RTA(r); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
753                 switch(rta->rta_type) {
754                 case NDA_LLADDR:
755                         lladdr = RTA_DATA(rta);
756                         break;
757                 case NDA_DST:
758                         ipaddr = RTA_DATA(rta);
759                         break;
760                 default:
761                         break;
762                 }
763         }
764
765         if (!lladdr || !ipaddr || (r->ndm_state & (NUD_INCOMPLETE|NUD_FAILED)))
766                 return;
767
768         if (!memcmp(lladdr, "\x00\x00\x00\x00\x00\x00", ETH_ALEN))
769                 return;
770
771         DPRINTF(1, "%s: Found ARP cache entry for host "IP_FMT" ("MAC_FMT")\n",
772                 rif->ifname, IP_BUF(ipaddr), MAC_BUF(lladdr));
773         refresh_host(rif, lladdr, ipaddr);
774 }
775
776 static void rtnl_parse_packet(void *data, int len)
777 {
778         struct nlmsghdr *h;
779
780         for (h = data; NLMSG_OK(h, len); h = NLMSG_NEXT(h, len)) {
781                 if (h->nlmsg_type == NLMSG_DONE ||
782                     h->nlmsg_type == NLMSG_ERROR)
783                         return;
784
785                 if (h->nlmsg_seq != rtnl_dump_seq)
786                         continue;
787
788                 if (h->nlmsg_type == RTM_NEWNEIGH)
789                         rtnl_parse_newneigh(h);
790         }
791 }
792
793 static void rtnl_cb(struct uloop_fd *fd, unsigned int events)
794 {
795         struct sockaddr_nl nladdr;
796         static uint8_t buf[16384];
797         struct iovec iov = {
798                 .iov_base = buf,
799                 .iov_len = sizeof(buf),
800         };
801         struct msghdr msg = {
802                 .msg_name = &nladdr,
803                 .msg_namelen = sizeof(nladdr),
804                 .msg_iov = &iov,
805                 .msg_iovlen = 1,
806         };
807
808         do {
809                 int len;
810
811                 len = recvmsg(rtnl_sock.fd, &msg, 0);
812                 if (len < 0) {
813                         if (errno == EINTR)
814                                 continue;
815
816                         return;
817                 }
818
819                 if (!len)
820                         break;
821
822                 if (nladdr.nl_pid != 0)
823                         continue;
824
825                 rtnl_parse_packet(buf, len);
826         } while (1);
827 }
828
829 static int rtnl_init(void)
830 {
831         struct sockaddr_nl snl_local;
832         static struct {
833                 struct nlmsghdr nlh;
834                 struct rtgenmsg g;
835         } req = {
836                 .nlh = {
837                         .nlmsg_len = sizeof(req),
838                         .nlmsg_type = RTM_GETNEIGH,
839                         .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,
840                         .nlmsg_pid = 0,
841                 },
842                 .g.rtgen_family = AF_INET,
843         };
844
845         rtnl_sock.fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
846         if (rtnl_sock.fd < 0) {
847                 perror("socket(AF_NETLINK)");
848                 return -1;
849         }
850
851         snl_local.nl_family = AF_NETLINK;
852
853         if (bind(rtnl_sock.fd, (struct sockaddr *) &snl_local, sizeof(struct sockaddr_nl)) < 0) {
854                 perror("bind");
855                 close(rtnl_sock.fd);
856                 return -1;
857         }
858
859         rtnl_sock.cb = rtnl_cb;
860         uloop_fd_add(&rtnl_sock, ULOOP_READ | ULOOP_EDGE_TRIGGER);
861
862         rtnl_seq = time(NULL);
863         rtnl_dump_seq = rtnl_seq;
864         req.nlh.nlmsg_seq = rtnl_seq;
865         send(rtnl_sock.fd, &req, sizeof(req), 0);
866
867         return 0;
868 }
869
870 static void die(int signo)
871 {
872         /*
873          * When we hit SIGTERM, clean up interfaces directly, so that we
874          * won't leave our routing in an invalid state.
875          */
876         cleanup_interfaces();
877         exit(1);
878 }
879
880 static int usage(const char *progname)
881 {
882         fprintf(stderr, "Usage: %s <options>\n"
883                         "\n"
884                         "Options:\n"
885                         "       -d              Enable debug messages\n"
886                         "       -i <ifname>     Add an interface for relaying\n"
887                         "       -I <ifname>     Same as -i, except with ARP cache and host route management\n"
888                         "                       You need to specify at least two interfaces\n"
889                         "       -t <timeout>    Host entry expiry timeout\n"
890                         "       -B              Enable broadcast forwarding\n"
891                         "       -D              Enable DHCP forwarding\n"
892                         "\n",
893                 progname);
894         return -1;
895 }
896
897 int main(int argc, char **argv)
898 {
899         bool managed;
900         int ifnum = 0;
901         int ch;
902
903         debug = 0;
904         inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
905         if (inet_sock < 0) {
906                 perror("socket(AF_INET)");
907                 return 1;
908         }
909
910         host_timeout = 60;
911         forward_bcast = 0;
912         uloop_init();
913
914         while ((ch = getopt(argc, argv, "I:i:t:BDd")) != -1) {
915                 switch(ch) {
916                 case 'I':
917                         managed = true;
918                         /* fall through */
919                 case 'i':
920                         ifnum++;
921                         if (alloc_interface(optarg, managed) < 0)
922                                 return 1;
923
924                         managed = false;
925                         break;
926                 case 't':
927                         host_timeout = atoi(optarg);
928                         if (host_timeout <= 0)
929                                 return usage(argv[0]);
930                         break;
931                 case 'd':
932                         debug++;
933                         break;
934                 case 'B':
935                         forward_bcast = 1;
936                         break;
937                 case 'D':
938                         forward_dhcp = 1;
939                         break;
940                 case '?':
941                 default:
942                         return usage(argv[0]);
943                 }
944         }
945
946         if (list_empty(&interfaces))
947                 return usage(argv[0]);
948
949         if (ifnum < 2) {
950                 fprintf(stderr, "ERROR: Need at least 2 interfaces for relaying\n");
951                 return -1;
952         }
953
954         argc -= optind;
955         argv += optind;
956
957         signal(SIGTERM, die);
958         signal(SIGHUP, die);
959         signal(SIGUSR1, die);
960         signal(SIGUSR2, die);
961
962         if (init_interfaces() < 0)
963                 return 1;
964
965         if (rtnl_init() < 0)
966                 return 1;
967
968         uloop_run();
969         uloop_done();
970
971         cleanup_interfaces();
972         uloop_fd_delete(&rtnl_sock);
973         close(rtnl_sock.fd);
974         close(inet_sock);
975
976         return 0;
977 }