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