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