Do not forward ARP responses to the interface that they came from
[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         if (host->rif == rif)
430                 return;
431
432         send_arp_reply(host->rif, pkt->arp.arp_spa, host->lladdr, host->ipaddr);
433 }
434
435 static void recv_packet(struct uloop_fd *fd, unsigned int events)
436 {
437         struct relayd_interface *rif = container_of(fd, struct relayd_interface, fd);
438         struct arp_packet *pkt;
439         static char pktbuf[4096];
440         int pktlen;
441
442         do {
443                 if (rif->fd.error)
444                         uloop_end();
445
446                 pktlen = recv(rif->fd.fd, pktbuf, sizeof(pktbuf), 0);
447                 if (pktlen < 0) {
448                         if (errno == EINTR)
449                                 continue;
450
451                         break;
452                 }
453
454                 if (!pktlen)
455                         break;
456
457                 pkt = (void *)pktbuf;
458                 if (pkt->arp.arp_op == htons(ARPOP_REPLY))
459                         recv_arp_reply(rif, pkt);
460                 else if (pkt->arp.arp_op == htons(ARPOP_REQUEST))
461                         recv_arp_request(rif, pkt);
462                 else
463                         DPRINTF(1, "received unknown packet type: %04x\n", ntohs(pkt->arp.arp_op));
464
465         } while (1);
466 }
467
468 static void forward_bcast_packet(struct relayd_interface *from_rif, void *packet, int len)
469 {
470         struct relayd_interface *rif;
471         struct ether_header *eth = packet;
472
473         list_for_each_entry(rif, &interfaces, list) {
474                 if (rif == from_rif)
475                         continue;
476
477                 DPRINTF(3, "%s: forwarding broadcast packet to %s\n", from_rif->ifname, rif->ifname);
478                 memcpy(eth->ether_shost, rif->sll.sll_addr, ETH_ALEN);
479                 send(rif->bcast_fd.fd, packet, len, 0);
480         }
481 }
482
483 static uint16_t
484 chksum(uint16_t sum, const uint8_t *data, uint16_t len)
485 {
486         const uint8_t *last;
487         uint16_t t;
488
489         last = data + len - 1;
490
491         while(data < last) {
492                 t = (data[0] << 8) + data[1];
493                 sum += t;
494                 if(sum < t)
495                         sum++;
496                 data += 2;
497         }
498
499         if(data == last) {
500                 t = (data[0] << 8) + 0;
501                 sum += t;
502                 if(sum < t)
503                         sum++;
504         }
505
506         return sum;
507 }
508
509 static bool forward_dhcp_packet(struct relayd_interface *rif, void *data, int len)
510 {
511         struct ip_packet *pkt = data;
512         struct udphdr *udp;
513         struct dhcp_header *dhcp;
514         int udplen;
515         uint16_t sum;
516
517         if (pkt->eth.ether_type != htons(ETH_P_IP))
518                 return false;
519
520         if (pkt->iph.version != 4)
521                 return false;
522
523         if (pkt->iph.protocol != IPPROTO_UDP)
524                 return false;
525
526         udp = (void *) ((char *) &pkt->iph + (pkt->iph.ihl << 2));
527         dhcp = (void *) (udp + 1);
528
529         udplen = ntohs(udp->len);
530         if (udplen > len - ((char *) udp - (char *) data))
531                 return false;
532
533         if (udp->dest != htons(67) && udp->source != htons(67))
534                 return false;
535
536         if (dhcp->op != 1 && dhcp->op != 2)
537                 return false;
538
539         if (!forward_dhcp)
540                 return true;
541
542         if (dhcp->op == 2)
543                 refresh_host(rif, pkt->eth.ether_shost, (void *) &pkt->iph.saddr);
544
545         DPRINTF(2, "%s: handling DHCP %s\n", rif->ifname, (dhcp->op == 1 ? "request" : "response"));
546
547         dhcp->flags |= htons(DHCP_FLAG_BROADCAST);
548
549         udp->check = 0;
550         sum = udplen + IPPROTO_UDP;
551         sum = chksum(sum, (void *) &pkt->iph.saddr, 8);
552         sum = chksum(sum, (void *) udp, udplen);
553         if (sum == 0)
554                 sum = 0xffff;
555
556         udp->check = htons(~sum);
557
558         forward_bcast_packet(rif, data, len);
559
560         return true;
561 }
562
563 static void recv_bcast_packet(struct uloop_fd *fd, unsigned int events)
564 {
565         struct relayd_interface *rif = container_of(fd, struct relayd_interface, bcast_fd);
566         static char pktbuf[4096];
567         int pktlen;
568
569         do {
570                 if (rif->fd.error)
571                         uloop_end();
572
573                 pktlen = recv(rif->bcast_fd.fd, pktbuf, sizeof(pktbuf), 0);
574                 if (pktlen < 0) {
575                         if (errno == EINTR)
576                                 continue;
577
578                         break;
579                 }
580
581                 if (!pktlen)
582                         break;
583
584                 if (!forward_bcast && !forward_dhcp)
585                         continue;
586
587                 if (forward_dhcp_packet(rif, pktbuf, pktlen))
588                         continue;
589
590                 if (forward_bcast)
591                         forward_bcast_packet(rif, pktbuf, pktlen);
592         } while (1);
593 }
594
595
596 static int init_interface(struct relayd_interface *rif)
597 {
598         struct sockaddr_ll *sll = &rif->sll;
599         struct sockaddr_in *sin;
600         struct ifreq ifr;
601         int fd = rif->fd.fd;
602 #ifdef PACKET_RECV_TYPE
603         unsigned int pkt_type;
604 #endif
605
606         fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
607         if (fd < 0)
608                 return -1;
609
610         rif->fd.fd = fd;
611
612         memset(&ifr, 0, sizeof(ifr));
613         strcpy(ifr.ifr_name, rif->ifname);
614
615         if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
616                 perror("ioctl(SIOCGIFHWADDR)");
617                 return -1;
618         }
619
620         memcpy(sll->sll_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
621         sll->sll_family = AF_PACKET;
622         sll->sll_protocol = htons(ETH_P_ARP);
623         sll->sll_pkttype = PACKET_BROADCAST;
624         sll->sll_hatype = ARPHRD_ETHER;
625         sll->sll_halen = ETH_ALEN;
626
627         if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
628                 perror("ioctl(SIOCGIFINDEX)");
629                 return -1;
630         }
631
632         sll->sll_ifindex = ifr.ifr_ifindex;
633
634         if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) {
635                 memcpy(rif->src_ip, DUMMY_IP, sizeof(rif->src_ip));
636         } else {
637                 sin = (struct sockaddr_in *) &ifr.ifr_addr;
638                 memcpy(rif->src_ip, &sin->sin_addr.s_addr, sizeof(rif->src_ip));
639         }
640
641         if (bind(fd, (struct sockaddr *)sll, sizeof(struct sockaddr_ll)) < 0) {
642                 perror("bind(ETH_P_ARP)");
643                 return -1;
644         }
645
646         rif->fd.cb = recv_packet;
647         uloop_fd_add(&rif->fd, ULOOP_READ | ULOOP_EDGE_TRIGGER);
648
649         if (!forward_bcast && !forward_dhcp)
650                 return 0;
651
652         fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
653         if (fd < 0)
654                 return 0;
655
656         rif->bcast_fd.fd = fd;
657         rif->bcast_fd.cb = recv_bcast_packet;
658
659         memcpy(&rif->bcast_sll, &rif->sll, sizeof(rif->bcast_sll));
660         sll = &rif->bcast_sll;
661         sll->sll_protocol = htons(ETH_P_IP);
662
663         if (bind(fd, (struct sockaddr *)sll, sizeof(struct sockaddr_ll)) < 0) {
664                 perror("bind(ETH_P_IP)");
665                 return 0;
666         }
667
668 #ifdef PACKET_RECV_TYPE
669         pkt_type = (1 << PACKET_BROADCAST);
670         setsockopt(fd, SOL_PACKET, PACKET_RECV_TYPE, &pkt_type, sizeof(pkt_type));
671 #endif
672
673         uloop_fd_add(&rif->bcast_fd, ULOOP_READ | ULOOP_EDGE_TRIGGER);
674         return 0;
675 }
676
677 static int init_interfaces(void)
678 {
679         struct relayd_interface *rif;
680         int ret;
681
682         list_for_each_entry(rif, &interfaces, list) {
683                 ret = init_interface(rif);
684                 if (ret < 0)
685                         return ret;
686         }
687
688         return 0;
689 }
690
691 static void del_interface(struct relayd_interface *rif)
692 {
693         struct relayd_host *host, *htmp;
694
695         list_for_each_entry_safe(host, htmp, &rif->hosts, list) {
696                 del_host(host);
697         }
698         free(rif);
699 }
700
701 static void cleanup_interfaces(void)
702 {
703         struct relayd_interface *rif, *rtmp;
704
705         list_for_each_entry_safe(rif, rtmp, &interfaces, list) {
706                 del_interface(rif);
707         }
708 }
709
710 static int alloc_interface(const char *ifname, bool managed)
711 {
712         struct relayd_interface *rif;
713
714         if (strlen(ifname) >= IFNAMSIZ)
715                 return -1;
716
717         rif = calloc(1, sizeof(*rif));
718         if (!rif)
719                 return -1;
720
721         INIT_LIST_HEAD(&rif->list);
722         INIT_LIST_HEAD(&rif->hosts);
723         strcpy(rif->ifname, ifname);
724         list_add(&rif->list, &interfaces);
725         rif->managed = managed;
726
727         return 0;
728 }
729
730 #ifndef NDA_RTA
731 #define NDA_RTA(r) \
732     ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ndmsg))))
733 #endif
734
735 static void rtnl_parse_newneigh(struct nlmsghdr *h)
736 {
737         struct relayd_interface *rif = NULL;
738         struct ndmsg *r = NLMSG_DATA(h);
739         const uint8_t *lladdr = NULL;
740         const uint8_t *ipaddr = NULL;
741         struct rtattr *rta;
742         int len;
743
744         if (r->ndm_family != AF_INET)
745                 return;
746
747         list_for_each_entry(rif, &interfaces, list) {
748                 if (rif->sll.sll_ifindex == r->ndm_ifindex)
749                         goto found_interface;
750         }
751         return;
752
753 found_interface:
754         len = h->nlmsg_len - NLMSG_LENGTH(sizeof(*r));
755         for (rta = NDA_RTA(r); RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
756                 switch(rta->rta_type) {
757                 case NDA_LLADDR:
758                         lladdr = RTA_DATA(rta);
759                         break;
760                 case NDA_DST:
761                         ipaddr = RTA_DATA(rta);
762                         break;
763                 default:
764                         break;
765                 }
766         }
767
768         if (!lladdr || !ipaddr || (r->ndm_state & (NUD_INCOMPLETE|NUD_FAILED)))
769                 return;
770
771         if (!memcmp(lladdr, "\x00\x00\x00\x00\x00\x00", ETH_ALEN))
772                 return;
773
774         DPRINTF(1, "%s: Found ARP cache entry for host "IP_FMT" ("MAC_FMT")\n",
775                 rif->ifname, IP_BUF(ipaddr), MAC_BUF(lladdr));
776         refresh_host(rif, lladdr, ipaddr);
777 }
778
779 static void rtnl_parse_packet(void *data, int len)
780 {
781         struct nlmsghdr *h;
782
783         for (h = data; NLMSG_OK(h, len); h = NLMSG_NEXT(h, len)) {
784                 if (h->nlmsg_type == NLMSG_DONE ||
785                     h->nlmsg_type == NLMSG_ERROR)
786                         return;
787
788                 if (h->nlmsg_seq != rtnl_dump_seq)
789                         continue;
790
791                 if (h->nlmsg_type == RTM_NEWNEIGH)
792                         rtnl_parse_newneigh(h);
793         }
794 }
795
796 static void rtnl_cb(struct uloop_fd *fd, unsigned int events)
797 {
798         struct sockaddr_nl nladdr;
799         static uint8_t buf[16384];
800         struct iovec iov = {
801                 .iov_base = buf,
802                 .iov_len = sizeof(buf),
803         };
804         struct msghdr msg = {
805                 .msg_name = &nladdr,
806                 .msg_namelen = sizeof(nladdr),
807                 .msg_iov = &iov,
808                 .msg_iovlen = 1,
809         };
810
811         do {
812                 int len;
813
814                 len = recvmsg(rtnl_sock.fd, &msg, 0);
815                 if (len < 0) {
816                         if (errno == EINTR)
817                                 continue;
818
819                         return;
820                 }
821
822                 if (!len)
823                         break;
824
825                 if (nladdr.nl_pid != 0)
826                         continue;
827
828                 rtnl_parse_packet(buf, len);
829         } while (1);
830 }
831
832 static int rtnl_init(void)
833 {
834         struct sockaddr_nl snl_local;
835         static struct {
836                 struct nlmsghdr nlh;
837                 struct rtgenmsg g;
838         } req = {
839                 .nlh = {
840                         .nlmsg_len = sizeof(req),
841                         .nlmsg_type = RTM_GETNEIGH,
842                         .nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST,
843                         .nlmsg_pid = 0,
844                 },
845                 .g.rtgen_family = AF_INET,
846         };
847
848         rtnl_sock.fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
849         if (rtnl_sock.fd < 0) {
850                 perror("socket(AF_NETLINK)");
851                 return -1;
852         }
853
854         snl_local.nl_family = AF_NETLINK;
855
856         if (bind(rtnl_sock.fd, (struct sockaddr *) &snl_local, sizeof(struct sockaddr_nl)) < 0) {
857                 perror("bind");
858                 close(rtnl_sock.fd);
859                 return -1;
860         }
861
862         rtnl_sock.cb = rtnl_cb;
863         uloop_fd_add(&rtnl_sock, ULOOP_READ | ULOOP_EDGE_TRIGGER);
864
865         rtnl_seq = time(NULL);
866         rtnl_dump_seq = rtnl_seq;
867         req.nlh.nlmsg_seq = rtnl_seq;
868         send(rtnl_sock.fd, &req, sizeof(req), 0);
869
870         return 0;
871 }
872
873 static void die(int signo)
874 {
875         /*
876          * When we hit SIGTERM, clean up interfaces directly, so that we
877          * won't leave our routing in an invalid state.
878          */
879         cleanup_interfaces();
880         exit(1);
881 }
882
883 static int usage(const char *progname)
884 {
885         fprintf(stderr, "Usage: %s <options>\n"
886                         "\n"
887                         "Options:\n"
888                         "       -d              Enable debug messages\n"
889                         "       -i <ifname>     Add an interface for relaying\n"
890                         "       -I <ifname>     Same as -i, except with ARP cache and host route management\n"
891                         "                       You need to specify at least two interfaces\n"
892                         "       -t <timeout>    Host entry expiry timeout\n"
893                         "       -B              Enable broadcast forwarding\n"
894                         "       -D              Enable DHCP forwarding\n"
895                         "\n",
896                 progname);
897         return -1;
898 }
899
900 int main(int argc, char **argv)
901 {
902         bool managed;
903         int ifnum = 0;
904         int ch;
905
906         debug = 0;
907         inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
908         if (inet_sock < 0) {
909                 perror("socket(AF_INET)");
910                 return 1;
911         }
912
913         host_timeout = 60;
914         forward_bcast = 0;
915         uloop_init();
916
917         while ((ch = getopt(argc, argv, "I:i:t:BDd")) != -1) {
918                 switch(ch) {
919                 case 'I':
920                         managed = true;
921                         /* fall through */
922                 case 'i':
923                         ifnum++;
924                         if (alloc_interface(optarg, managed) < 0)
925                                 return 1;
926
927                         managed = false;
928                         break;
929                 case 't':
930                         host_timeout = atoi(optarg);
931                         if (host_timeout <= 0)
932                                 return usage(argv[0]);
933                         break;
934                 case 'd':
935                         debug++;
936                         break;
937                 case 'B':
938                         forward_bcast = 1;
939                         break;
940                 case 'D':
941                         forward_dhcp = 1;
942                         break;
943                 case '?':
944                 default:
945                         return usage(argv[0]);
946                 }
947         }
948
949         if (list_empty(&interfaces))
950                 return usage(argv[0]);
951
952         if (ifnum < 2) {
953                 fprintf(stderr, "ERROR: Need at least 2 interfaces for relaying\n");
954                 return -1;
955         }
956
957         argc -= optind;
958         argv += optind;
959
960         signal(SIGTERM, die);
961         signal(SIGHUP, die);
962         signal(SIGUSR1, die);
963         signal(SIGUSR2, die);
964
965         if (init_interfaces() < 0)
966                 return 1;
967
968         if (rtnl_init() < 0)
969                 return 1;
970
971         uloop_run();
972         uloop_done();
973
974         cleanup_interfaces();
975         uloop_fd_delete(&rtnl_sock);
976         close(rtnl_sock.fd);
977         close(inet_sock);
978
979         return 0;
980 }