81cc84db76e3ad224de63c47ba54aabf575e0efd
[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 #include <sys/socket.h>
20
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <stddef.h>
25 #include <stdlib.h>
26 #include <stdint.h>
27 #include <stdbool.h>
28 #include <errno.h>
29 #include <signal.h>
30 #include <string.h>
31
32 #include "relayd.h"
33
34 LIST_HEAD(interfaces);
35 int debug;
36
37 static int host_timeout;
38 static int inet_sock;
39 static int forward_bcast;
40 static int forward_dhcp;
41
42 static struct relayd_host *find_host_by_ipaddr(struct relayd_interface *rif, const uint8_t *ipaddr)
43 {
44         struct relayd_host *host;
45
46         if (!rif) {
47                 list_for_each_entry(rif, &interfaces, list) {
48                         host = find_host_by_ipaddr(rif, ipaddr);
49                         if (!host)
50                                 continue;
51
52                         return host;
53                 }
54                 return NULL;
55         }
56
57         list_for_each_entry(host, &rif->hosts, list) {
58                 if (memcmp(ipaddr, host->ipaddr, sizeof(host->ipaddr)) != 0)
59                         continue;
60
61                 return host;
62         }
63         return NULL;
64 }
65
66 static void add_arp(struct relayd_host *host)
67 {
68         struct sockaddr_in *sin;
69         struct arpreq arp;
70
71         strncpy(arp.arp_dev, host->rif->ifname, sizeof(arp.arp_dev));
72         arp.arp_flags = ATF_COM;
73
74         arp.arp_ha.sa_family = ARPHRD_ETHER;
75         memcpy(arp.arp_ha.sa_data, host->lladdr, ETH_ALEN);
76
77         sin = (struct sockaddr_in *) &arp.arp_pa;
78         sin->sin_family = AF_INET;
79         memcpy(&sin->sin_addr, host->ipaddr, sizeof(host->ipaddr));
80
81         ioctl(inet_sock, SIOCSARP, &arp);
82 }
83
84 static void del_host(struct relayd_host *host)
85 {
86         DPRINTF(1, "%s: deleting host "IP_FMT" ("MAC_FMT")\n", host->rif->ifname,
87                 IP_BUF(host->ipaddr), MAC_BUF(host->lladdr));
88
89         if (host->rif->managed)
90                 relayd_del_route(host);
91         uloop_timeout_cancel(&host->timeout);
92         list_del(&host->list);
93         free(host);
94 }
95
96 static void fill_arp_request(struct arp_packet *pkt, struct relayd_interface *rif,
97                              uint8_t spa[4], uint8_t tpa[4])
98 {
99         memset(pkt, 0, sizeof(*pkt));
100
101         pkt->eth.ether_type = htons(ETHERTYPE_ARP);
102         memcpy(pkt->eth.ether_shost, rif->sll.sll_addr, ETH_ALEN);
103
104         memcpy(pkt->arp.arp_sha, rif->sll.sll_addr, ETH_ALEN);
105         memcpy(pkt->arp.arp_spa, spa, 4);
106         memcpy(pkt->arp.arp_tpa, tpa, 4);
107
108         pkt->arp.arp_hrd = htons(ARPHRD_ETHER);
109         pkt->arp.arp_pro = htons(ETH_P_IP);
110         pkt->arp.arp_hln = ETH_ALEN;
111         pkt->arp.arp_pln = 4;
112 }
113
114 static void send_arp_request(struct relayd_host *host)
115 {
116         struct relayd_interface *rif = host->rif;
117         struct arp_packet pkt;
118
119         fill_arp_request(&pkt, host->rif, host->rif->src_ip, host->ipaddr);
120
121         pkt.arp.arp_op = htons(ARPOP_REQUEST);
122         memcpy(pkt.arp.arp_spa, rif->src_ip, ETH_ALEN);
123         memset(pkt.arp.arp_tha, 0, ETH_ALEN);
124         memset(pkt.eth.ether_dhost, 0xff, ETH_ALEN);
125
126         DPRINTF(2, "%s: sending ARP who-has "IP_FMT", tell "IP_FMT" ("MAC_FMT")\n",
127                 rif->ifname, IP_BUF(pkt.arp.arp_tpa),
128                 IP_BUF(pkt.arp.arp_spa), MAC_BUF(pkt.eth.ether_shost));
129
130         sendto(rif->fd.fd, &pkt, sizeof(pkt), 0,
131                 (struct sockaddr *) &rif->sll, sizeof(rif->sll));
132 }
133
134 static void send_arp_reply(struct relayd_interface *rif, uint8_t spa[4],
135                            uint8_t tha[ETH_ALEN], uint8_t tpa[4])
136 {
137         struct arp_packet pkt;
138
139         fill_arp_request(&pkt, rif, spa, tpa);
140
141         pkt.arp.arp_op = htons(ARPOP_REPLY);
142         memcpy(pkt.eth.ether_dhost, tha, ETH_ALEN);
143         memcpy(pkt.arp.arp_tha, tha, ETH_ALEN);
144
145         DPRINTF(2, "%s: sending ARP reply to "IP_FMT", "IP_FMT" is at ("MAC_FMT")\n",
146                 rif->ifname, IP_BUF(pkt.arp.arp_tpa),
147                 IP_BUF(pkt.arp.arp_spa), MAC_BUF(pkt.eth.ether_shost));
148
149         sendto(rif->fd.fd, &pkt, sizeof(pkt), 0,
150                 (struct sockaddr *) &rif->sll, sizeof(rif->sll));
151 }
152
153 static void host_entry_timeout(struct uloop_timeout *timeout)
154 {
155         struct relayd_host *host = container_of(timeout, struct relayd_host, timeout);
156
157         /*
158          * When a host is behind a managed interface, we must not expire its host
159          * entry prematurely, as this will cause routes to the node to expire,
160          * leading to loss of connectivity from the other side.
161          * When the timeout is reached, try pinging the host a few times before
162          * giving up on it.
163          */
164         if (host->rif->managed && host->cleanup_pending < 2) {
165                 send_arp_request(host);
166                 host->cleanup_pending++;
167                 uloop_timeout_set(&host->timeout, 1000);
168                 return;
169         }
170         del_host(host);
171 }
172
173 static struct relayd_host *add_host(struct relayd_interface *rif, const uint8_t *lladdr, const uint8_t *ipaddr)
174 {
175         struct relayd_host *host;
176
177         DPRINTF(1, "%s: adding host "IP_FMT" ("MAC_FMT")\n", rif->ifname,
178                         IP_BUF(ipaddr), MAC_BUF(lladdr));
179
180         host = calloc(1, sizeof(*host));
181         host->rif = rif;
182         memcpy(host->ipaddr, ipaddr, sizeof(host->ipaddr));
183         memcpy(host->lladdr, lladdr, sizeof(host->lladdr));
184         list_add(&host->list, &rif->hosts);
185         host->timeout.cb = host_entry_timeout;
186         uloop_timeout_set(&host->timeout, host_timeout * 1000);
187
188         add_arp(host);
189         if (rif->managed)
190                 relayd_add_route(host);
191
192         return host;
193 }
194
195 struct relayd_host *relayd_refresh_host(struct relayd_interface *rif, const uint8_t *lladdr, const uint8_t *ipaddr)
196 {
197         struct relayd_host *host;
198
199         host = find_host_by_ipaddr(rif, ipaddr);
200         if (!host) {
201                 host = find_host_by_ipaddr(NULL, ipaddr);
202
203                 /* 
204                  * When we suddenly see the host appearing on a different interface,
205                  * reduce the timeout to make the old entry expire faster, in case the
206                  * host has moved.
207                  * If the old entry is behind a managed interface, it will be pinged
208                  * before we expire it
209                  */
210                 if (host && !host->cleanup_pending)
211                         uloop_timeout_set(&host->timeout, 1);
212
213                 host = add_host(rif, lladdr, ipaddr);
214         } else {
215                 host->cleanup_pending = false;
216                 uloop_timeout_set(&host->timeout, host_timeout * 1000);
217         }
218
219         return host;
220 }
221
222 static void relay_arp_request(struct relayd_interface *from_rif, struct arp_packet *pkt)
223 {
224         struct relayd_interface *rif;
225         struct arp_packet reqpkt;
226
227         memcpy(&reqpkt, pkt, sizeof(reqpkt));
228         list_for_each_entry(rif, &interfaces, list) {
229                 if (rif == from_rif)
230                         continue;
231
232                 memcpy(reqpkt.eth.ether_shost, rif->sll.sll_addr, ETH_ALEN);
233                 memcpy(reqpkt.arp.arp_sha, rif->sll.sll_addr, ETH_ALEN);
234
235                 DPRINTF(2, "%s: sending ARP who-has "IP_FMT", tell "IP_FMT" ("MAC_FMT")\n",
236                         rif->ifname, IP_BUF(reqpkt.arp.arp_tpa),
237                         IP_BUF(reqpkt.arp.arp_spa), MAC_BUF(reqpkt.eth.ether_shost));
238
239                 sendto(rif->fd.fd, &reqpkt, sizeof(reqpkt), 0,
240                         (struct sockaddr *) &rif->sll, sizeof(rif->sll));
241         }
242 }
243
244 static void recv_arp_request(struct relayd_interface *rif, struct arp_packet *pkt)
245 {
246         struct relayd_host *host;
247
248         DPRINTF(2, "%s: ARP who-has "IP_FMT", tell "IP_FMT" ("MAC_FMT")\n",
249                 rif->ifname,
250                 IP_BUF(pkt->arp.arp_tpa),
251                 IP_BUF(pkt->arp.arp_spa),
252                 MAC_BUF(pkt->eth.ether_shost));
253
254         if (!memcmp(pkt->arp.arp_spa, "\x00\x00\x00\x00", 4))
255                 return;
256
257         relayd_refresh_host(rif, pkt->eth.ether_shost, pkt->arp.arp_spa);
258
259         host = find_host_by_ipaddr(NULL, pkt->arp.arp_tpa);
260
261         /*
262          * If a host is being pinged because of a timeout, do not use the cached
263          * entry here. That way we can avoid giving out stale data in case the node
264          * has moved. We shouldn't relay requests here either, as we might miss our
265          * chance to create a host route.
266          */
267         if (host && host->cleanup_pending)
268                 return;
269
270         relay_arp_request(rif, pkt);
271 }
272
273
274 static void recv_arp_reply(struct relayd_interface *rif, struct arp_packet *pkt)
275 {
276         struct relayd_host *host;
277
278         DPRINTF(2, "%s: received ARP reply for "IP_FMT" from "MAC_FMT", deliver to "IP_FMT"\n",
279                 rif->ifname,
280                 IP_BUF(pkt->arp.arp_spa),
281                 MAC_BUF(pkt->eth.ether_shost),
282                 IP_BUF(pkt->arp.arp_tpa));
283
284         relayd_refresh_host(rif, pkt->arp.arp_sha, pkt->arp.arp_spa);
285
286         if (!memcmp(pkt->arp.arp_tpa, rif->src_ip, 4))
287                 return;
288
289         host = find_host_by_ipaddr(NULL, pkt->arp.arp_tpa);
290         if (!host)
291                 return;
292
293         if (host->rif == rif)
294                 return;
295
296         send_arp_reply(host->rif, pkt->arp.arp_spa, host->lladdr, host->ipaddr);
297 }
298
299 static void recv_packet(struct uloop_fd *fd, unsigned int events)
300 {
301         struct relayd_interface *rif = container_of(fd, struct relayd_interface, fd);
302         struct arp_packet *pkt;
303         static char pktbuf[4096];
304         int pktlen;
305
306         do {
307                 if (rif->fd.error)
308                         uloop_end();
309
310                 pktlen = recv(rif->fd.fd, pktbuf, sizeof(pktbuf), 0);
311                 if (pktlen < 0) {
312                         if (errno == EINTR)
313                                 continue;
314
315                         break;
316                 }
317
318                 if (!pktlen)
319                         break;
320
321                 pkt = (void *)pktbuf;
322                 if (pkt->arp.arp_op == htons(ARPOP_REPLY))
323                         recv_arp_reply(rif, pkt);
324                 else if (pkt->arp.arp_op == htons(ARPOP_REQUEST))
325                         recv_arp_request(rif, pkt);
326                 else
327                         DPRINTF(1, "received unknown packet type: %04x\n", ntohs(pkt->arp.arp_op));
328
329         } while (1);
330 }
331
332 static void forward_bcast_packet(struct relayd_interface *from_rif, void *packet, int len)
333 {
334         struct relayd_interface *rif;
335         struct ether_header *eth = packet;
336
337         list_for_each_entry(rif, &interfaces, list) {
338                 if (rif == from_rif)
339                         continue;
340
341                 DPRINTF(3, "%s: forwarding broadcast packet to %s\n", from_rif->ifname, rif->ifname);
342                 memcpy(eth->ether_shost, rif->sll.sll_addr, ETH_ALEN);
343                 send(rif->bcast_fd.fd, packet, len, 0);
344         }
345 }
346
347 static uint16_t
348 chksum(uint16_t sum, const uint8_t *data, uint16_t len)
349 {
350         const uint8_t *last;
351         uint16_t t;
352
353         last = data + len - 1;
354
355         while(data < last) {
356                 t = (data[0] << 8) + data[1];
357                 sum += t;
358                 if(sum < t)
359                         sum++;
360                 data += 2;
361         }
362
363         if(data == last) {
364                 t = (data[0] << 8) + 0;
365                 sum += t;
366                 if(sum < t)
367                         sum++;
368         }
369
370         return sum;
371 }
372
373 static bool forward_dhcp_packet(struct relayd_interface *rif, void *data, int len)
374 {
375         struct ip_packet *pkt = data;
376         struct udphdr *udp;
377         struct dhcp_header *dhcp;
378         int udplen;
379         uint16_t sum;
380
381         if (pkt->eth.ether_type != htons(ETH_P_IP))
382                 return false;
383
384         if (pkt->iph.version != 4)
385                 return false;
386
387         if (pkt->iph.protocol != IPPROTO_UDP)
388                 return false;
389
390         udp = (void *) ((char *) &pkt->iph + (pkt->iph.ihl << 2));
391         dhcp = (void *) (udp + 1);
392
393         udplen = ntohs(udp->len);
394         if (udplen > len - ((char *) udp - (char *) data))
395                 return false;
396
397         if (udp->dest != htons(67) && udp->source != htons(67))
398                 return false;
399
400         if (dhcp->op != 1 && dhcp->op != 2)
401                 return false;
402
403         if (!forward_dhcp)
404                 return true;
405
406         if (dhcp->op == 2)
407                 relayd_refresh_host(rif, pkt->eth.ether_shost, (void *) &pkt->iph.saddr);
408
409         DPRINTF(2, "%s: handling DHCP %s\n", rif->ifname, (dhcp->op == 1 ? "request" : "response"));
410
411         dhcp->flags |= htons(DHCP_FLAG_BROADCAST);
412
413         udp->check = 0;
414         sum = udplen + IPPROTO_UDP;
415         sum = chksum(sum, (void *) &pkt->iph.saddr, 8);
416         sum = chksum(sum, (void *) udp, udplen);
417         if (sum == 0)
418                 sum = 0xffff;
419
420         udp->check = htons(~sum);
421
422         forward_bcast_packet(rif, data, len);
423
424         return true;
425 }
426
427 static void recv_bcast_packet(struct uloop_fd *fd, unsigned int events)
428 {
429         struct relayd_interface *rif = container_of(fd, struct relayd_interface, bcast_fd);
430         static char pktbuf[4096];
431         int pktlen;
432
433         do {
434                 if (rif->fd.error)
435                         uloop_end();
436
437                 pktlen = recv(rif->bcast_fd.fd, pktbuf, sizeof(pktbuf), 0);
438                 if (pktlen < 0) {
439                         if (errno == EINTR)
440                                 continue;
441
442                         break;
443                 }
444
445                 if (!pktlen)
446                         break;
447
448                 if (!forward_bcast && !forward_dhcp)
449                         continue;
450
451                 if (forward_dhcp_packet(rif, pktbuf, pktlen))
452                         continue;
453
454                 if (forward_bcast)
455                         forward_bcast_packet(rif, pktbuf, pktlen);
456         } while (1);
457 }
458
459
460 static int init_interface(struct relayd_interface *rif)
461 {
462         struct sockaddr_ll *sll = &rif->sll;
463         struct sockaddr_in *sin;
464         struct ifreq ifr;
465         int fd = rif->fd.fd;
466 #ifdef PACKET_RECV_TYPE
467         unsigned int pkt_type;
468 #endif
469
470         fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ARP));
471         if (fd < 0)
472                 return -1;
473
474         rif->fd.fd = fd;
475
476         memset(&ifr, 0, sizeof(ifr));
477         strcpy(ifr.ifr_name, rif->ifname);
478
479         if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
480                 perror("ioctl(SIOCGIFHWADDR)");
481                 return -1;
482         }
483
484         memcpy(sll->sll_addr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
485         sll->sll_family = AF_PACKET;
486         sll->sll_protocol = htons(ETH_P_ARP);
487         sll->sll_pkttype = PACKET_BROADCAST;
488         sll->sll_hatype = ARPHRD_ETHER;
489         sll->sll_halen = ETH_ALEN;
490
491         if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
492                 perror("ioctl(SIOCGIFINDEX)");
493                 return -1;
494         }
495
496         sll->sll_ifindex = ifr.ifr_ifindex;
497
498         if (ioctl(fd, SIOCGIFADDR, &ifr) < 0) {
499                 memcpy(rif->src_ip, DUMMY_IP, sizeof(rif->src_ip));
500         } else {
501                 sin = (struct sockaddr_in *) &ifr.ifr_addr;
502                 memcpy(rif->src_ip, &sin->sin_addr.s_addr, sizeof(rif->src_ip));
503         }
504
505         if (bind(fd, (struct sockaddr *)sll, sizeof(struct sockaddr_ll)) < 0) {
506                 perror("bind(ETH_P_ARP)");
507                 return -1;
508         }
509
510         rif->fd.cb = recv_packet;
511         uloop_fd_add(&rif->fd, ULOOP_READ | ULOOP_EDGE_TRIGGER);
512
513         if (!forward_bcast && !forward_dhcp)
514                 return 0;
515
516         fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_IP));
517         if (fd < 0)
518                 return 0;
519
520         rif->bcast_fd.fd = fd;
521         rif->bcast_fd.cb = recv_bcast_packet;
522
523         memcpy(&rif->bcast_sll, &rif->sll, sizeof(rif->bcast_sll));
524         sll = &rif->bcast_sll;
525         sll->sll_protocol = htons(ETH_P_IP);
526
527         if (bind(fd, (struct sockaddr *)sll, sizeof(struct sockaddr_ll)) < 0) {
528                 perror("bind(ETH_P_IP)");
529                 return 0;
530         }
531
532 #ifdef PACKET_RECV_TYPE
533         pkt_type = (1 << PACKET_BROADCAST);
534         setsockopt(fd, SOL_PACKET, PACKET_RECV_TYPE, &pkt_type, sizeof(pkt_type));
535 #endif
536
537         uloop_fd_add(&rif->bcast_fd, ULOOP_READ | ULOOP_EDGE_TRIGGER);
538         return 0;
539 }
540
541 static int init_interfaces(void)
542 {
543         struct relayd_interface *rif;
544         int ret;
545
546         list_for_each_entry(rif, &interfaces, list) {
547                 ret = init_interface(rif);
548                 if (ret < 0)
549                         return ret;
550         }
551
552         return 0;
553 }
554
555 static void del_interface(struct relayd_interface *rif)
556 {
557         struct relayd_host *host, *htmp;
558
559         list_for_each_entry_safe(host, htmp, &rif->hosts, list) {
560                 del_host(host);
561         }
562         free(rif);
563 }
564
565 static void cleanup_interfaces(void)
566 {
567         struct relayd_interface *rif, *rtmp;
568
569         list_for_each_entry_safe(rif, rtmp, &interfaces, list) {
570                 del_interface(rif);
571         }
572 }
573
574 static int alloc_interface(const char *ifname, bool managed)
575 {
576         struct relayd_interface *rif;
577
578         if (strlen(ifname) >= IFNAMSIZ)
579                 return -1;
580
581         rif = calloc(1, sizeof(*rif));
582         if (!rif)
583                 return -1;
584
585         INIT_LIST_HEAD(&rif->list);
586         INIT_LIST_HEAD(&rif->hosts);
587         strcpy(rif->ifname, ifname);
588         list_add(&rif->list, &interfaces);
589         rif->managed = managed;
590
591         return 0;
592 }
593
594 static void die(int signo)
595 {
596         /*
597          * When we hit SIGTERM, clean up interfaces directly, so that we
598          * won't leave our routing in an invalid state.
599          */
600         cleanup_interfaces();
601         exit(1);
602 }
603
604 static int usage(const char *progname)
605 {
606         fprintf(stderr, "Usage: %s <options>\n"
607                         "\n"
608                         "Options:\n"
609                         "       -d              Enable debug messages\n"
610                         "       -i <ifname>     Add an interface for relaying\n"
611                         "       -I <ifname>     Same as -i, except with ARP cache and host route management\n"
612                         "                       You need to specify at least two interfaces\n"
613                         "       -t <timeout>    Host entry expiry timeout\n"
614                         "       -B              Enable broadcast forwarding\n"
615                         "       -D              Enable DHCP forwarding\n"
616                         "\n",
617                 progname);
618         return -1;
619 }
620
621 int main(int argc, char **argv)
622 {
623         bool managed;
624         int ifnum = 0;
625         int ch;
626
627         debug = 0;
628         inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
629         if (inet_sock < 0) {
630                 perror("socket(AF_INET)");
631                 return 1;
632         }
633
634         host_timeout = 60;
635         forward_bcast = 0;
636         uloop_init();
637
638         while ((ch = getopt(argc, argv, "I:i:t:BDd")) != -1) {
639                 switch(ch) {
640                 case 'I':
641                         managed = true;
642                         /* fall through */
643                 case 'i':
644                         ifnum++;
645                         if (alloc_interface(optarg, managed) < 0)
646                                 return 1;
647
648                         managed = false;
649                         break;
650                 case 't':
651                         host_timeout = atoi(optarg);
652                         if (host_timeout <= 0)
653                                 return usage(argv[0]);
654                         break;
655                 case 'd':
656                         debug++;
657                         break;
658                 case 'B':
659                         forward_bcast = 1;
660                         break;
661                 case 'D':
662                         forward_dhcp = 1;
663                         break;
664                 case '?':
665                 default:
666                         return usage(argv[0]);
667                 }
668         }
669
670         if (list_empty(&interfaces))
671                 return usage(argv[0]);
672
673         if (ifnum < 2) {
674                 fprintf(stderr, "ERROR: Need at least 2 interfaces for relaying\n");
675                 return -1;
676         }
677
678         argc -= optind;
679         argv += optind;
680
681         signal(SIGTERM, die);
682         signal(SIGHUP, die);
683         signal(SIGUSR1, die);
684         signal(SIGUSR2, die);
685
686         if (init_interfaces() < 0)
687                 return 1;
688
689         if (relayd_rtnl_init() < 0)
690                 return 1;
691
692         uloop_run();
693         uloop_done();
694
695         cleanup_interfaces();
696         relayd_rtnl_done();
697         close(inet_sock);
698
699         return 0;
700 }