pax_global_header 0000666 0000000 0000000 00000000064 11073442770 0014517 g ustar 00root root 0000000 0000000 52 comment=123f9ffbf6fb0f9b1e21992d914187d5aed89727
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/ 0000775 0000000 0000000 00000000000 11073442770 0017764 5 ustar 00root root 0000000 0000000 babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/CHANGES 0000664 0000000 0000000 00000013402 11073442770 0020757 0 ustar 00root root 0000000 0000000 29 September 2008: babel 0.16
* Tweaked cost computation to be slightly slower.
* Implemented a local interface for GUIs.
* INCOMPATIBLE CHANGE: the -X command-line option is no more.
8 July 2008: babel 0.15
* Fixed a bug that could break link-quality estimation on yo-yo links.
* Protect against duplicate neighbour ids on the same interface.
* More tweaks to improve scaling with the number of kernel routes.
* Tweaked the default update interval.
1 July 2008: babel 0.14
* Use POSIX clocks if available to protect against clock stepping.
* Made babel use available internal routes straight away when the
set of redistributed routes changes.
* Lifted the arbitrary limit on the number of kernel routes.
* Changed the routing metric used on wireless links to plain ETX.
* Bridges are now automatically detected and treated as potential
wireless interfaces.
* Reduced the default hello interval.
24 May 2008: babel 0.13
* Removed all arbitrary limits (interfaces, neighbours, routes,
xroutes and sources).
* Fixed a bug that prevented expiration of stale sources.
* Updated the kernel interface to work with recent Linux kernels.
* More tweaks to the order in which updates are sent.
7 April 2008: babel 0.12
* Retractions are now sent multiple times, which should speed up
convergence in presence of packet loss.
* Optimised the sending of updates to make them smaller.
* Don't forward requests multiple times; this should reduce the
noise due to requests with no increase in convergence time.
* Fixed a bug that could cause a crash when resending requests.
* Added some protection against clock stepping.
29 March 2008: babel 0.11
* Implemented sub-second hello and update intervals.
* Fixed a bug that could prevent the best route from being selected
for extended periods of time.
* Implemented protection against out-of-date requests being sent and
forwarded when a node loses its sequence number.
* INCOMPATIBLE CHANGE: reduced the cost of wired networks down to 96
from 128.
* Tweaked the frequency at which a router's seqno increases, to make
it more likely that a feasible route will be available when needed.
* Implemented garbage collection of old sources.
* Implemented coalescing of unicast messages.
* Fixed a bug that could cause a crash when a link's MTU changes.
* Fixed a bug that could delay noticing that a network is no longer
idle when running Babel with the -i flag.
* Fixed a bug that could cause incorrect metrics to be advertised
when output filtering was used.
* Fixed a bug that could cause incorrect link costs to be computed when
a neighbour reduces its hello interval.
* Fixed some minor issues with the ordering of outgoing messages.
11 March 2008: babel 0.10
* Implemented the ability to automatically export local addresses (see
the ``local'' keyword in redistribute specifications). This should
avoid the need to explicitly specify -X on the command line
(Julien Cristau and Juliusz Chroboczek).
* INCOMPATIBLE CHANGE: local routes (local interface addresses) are
now exported by default. Specify ``redistribute local deny'' to
avoid that.
* Babel will now automatically choose a router id if none is
specified on the command line.
* Automatically adapt to interfaces appearing or disappearing at runtime,
as is usually the case when running over tunnels or VPNs.
* Changed the link quality computation algorithm to not discard very
lossy links.
* Multi-hop requests will now be forwarded to an unfeasible successor
under some circumstances.
* Send multi-hop requests more aggressively.
* Send requests for a new seqno upon receiving an unfeasible update
if it's better than what we have.
* No longer consider the age of routes in route selection.
* Added ability to run as a daemon.
14 February 2008: babel 0.9
* Implemented a proper configuration language to specify input and
output filters and redistribution policies.
* INCOMPATIBLE CHANGE: the flags -4, -x and -c are no longer supported.
8 February 2008: babel 0.8
* Babel will now automatically check for interfaces' up/down status,
IPv4 address, and optionally for carrier sense.
* Implemented the -w option, which disables all optimisations for
wired interfaces.
* Implemented support for non-default routing tables.
* Fixed a bug that could spuriously remove IPv4 routes (thanks to
Julien Cristau).
3 January 2008: babel 0.7
* Implemented support for IPv4.
* Fixed sending of unicast requests.
* Don't send poison when receiving a request for an unknown route.
* Basic filtering infrastructure.
* Removed support for broadcast IHU.
* Changed the behaviour of -d.
16 October 2007: babel 0.6
* Implemented resending of unsatisfied requests, with exponential backoff.
* Fixed a potential crash in the request handling code.
* Send IHUs more aggressively.
9 October 2007: babel 0.5
* Implemented forwarding of requests and replies.
* Fixed a bug that prevented requests from being parsed correctly.
* Fixed a bug that prevented IHU intervals from being sent.
* Respect reboot_time even after an id change.
* Deal with neighbours rebooting and losing their hello seqno when
computing link quality.
23 September 2007: babel 0.4
* Fixed incorrect expiration of old sources. This could prevent
convergence in some cases.
16 September 2007: babel 0.3
* Fixes to Mac OS X support (Grégoire Henry).
29 August 2007: babel 0.2
* Made jitter computation depend on how urgent a given message is.
This dramatically improves convergence speed, without increasing
network load.
* Fixed a bug that prevented neighbour associations from being
discarded at shutdown.
22 August 2007: babel 0.1
* Initial public release.
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/LICENCE 0000664 0000000 0000000 00000002060 11073442770 0020747 0 ustar 00root root 0000000 0000000 Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/Makefile 0000664 0000000 0000000 00000002372 11073442770 0021430 0 ustar 00root root 0000000 0000000 PREFIX = /usr/local
CDEBUGFLAGS = -Os -g -Wall
DEFINES = $(PLATFORM_DEFINES)
CFLAGS = $(CDEBUGFLAGS) $(DEFINES) $(EXTRA_DEFINES)
LDLIBS = -lrt
SRCS = babel.c net.c kernel.c util.c network.c source.c neighbour.c \
route.c xroute.c message.c resend.c filter.c local.c
OBJS = babel.o net.o kernel.o util.o network.o source.o neighbour.o \
route.o xroute.o message.o resend.o filter.o local.o
babel: $(OBJS)
$(CC) $(CFLAGS) $(LDFLAGS) -o babel $(OBJS) $(LDLIBS)
.SUFFIXES: .man .html
.man.html:
rman -f html $< | \
sed -e "s|\\(.*(8)\\)|\1|" \
> $@
babel.html: babel.man
.PHONY: all install install.minimal uninstall clean
all: babel babel.man
install.minimal: babel
-rm -f $(TARGET)$(PREFIX)/bin/babel
mkdir -p $(TARGET)$(PREFIX)/bin
cp -f babel $(TARGET)$(PREFIX)/bin
install: install.minimal all
mkdir -p $(TARGET)$(PREFIX)/man/man8
cp -f babel.man $(TARGET)$(PREFIX)/man/man8/babel.8
uninstall:
-rm -f $(TARGET)$(PREFIX)/bin/babel
-rm -f $(TARGET)$(PREFIX)/man/man8/babel.8
clean:
-rm -f babel babel.html *.o *~ core TAGS gmon.out
kernel.o: kernel_netlink.c kernel_socket.c
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/README 0000664 0000000 0000000 00000006255 11073442770 0020654 0 ustar 00root root 0000000 0000000 Babel
*****
Babel is a loop-avoiding distance-vector routing protocol roughly
based on HSDV and AODV, but with provisions for link cost estimation
and redistribution of routes from other routing protocols.
Installation
************
$ make
$ su -c 'make install'
If compiling for OpenWRT, you will probably want to say something like
$ make CC=mipsel-linux-gcc PLATFORM_DEFINES='-march=mips32'
Setting up a network for use with Babel
***************************************
1. Set up every node's interface
================================
On every node, set up the wireless interface:
# iwconfig eth1 mode ad-hoc channel 11 essid "my-mesh-network"
# ip link set up dev eth1
2. Set up every node's IP addresses
===================================
You will need to make sure that all of your nodes have a unique IPv6
address, and/or a unique IPv4 address.
On every node, run something like:
# ip addr add 192.168.13.33/32 dev eth1
# ip -6 addr add $(ahcp-generate-address -r)/128 dev eth1
You will find the ahcp-generate-address utility, which can generate
random IPv6 addresses according to RFC 4193, in the ahcpd package.
A note about tunnels and VPNs
-----------------------------
Some VPN implementations (notably OpenVPN and Linux GRE) do not
automatically add an IPv6 link-local address to the tunnel interface.
If you attempt to run Babel over such an interface, it will complain
that it ``couldn't allocate requested address''.
The solution is to manually add the link-local address to the
interface. This can be done by running e.g.
# ip -6 addr add $(ahcp-generate-address fe80::) dev gre0
3. Start the routing daemon
===========================
Run Babel on every node, specifying the set of interfaces that it
should consider:
# babel eth1
If your node has multiple interfaces which you want to participate in
the Babel network, just list them all:
# babel eth0 eth1 sit1
4. Setting up an Internet gateway
=================================
If you have one or more Internet gateways on your mesh network, you
will want to set them up so that they redistribute the default route.
Babel will only redistribute routes with an explicit protocol
attached, so you must say something like:
# ip route add 0.0.0.0/0 via 1.2.3.4 dev eth0 proto static
In order to redistribute all routes, you will say:
# babel -C 'redistribute metric 128' eth1
You may also be more selective in the routes you redistribute, for
instance by specifying the interface over which the route goes out:
# babel -C 'redistribute if eth0 metric 128' eth1
or by constraining the prefix length:
# babel -C 'redistribute ip ::/0 le 64 metric 128' \
-C 'redistribute ip 0.0.0.0/0 le 28 metric 128' \
eth1
You may also want to constrain which local routes (routes to local
interface addresses) you advertise:
# babel -C 'redistribute local if eth1' -C 'redistribute local deny' \
-C 'redistribute metric 128' \
eth1
If you find all of this too complicated and error-prone (as I do), you
may want to consider autoconfiguring your routing domain using AHCP:
http://www.pps.jussieu.fr/~jch/software/ahcp/
Juliusz Chroboczek
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/babel.c 0000664 0000000 0000000 00000071735 11073442770 0021212 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "net.h"
#include "kernel.h"
#include "network.h"
#include "source.h"
#include "neighbour.h"
#include "route.h"
#include "xroute.h"
#include "message.h"
#include "resend.h"
#include "filter.h"
#include "local.h"
struct timeval now;
unsigned char myid[16];
int debug = 0;
time_t reboot_time;
int idle_time = 320;
int link_detect = 0;
int all_wireless = 0;
int wireless_hello_interval = -1;
int wired_hello_interval = -1;
int idle_hello_interval = -1;
int update_interval = -1;
int do_daemonise = 0;
char *logfile = NULL, *pidfile = NULL;
unsigned char *receive_buffer = NULL;
int receive_buffer_size = 0;
const unsigned char zeroes[16] = {0};
const unsigned char ones[16] =
{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
char *state_file = "/var/lib/babel-state";
int protocol_port;
unsigned char protocol_group[16];
int protocol_socket = -1;
int kernel_socket = -1;
static int kernel_routes_changed = 0;
static int kernel_link_changed = 0;
static int kernel_addr_changed = 0;
struct timeval check_neighbours_timeout;
static volatile sig_atomic_t exiting = 0, dumping = 0, changed = 0;
int local_server_socket = -1, local_socket = -1;
int local_server_port = -1;
static int kernel_routes_callback(int changed, void *closure);
static void init_signals(void);
static void dump_tables(FILE *out);
static int reopen_logfile();
int
main(int argc, char **argv)
{
struct sockaddr_in6 sin6;
int i, rc, fd, rfd, have_id = 0;
time_t expiry_time, source_expiry_time, kernel_dump_time;
char *config_file = NULL;
void *vrc;
unsigned int seed;
char **arg;
struct network *net;
parse_address("ff02::cca6:c0f9:e182:5373", protocol_group, NULL);
protocol_port = 8475;
#define SHIFT() do { arg++; } while(0)
#define SHIFTE() do { arg++; if(*arg == NULL) goto syntax; } while(0)
arg = argv;
SHIFTE();
while((*arg)[0] == '-') {
if(strcmp(*arg, "--") == 0) {
SHIFTE();
break;
} else if(strcmp(*arg, "-m") == 0) {
SHIFTE();
rc = parse_address(*arg, protocol_group, NULL);
if(rc < 0)
goto syntax;
if(protocol_group[0] != 0xff) {
fprintf(stderr,
"%s is not a multicast address\n", *arg);
goto syntax;
}
if(protocol_group[1] != 2) {
fprintf(stderr,
"Warning: %s is not a link-local multicast address\n",
*arg);
}
} else if(strcmp(*arg, "-p") == 0) {
SHIFTE();
protocol_port = atoi(*arg);
} else if(strcmp(*arg, "-h") == 0) {
SHIFTE();
wireless_hello_interval = parse_msec(*arg);
if(wireless_hello_interval <= 0)
goto syntax;
} else if(strcmp(*arg, "-H") == 0) {
SHIFTE();
wired_hello_interval = parse_msec(*arg);
if(wired_hello_interval <= 0)
goto syntax;
} else if(strcmp(*arg, "-i") == 0) {
SHIFTE();
idle_hello_interval = parse_msec(*arg);
if(idle_hello_interval <= 0)
goto syntax;
} else if(strcmp(*arg, "-u") == 0) {
SHIFTE();
update_interval = parse_msec(*arg);
if(update_interval <= 0)
goto syntax;
} else if(strcmp(*arg, "-k") == 0) {
SHIFTE();
kernel_metric = atoi(*arg);
if(kernel_metric < 0 || kernel_metric > 0xFFFF)
goto syntax;
} else if(strcmp(*arg, "-P") == 0) {
parasitic = 1;
} else if(strcmp(*arg, "-s") == 0) {
split_horizon = 0;
} else if(strcmp(*arg, "-S") == 0) {
SHIFTE();
state_file = *arg;
} else if(strcmp(*arg, "-d") == 0) {
SHIFTE();
debug = atoi(*arg);
#ifndef NO_LOCAL_INTERFACE
} else if(strcmp(*arg, "-g") == 0) {
SHIFTE();
local_server_port = atoi(*arg);
#endif
} else if(strcmp(*arg, "-l") == 0) {
link_detect = 1;
} else if(strcmp(*arg, "-w") == 0) {
all_wireless = 1;
} else if(strcmp(*arg, "-t") == 0) {
SHIFTE();
export_table = atoi(*arg);
if(export_table < 0 || export_table > 0xFFFF)
goto syntax;
} else if(strcmp(*arg, "-T") == 0) {
SHIFTE();
import_table = atoi(*arg);
if(import_table < 0 || import_table > 0xFFFF)
goto syntax;
} else if(strcmp(*arg, "-c") == 0) {
SHIFTE();
config_file = *arg;
} else if(strcmp(*arg, "-C") == 0) {
int rc;
SHIFTE();
rc = parse_config_from_string(*arg);
if(rc < 0) {
fprintf(stderr,
"Couldn't parse configuration from command line.\n");
exit(1);
}
} else if(strcmp(*arg, "-D") == 0) {
do_daemonise = 1;
} else if(strcmp(*arg, "-L") == 0) {
SHIFTE();
logfile = *arg;
} else if(strcmp(*arg, "-I") == 0) {
SHIFTE();
pidfile = *arg;
} else {
goto syntax;
}
SHIFTE();
}
if(!config_file) {
if(access("/etc/babel.conf", R_OK) >= 0)
config_file = "/etc/babel.conf";
}
if(config_file) {
rc = parse_config_from_file(config_file);
if(rc < 0) {
fprintf(stderr,
"Couldn't parse configuration from file %s.\n",
config_file);
exit(1);
}
}
rc = finalise_filters();
if(rc < 0) {
fprintf(stderr, "Couldn't finalise filters.\n");
exit(1);
}
if(wireless_hello_interval <= 0)
wireless_hello_interval = 4000;
wireless_hello_interval = MAX(wireless_hello_interval, 5);
if(wired_hello_interval <= 0)
wired_hello_interval = 20000;
wired_hello_interval = MAX(wired_hello_interval, 5);
if(update_interval <= 0)
update_interval =
MIN(MIN(wireless_hello_interval * 5, wired_hello_interval * 2),
70000);
update_interval = MAX(update_interval, 70);
if(seqno_interval <= 0)
seqno_interval = MAX(40000, update_interval * 9 / 10);
seqno_interval = MAX(seqno_interval, 20);
if(do_daemonise) {
if(logfile == NULL)
logfile = "/var/log/babel.log";
}
rc = reopen_logfile();
if(rc < 0) {
perror("reopen_logfile()");
goto fail;
}
fd = open("/dev/null", O_RDONLY);
if(fd < 0) {
perror("open(null)");
goto fail;
}
rc = dup2(fd, 0);
if(rc < 0) {
perror("dup2(null, 0)");
goto fail;
}
close(fd);
if(do_daemonise) {
rc = daemonise();
if(rc < 0) {
perror("daemonise");
goto fail_nopid;
}
}
if(pidfile) {
int pfd, len;
char buf[100];
len = snprintf(buf, 100, "%lu", (unsigned long)getpid());
if(len < 0 || len >= 100) {
perror("snprintf(getpid)");
goto fail_nopid;
}
pfd = open(pidfile, O_WRONLY | O_CREAT | O_EXCL, 0644);
if(pfd < 0) {
perror("creat(pidfile)");
goto fail_nopid;
}
rc = write(pfd, buf, len);
if(rc < len) {
perror("write(pidfile)");
goto fail;
}
close(pfd);
}
rc = kernel_setup(1);
if(rc < 0) {
fprintf(stderr, "kernel_setup failed.\n");
exit(1);
}
rc = kernel_setup_socket(1);
if(rc < 0) {
fprintf(stderr, "kernel_setup_socket failed.\n");
kernel_setup(0);
exit(1);
}
gettime(&now);
rfd = open("/dev/urandom", O_RDONLY);
if(rfd < 0) {
perror("open(random)");
}
rc = parse_address(*arg, myid, NULL);
if(rc >= 0) {
have_id = 1;
/* Cannot use SHIFTE -- need to goto fail */
SHIFT();
if(*arg == NULL) {
fprintf(stderr, "No interfaces given.\n");
goto fail;
}
} else {
struct kernel_route routes[240];
rc = kernel_addresses(routes, 240);
if(rc < 0) {
perror("kernel_addresses");
}
if(rc > 0) {
/* Search for a global IPv6 address */
for(i = 0; i < rc; i++) {
if(martian_prefix(routes[i].prefix, routes[i].plen))
continue;
if(routes[i].plen == 128 &&
(routes[i].prefix[0] & 0xE0) == 0x20) {
memcpy(myid, routes[i].prefix, 16);
have_id = 1;
break;
}
}
/* Try a global Ipv4 address */
if(!have_id) {
for(i = 0; i < rc; i++) {
if(martian_prefix(routes[i].prefix, routes[i].plen))
continue;
if(routes[i].plen == 128 &&
v4mapped(routes[i].prefix) &&
routes[i].prefix[12] != 10 &&
(routes[i].prefix[12] != 172 ||
(routes[i].prefix[13] & 0xF0) != 16) &&
(routes[i].prefix[12] != 192 ||
routes[i].prefix[13] != 168)) {
memcpy(myid, routes[i].prefix, 16);
have_id = 1;
break;
}
}
}
}
}
if(!have_id) {
if(rfd < 0) {
fprintf(stderr, "Couldn't find suitable router-id.\n");
goto fail;
}
fprintf(stderr,
"Warning: couldn't find suitable router-id, "
"using random value.\n");
rc = read(rfd, myid, 16);
if(rc < 16) {
perror("read(random)");
goto fail;
} else {
have_id = 1;
}
}
if(rfd < 0) {
memcpy(&seed, myid + 12, 4);
} else {
rc = read(rfd, &seed, sizeof(unsigned int));
if(rc < sizeof(unsigned int)) {
perror("read(random)");
memcpy(&seed, myid + 12, 4);
}
close(rfd);
rfd = -1;
}
seed ^= (now.tv_sec ^ now.tv_usec);
srandom(seed);
reboot_time = now.tv_sec;
myseqno = (random() & 0xFFFF);
fd = open(state_file, O_RDONLY);
if(fd < 0 && errno != ENOENT)
perror("open(babel-state)");
rc = unlink(state_file);
if(fd >= 0 && rc < 0) {
perror("unlink(babel-state)");
/* If we couldn't unlink it, it's probably stale. */
close(fd);
fd = -1;
}
if(fd >= 0) {
char buf[100];
char buf2[100];
int s;
long t;
rc = read(fd, buf, 99);
if(rc < 0) {
perror("read(babel-state)");
} else {
buf[rc] = '\0';
rc = sscanf(buf, "%99s %d %ld\n", buf2, &s, &t);
if(rc == 3 && s >= 0 && s <= 0xFFFF) {
unsigned char sid[16];
rc = parse_address(buf2, sid, NULL);
if(rc < 0) {
fprintf(stderr, "Couldn't parse babel-state.\n");
} else {
struct timeval realnow;
debugf("Got %s %d %ld from babel-state.\n",
format_address(sid), s, t);
gettimeofday(&realnow, NULL);
if(memcmp(sid, myid, 16) == 0)
myseqno = seqno_plus(s, 1);
else
fprintf(stderr, "ID mismatch in babel-state.\n");
/* Convert realtime into monotonic time. */
if(t >= 1176800000L && t <= realnow.tv_sec)
reboot_time = now.tv_sec - (realnow.tv_sec - t);
}
} else {
fprintf(stderr, "Couldn't parse babel-state.\n");
}
}
close(fd);
fd = -1;
}
if(reboot_time + silent_time > now.tv_sec)
fprintf(stderr, "Respecting %ld second silent time.\n",
(long int)(reboot_time + silent_time - now.tv_sec));
protocol_socket = babel_socket(protocol_port);
if(protocol_socket < 0) {
perror("Couldn't create link local socket");
goto fail;
}
while(*arg) {
debugf("Adding network %s.\n", *arg);
vrc = add_network(*arg);
if(vrc == NULL)
goto fail;
SHIFT();
}
#ifndef NO_LOCAL_INTERFACE
if(local_server_port >= 0) {
local_server_socket = tcp_server_socket(local_server_port, 1);
if(local_server_socket < 0) {
perror("local_server_socket");
goto fail;
}
}
#endif
init_signals();
resize_receive_buffer(1500);
check_networks();
if(receive_buffer == NULL)
goto fail;
rc = check_xroutes(0);
if(rc < 0)
fprintf(stderr, "Warning: couldn't check exported routes.\n");
kernel_routes_changed = 0;
kernel_link_changed = 0;
kernel_addr_changed = 0;
kernel_dump_time = now.tv_sec + roughly(30);
schedule_neighbours_check(5000, 1);
expiry_time = now.tv_sec + roughly(30);
source_expiry_time = now.tv_sec + roughly(300);
/* Make some noise so that others notice us */
FOR_ALL_NETS(net) {
if(!net->up)
continue;
/* Apply jitter before we send the first message. */
usleep(roughly(10000));
gettime(&now);
send_hello(net);
send_self_update(net, 0);
send_request(net, NULL, 0, 0, 0, 0);
flushupdates();
flushbuf(net);
}
debugf("Entering main loop.\n");
while(1) {
struct timeval tv;
fd_set readfds;
gettime(&now);
tv = check_neighbours_timeout;
timeval_min_sec(&tv, expiry_time);
timeval_min_sec(&tv, source_expiry_time);
timeval_min_sec(&tv, kernel_dump_time);
timeval_min(&tv, &resend_time);
FOR_ALL_NETS(net) {
if(!net->up)
continue;
timeval_min(&tv, &net->flush_timeout);
timeval_min(&tv, &net->hello_timeout);
if(!network_idle(net)) {
timeval_min(&tv, &net->self_update_timeout);
timeval_min(&tv, &net->update_timeout);
}
}
timeval_min(&tv, &update_flush_timeout);
timeval_min(&tv, &unicast_flush_timeout);
FD_ZERO(&readfds);
if(timeval_compare(&tv, &now) > 0) {
int maxfd = 0;
timeval_minus(&tv, &tv, &now);
FD_SET(protocol_socket, &readfds);
maxfd = MAX(maxfd, protocol_socket);
if(kernel_socket < 0) kernel_setup_socket(1);
if(kernel_socket >= 0) {
FD_SET(kernel_socket, &readfds);
maxfd = MAX(maxfd, kernel_socket);
}
#ifndef NO_LOCAL_INTERFACE
if(local_socket >= 0) {
FD_SET(local_socket, &readfds);
maxfd = MAX(maxfd, local_socket);
} else if(local_server_socket >= 0) {
FD_SET(local_server_socket, &readfds);
maxfd = MAX(maxfd, local_server_socket);
}
#endif
rc = select(maxfd + 1, &readfds, NULL, NULL, &tv);
if(rc < 0) {
if(errno != EINTR) {
perror("select");
sleep(1);
}
rc = 0;
FD_ZERO(&readfds);
}
}
gettime(&now);
if(exiting)
break;
if(kernel_socket >= 0 && FD_ISSET(kernel_socket, &readfds))
kernel_callback(kernel_routes_callback, NULL);
if(FD_ISSET(protocol_socket, &readfds)) {
rc = babel_recv(protocol_socket,
receive_buffer, receive_buffer_size,
(struct sockaddr*)&sin6, sizeof(sin6));
if(rc < 0) {
if(errno != EAGAIN && errno != EINTR) {
perror("recv");
sleep(1);
}
} else {
FOR_ALL_NETS(net) {
if(!net->up)
continue;
if(net->ifindex == sin6.sin6_scope_id) {
parse_packet((unsigned char*)&sin6.sin6_addr, net,
receive_buffer, rc);
VALGRIND_MAKE_MEM_UNDEFINED(receive_buffer,
receive_buffer_size);
break;
}
}
}
}
#ifndef NO_LOCAL_INTERFACE
if(local_server_socket >= 0 &&
FD_ISSET(local_server_socket, &readfds)) {
if(local_socket >= 0) {
close(local_socket);
local_socket = -1;
}
local_socket = accept(local_server_socket, NULL, NULL);
if(local_socket < 0) {
if(errno != EINTR && errno != EAGAIN)
perror("accept(local_server_socket)");
} else {
local_dump();
}
}
if(local_socket >= 0 && FD_ISSET(local_socket, &readfds)) {
rc = local_read(local_socket);
if(rc <= 0) {
if(rc < 0)
perror("read(local_socket)");
close(local_socket);
local_socket = -1;
}
}
#endif
if(changed) {
kernel_dump_time = now.tv_sec;
check_neighbours_timeout = now;
expiry_time = now.tv_sec;
rc = reopen_logfile();
if(rc < 0) {
perror("reopen_logfile");
break;
}
changed = 0;
}
if(kernel_link_changed || kernel_addr_changed) {
check_networks();
kernel_link_changed = 0;
}
if(kernel_routes_changed || kernel_addr_changed ||
now.tv_sec >= kernel_dump_time) {
rc = check_xroutes(1);
if(rc < 0)
fprintf(stderr, "Warning: couldn't check exported routes.\n");
kernel_routes_changed = kernel_addr_changed = 0;
if(kernel_socket >= 0)
kernel_dump_time = now.tv_sec + roughly(300);
else
kernel_dump_time = now.tv_sec + roughly(30);
}
if(timeval_compare(&check_neighbours_timeout, &now) < 0) {
int msecs;
msecs = check_neighbours();
msecs = MAX(msecs, 10);
schedule_neighbours_check(msecs, 1);
}
if(now.tv_sec >= expiry_time) {
check_networks();
expire_routes();
expire_resend();
expiry_time = now.tv_sec + roughly(30);
}
if(now.tv_sec >= source_expiry_time) {
expire_sources();
source_expiry_time = now.tv_sec + roughly(300);
}
FOR_ALL_NETS(net) {
if(!net->up)
continue;
if(timeval_compare(&now, &net->hello_timeout) >= 0)
send_hello(net);
if(!network_idle(net)) {
if(timeval_compare(&now, &net->update_timeout) >= 0)
send_update(net, 0, NULL, 0);
if(timeval_compare(&now, &net->self_update_timeout) >= 0)
send_self_update(net, 0);
}
}
if(resend_time.tv_sec != 0) {
if(timeval_compare(&now, &resend_time) >= 0)
do_resend();
}
if(update_flush_timeout.tv_sec != 0) {
if(timeval_compare(&now, &update_flush_timeout) >= 0)
flushupdates();
}
if(unicast_flush_timeout.tv_sec != 0) {
if(timeval_compare(&now, &unicast_flush_timeout) >= 0)
flush_unicast(1);
}
FOR_ALL_NETS(net) {
if(!net->up)
continue;
if(net->flush_timeout.tv_sec != 0) {
if(timeval_compare(&now, &net->flush_timeout) >= 0)
flushbuf(net);
}
}
if(debug || dumping) {
dump_tables(stdout);
dumping = 0;
}
}
debugf("Exiting...\n");
usleep(roughly(10000));
gettime(&now);
/* Uninstall and retract all routes. */
while(numroutes > 0) {
if(routes[0].installed) {
uninstall_route(&routes[0]);
send_update(NULL, 1, routes[0].src->prefix, routes[0].src->plen);
}
/* We need to flush the route so network_up won't reinstall it */
flush_route(&routes[0]);
}
while(numxroutes > 0) {
xroutes[0].metric = INFINITY;
send_update(NULL, 1, xroutes[0].prefix, xroutes[0].plen);
flush_xroute(&xroutes[0]);
}
flushupdates();
FOR_ALL_NETS(net) {
if(!net->up)
continue;
/* Make sure that we expire quickly from our neighbours'
association caches. */
send_hello_noupdate(net, 10);
flushbuf(net);
usleep(roughly(1000));
gettime(&now);
}
FOR_ALL_NETS(net) {
if(!net->up)
continue;
/* Make sure they got it. */
send_hello_noupdate(net, 1);
flushbuf(net);
usleep(roughly(10000));
gettime(&now);
network_up(net, 0);
}
kernel_setup_socket(0);
kernel_setup(0);
fd = open(state_file, O_WRONLY | O_TRUNC | O_CREAT, 0644);
if(fd < 0) {
perror("creat(babel-state)");
unlink(state_file);
} else {
struct timeval realnow;
char buf[100];
gettimeofday(&realnow, NULL);
rc = snprintf(buf, 100, "%s %d %ld\n",
format_address(myid), (int)myseqno,
(long)realnow.tv_sec);
if(rc < 0 || rc >= 100) {
fprintf(stderr, "write(babel-state): overflow.\n");
unlink(state_file);
} else {
rc = write(fd, buf, rc);
if(rc < 0) {
perror("write(babel-state)");
unlink(state_file);
}
fsync(fd);
}
close(fd);
}
if(pidfile)
unlink(pidfile);
debugf("Done.\n");
return 0;
syntax:
fprintf(stderr,
"Syntax: %s "
"[-m multicast_address] [-p port] [-S state-file]\n"
" "
"[-h hello] [-H wired_hello] [-i idle_hello] [-u update]\n"
" "
"[-k metric] [-s] [-p] [-l] [-w] [-d level] [-g port]\n"
" "
"[-t table] [-T table] [-c file] [-C statement]\n"
" "
"[-D] [-L logfile] [-I pidfile]\n"
" "
"[id] interface...\n",
argv[0]);
exit(1);
fail:
if(pidfile)
unlink(pidfile);
fail_nopid:
FOR_ALL_NETS(net) {
if(!net->up)
continue;
network_up(net, 0);
}
kernel_setup_socket(0);
kernel_setup(0);
exit(1);
}
/* Schedule a neighbours check after roughly 3/2 msecs have elapsed. */
void
schedule_neighbours_check(int msecs, int override)
{
struct timeval timeout;
timeval_plus_msec(&timeout, &now, roughly(msecs * 3 / 2));
if(override)
check_neighbours_timeout = timeout;
else
timeval_min(&check_neighbours_timeout, &timeout);
}
void
resize_receive_buffer(int size)
{
if(size <= receive_buffer_size)
return;
if(receive_buffer == NULL) {
receive_buffer = malloc(size);
if(receive_buffer == NULL) {
perror("malloc(receive_buffer)");
return;
}
receive_buffer_size = size;
} else {
unsigned char *new;
new = realloc(receive_buffer, size);
if(new == NULL) {
perror("realloc(receive_buffer)");
return;
}
receive_buffer = new;
receive_buffer_size = size;
}
}
static void
sigexit(int signo)
{
exiting = 1;
}
static void
sigdump(int signo)
{
dumping = 1;
}
static void
sigchanged(int signo)
{
changed = 1;
}
static void
init_signals(void)
{
struct sigaction sa;
sigset_t ss;
sigemptyset(&ss);
sa.sa_handler = sigexit;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigemptyset(&ss);
sa.sa_handler = sigexit;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGHUP, &sa, NULL);
sigemptyset(&ss);
sa.sa_handler = sigexit;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGINT, &sa, NULL);
sigemptyset(&ss);
sa.sa_handler = SIG_IGN;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGPIPE, &sa, NULL);
sigemptyset(&ss);
sa.sa_handler = sigdump;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGUSR1, &sa, NULL);
sigemptyset(&ss);
sa.sa_handler = sigchanged;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGUSR2, &sa, NULL);
#ifdef SIGINFO
sigemptyset(&ss);
sa.sa_handler = sigdump;
sa.sa_mask = ss;
sa.sa_flags = 0;
sigaction(SIGINFO, &sa, NULL);
#endif
}
static void
dump_tables(FILE *out)
{
struct neighbour *neigh;
int i;
fprintf(out, "\n");
fprintf(out, "My id %s seqno %d\n", format_address(myid), myseqno);
FOR_ALL_NEIGHBOURS(neigh) {
fprintf(out, "Neighbour %s ", format_address(neigh->id));
fprintf(out, "at %s dev %s reach %04x rxcost %d txcost %d%s.\n",
format_address(neigh->address),
neigh->network->ifname,
neigh->reach,
neighbour_rxcost(neigh),
neigh->txcost,
neigh->network->up ? "" : " (down)");
}
for(i = 0; i < numxroutes; i++) {
fprintf(out, "%s metric %d (exported)\n",
format_prefix(xroutes[i].prefix, xroutes[i].plen),
xroutes[i].metric);
}
for(i = 0; i < numroutes; i++) {
int id =
routes[i].src->plen != 128 ||
memcmp(routes[i].src->prefix, routes[i].src->id, 16) != 0;
const unsigned char *nexthop =
memcmp(routes[i].nexthop, routes[i].neigh->address, 16) == 0 ?
NULL : routes[i].nexthop;
fprintf(out, "%s metric %d refmetric %d %s%s seqno %d age %d "
"via %s neigh %s%s%s%s\n",
format_prefix(routes[i].src->prefix, routes[i].src->plen),
routes[i].metric, routes[i].refmetric,
id ? "id " : "",
id ? format_address(routes[i].src->id) : "",
(int)routes[i].seqno,
(int)(now.tv_sec - routes[i].time),
routes[i].neigh->network->ifname,
format_address(routes[i].neigh->address),
nexthop ? " nexthop " : "",
nexthop ? format_address(nexthop) : "",
routes[i].installed ? " (installed)" :
route_feasible(&routes[i]) ? " (feasible)" : "");
}
fflush(out);
}
static int
reopen_logfile()
{
int lfd, rc;
if(logfile == NULL)
return 0;
lfd = open(logfile, O_CREAT | O_WRONLY | O_APPEND, 0644);
if(lfd < 0)
return -1;
fflush(stdout);
fflush(stderr);
rc = dup2(lfd, 1);
if(rc < 0)
return -1;
rc = dup2(lfd, 2);
if(rc < 0)
return -1;
if(lfd > 2)
close(lfd);
return 1;
}
static int
kernel_routes_callback(int changed, void *closure)
{
if (changed & CHANGE_LINK)
kernel_link_changed = 1;
if (changed & CHANGE_ADDR)
kernel_addr_changed = 1;
if (changed & CHANGE_ROUTE)
kernel_routes_changed = 1;
return 1;
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/babel.h 0000664 0000000 0000000 00000004501 11073442770 0021202 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define INFINITY ((unsigned short)(~0))
#ifndef RTPROT_BABEL
#define RTPROT_BABEL 42
#endif
#define RTPROT_BABEL_LOCAL -2
#undef MAX
#undef MIN
#define MAX(x,y) ((x)<=(y)?(y):(x))
#define MIN(x,y) ((x)<=(y)?(x):(y))
#if defined(__GNUC__) && (__GNUC__ >= 3)
#define ATTRIBUTE(x) __attribute__(x)
#else
#define ATTRIBUTE(x) /**/
#endif
#ifndef IF_NAMESIZE
#include
#include
#endif
#ifdef HAVE_VALGRIND
#include
#else
#ifndef VALGRIND_MAKE_MEM_UNDEFINED
#define VALGRIND_MAKE_MEM_UNDEFINED(a, b) do {} while(0)
#endif
#ifndef VALGRIND_CHECK_MEM_IS_DEFINED
#define VALGRIND_CHECK_MEM_IS_DEFINED(a, b) do {} while(0)
#endif
#endif
extern struct timeval now;
extern int debug;
extern time_t reboot_time;
extern int wireless_hello_interval, wired_hello_interval, idle_hello_interval;
extern int idle_time;
extern int link_detect;
extern int all_wireless;
extern int local_socket;
extern unsigned char myid[16];
extern const unsigned char zeroes[16], ones[16];
extern int protocol_port;
extern unsigned char protocol_group[16];
extern int protocol_socket;
extern int kernel_socket;
extern int max_request_hopcount;
extern int update_interval;
void schedule_neighbours_check(int msecs, int override);
void resize_receive_buffer(int size);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/babel.man 0000664 0000000 0000000 00000021546 11073442770 0021536 0 ustar 00root root 0000000 0000000 .TH BABEL 8
.SH NAME
babel \- ad-hoc network routing daemon
.SH SYNOPSIS
.B babel
.IR option ...
[
.B \-\-
] [
.I id
]
.IR interface ...
.SH DESCRIPTION
Babel is a loop-avoiding distance-vector routing protocol roughly
based on DSDV and AODV, but with provisions for link cost estimation
and redistribution of routes from other routing protocols.
While it is optimised for wireless mesh networks, Babel will also work
efficiently on wired networks.
.SH OPTIONS
.TP
.BI \-m " multicast-address"
Specify the link-local multicast address to be used by the protocol.
.TP
.BI \-p " port"
Specify the UDP port number to be used by the protocol.
.TP
.BI \-S " state-file"
Set the name of the file used for preserving long-term information
between invocations of the
.B babel
daemon. If this file is deleted, the daemon will run in passive mode
for 3 minutes when it is next started (see
.B -P
below), and other hosts might initially ignore it. The default is
.BR /var/lib/babel-state .
.TP
.BI \-h " hello-interval"
Specify the interval in seconds at which scheduled hello packets are
sent on wireless interfaces. The default is 4 seconds.
.TP
.BI \-H " wired-hello-interval"
Specify the interval in seconds at which scheduled hello packets are
sent on wired interfaces. The default is 20 seconds.
.TP
.BI \-i " idle-hello-interval"
Enable detection of idle networks (networks on which we haven't
accepted a hello packet in 5 minutes) and specify the interval in
seconds at which scheduled hello packets are sent on idle interfaces.
This functonality is experimental, don't use it unless you know what
you are doing.
.TP
.BI \-u " update-interval"
Specify the interval in seconds at which scheduled routing table dumps
are made on all interfaces. The default is either 5 times the
wireless hello interval, twice wired hello interval, or 70 seconds,
whichever is less. Babel uses triggered updates in addition to
scheduled updates, so this value may be set to a fairly large value.
.TP
.BI \-k " kernel-metric"
Specify a value that will be added to routes' metrics before
installing them in the kernel; this is useful when a single node
participates in multiple routing protocols. The default is 0.
.TP
.B \-l
Use IFF_RUNNING (carrier sense) when determining interface availability.
.TP
.B \-w
Don't optimise wired links, assume all interfaces are wireless.
.TP
.B \-s
Do not perform split-horizon processing on wired interfaces.
Split-horizon is never performed on wireless interfaces.
.TP
.B \-P
Run in parasitic (passive) mode. The daemon will only announce
redistributed routes.
.TP
.BI \-d " level"
Debug level. A value of 1 requests a routing table dump at every
iteration through the daemon's main loop. A value of 2 additionally
requests tracing every message sent or received. A value of
3 additionally dumps all interactions with the OS kernel. The default
is 0.
.TP
.BI \-g " port"
Listen for connections from a front-end on port
.IR port .
.TP
.BI \-t " table"
Use the given kernel routing table for routes inserted by Babel.
.TP
.BI \-T " table"
Export routes from the given kernel routing table.
.TP
.BI \-c " filename"
Specify the name of the configuration file. The default is
.BR /etc/babel.conf .
.TP
.B \-D
Daemonise at startup.
.TP
.BI \-L " logfile"
Specify a file to log random ``how do you do?'' messages to. This
defaults to standard error if not daemonising, and to
.B /var/log/babel.log
otherwise.
.TP
.BI \-I " pidfile"
Specify a file to write our process id to.
.TP
.RI "[ " id " ]"
The router-id of this daemon. This should normally be an IPv6 or IPv4
address of this machine, but can be any unique 128-bit string. If
omitted, Babel will try to determine a suitable router-id automatically.
.TP
.IR interface ...
The list of interfaces on which the protocol should operate.
.SH METRICS
.B Babel
manipulates costs and metrics that are 16-bit unsigned integers, with
the value 65535 representing infinity. A cost of 256 is interpreted
as a wireless hop with no packet losses. A cost of 255 or less is
interpreted as a wired link.
.SH CONFIG FILE FORMAT
The configuration file is a sequence of lines each of which specifies
a filter entry. Each of these lines has the following format:
.IP
.I filter selector... action
.PP
.I Filter
specifies the filter to which this entry will be added, and can be one of
.BR in ,
.BR out ,
or
.BR redistribute .
.I Selector
specifies the conditions under which the given statement matches. It
can be one of
.TP
.BI ip " prefix"
This entry only applies to routes in the given prefix.
.TP
.BI eq " plen"
This entry only applies to routes with a prefix length equal to
.BR plen .
.TP
.BI le " plen"
This entry only applies to routes with a prefix length less or equal to
.BR plen .
.TP
.BI ge " plen"
This entry only applies to routes with a prefix length greater or equal to
.BR plen .
.TP
.BI neigh " id"
This entry only applies to routes learned from a neighbour with router-id
.IR id .
.TP
.BI id " id"
This entry only applies to routes originated by a router with router-id
.IR id .
.TP
.BI proto " p"
This entry only applies to kernel routes with kernel protocol number
.IR p .
If neither
.B proto
nor
.B local
is specified, this entry applies to all non-local kernel routes.
.TP
.B local
This entry only applies to local addresses.
.TP
.BI if " interface"
For an input filter, this specifies the interface over which the route
is learned. For an output filter, this specifies the interface over
which this route is advertised. For a redistribute statement, this
specifies the interface over which the route forwards packets.
.PP
.I Action
specifies the action to be taken when this entry matches. It can have
one of the following values:
.TP
.B allow
Allow this route, without changing its metric (or setting its metric
to 0 in case of a redistribute filter).
.TP
.B deny
Ignore this route.
.TP
.BI metric " value"
For an input or output filter, allow this route after increasing its metric by
.IR value .
For a redistribute filter, redistribute this route with metric
.IR value .
.TP
.B inherit
For a redistribute filter, redistribute this route with the metric
provided by the kernel.
.PP
If
.I action
is not specified, it defaults to
.BR allow .
By default,
.B Babel
redistributes all local addresses, and no other routes. In order to
make sure that only the routes you specify are redistributed, you
should include the line
.IP
redistribute local deny
.PP
as the last line in your configuration file.
.SH EXAMPLES
You can participate in a Babel mesh network by simply running
.IP
# babel \-C 'redistribute local' eth1
.PP
where
.B eth1
is your wireless interface.
In order to gateway between multiple interfaces, just list them all on
the command line:
.IP
# babel \-C 'redistribute local' eth1 eth0 sit1
.PP
On an access point, you'll probably want to redistribute some external
routes into Babel:
.IP
# babel \\
\-C 'redistribute local' \\
\-C 'redistribute metric 256' \\
eth1
.PP
or, if you want to constrain the routes that you redistribute,
.IP
# babel \\
\-C 'redistribute local' \\
\-C 'redistribute proto 11 ip ::/0 le 64 metric 256' \\
\-C 'redistribute proto 11 ip 0.0.0.0/0 le 24 metric 256' \\
eth1
.PP
.SH WIRED INTERFACES
By default, the daemon optimises traffic on wired interfaces by
sending fewer scheduled hello messages and performing split-horizon
processing. These optimisations can be disabled by using the
.B \-H
and
.B \-s
options respectively.
No link cost estimation is ever performed on wired interfaces: a wired
adjacency is assumed to be up if at least two of the last three hello
messages have been received, and down otherwise.
All of these optimisations can be disabled by using the
.B \-w
flag. This is recommended if you are running Babel over bridge
interfaces, since such interfaces will be detected as wired interfaces.
.SH FILES
.TP
.B /etc/babel.conf
The default location of the configuration file.
.TP
.B /var/lib/babel\-state
The default location of the file storing long-term state.
.TP
.B /var/log/babel.log
The default location of the log file.
.SH SIGNALS
.TP
.B SIGUSR1
Dump Babel's routing tables to standard output or to the log file.
.TP
.B SIGUSR2
Check interfaces and kernel routes right now, then reopen the log file.
.SH SECURITY
Babel is a completely insecure protocol: any attacker able to inject
IP packets with a link-local source address can disrupt the protocol's
operation. This is no different from unsecured neighbour discovery
(ARP in IPv4).
Since Babel uses link-local addresses only, there is no need to update
firewalls to allow forwarding of Babel protocol packets. If local
filtering is being done, UDP datagrams to the port used by the
protocol should be allowed. As Babel uses unicast packets in some
cases, it is not enough to just allow packets destined to Babel's
multicast address.
.SH BUGS
Plenty. This is experimental software, run at your own risk.
.SH SEE ALSO
.BR routed (8),
.BR route6d (8),
.BR zebra (8),
.BR ahcpd (8).
.SH AUTHOR
Juliusz Chroboczek.
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/babel.text 0000664 0000000 0000000 00000116555 11073442770 0021754 0 ustar 00root root 0000000 0000000 The Babel Routing Protocol
Juliusz Chroboczek
3 April 2008
1. Introduction
Babel is a distance vector protocol that is designed to be robust both on
classical wired networks and on wireless mesh networks.
Babel operation is similar to that of familiar distance-vector routing
protocols, such as RIP and RIPng. Unlike these protocols, Babel decorates
each update with two additional pieces of data,
(i) the router-id of the originating router, which uniquely identifies
the router that injected this route into the Babel routing domain;
(ii) the sequence number of this update, a small integer that is
non-decreasing (modulo 2^16) for all updates originated by this
router.
These two pieces of data allow Babel to avoid the infamous ``counting to
infinity'' phenomenon familiar in classical distance-vector protocols by
using a feasibility condition similar to the one used by the DUAL algorithm
[DUAL] used by Cisco's EIGRP [EIGRP]. Unlike DUAL, however, Babel doesn't
use any hard state to make routes feasible; instead, it uses sequenced
updates in a manner similar to DSDV [DSDV] and AODV [RFC3561].
More precisely, Babel's feasibility condition ensures the following
properties:
(i) in the absence of multiple gateways to the same destination, Babel
never causes rooting loops, not even transient ones;
(ii) in the presence of multiple gateways to the same destination,
transient loops may appear; however, such loops disappear after
n successful updates at most, where n is the size of the loop;
additionally, none of the nodes in that loop can participate in
a loop involving the same prefix and the same gateways for the
duration of the router-id garbage collection timer.
Additionally, Babel is designed to be a flexible protocol. A large number
of parameters are left to the implementer's discretion, such as the
frequency of link quality sensing ``Hello'' messages, the frequency of
periodic updates, the link quality estimation algorithm, or the route
selection policy. This flexibility makes it possible to implement Babel
simply and efficiently on ``simple'' link-layer technologies, while using
more complex techniques on wireless links.
2. Protocol operation
Every Babel speaker has a router id, which is an arbitrary string of 16
bytes that MUST be unique across the routing domain. A natural choice is
to use one of the speaker's global IPv6 addresses as the router id; the
encoding of some messages is slightly more efficient when this is indeed
the case.
2.1 Message emission and reception
Babel speakers exchange Babel protocol messages. One or more Babel
messages are appended to form a Babel packet, which is sent as a UDP
datagram over IPv6.
The source address of a Babel packet is always a link-local unicast IPv6
address; a Babel speaker MUST silently discard any packets whose source
address is not a unicast link-local address. Babel packets may be sent to
a well-known link-local multicast address (this is the usual case) or
to a link-local unicast address.
With the exception of Hello messages, all Babel messages can be sent either
in unicast and multicast packets, and their semantics does not depend on
whether the destination was unicast or multicast. In other words, a Babel
speaker does not need to determine the destination address of a packet that
it has received.
Hello messages may be sent to multicast addresses only.
2.1.1 Jitter and aggregation
A moderate amount of jitter is applied to messages sent by a Babel speaker.
This is done for two purposes: it avoids synchronisation of multiple Babel
speakers across a network [JITTER], and allows for the aggregation of
multiple messages into a single packet.
The amount of jitter applied to a message depends on whether a message is
urgent or not; urgent messages SHOULD be sent in a timely manner whenever
possible, while non-urgent messages can be delayed by up to half the hello
interval. The following kinds of messages are urgent:
- route retractions (Section 2.3);
- route announcements just after changing gateways (Section 2.3);
- requests for a lost route (Section 2.5);
- replies to requests (Section 2.5).
All other messages are not urgent.
2.2 Adjacency establishment and link quality sensing
Every Babel node maintains a table of neighbours. The neighbour table is
indexed by triples of the form (id, interface, address), where id is the
router-id of the neighbour, interface is the interface over which the
neighbour is reachable, and address is its link-local address.
2.2.1 Inverse link sensing
Every Babel node broadcasts periodic Hello messages. Every Hello message
carries a sequence number and the interval at which Hellos are being
broadcast.
When a hello is received, its sequence number is compared with the next
expected sequence number for this neighbour. If the sequence number of the
received Hello is higher than expected, then one or more Hellos have been
missed. If the sequence number is lower, then this neighbour decreased the
Hello interval without us noticing, and part of the history must be undone.
In order to avoid undoing history, a node SHOULD always send a Hello
immediately after increasing its periodic Hello interval.
When a mobility event is detected (such as a new neighbour appearing),
a node MAY send a gratuitous Hello or temporarily decrease its Hello
interval. Conversely, when no mobility event has happened for an extended
period of time, a node MAY increase its periodic Hello interval.
From the history of received Hellos, a node computes an estimate of the
link quality in the inverse direction. This computation is a purely local
matter, and different nodes MAY use different link quality strategies;
a number of such strategies are suggested in Section 2.2.3 below.
2.2.2 Direct link sensing
In order to ascertain link symmetry and determine link quality in the
direct direction, every Babel node sends periodic IHU (``I Heard You'')
messages to every neighbour. An IHU message contains the link quality in
the direct direction, as estimated by the sending node (see Section 2.2.3),
and the interval at which periodic IHU packets are being sent.
The direct link quality is initialised at infinity. After an IHU message
has been received, it is set to the value carried by that packet. After
three IHU packets have been missed, it is again set to infinity.
2.2.3 Link quality computation
The strategy for computing the link quality is a local matter; different
nodes MAY use different strategies in a single network, and MAY use
different strategies on different interface types. This section suggests
a few such strategies.
In the following, we write rxcost for the inverse cost of a link, and
txcost for the direct cost. From these values, we compute the cost, which
is used for routing.
The sample implementation of Babel uses modified ETX (Section 2.2.3.3) on
wireless links, and 2-out-of-3 (Section 2.2.3.1) on wired links.
2.2.3.1 k-out-of-j
K-out-of-j link sensing is useful for bimodal links, such as wired links,
that are either on or off but on which a packet may occasionally be lost.
It was first used in the EGP [RFC904] external routing protocol.
The k-out-of-j strategy is parameterised by two small integers k and j,
such that 0 < k <= j, and the link cost, a constant K <= 1. A node keeps
a history of the last j hellos; if k or more of those have been correctly
received, the link is assumed to be up, and the rxcost is set to K;
otherwise, the link is assumed to be down, and the rxcost is set to
infinity.
The cost of such a link is defined as
cost = MAX(rxcost, txcost).
2.2.3.2 ETX
ETX [ETX] computes the cost by estimating the number of times that
a unicast frame will need to be retransmitted using the IEEE 802.11 MAC.
A node performing the Estimated Transmission Count (ETX) metric computes an
exponentially decaying average beta of the probability beta that a Hello
message is successfully received. The rxcost is defined as 1/beta.
Let alpha be MAX(1, 1/txcost), an estimate of the probability of
successfully sending a Hello message. The cost is then computed by
cost = 1/(1/(alpha * beta))
or, equivalently,
cost = MAX(txcost, 1) * rxcost.
2.2.3.3 Modified ETX
Modified ETX computes the cost by estimating half the number of times
a frame will need to be either transmitted or acknowledged using the IEEE
802.11 MAC. Compared to ETX, it slightly deprecates links that have poor
quality in the inverse direction.
Let alpha and beta be as above, and rxcost be 1/beta. Then the cost is
defined by
cost = 1/(2/(alpha * beta) + 2/beta)
or equivalently
cost = (MAX(txcost, 1) * rxcost + rxcost) / 2.
2.2.3.4 Link-specific strategies
A lot of thought has been given by a lot of smart people to using
link-layer information in order to estimate link quality. Common
approaches include:
- discarding neighbour relationships when the link is down;
- using physical layer information, such as the signal/noise ratio;
- using the modulation rate used by the MAC sublayer as input to the link
cost computation.
At the current time, however, the published results on the effectiveness of
such ``cross-layer'' approaches appear to yield contradictory data; hence,
their use should be considered as experimental.
2.3 Reachability information
Reachability information is carried in update and prefix messages.
Conceptually, an update is a quadruple
(id, prefix, seqno, metric)
where id is the router-id of the router that originates this route, prefix
is the destination of the route, seqno is a sequentially increasing
(modulo 2^16) sequence number, and metric is the sum of the costs of the
links constituting the path.
If the metric is infinite, the update is in fact a retraction.
2.3.1 Feasibility condition
A source is a pair (id, prefix). A distance is a pair of a sequence number
and a metric; we say that a distance (seqno, metric) is better than
a distance (seqno', metric'), written
(seqno, metric) < (seqno', metric')
when
seqno > seqno' or (seqno = seqno' and metric < metric').
In other words, distances are pairs of the form (seqno, metric), ordered
lexicographically, with the first component inverted.
The reference distance of a source is the minimum, according to the
previous order, of the reference distances of all the updates ever sent for
that source.
Every Babel node maintains a table of sources, indexed by (id, prefix)
pairs. Every entry in the source table contains the reference distance of
the source, a pair (seqno, metric).
Whenever an update (id, prefix, seqno', metric') is sent, the corresponding
source table entry is updated according to the following rules:
- if metric' is infinite, then nothing is done;
- if seqno' > seqno, then seqno := seqno', metric := metric', and the
garbage collection timer for the entry is reset;
- if seqno' = seqno and metric < metric', then seqno := seqno',
metric := metric', and the garbage collection timer for the entry is
reset;
- otherwise, the garbage collection timer for the entry is reset.
An entry in the table of sources is purged when its garbage collection
timer hasn't been reset for 200 seconds.
An update (id, prefix, seqno', metric') received from a neighbouring node
(Section 2.3.2) is feasible when either metric' is infinite, or
(seqno', metric') is strictly smaller than the reference distance of (id,
prefix). In other words, an update (id, prefix, seqno', metric') is
feasible when one of the following conditions is true:
- no entry exists in the source table for (id, prefix); or
- metric' is infinite; or
- an entry (id, prefix, seqno, metric) exists, and either
* seqno' > seqno or
* seqno' = seqno and metric' < metric.
2.3.2 The Routing Information Base
Every node maintains a Routing Information Base (RIB), a table of recently
received routing information. The route selection procedure (Section 2.4)
will choose routes from the RIB to include them in the Forwarding
Information Base (FIB), the actual ``routing table''.
The RIB is indexed by triples of the form (neighbour, id, prefix), where
neighbour is the neighbour who sent the update that created this entry (and
also the next hop for this route), id is the router id of the node that
originated the route, and prefix is the destination of the route. An RIB
entry also contains the sequence number of the most recent update for this
route, the time at which this update was received, the reference metric of
the route (the metric carried by the update) and the route's metric, which
is the sum of the route's reference metric and the cost of the neighbour
association over which it was received.
An RIB entry may also carry extra information used for route selection,
such as historical information about the route's stability.
An RIB entry is garbage collected either when its nexthop is removed from
the neighbour table, or when it has not been refreshed by a feasible update
in 180 seconds.
2.3.3 Receiving updates
When a Babel node receives an update (id, prefix, seqno, metric) from
a neighbour neigh with a link cost value equal to cost, it checks whether
it already has in its RIB an entry indexed by (neigh, id, prefix).
If no such entry exists:
- if the update is unfeasible, it is ignored;
- if the metric is infinite, the update is ignored;
- otherwise, a new RIB entry is created, indexed by (neigh, id, prefix),
with seqno seqno, reference metric equal to the metric carried by the
update, and metric equal to metric + cost.
If such an entry exists:
- if the entry is currently selected, and the update is unfeasible, then
the metric of the entry is set to infinity and a different route is
selected; if no different route exists, the route is retracted;
- if the update is feasible, then the entry's sequence number,
reference metric and metric are updated and the garbage collection
timer for the route is reset;
- otherwise, the update is ignored.
A node SHOULD send triggered updates when a selected route changes (see
Section 2.3.4 below).
After the RIB is modified, route selection (Section 2.4) is performed for
the affected destination.
2.3.4 Sending updates
A node that originates a route -- for example a route to itself, a route to
a directly attached network, or a route imported from another routing
protocol -- MUST periodically broadcast an update where
- id is the node's router-id;
- prefix is the destination of the route;
- seqno is an integer that is increased by 1 (modulo 2^16) every time an
update is sent;
- metric is an arbitrary value that reflects the desirability of using
this route; it should normally be 0 for a route to this node, and
a small positive value for a directly attached network.
When a node has selected a route (Section 2.4 below), it SHOULD
periodically broadcast, with an interval no larger than 60 seconds, an
update for this route where:
- id is the id of the selected route;
- prefix is the destination of the selected route;
- seqno is the seqno of the selected route;
- metric is no less than the metric of the selected route.
When a node has retracted a route, or when it changes to a route with
a different router id for a given destination, it MUST urgently send an
update for that destination. When the metric of a selected route changes
by more than 2, it SHOULD send an update for that destination. A node MAY
also send a spontaneous update when it detects a mobility event.
Additionally, a node SHOULD send updates in response to explicit quieries
from its neighbours (see Section 2.5 below).
2.4 Route selection
The goal of a routing protocol is to select routes for inclusion in the
Forwarding Information Base, the table of routes used by the system for
forwarding packets.
Babel is designed to allow flexible route selection policies. As long as
only feasible routes are ever selected, Babel will function correctly; the
actual choice of routes to be selected is left to the implementation.
2.4.1 Strategies for route selection
Route selection can be done according to multiple mutually contradictory
criteria:
- routes with a small metric should be preferred over routes with a large
metric;
- routes with a large seqno should be preferred over routes with a small
seqno;
- stable routes should be preferred over unstable routes;
- routes through stable neighbours should be preferred over routes
through unstable ones;
- switching routes should be avoided;
- changing source ids should be avoided.
Choosing a route selection policy for Babel is an open research problem; at
any rate, the optimal route selection policy will depend on the particular
network being routed. The current version of the sample implementation of
Babel uses the following route selection policy:
- source ids are not changed unless the new route's metric is smaller
by at least 1.5;
- routes are not switched unless the new route's metric is smaller by at
least 0.5;
- routes with a smaller metric are preferred;
- sequence numbers are ignored when performing route selection.
This strategy is likely to be reconsidered in a future version.
2.5 Accelerating convergence
When a Babel node moves or one of its selected successor crashes, it is
quite likely that some of its selected routes will become unfeasible; in
that case, it looses connectivity to the rest of the network until it
receives a new sequence number.
In order to recover its routes as promptly as possible, a node that has
lost all feasible routes to a given destination broadcasts a request for
a new sequence number. Any neighbouring node that can satisfy the request
responds with an update; a node that cannot satisfy the request but has
a route (feasible or not) to the requested source forwards the request to
a suitable next hop for the given source as a unicast packet.
Since the request forwarding mechanism does not necessarily obey the
feasibility condition, it may get caught into routing loops; hence,
requests carry a hop count to limit their propagation. However, since
requests are only ever forwarded as unicast packets, the maximum hop count
need not be kept particularly low.
A node MAY also send a broadcast or unicast request under other
circumstances. We recommend sending a broadcast request when the metric of
its selected route has increased significantly, and a unicast request when
it receives an unfeasible update with a metric significantly smaller than
that of its currently selected route.
A node SHOULD maintain a list of forwarded requests, and forward the reply
(using unicast or multicast) as soon as it arrives. A node SHOULD avoid
forwarding redundant requests.
2.6 Simplified implementations
Babel is a very economic protocol. Route updates take between 24 and 48
octets per destination; and the RIB takes about 50 bytes per entry. To put
these values into perspective, a single Ethernet packet can carry up to
60 route updates, and a megabyte of memory can contain a 20000-entry RIB.
Babel is also a fairly simple protocol. The sample implementation consists
of less than 6000 lines of C code, and compiles to less than 50 kB of text
on a 32-bit CISC architecture.
However, in some very constrained environments, such as PDAs, microwave
ovens or abacuses, it may be desirable to have subset implementations of
the protocol. The following sections give two examples of such
implementations that do not endanger the integrity of the network.
2.6.1 The simplified feasibility condition
The feasibility condition described in Section 2.3.1 requires maintaining
a table of sources. The following describes a feasibility condition,
DSDV-feasibility, that is strictly stronger than the feasibility condition
in 2.3.1.
An update (id, prefix, seqno', metric') is DSDV-feasible when
- either there is no route with source (id, prefix) in the RIB; or
- there is a route (id, prefix, seqno', metric', nexthop) in the
RIB, and either
- seqno > seqno'; or
- seqno = seqno' and metric < metric'.
The correctness of this condition is dependent on the fact that retracted
routes are not garbage collected too early. In other words, an implementation
that uses DSDV-feasibility MUST keep a RIB entry for a route for at least
a few minutes after it is retracted.
2.6.2 Parasitic implementations
A parasitic implementation is one that uses a Babel network for routing its
packets but does not announce any routes except to itself.
A parasitic implementation MUST participate in the Hello and IHU protocols.
It may either maintain a full routing table, or simply select one of its
non-parasitic neighbours (i.e. one that does announce routes with an id
that is not its router-id) as its default gateway.
Since a parasitic implementation cannot possibly participate in routing
loops, it need not evaluate the feasibility condition, and can instead
consider all routes as feasible. It SHOULD, however, be able to reply to
non-specific request messages and request messages for routes that it
advertises.
3. Packet and message format
Babel aggregates multiple messages into a single transport layer datagram;
we say that multiple Babel messages are sent as a single Babel packet.
3.1 Packet format
Babel packets are sent as link-local UDP datagrams to port 8475, using
either multicast to group ff02::cca6:c0f9:e182:5373 or unicast to
a link-local address. The meaning of a received message does not depend on
the transport being used.
A Babel packet has the following structure:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Magic | Version | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Body ...
+-+-+-+-+-+-+-+-+-+-+-+-+-
Fields:
Magic This octet has an arbitrary but carefully chosen value 42;
packets with a first octet different from 42 MUST be
silently ignored.
Version This document specifies version 1 of the Babel protocol.
Packets with a second octet different from 1 MUST be
silently ignored.
Reserved This field MUST be sent as 0, and ignored upon reception.
Body This field consists of an arbitrary number of messages (up
to the link MTU or the minimum maximum datagram size,
whichever is more) of 24 octets each.
3.2 Message format
All Babel messages have a length of 24 octets, and follow the following
format:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type | |
+-+-+-+-+-+-+-+-+ +
| |
+ +
| |
+ Body +
| |
+ +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
The Type field indicates the type of the message, and governs the
interpretation of the body.
Except for Hello messages (Section 3.2.1), all messages can be sent using
unicast or multicast, and their semantics does not depend on the transport
being used. Hello messages may be sent using multicast only.
All implementations of Babel MUST be able to interpret messages of types
0 to 4; unknown messages MUST be silently ignored.
3.2.1 Hello messages
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 0 | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Seqno | Hello Interval |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Router ID +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fields:
Type Set to 0 to indicate a Hello message.
Reserved The reserved field must be set to 0 on emission, and
ignored on reception.
Seqno Indicates the sequence number of this hello message; it is
incremented by one (modulo 2^16) every time a hello is sent
by this router on this subnet.
Hello Interval
Indicates the interval in centiseconds after which the next
hello will be scheduled; the sending node MAY send the next
hello earlier than that, but MUST NOT send it later than
after 1.5 times this interval has expired.
Router ID Indicates the router ID of the sender.
In order to allow accurate link quality measurement, hello messages MUST
NOT be sent using unicast.
3.2.2 IHU messages
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 1 | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| IHU Interval | Txcost |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Destination Router ID +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fields:
Type Set to 1 to indicate an IHU (``I Heard You'') message.
IHU Interval
Indicates the interval in centiseconds after which the next
scheduled multicast IHU message will be sent by this
router; an IHU MAY be sent earlier than that, but MUST NOT
be sent later than after this interval plus half the hello
interval.
Txcost This fixed-point number in 8.8 bit format specifies the
cost, as estimated by the sender, of sending a link-layer
frame from the router identified by the Destination Router
ID field to the sender of this message. The value 0xFF.0xFF
(infinity) indicates that the link is not operational.
Destination Router ID
This field specifies the router-id of the router to whom
this message is addressed.
3.2.3 Request message
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 2 | Plen | Reserved | Hop Count |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Seqno | Id Hash |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Prefix +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fields:
Type Set to 2 to indicate a Request message.
Plen The length of the requested prefix, or 0xFF if this is
a wildcard request.
Hop Count The number of routers this request may be forwarded by.
Seqno The requested sequence number.
Id Hash A hash of the requested router id.
Prefix The requested prefix.
A request message is used for requesting an update from the receiver.
A reply to a request is a packet consisting of update and prefix messages,
sent either to the well-known multicast address, or to the source address
of the packet carrying the request message, at the sender's discretion.
There are three kinds of request messages.
3.2.3.1 Full table requests
If Plen is 0xFF, then this is a request for a full dump of the routing
table; in this case, the Hop Count field must be zero and is ignored on
reception. When a Babel speaker receives such a request, it responds with
a full dump of its routing table, including recently retracted routes.
3.2.3.2 Specific requests
If Plen is no more than 128 and hop count is 0, then this is a request for
a route with the destination specified by Prefix and Plen. If the
receiving Babel speaker has selected a route with that destination, it
replies with an update for this route. If the Babel speaker has recently
retracted a route with this destination, it sends a retreaction.
Otherwise, it remains silent.
If Prefix/Plen is an IPv6-mapped IPv4 prefix (i.e. it is within ::ffff:0:0/96),
then the request is a request for an IPv4 prefix, and should be satisfied
with an IPv4 Prefix message (see Section 3.2.6).
3.2.3.3 Multi-hop requests
Finally, if Plen is no more than 128 and hop count is larger than 0, then
this is a multi-hop request for a particular sequence number. If the
receiver is currently exporting a route to the required destination, it
first checks whether the router-id matches the Id Hash; if so, it increases
its sequence number to match the seqno field of the request. It then sends
an update.
Otherwise, if the receiver has selected a route with the destination
specified by Prefix and Plen, if either the selected route's router id
doesn't match the router hash, or the route has a sequence number no less
than Seqno, it replies with an update for that route.
Otherwise, if the receiver has selected a route to the given destination,
with matching router-id, but a too small seqno, if the hop count is at
least 2, it forwards the request as a unicast packet to the selected
successor if it is not the requestor, and otherwise to some other successor
(feasible or not) after decreasing the hop count by one. If the hop count
is 1, it remains silent. A speaker SHOULD keep track of forwarded
multi-hop requests, forward the replies whenever a request is satisfied,
and avoid forwarding redundant requests.
If the receiver has no route to the given destination (feasible or not), it
remains silent.
As above, if Prefix/Plen is an IPv6-mapped IPv4 prefix, then this is
a request for an IPv4 prefix.
3.2.4 Update
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 3 | Plen | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Seqno | Metric |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Router ID +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fields:
Type Set to 3 to indicate an Update message.
Plen The prefix length of the advertised prefix, or 0xFF.
Seqno The sequence number of this advertisement in 8.8 format, or
zero.
Metric The metric of the advertised route, or zero.
Router ID The router id of the originator of this route.
If Plen is 0xFF (the normal case), the field Router ID establishes the
context for the following update message; all the other fields MUST then be
sent as 0, and ignored upon reception.
If Plen is between 0 and 0x80, inclusive, the message is an abbreviation
for an update message followed by a prefix message (Section 3.2.5); the
implicit prefix is then taken to be the prefix of length plen of the
advertised router id. More precisely, the message
(3, plen, 0, seqno, metric, id)
is interpreted just like the sequence of two messages
(3, 0xFF, 0, 0, 0, id)
(4, plen, 0, seqno, metric, prefix)
where prefix is equal to id masked to plen bits.
3.2.5 Prefix information
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 4 | Plen | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Seqno | Metric |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ Prefix +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fields:
Type Set to 4 to indicate a Prefix message.
Plen The prefix length of the advertised prefix.
Seqno The sequence number of this advertisement.
Metric The metric of the advertised route, in 8.8 bit fixed-point
format.
Prefix The prefix being advertised.
A Prefix message MUST immediately follow either an Update message, another
Prefix message, or an IPv4 Prefix message.
The Metric field is a fixed-point number in 8.8 bit format, and represents
an additive metric. The value 0xFF.0xFF (infinity) indicates that this is
a route retraction.
A Prefix message specifies an update for the route to destination (prefix,
plen), with a sequence number given by the field Seqno, a metric given by
the Metric field, and a source indicated by the Router ID field of the
preceding update message.
3.2.6 IPv4 prefix information
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Type = 5 | Plen | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Seqno | Metric |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ Reserved +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Hop |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Prefix |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Fields:
Type Set to 5 to indicate an IPv4 Prefix message.
Plen The prefix length of the advertised prefix.
Seqno The sequence number of this advertisement.
Metric The metric of the advertised route, in 8.8 bit fixed-point
format.
Next Hop The IPv4 address of the sending interface.
Prefix The prefix being advertised.
An Ipv4 Prefix message MUST immediately follow either an Update message,
a Prefix message, or another IPv4 Prefix message.
The Metric and Seqno fields are interpreted as in the Prefix message.
An IPv4 Prefix message specifies an update for the route to destination
(prefix, plen), with a sequence number given by the field Seqno, a metric
given by the Metric field, a source indicated by the Router ID field of the
preceding update message, and a next hop specified by the Next Hop field.
A node that does not implement IPv4 MUST silently ignore IPv4 Prefix
messages, and MUST NOT send IPv4 Prefix messages.
4. Sample implementation
A sample implementation of the Babel protocol is available from
http://www.pps.jussieu.fr/~jch/software/babel/
References
[JITTER] Sally Floyd and Van Jacobson. The synchronization of periodic
routing messages. IEEE/ACM Trans. Netw. 2, 2 (Apr. 1994),
122-136. 1994.
[DSDV] Charles Perkins and Pravin Bhagwat. Highly Dynamic
Destination-Sequenced Distance-Vector Routing (DSDV) for Mobile
Computers. ACM SIGCOMM'94 Conference on Communications
Architectures, Protocols and Applications, 234-244. 1994
[RFC3561] Ad hoc On-Demand Distance Vector (AODV) Routing. C. Perkins,
E. Belding-Royer, S. Das. RFC 3561. July 2003.
[RFC904] Exterior Gateway Protocol formal specification. D. L. Mills.
RFC 904. April 1 1984.
[DUAL] J. J. Garcia Luna Aceves. Loop-Free Routing Using Diffusing
Computations. IEEE/ACM Transactions on Networking, 1:1.
February 1993.
[EIGRP] Bob Albrigtson, J. J. Garcia Luna Aceves and Joanne Boyle.
EIGRP -- a Fast Routing Protocol Based on Distance Vectors.
Proc. Interop 94. 1994.
[ETX] D. Defcouto, D. Aguayo, J. Bicket, and R. Morris. A high-
throughput path metric for multi-hop wireless networks.
Proc. MobiCom. 2003.
Local Variables:
fill-column: 75
End:
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/filter.c 0000664 0000000 0000000 00000027703 11073442770 0021426 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "filter.h"
struct filter *input_filters = NULL;
struct filter *output_filters = NULL;
struct filter *redistribute_filters = NULL;
/* get_next_char callback */
typedef int (*gnc_t)(void*);
static int
skip_whitespace(int c, gnc_t gnc, void *closure)
{
while(c == ' ' || c == '\t')
c = gnc(closure);
return c;
}
static int
skip_to_eol(int c, gnc_t gnc, void *closure)
{
while(c != '\n' && c >= 0)
c = gnc(closure);
if(c == '\n')
c = gnc(closure);
return c;
}
static int
getword(int c, char **token_r, gnc_t gnc, void *closure)
{
char buf[256];
int i = 0;
c = skip_whitespace(c, gnc, closure);
if(c < 0)
return c;
if(c == '\n')
return -2;
do {
if(i >= 255) return -2;
buf[i++] = c;
c = gnc(closure);
} while(c != ' ' && c != '\t' && c != '\n' && c >= 0);
buf[i] = '\0';
*token_r = strdup(buf);
return c;
}
static int
getint(int c, int *int_r, gnc_t gnc, void *closure)
{
char *t, *end;
int i;
c = getword(c, &t, gnc, closure);
if(c < -1)
return c;
i = strtol(t, &end, 0);
if(*end != '\0') {
free(t);
return -2;
}
free(t);
*int_r = i;
return c;
}
static int
getip(int c, unsigned char **ip_r, int *af_r, gnc_t gnc, void *closure)
{
char *t;
unsigned char *ip;
unsigned char addr[16];
int af, rc;
c = getword(c, &t, gnc, closure);
if(c < -1)
return c;
rc = parse_address(t, addr, &af);
if(rc < 0) {
free(t);
return -2;
}
free(t);
ip = malloc(16);
if(ip == NULL) {
return -2;
}
memcpy(ip, addr, 16);
*ip_r = ip;
if(af_r)
*af_r = af;
return c;
}
static int
getnet(int c, unsigned char **p_r, unsigned char *plen_r, int *af_r,
gnc_t gnc, void *closure)
{
char *t;
unsigned char *ip;
unsigned char addr[16];
unsigned char plen;
int af, rc;
c = getword(c, &t, gnc, closure);
if(c < -1)
return c;
rc = parse_net(t, addr, &plen, &af);
if(rc < 0) {
free(t);
return -2;
}
free(t);
ip = malloc(16);
if(ip == NULL)
return -2;
memcpy(ip, addr, 16);
*p_r = ip;
*plen_r = plen;
if(af_r) *af_r = af;
return c;
}
static struct filter error_filter;
static struct filter *
parse_filter(gnc_t gnc, void *closure)
{
int c;
char *token;
struct filter *filter;
filter = calloc(1, sizeof(struct filter));
if(filter == NULL)
goto error;
filter->plen_le = 128;
c = gnc(closure);
if(c < -1)
goto error;
while(c >= 0 && c != '\n') {
c = skip_whitespace(c, gnc, closure);
if(c == '#') {
c = skip_to_eol(c, gnc, closure);
break;
}
c = getword(c, &token, gnc, closure);
if(c < -1)
goto error;
if(strcmp(token, "ip") == 0) {
c = getnet(c, &filter->prefix, &filter->plen, &filter->af,
gnc, closure);
if(c < -1)
goto error;
} else if(strcmp(token, "eq") == 0) {
int p;
c = getint(c, &p, gnc, closure);
if(c < -1)
goto error;
filter->plen_ge = MAX(filter->plen_ge, p);
filter->plen_le = MIN(filter->plen_le, p);
} else if(strcmp(token, "le") == 0) {
int p;
c = getint(c, &p, gnc, closure);
if(c < -1)
goto error;
filter->plen_le = MIN(filter->plen_le, p);
} else if(strcmp(token, "ge") == 0) {
int p;
c = getint(c, &p, gnc, closure);
if(c < -1)
goto error;
filter->plen_ge = MAX(filter->plen_ge, p);
} else if(strcmp(token, "neigh") == 0) {
unsigned char *neigh;
c = getip(c, &neigh, NULL, gnc, closure);
if(c < -1)
goto error;
filter->neigh = neigh;
} else if(strcmp(token, "id") == 0) {
unsigned char *id;
c = getip(c, &id, NULL, gnc, closure);
if(c < -1)
goto error;
filter->id = id;
} else if(strcmp(token, "proto") == 0) {
int proto;
c = getint(c, &proto, gnc, closure);
if(c < -1)
goto error;
filter->proto = proto;
} else if(strcmp(token, "local") == 0) {
filter->proto = RTPROT_BABEL_LOCAL;
} else if(strcmp(token, "if") == 0) {
char *interface;
c = getword(c, &interface, gnc, closure);
if(c < -1)
goto error;
filter->ifname = strdup(interface);
filter->ifindex = if_nametoindex(interface);
} else if(strcmp(token, "allow") == 0) {
filter->result = 0;
} else if(strcmp(token, "deny") == 0) {
filter->result = INFINITY;
} else if(strcmp(token, "metric") == 0) {
int metric;
c = getint(c, &metric, gnc, closure);
if(c < -1) goto error;
if(metric <= 0 || metric > INFINITY)
goto error;
filter->result = metric;
} else if(strcmp(token, "inherit") == 0) {
filter->result = METRIC_INHERIT;
} else {
goto error;
}
free(token);
}
if(filter->af == 0) {
if(filter->plen_le < 128 || filter->plen_ge > 0)
filter->af = AF_INET6;
} else if(filter->af == AF_INET) {
filter->plen_le += 96;
filter->plen_ge += 96;
}
return filter;
error:
free(filter);
return &error_filter;
}
static void
add_filter(struct filter *filter, struct filter **filters)
{
struct filter *f;
if(*filters == NULL) {
filter->next = NULL;
*filters = filter;
} else {
f = *filters;
while(f->next)
f = f->next;
filter->next = NULL;
f->next = filter;
}
}
static int
parse_config(gnc_t gnc, void *closure)
{
int kind;
int c;
char *token;
struct filter *filter;
c = gnc(closure);
if(c < 2)
return -1;
while(c >= 0) {
c = skip_whitespace(c, gnc, closure);
if(c == '#') {
c = skip_to_eol(c, gnc, closure);
continue;
}
if(c == '\n') {
c = gnc(closure);
continue;
}
if(c < 0)
break;
c = getword(c, &token, gnc, closure);
if(c < -1)
return -1;
if(strcmp(token, "in") == 0) {
kind = 1;
} else if(strcmp(token, "out") == 0) {
kind = 2;
} else if(strcmp(token, "redistribute") == 0) {
kind = 3;
} else {
return -1;
}
free(token);
filter = parse_filter(gnc, closure);
if(filter == &error_filter)
return -1;
if(filter == NULL)
continue;
if(kind == 1)
add_filter(filter, &input_filters);
else if(kind == 2)
add_filter(filter, &output_filters);
else if(kind == 3)
add_filter(filter, &redistribute_filters);
else
return -1;
}
return 1;
}
int
parse_config_from_file(char *filename)
{
FILE *f;
int rc;
f = fopen(filename, "r");
if(f == NULL)
return -1;
rc = parse_config((gnc_t)fgetc, f);
fclose(f);
return rc;
}
struct string_state {
char *string;
int n;
};
static int
gnc_string(struct string_state *s)
{
if(s->string[s->n] == '\0')
return -1;
else
return s->string[s->n++];
}
int
parse_config_from_string(char *string)
{
struct string_state s = { string, 0 };
return parse_config((gnc_t)gnc_string, &s);
}
static void
renumber_filter(struct filter *filter)
{
while(filter) {
if(filter->ifname)
filter->ifindex = if_nametoindex(filter->ifname);
filter = filter->next;
}
}
void
renumber_filters()
{
renumber_filter(input_filters);
renumber_filter(output_filters);
renumber_filter(redistribute_filters);
}
static int
filter_match(struct filter *f, const unsigned char *id,
const unsigned char *prefix, unsigned short plen,
const unsigned char *neigh, unsigned int ifindex, int proto)
{
if(f->af) {
if(plen >= 96 && v4mapped(prefix)) {
if(f->af == AF_INET6) return 0;
} else {
if(f->af == AF_INET) return 0;
}
}
if(f->id) {
if(!id || memcmp(f->id, id, 16) != 0)
return 0;
}
if(f->prefix) {
if(!prefix || plen < f->plen || !in_prefix(prefix, f->prefix, f->plen))
return 0;
}
if(f->plen_ge > 0 || f->plen_le < 128) {
if(!prefix)
return 0;
if(plen > f->plen_le)
return 0;
if(plen < f->plen_ge)
return 0;
}
if(f->neigh) {
if(!neigh || memcmp(f->neigh, neigh, 16) != 0)
return 0;
}
if(f->ifname) {
if(!f->ifindex) /* no such interface */
return 0;
if(!ifindex || f->ifindex != ifindex)
return 0;
}
if(f->proto) {
if(!proto || f->proto != proto)
return 0;
} else if(proto == RTPROT_BABEL_LOCAL) {
return 0;
}
return 1;
}
static int
do_filter(struct filter *f, const unsigned char *id,
const unsigned char *prefix, unsigned short plen,
const unsigned char *neigh, unsigned int ifindex, int proto)
{
while(f) {
if(filter_match(f, id, prefix, plen, neigh, ifindex, proto))
return f->result;
f = f->next;
}
return -1;
}
int
input_filter(const unsigned char *id,
const unsigned char *prefix, unsigned short plen,
const unsigned char *neigh, unsigned int ifindex)
{
int res;
res = do_filter(input_filters, id, prefix, plen, neigh, ifindex, 0);
if(res < 0 || res == METRIC_INHERIT)
res = 0;
return res;
}
int
output_filter(const unsigned char *id, const unsigned char *prefix,
unsigned short plen, unsigned int ifindex)
{
int res;
res = do_filter(output_filters, id, prefix, plen, NULL, ifindex, 0);
if(res < 0 || res == METRIC_INHERIT)
res = 0;
return res;
}
int
redistribute_filter(const unsigned char *prefix, unsigned short plen,
unsigned int ifindex, int proto)
{
int res;
res = do_filter(redistribute_filters, NULL, prefix, plen, NULL,
ifindex, proto);
if(res < 0)
res = INFINITY;
return res;
}
int
finalise_filters()
{
struct filter *filter = calloc(1, sizeof(struct filter));
if(filter == NULL)
return -1;
filter->proto = RTPROT_BABEL_LOCAL;
filter->plen_le = 128;
add_filter(filter, &redistribute_filters);
return 1;
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/filter.h 0000664 0000000 0000000 00000003700 11073442770 0021422 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define METRIC_INHERIT (INFINITY + 1)
struct filter {
int af;
char *ifname;
unsigned int ifindex;
unsigned char *id;
unsigned char *prefix;
unsigned char plen;
unsigned char plen_ge, plen_le;
unsigned char *neigh;
int proto;
unsigned int result;
struct filter *next;
};
int parse_config_from_file(char *filename);
int parse_config_from_string(char *string);
void renumber_filters(void);
int input_filter(const unsigned char *id,
const unsigned char *prefix, unsigned short plen,
const unsigned char *neigh, unsigned int ifindex);
int output_filter(const unsigned char *id, const unsigned char *prefix,
unsigned short plen, unsigned int ifindex);
int redistribute_filter(const unsigned char *prefix, unsigned short plen,
unsigned int ifindex, int proto);
int finalise_filters(void);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/kernel.c 0000664 0000000 0000000 00000004030 11073442770 0021405 0 ustar 00root root 0000000 0000000 /*
Copyright 2007, 2008 by Grégoire Henry, Julien Cristau and Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#ifdef __APPLE__
#include "kernel_socket.c"
#else
#include "kernel_netlink.c"
#endif
/* Like gettimeofday, but should return monotonic time. If POSIX clocks
are not available, falls back to gettimeofday. */
int
gettime(struct timeval *tv)
{
#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0 && defined(CLOCK_MONOTONIC)
static int have_posix_clocks = -1;
if(have_posix_clocks < 0) {
struct timespec ts;
int rc;
rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if(rc < 0) {
have_posix_clocks = 0;
} else {
have_posix_clocks = 1;
}
}
if(have_posix_clocks) {
struct timespec ts;
int rc;
rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if(rc < 0)
return rc;
tv->tv_sec = ts.tv_sec;
tv->tv_usec = ts.tv_nsec / 1000;
return rc;
}
#endif
return gettimeofday(tv, NULL);
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/kernel.h 0000664 0000000 0000000 00000004547 11073442770 0021427 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#define KERNEL_INFINITY 0xFFFF
struct kernel_route {
unsigned char prefix[16];
int plen;
int metric;
unsigned int ifindex;
int proto;
unsigned char gw[16];
};
#define ROUTE_FLUSH 0
#define ROUTE_ADD 1
#define ROUTE_MODIFY 2
#define CHANGE_LINK (1 << 0)
#define CHANGE_ROUTE (1 << 1)
#define CHANGE_ADDR (1 << 2)
extern int export_table, import_table;
int kernel_setup(int setup);
int kernel_setup_socket(int setup);
int kernel_setup_interface(int setup, const char *ifname, int ifindex);
int kernel_interface_operational(const char *ifname, int ifindex);
int kernel_interface_ipv4(const char *ifname, int ifindex,
unsigned char *addr_r);
int kernel_interface_mtu(const char *ifname, int ifindex);
int kernel_interface_wireless(const char *ifname, int ifindex);
int kernel_route(int operation, const unsigned char *dest, unsigned short plen,
const unsigned char *gate, int ifindex, unsigned int metric,
const unsigned char *newgate, int newifindex,
unsigned int newmetric);
int kernel_routes(struct kernel_route *routes, int maxroutes);
int kernel_callback(int (*fn)(int, void*), void *closure);
int kernel_addresses(struct kernel_route *routes, int maxroutes);
int gettime(struct timeval *tv);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/kernel_netlink.c 0000664 0000000 0000000 00000100361 11073442770 0023135 0 ustar 00root root 0000000 0000000 /*
Copyright 2007, 2008 by Grégoire Henry, Julien Cristau and Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 5)
#define RTA_TABLE 15
#endif
#include "babel.h"
#include "kernel.h"
#include "util.h"
#include "network.h"
int export_table = -1, import_table = -1;
static int old_forwarding = -1;
static int old_ipv4_forwarding = -1;
static int old_accept_redirects = -1;
static int old_rp_filter = -1;
static int dgram_socket = -1;
static int
read_proc(char *filename)
{
char buf[100];
int fd, rc;
fd = open(filename, O_RDONLY);
if(fd < 0)
return -1;
rc = read(fd, buf, 99);
if(rc < 0) {
int saved_errno = errno;
close(fd);
errno = saved_errno;
return -1;
}
close(fd);
if(rc == 0)
return -1;
buf[rc] = '\0';
return atoi(buf);
}
static int
write_proc(char *filename, int value)
{
char buf[100];
int fd, rc, n;
n = snprintf(buf, 100, "%d", value);
fd = open(filename, O_WRONLY);
if(fd < 0)
return -1;
rc = write(fd, buf, n);
if(rc < n) {
int saved_errno = errno;
close(fd);
errno = saved_errno;
return -1;
}
close(fd);
return 1;
}
struct netlink {
unsigned short seqno;
int sock;
struct sockaddr_nl sockaddr;
socklen_t socklen;
};
static struct netlink nl_command = { 0, -1, {0}, 0 };
static struct netlink nl_listen = { 0, -1, {0}, 0 };
static int nl_setup = 0;
static int
netlink_socket(struct netlink *nl, uint32_t groups)
{
int rc;
nl->sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if(nl->sock < 0)
return -1;
memset(&nl->sockaddr, 0, sizeof(nl->sockaddr));
nl->sockaddr.nl_family = AF_NETLINK;
nl->sockaddr.nl_groups = groups;
nl->socklen = sizeof(nl->sockaddr);
nl->seqno = time(NULL);
rc = fcntl(nl->sock, F_GETFL, 0);
if(rc < 0)
goto fail;
rc = fcntl(nl->sock, F_SETFL, (rc | O_NONBLOCK));
if(rc < 0)
goto fail;
rc = bind(nl->sock, (struct sockaddr *)&nl->sockaddr, nl->socklen);
if(rc < 0)
goto fail;
rc = getsockname(nl->sock, (struct sockaddr *)&nl->sockaddr, &nl->socklen);
if(rc < 0)
goto fail;
return 0;
fail:
{
int saved_errno = errno;
close(nl->sock);
nl->sock = -1;
errno = saved_errno;
return -1;
}
}
static int
netlink_read(struct netlink *nl, struct netlink *nl_ignore, int answer,
int (*fn)(struct nlmsghdr *nh, void *data), void *data)
{
/* 'answer' must be true when we just have send a request on 'nl_socket' */
/* 'nl_ignore' is used in kernel_callback to ignore message originating */
/* from 'nl_command' while reading 'nl_listen' */
/* Return code : */
/* -1 : error */
/* 0 : if(fn) found_interesting; else found_ack; */
/* 1 : only if(fn) nothing interesting has been found */
/* 2 : nothing found, retry */
int err;
struct msghdr msg;
struct sockaddr_nl nladdr;
struct iovec iov;
struct nlmsghdr *nh;
int len;
int interesting = 0;
int done = 0;
char buf[8192];
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &nladdr;
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
iov.iov_base = &buf;
do {
iov.iov_len = sizeof(buf);
len = recvmsg(nl->sock, &msg, 0);
if(len < 0 && (errno == EAGAIN || errno == EINTR)) {
int rc;
rc = wait_for_fd(0, nl->sock, 100);
if(rc <= 0) {
if(rc == 0)
errno = EAGAIN;
} else {
len = recvmsg(nl->sock, &msg, 0);
}
}
if(len < 0) {
perror("netlink_read: recvmsg()");
return 2;
} else if(len == 0) {
fprintf(stderr, "netlink_read: EOF\n");
goto socket_error;
} else if(msg.msg_namelen != nl->socklen) {
fprintf(stderr,
"netlink_read: unexpected sender address length (%d)\n",
msg.msg_namelen);
goto socket_error;
} else if(nladdr.nl_pid != 0) {
kdebugf("netlink_read: message not sent by kernel.\n");
return 2;
}
kdebugf("Netlink message: ");
for(nh = (struct nlmsghdr *)buf;
NLMSG_OK(nh, len);
nh = NLMSG_NEXT(nh, len)) {
kdebugf("%s", (nh->nlmsg_flags & NLM_F_MULTI) ? "[multi] " : "");
if(!answer)
done = 1;
if(nl_ignore && nh->nlmsg_pid == nl_ignore->sockaddr.nl_pid) {
kdebugf("(ignore), ");
continue;
} else if(answer && (nh->nlmsg_pid != nl->sockaddr.nl_pid ||
nh->nlmsg_seq != nl->seqno)) {
kdebugf("(wrong seqno %d %d /pid %d %d), ",
nh->nlmsg_seq, nl->seqno,
nh->nlmsg_pid, nl->sockaddr.nl_pid);
continue;
} else if(nh->nlmsg_type == NLMSG_DONE) {
kdebugf("(done)\n");
done = 1;
break;
} else if(nh->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(nh);
if(err->error == 0) {
kdebugf("(ACK)\n");
return 0;
} else {
errno = -err->error;
perror("netlink_read");
errno = -err->error;
return -1;
}
} else if(fn) {
kdebugf("(msg -> \"");
err = fn(nh,data);
kdebugf("\" %d), ", err);
if(err < 0) return err;
interesting = interesting || err;
continue;
}
kdebugf(", ");
}
kdebugf("\n");
if(msg.msg_flags & MSG_TRUNC)
fprintf(stderr, "netlink_read: message truncated\n");
} while (!done);
return interesting;
socket_error:
close(nl->sock);
nl->sock = -1;
errno = EIO;
return -1;
}
static int
netlink_talk(struct nlmsghdr *nh)
{
int rc;
struct sockaddr_nl nladdr;
struct msghdr msg;
struct iovec iov;
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
nladdr.nl_pid = 0;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &nladdr;
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
iov.iov_base = nh;
iov.iov_len = nh->nlmsg_len;
nh->nlmsg_flags |= NLM_F_ACK;
nh->nlmsg_seq = ++nl_command.seqno;
rc = sendmsg(nl_command.sock, &msg, 0);
if(rc < 0 && (errno == EAGAIN || errno == EINTR)) {
rc = wait_for_fd(1, nl_command.sock, 100);
if(rc <= 0) {
if(rc == 0)
errno = EAGAIN;
} else {
rc = sendmsg(nl_command.sock, &msg, 0);
}
}
if(rc < nh->nlmsg_len) {
int saved_errno = errno;
perror("sendmsg");
errno = saved_errno;
return -1;
}
rc = netlink_read(&nl_command, NULL, 1, NULL, NULL); /* ACK */
return rc;
}
static int
netlink_send_dump(int type, void *data, int len) {
struct sockaddr_nl nladdr;
struct msghdr msg;
struct iovec iov[2];
union {
char raw[NLMSG_ALIGN(sizeof(struct nlmsghdr))];
struct nlmsghdr nh;
} buf;
int rc;
/* At least we should send an 'struct rtgenmsg' */
if(data == NULL || len == 0) {
errno = EIO;
return -1;
}
/* And more : using anything else that 'struct rtgenmsg' is currently */
/* ignored by the linux kernel (today: 2.6.21) because NLM_F_MATCH is */
/* not yet implemented */
memset(&nladdr, 0, sizeof(nladdr));
nladdr.nl_family = AF_NETLINK;
memset(&msg, 0, sizeof(msg));
msg.msg_name = &nladdr;
msg.msg_namelen = sizeof(nladdr);
msg.msg_iov = iov;
msg.msg_iovlen = 2;
iov[0].iov_base = buf.raw;
iov[0].iov_len = sizeof(buf.raw);
iov[1].iov_base = data;
iov[1].iov_len = len;
memset(buf.raw, 0, sizeof(buf.raw));
buf.nh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
buf.nh.nlmsg_type = type;
buf.nh.nlmsg_seq = ++nl_command.seqno;
buf.nh.nlmsg_len = NLMSG_LENGTH(len);
rc = sendmsg(nl_command.sock, &msg, 0);
if(rc < buf.nh.nlmsg_len) {
int saved_errno = errno;
perror("sendmsg");
errno = saved_errno;
return -1;
}
return 0;
}
int
kernel_setup(int setup)
{
int rc;
if(setup) {
if(export_table < 0)
export_table = RT_TABLE_MAIN;
if(import_table < 0)
import_table = RT_TABLE_MAIN;
dgram_socket = socket(PF_INET, SOCK_DGRAM, 0);
if(dgram_socket < 0)
return -1;
rc = netlink_socket(&nl_command, 0);
if(rc < 0) {
perror("netlink_socket(0)");
return -1;
}
nl_setup = 1;
old_forwarding = read_proc("/proc/sys/net/ipv6/conf/all/forwarding");
if(old_forwarding < 0) {
perror("Couldn't read forwarding knob.");
return -1;
}
rc = write_proc("/proc/sys/net/ipv6/conf/all/forwarding", 1);
if(rc < 0) {
perror("Couldn't write forwarding knob.");
return -1;
}
old_ipv4_forwarding =
read_proc("/proc/sys/net/ipv4/conf/all/forwarding");
if(old_ipv4_forwarding < 0) {
perror("Couldn't read IPv4 forwarding knob.");
return -1;
}
rc = write_proc("/proc/sys/net/ipv4/conf/all/forwarding", 1);
if(rc < 0) {
perror("Couldn't write IPv4 forwarding knob.");
return -1;
}
old_accept_redirects =
read_proc("/proc/sys/net/ipv6/conf/all/accept_redirects");
if(old_accept_redirects < 0) {
perror("Couldn't read accept_redirects knob.");
return -1;
}
rc = write_proc("/proc/sys/net/ipv6/conf/all/accept_redirects", 0);
if(rc < 0) {
perror("Couldn't write accept_redirects knob.");
return -1;
}
old_rp_filter =
read_proc("/proc/sys/net/ipv4/conf/all/rp_filter");
if(old_rp_filter < 0) {
perror("Couldn't read rp_filter knob.");
return -1;
}
rc = write_proc("/proc/sys/net/ipv4/conf/all/rp_filter", 0);
if(rc < 0) {
perror("Couldn't write rp_filter knob.");
return -1;
}
return 1;
} else {
close(dgram_socket);
dgram_socket = -1;
if(old_forwarding >= 0) {
rc = write_proc("/proc/sys/net/ipv6/conf/all/forwarding",
old_forwarding);
if(rc < 0) {
perror("Couldn't write forwarding knob.\n");
return -1;
}
}
if(old_ipv4_forwarding >= 0) {
rc = write_proc("/proc/sys/net/ipv4/conf/all/forwarding",
old_ipv4_forwarding);
if(rc < 0) {
perror("Couldn't write IPv4 forwarding knob.\n");
return -1;
}
}
if(old_accept_redirects >= 0) {
rc = write_proc("/proc/sys/net/ipv6/conf/all/accept_redirects",
old_accept_redirects);
if(rc < 0) {
perror("Couldn't write accept_redirects knob.\n");
return -1;
}
}
if(old_rp_filter >= 0) {
rc = write_proc("/proc/sys/net/ipv4/conf/all/rp_filter",
old_accept_redirects);
if(rc < 0) {
perror("Couldn't write rp_filter knob.\n");
return -1;
}
}
close(nl_command.sock);
nl_command.sock = -1;
nl_setup = 0;
return 1;
}
}
int
kernel_setup_socket(int setup)
{
int rc;
if(setup) {
rc = netlink_socket(&nl_listen,
RTMGRP_IPV6_ROUTE | RTMGRP_IPV4_ROUTE
| RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR);
if(rc < 0) {
perror("netlink_socket(RTMGRP_ROUTE | RTMGRP_LINK | RTMGRP_IFADDR)");
kernel_socket = -1;
return -1;
}
kernel_socket = nl_listen.sock;
return 1;
} else {
close(nl_listen.sock);
nl_listen.sock = -1;
kernel_socket = -1;
return 1;
}
}
int
kernel_setup_interface(int setup, const char *ifname, int ifindex)
{
return 1;
}
int
kernel_interface_operational(const char *ifname, int ifindex)
{
struct ifreq req;
int rc;
int flags = link_detect ? (IFF_UP | IFF_RUNNING) : IFF_UP;
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
rc = ioctl(dgram_socket, SIOCGIFFLAGS, &req);
if(rc < 0)
return -1;
return ((req.ifr_flags & flags) == flags);
}
int
kernel_interface_ipv4(const char *ifname, int ifindex, unsigned char *addr_r)
{
struct ifreq req;
int rc;
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
req.ifr_addr.sa_family = AF_INET;
rc = ioctl(dgram_socket, SIOCGIFADDR, &req);
if(rc < 0)
return -1;
memcpy(addr_r, &((struct sockaddr_in*)&req.ifr_addr)->sin_addr, 4);
return 1;
}
int
kernel_interface_mtu(const char *ifname, int ifindex)
{
struct ifreq req;
int rc;
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
rc = ioctl(dgram_socket, SIOCGIFMTU, &req);
if(rc < 0)
return -1;
return req.ifr_mtu;
}
static int
isbridge(const char *ifname, int ifindex)
{
char buf[256];
int rc, i;
unsigned long args[3];
int indices[256];
rc = snprintf(buf, 256, "/sys/class/net/%s", ifname);
if(rc < 0 || rc >= 256)
goto fallback;
if(access(buf, R_OK) < 0)
goto fallback;
rc = snprintf(buf, 256, "/sys/class/net/%s/bridge", ifname);
if(rc < 0 || rc >= 256)
goto fallback;
if(access(buf, F_OK) >= 0)
return 1;
else if(errno == ENOENT)
return 0;
fallback:
args[0] = BRCTL_GET_BRIDGES;
args[1] = (unsigned long)indices;
args[2] = 256;
rc = ioctl(dgram_socket, SIOCGIFBR, args);
if(rc < 0) {
if(errno == ENOPKG)
return 0;
else
return -1;
}
for(i = 0; i < rc; i++) {
if(indices[i] == ifindex)
return 1;
}
return 0;
}
int
kernel_interface_wireless(const char *ifname, int ifindex)
{
#ifndef SIOCGIWNAME
#define SIOCGIWNAME 0x8B01
#endif
struct ifreq req;
int rc;
if(isbridge(ifname, ifindex) != 0) {
/* Give up. */
return -1;
}
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
rc = ioctl(dgram_socket, SIOCGIWNAME, &req);
if(rc < 0) {
if(errno == EOPNOTSUPP || errno == EINVAL)
rc = 0;
else {
perror("ioctl(SIOCGIWNAME)");
rc = -1;
}
} else {
rc = 1;
}
return rc;
}
int
kernel_route(int operation, const unsigned char *dest, unsigned short plen,
const unsigned char *gate, int ifindex, unsigned int metric,
const unsigned char *newgate, int newifindex,
unsigned int newmetric)
{
union { char raw[1024]; struct nlmsghdr nh; } buf;
struct rtmsg *rtm;
struct rtattr *rta;
int len = sizeof(buf.raw);
int rc, ipv4;
if(!nl_setup) {
fprintf(stderr,"kernel_route: netlink not initialized.\n");
errno = EIO;
return -1;
}
/* if the socket has been closed after an IO error, */
/* we try to re-open it. */
if(nl_command.sock < 0) {
rc = netlink_socket(&nl_command, 0);
if(rc < 0) {
int olderrno = errno;
perror("kernel_route: netlink_socket()");
errno = olderrno;
return -1;
}
}
/* Check that the protocol family is consistent. */
if(plen >= 96 && v4mapped(dest)) {
if(!v4mapped(gate)) {
errno = EINVAL;
return -1;
}
} else {
if(v4mapped(gate)) {
errno = EINVAL;
return -1;
}
}
ipv4 = v4mapped(gate);
if(operation == ROUTE_MODIFY) {
if(newmetric == metric && memcmp(newgate, gate, 16) == 0 &&
newifindex == ifindex)
return 0;
/* It is better to add the new route before removing the old
one, to avoid losing packets. However, this only appears
to work if the metrics are different. */
if(newmetric != metric) {
rc = kernel_route(ROUTE_ADD, dest, plen,
newgate, newifindex, newmetric,
NULL, 0, 0);
if(rc < 0 && errno != EEXIST)
return rc;
rc = kernel_route(ROUTE_FLUSH, dest, plen,
gate, ifindex, metric,
NULL, 0, 0);
if(rc < 0 && (errno == ENOENT || errno == ESRCH))
rc = 1;
} else {
rc = kernel_route(ROUTE_FLUSH, dest, plen,
gate, ifindex, metric,
NULL, 0, 0);
rc = kernel_route(ROUTE_ADD, dest, plen,
newgate, newifindex, newmetric,
NULL, 0, 0);
if(rc < 0 && errno == EEXIST)
rc = 1;
}
return rc;
}
kdebugf("kernel_route: %s %s/%d metric %d dev %d nexthop %s\n",
operation == ROUTE_ADD ? "add" :
operation == ROUTE_FLUSH ? "flush" : "???",
format_address(dest), plen, metric, ifindex,
format_address(gate));
/* Unreachable default routes cause all sort of weird interactions;
ignore them. */
if(metric >= KERNEL_INFINITY && (plen == 0 || (ipv4 && plen == 96)))
return 0;
memset(buf.raw, 0, sizeof(buf.raw));
if(operation == ROUTE_ADD) {
buf.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL;
buf.nh.nlmsg_type = RTM_NEWROUTE;
} else {
buf.nh.nlmsg_flags = NLM_F_REQUEST;
buf.nh.nlmsg_type = RTM_DELROUTE;
}
rtm = NLMSG_DATA(&buf.nh);
rtm->rtm_family = ipv4 ? AF_INET : AF_INET6;
rtm->rtm_dst_len = ipv4 ? plen - 96 : plen;
rtm->rtm_table = export_table;
rtm->rtm_scope = RT_SCOPE_UNIVERSE;
if(metric < KERNEL_INFINITY)
rtm->rtm_type = RTN_UNICAST;
else
rtm->rtm_type = RTN_UNREACHABLE;
rtm->rtm_protocol = RTPROT_BABEL;
rtm->rtm_flags |= RTNH_F_ONLINK;
rta = RTM_RTA(rtm);
if(ipv4) {
rta = RTA_NEXT(rta, len);
rta->rta_len = RTA_LENGTH(sizeof(struct in_addr));
rta->rta_type = RTA_DST;
memcpy(RTA_DATA(rta), dest + 12, sizeof(struct in_addr));
} else {
rta = RTA_NEXT(rta, len);
rta->rta_len = RTA_LENGTH(sizeof(struct in6_addr));
rta->rta_type = RTA_DST;
memcpy(RTA_DATA(rta), dest, sizeof(struct in6_addr));
}
rta = RTA_NEXT(rta, len);
rta->rta_len = RTA_LENGTH(sizeof(int));
rta->rta_type = RTA_PRIORITY;
if(metric < KERNEL_INFINITY) {
*(int*)RTA_DATA(rta) = metric;
rta = RTA_NEXT(rta, len);
rta->rta_len = RTA_LENGTH(sizeof(int));
rta->rta_type = RTA_OIF;
*(int*)RTA_DATA(rta) = ifindex;
if(ipv4) {
rta = RTA_NEXT(rta, len);
rta->rta_len = RTA_LENGTH(sizeof(struct in_addr));
rta->rta_type = RTA_GATEWAY;
memcpy(RTA_DATA(rta), gate + 12, sizeof(struct in_addr));
} else {
rta = RTA_NEXT(rta, len);
rta->rta_len = RTA_LENGTH(sizeof(struct in6_addr));
rta->rta_type = RTA_GATEWAY;
memcpy(RTA_DATA(rta), gate, sizeof(struct in6_addr));
}
} else {
*(int*)RTA_DATA(rta) = -1;
}
buf.nh.nlmsg_len = (char*)rta + rta->rta_len - buf.raw;
return netlink_talk(&buf.nh);
}
static int
parse_kernel_route_rta(struct rtmsg *rtm, int len, struct kernel_route *route)
{
int table = rtm->rtm_table;
struct rtattr *rta= RTM_RTA(rtm);;
len -= NLMSG_ALIGN(sizeof(*rtm));
memset(&route->prefix, 0, sizeof(struct in6_addr));
memset(&route->gw, 0, sizeof(struct in6_addr));
route->plen = rtm->rtm_dst_len;
if(rtm->rtm_family == AF_INET) {
const unsigned char zeroes[4] = {0, 0, 0, 0};
v4tov6(route->prefix, zeroes);
route->plen += 96;
}
route->metric = 0;
route->ifindex = 0;
route->proto = rtm->rtm_protocol;
#define COPY_ADDR(d, s) \
do { \
if(rtm->rtm_family == AF_INET6) \
memcpy(d, s, 16); \
else if(rtm->rtm_family == AF_INET) \
v4tov6(d, s); \
else \
return -1; \
} while(0)
while(RTA_OK(rta, len)) {
switch (rta->rta_type) {
case RTA_DST:
COPY_ADDR(route->prefix, RTA_DATA(rta));
break;
case RTA_GATEWAY:
COPY_ADDR(route->gw, RTA_DATA(rta));
break;
case RTA_OIF:
route->ifindex = *(int*)RTA_DATA(rta);
break;
case RTA_PRIORITY:
route->metric = *(int*)RTA_DATA(rta);
if(route->metric < 0 || route->metric > KERNEL_INFINITY)
route->metric = KERNEL_INFINITY;
break;
case RTA_TABLE:
table = *(int*)RTA_DATA(rta);
break;
default:
break;
}
rta = RTA_NEXT(rta, len);
}
#undef COPY_ADDR
if(table != import_table)
return -1;
return 0;
}
static void
print_kernel_route(int add, int protocol, int type,
struct kernel_route *route)
{
char ifname[IFNAMSIZ];
char addr_prefix[INET6_ADDRSTRLEN];
char addr_gw[INET6_ADDRSTRLEN];
if(!inet_ntop(AF_INET6, route->prefix,
addr_prefix, sizeof(addr_prefix)) ||
!inet_ntop(AF_INET6,route->gw, addr_gw, sizeof(addr_gw)) ||
!if_indextoname(route->ifindex, ifname)) {
kdebugf("Couldn't format kernel route for printing.");
return;
}
kdebugf("%s kernel route: dest: %s/%d gw: %s metric: %d if: %s "
"(proto: %d, type: %d)",
add == RTM_NEWROUTE ? "Add" : "Delete",
addr_prefix, route->plen, addr_gw, route->metric, ifname,
protocol, type);
}
static int
filter_kernel_routes(struct nlmsghdr *nh, void *data)
{
int rc;
struct kernel_route *current_route;
struct kernel_route route;
int maxroutes = 0;
struct kernel_route *routes = NULL;
int *found = NULL;
int len;
struct rtmsg *rtm;
if(data) {
void **args = (void**)data;
maxroutes = *(int*)args[0];
routes = (struct kernel_route *)args[1];
found = (int*)args[2];
}
len = nh->nlmsg_len;
if(data && *found >= maxroutes)
return 0;
if(nh->nlmsg_type != RTM_NEWROUTE &&
(data || nh->nlmsg_type != RTM_DELROUTE))
return 0;
rtm = (struct rtmsg*)NLMSG_DATA(nh);
len -= NLMSG_LENGTH(0);
if(rtm->rtm_protocol == RTPROT_BOOT || rtm->rtm_protocol == RTPROT_BABEL)
return 0;
if(rtm->rtm_src_len != 0)
return 0;
if(data)
current_route = &routes[*found];
else
current_route = &route;
rc = parse_kernel_route_rta(rtm, len, current_route);
if(rc < 0)
return 0;
if(martian_prefix(current_route->prefix, current_route->plen))
return 0;
/* Ignore default unreachable routes; no idea where they come from. */
if(current_route->plen == 0 && current_route->metric >= KERNEL_INFINITY)
return 0;
if(debug >= 2) {
if(rc >= 0) {
print_kernel_route(nh->nlmsg_type, rtm->rtm_protocol,
rtm->rtm_type, current_route);
}
}
if (data) *found = (*found)+1;
return 1;
}
/* This function should not return routes installed by us. */
int
kernel_routes(struct kernel_route *routes, int maxroutes)
{
int i, rc;
int maxr = maxroutes;
int found = 0;
void *data[3] = { &maxr, routes, &found };
int families[2] = { AF_INET6, AF_INET };
struct rtgenmsg g;
if(!nl_setup) {
fprintf(stderr,"kernel_routes: netlink not initialized.\n");
errno = EIO;
return -1;
}
if(nl_command.sock < 0) {
rc = netlink_socket(&nl_command, 0);
if(rc < 0) {
perror("kernel_routes: netlink_socket()");
return -1;
}
}
for(i = 0; i < 2; i++) {
memset(&g, 0, sizeof(g));
g.rtgen_family = families[i];
rc = netlink_send_dump(RTM_GETROUTE, &g, sizeof(g));
if(rc < 0)
return -1;
rc = netlink_read(&nl_command, NULL, 1,
filter_kernel_routes, (void *)data);
if(rc < 0)
return -1;
}
return found;
}
char *
parse_ifname_rta(struct ifinfomsg *info, int len)
{
struct rtattr *rta = IFLA_RTA(info);
char *ifname = NULL;
len -= NLMSG_ALIGN(sizeof(*info));
while(RTA_OK(rta, len)) {
switch (rta->rta_type) {
case IFLA_IFNAME:
ifname = RTA_DATA(rta);
break;
default:
break;
}
rta = RTA_NEXT(rta, len);
}
return ifname;
}
int
parse_addr_rta(struct ifaddrmsg *addr, int len, struct in6_addr *res)
{
struct rtattr *rta;
len -= NLMSG_ALIGN(sizeof(*addr));
rta = IFA_RTA(addr);
while (RTA_OK(rta, len)) {
switch(rta->rta_type) {
case IFA_LOCAL:
case IFA_ADDRESS:
switch (addr->ifa_family) {
case AF_INET:
if (res)
v4tov6(res->s6_addr, RTA_DATA(rta));
break;
case AF_INET6:
if (res)
memcpy(res->s6_addr, RTA_DATA(rta), 16);
break;
default:
kdebugf("ifaddr: unexpected address family %d\n", addr->ifa_family);
return -1;
break;
}
break;
default:
break;
}
rta = RTA_NEXT(rta, len);
}
return 0;
}
int
filter_link(struct nlmsghdr *nh, void *data)
{
struct ifinfomsg *info;
int len;
int ifindex;
char *ifname;
unsigned int ifflags;
struct network *net;
len = nh->nlmsg_len;
if(nh->nlmsg_type != RTM_NEWLINK && nh->nlmsg_type != RTM_DELLINK)
return 0;
info = (struct ifinfomsg*)NLMSG_DATA(nh);
len -= NLMSG_LENGTH(0);
ifindex = info->ifi_index;
ifflags = info->ifi_flags;
ifname = parse_ifname_rta(info, len);
if(ifname == NULL)
return 0;
kdebugf("filter_interfaces: link change on if %s(%d): 0x%x\n",
ifname, ifindex, (unsigned)ifflags);
FOR_ALL_NETS(net) {
if (strcmp(net->ifname, ifname) == 0)
return 1;
}
return 0;
}
int
filter_addresses(struct nlmsghdr *nh, void *data)
{
int rc;
int maxroutes = 0;
struct kernel_route *routes = NULL;
struct in6_addr addr;
int *found = NULL;
int len;
struct ifaddrmsg *ifa;
char ifname[IFNAMSIZ];
if (data) {
void **args = (void **)data;
maxroutes = *(int *)args[0];
routes = (struct kernel_route*)args[1];
found = (int *)args[2];
}
len = nh->nlmsg_len;
if (data && *found >= maxroutes)
return 0;
if (nh->nlmsg_type != RTM_NEWADDR &&
(data || nh->nlmsg_type != RTM_DELADDR))
return 0;
ifa = (struct ifaddrmsg *)NLMSG_DATA(nh);
len -= NLMSG_LENGTH(0);
rc = parse_addr_rta(ifa, len, &addr);
if (rc < 0)
return 0;
if (IN6_IS_ADDR_LINKLOCAL(&addr))
return 0;
kdebugf("found address on interface %s(%d): %s\n",
if_indextoname(ifa->ifa_index, ifname), ifa->ifa_index,
format_address(addr.s6_addr));
if (data) {
struct kernel_route *route = &routes[*found];
memcpy(route->prefix, addr.s6_addr, 16);
route->plen = 128;
route->metric = 0;
route->ifindex = ifa->ifa_index;
route->proto = RTPROT_BABEL_LOCAL;
memset(route->gw, 0, 16);
*found = (*found)+1;
}
return 1;
}
int
filter_netlink(struct nlmsghdr *nh, void *data)
{
int rc;
int *changed = data;
switch (nh->nlmsg_type) {
case RTM_NEWROUTE:
case RTM_DELROUTE:
rc = filter_kernel_routes(nh, NULL);
if (changed && rc > 0)
*changed |= CHANGE_ROUTE;
return rc;
case RTM_NEWLINK:
case RTM_DELLINK:
rc = filter_link(nh, NULL);
if (changed && rc > 0)
*changed |= CHANGE_LINK;
return rc;
case RTM_NEWADDR:
case RTM_DELADDR:
rc = filter_addresses(nh, NULL);
if (changed && rc > 0)
*changed |= CHANGE_ADDR;
return rc;
default:
kdebugf("filter_netlink: unexpected message type %d\n",
nh->nlmsg_type);
break;
}
return 0;
}
int
kernel_addresses(struct kernel_route *routes, int maxroutes)
{
int maxr = maxroutes;
int found = 0;
void *data[] = { &maxr, routes, &found, NULL};
struct rtgenmsg g;
int rc;
if (!nl_setup) {
fprintf(stderr, "kernel_addresses: netlink not initialized.\n");
errno = ENOSYS;
return -1;
}
if (nl_command.sock < 0) {
rc = netlink_socket(&nl_command, 0);
if (rc < 0) {
int save = errno;
perror("kernel_addresses: netlink_socket()");
errno = save;
return -1;
}
}
memset(&g, 0, sizeof(g));
g.rtgen_family = AF_UNSPEC;
rc = netlink_send_dump(RTM_GETADDR, &g, sizeof(g));
if (rc < 0)
return -1;
rc = netlink_read(&nl_command, NULL, 1, filter_addresses, (void*)data);
if (rc < 0)
return -1;
return found;
}
int
kernel_callback(int (*fn)(int, void*), void *closure)
{
int rc;
int changed = 0;
kdebugf("\nReceived changes in kernel tables.\n");
if(nl_listen.sock < 0) {
rc = kernel_setup_socket(1);
if(rc < 0) {
perror("kernel_callback: kernel_setup_socket(1)");
return -1;
}
}
rc = netlink_read(&nl_listen, &nl_command, 0, filter_netlink, &changed);
if(rc < 0 && nl_listen.sock < 0)
kernel_setup_socket(1);
/* if netlink return 0 (found something interesting) */
/* or -1 (i.e. IO error), we call... back ! */
if(rc)
return fn(changed, closure);
return 0;
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/kernel_socket.c 0000664 0000000 0000000 00000037127 11073442770 0022772 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007 by Grégoire Henry
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "babel.h"
#include "neighbour.h"
#include "kernel.h"
#include "util.h"
int export_table = -1, import_table = -1;
/* KAME said : "Following two macros are highly depending on KAME Release" */
#define IN6_LINKLOCAL_IFINDEX(a) ((a).s6_addr[2] << 8 | (a).s6_addr[3])
#define SET_IN6_LINKLOCAL_IFINDEX(a, i) \
do { \
(a).s6_addr[2] = ((i) >> 8) & 0xff; \
(a).s6_addr[3] = (i) & 0xff; \
} while (0)
#define ROUNDUP(a) \
((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
static int old_forwarding = -1;
static int old_accept_redirects = -1;
static int ifindex_lo = -1;
static int seq;
static int get_sysctl_int(char *name)
{
int old;
size_t len = sizeof (old);
if (sysctlbyname(name, &old, &len, NULL, 0) < 0)
return -1;
return old;
}
static int set_sysctl_int(char *name, int new)
{
int old;
size_t len = sizeof (old);
if (sysctlbyname(name, &old, &len, &new, sizeof (new)) < 0)
return -1;
return old;
}
int
mask2len(const struct in6_addr *addr)
{
int i = 0, j;
const u_char *p = (const u_char *)addr;
for(j = 0; j < 16; j++, p++) {
if(*p != 0xff)
break;
i += 8;
}
if(j < 16) {
switch(*p) {
#define MASKLEN(m, l) case m: do { i += l; break; } while (0)
MASKLEN(0xfe, 7); break;
MASKLEN(0xfc, 6); break;
MASKLEN(0xf8, 5); break;
MASKLEN(0xf0, 4); break;
MASKLEN(0xe0, 3); break;
MASKLEN(0xc0, 2); break;
MASKLEN(0x80, 1); break;
#undef MASKLEN
}
}
return i;
}
void
plen2mask(int n, struct in6_addr *dest)
{
unsigned char *p;
int i;
static const int pl2m[9] = {
0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff
};
memset(dest, 0, sizeof(struct in6_addr));
p = (u_char *)dest;
for (i = 0; i < 16; i++, p++, n -= 8) {
if (n >= 8) {
*p = 0xff;
continue;
}
*p = pl2m[n];
break;
}
return;
}
int
kernel_setup(int setup)
{
int rc;
if(setup) {
seq = time(NULL);
old_forwarding = get_sysctl_int("net.inet6.ip6.forwarding");
if(old_forwarding < 0) {
perror("Couldn't read forwarding knob.");
return -1;
}
rc = set_sysctl_int("net.inet6.ip6.forwarding",1);
if(rc < 0) {
perror("Couldn't write forwarding knob.");
return -1;
}
old_accept_redirects = get_sysctl_int("net.inet6.icmp6.rediraccept");
if(old_accept_redirects < 0) {
perror("Couldn't read accept_redirects knob.");
return -1;
}
rc = set_sysctl_int("net.inet6.icmp6.rediraccept",0);
if(rc < 0) {
perror("Couldn't write accept_redirects knob.");
return -1;
}
return 1;
} else {
if(old_forwarding >= 0) {
rc = set_sysctl_int("net.inet6.ip6.forwarding",old_forwarding);
if(rc < 0) {
perror("Couldn't write accept_redirects knob.\n");
return -1;
}
}
if(old_accept_redirects >= 0) {
rc = set_sysctl_int("net.inet6.icmp6.rediraccept",
old_accept_redirects);
if(rc < 0) {
perror("Couldn't write accept_redirects knob.\n");
return -1;
}
}
return 1;
}
}
int
kernel_setup_socket(int setup)
{
int rc;
int zero = 0;
if(setup) {
if(kernel_socket < 0) {
kernel_socket = socket(PF_ROUTE, SOCK_RAW, AF_INET6);
if(kernel_socket < 0)
return -1;
}
rc = setsockopt(kernel_socket, SOL_SOCKET, SO_USELOOPBACK,
&zero, sizeof(zero));
if(rc < 0)
goto error;
return 1;
} else {
close(kernel_socket);
kernel_socket = -1;
return 1;
}
error: {
int savederrno = errno;
perror("setsockopt(kernel_socket)");
close(kernel_socket);
errno = savederrno;
kernel_socket = -1;
return -1;
}
}
int
kernel_setup_interface(int setup, const char *ifname, int ifindex)
{
return 1;
}
int
kernel_interface_operational(const char *ifname, int ifindex)
{
struct ifreq req;
int s, rc;
int flags = link_detect ? (IFF_UP | IFF_RUNNING) : IFF_UP;
s = socket(PF_INET, SOCK_DGRAM, 0);
if(s < 0)
return -1;
memset(&req, 0, sizeof(req));
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
rc = ioctl(s, SIOCGIFFLAGS, &req);
close(s);
if(rc < 0)
return -1;
return ((req.ifr_flags & flags) == flags);
}
int
kernel_interface_ipv4(const char *ifname, int ifindex, unsigned char *addr_r)
{
struct ifreq req;
int s, rc;
s = socket(PF_INET, SOCK_DGRAM, 0);
if(s < 0)
return -1;
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
req.ifr_addr.sa_family = AF_INET;
rc = ioctl(s, SIOCGIFADDR, &req);
close(s);
if(rc < 0) {
return -1;
}
memcpy(addr_r, &((struct sockaddr_in*)&req.ifr_addr)->sin_addr, 4);
return 1;
}
int
kernel_interface_mtu(const char *ifname, int ifindex)
{
struct ifreq req;
int s, rc;
s = socket(PF_INET, SOCK_DGRAM, 0);
if(s < 0)
return -1;
memset(&req, 0, sizeof(req));
strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
rc = ioctl(s, SIOCGIFMTU, &req);
if(rc < 0) {
close(s);
return -1;
}
return req.ifr_mtu;
}
int
kernel_interface_wireless(const char *ifname, int ifindex)
{
return -1;
}
int
kernel_route(int operation, const unsigned char *dest, unsigned short plen,
const unsigned char *gate, int ifindex, unsigned int metric,
const unsigned char *newgate, int newifindex,
unsigned int newmetric)
{
unsigned char msg[512];
struct rt_msghdr *rtm;
struct sockaddr_in6 *sin6;
int rc, len;
char local[1][1][16] = IN6ADDR_LOOPBACK_INIT;
/* Check that the protocol family is consistent. */
if(plen >= 96 && v4mapped(dest)) {
if(!v4mapped(gate)) {
errno = EINVAL;
return -1;
}
} else {
if(v4mapped(gate)) {
errno = EINVAL;
return -1;
}
}
if(v4mapped(gate)) {
/* Not implemented yet. */
errno = ENOSYS;
return -1;
}
if(operation == ROUTE_MODIFY && newmetric == metric &&
memcmp(newgate, gate, 16) == 0 && newifindex == ifindex)
return 0;
if(operation == ROUTE_MODIFY) {
metric = newmetric;
gate = newgate;
ifindex = newifindex;
}
kdebugf("kernel_route: %s %s/%d metric %d dev %d nexthop %s\n",
operation == ROUTE_ADD ? "add" :
operation == ROUTE_FLUSH ? "flush" : "change",
format_address(dest), plen, metric, ifindex,
format_address(gate));
if(kernel_socket < 0) kernel_setup_socket(1);
memset(&msg, 0, sizeof(msg));
rtm = (struct rt_msghdr *)msg;
rtm->rtm_version = RTM_VERSION;
switch(operation) {
case ROUTE_FLUSH:
rtm->rtm_type = RTM_DELETE; break;
case ROUTE_ADD:
rtm->rtm_type = RTM_ADD; break;
case ROUTE_MODIFY:
rtm->rtm_type = RTM_CHANGE; break;
default:
return -1;
};
rtm->rtm_index = ifindex;
rtm->rtm_flags = RTF_UP | RTF_PROTO2;
if(plen == 128) rtm->rtm_flags |= RTF_HOST;
/* if(memcmp(nexthop->id, dest, 16) == 0) { */
/* rtm -> rtm_flags |= RTF_LLINFO; */
/* rtm -> rtm_flags |= RTF_CLONING; */
/* } else { */
rtm->rtm_flags |= RTF_GATEWAY;
/* } */
if(metric == KERNEL_INFINITY) {
rtm->rtm_flags |= RTF_BLACKHOLE;
if(ifindex_lo < 0) {
ifindex_lo = if_nametoindex("lo0");
if(ifindex_lo <= 0)
return -1;
}
rtm->rtm_index = ifindex_lo;
}
rtm->rtm_seq = ++seq;
rtm->rtm_addrs = RTA_DST | RTA_GATEWAY;
if(!(operation == ROUTE_MODIFY && plen == 128)) {
rtm->rtm_addrs |= RTA_NETMASK;
}
rtm->rtm_rmx.rmx_hopcount = metric;
rtm->rtm_inits = RTV_HOPCOUNT;
sin6 = (struct sockaddr_in6 *)&msg[sizeof(struct rt_msghdr)];
/* Destination */
sin6->sin6_len = sizeof(struct sockaddr_in6);
sin6->sin6_family = AF_INET6;
sin6->sin6_addr = *((struct in6_addr *)dest);
sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
/* Gateway */
sin6->sin6_len = sizeof(struct sockaddr_in6);
sin6->sin6_family = AF_INET6;
if (metric == KERNEL_INFINITY)
sin6->sin6_addr = *((struct in6_addr *)*local);
else
sin6->sin6_addr = *((struct in6_addr *)gate);
if(IN6_IS_ADDR_LINKLOCAL (&sin6->sin6_addr))
SET_IN6_LINKLOCAL_IFINDEX (sin6->sin6_addr, ifindex);
sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
/* Netmask */
if((rtm->rtm_addrs | RTA_NETMASK) != 0) {
sin6->sin6_len = sizeof(struct sockaddr_in6);
sin6->sin6_family = AF_INET6;
plen2mask(plen, &sin6->sin6_addr);
sin6 = (struct sockaddr_in6 *)((char *)sin6 + ROUNDUP(sin6->sin6_len));
}
len = (char *)sin6 - (char *)msg;
rtm->rtm_msglen = len;
rc = write(kernel_socket, msg, rtm->rtm_msglen);
if (rc < rtm->rtm_msglen)
return -1;
return 1;
}
static void
print_kernel_route(int add, struct kernel_route *route)
{
char ifname[IFNAMSIZ];
char addr_prefix[INET6_ADDRSTRLEN];
char addr_gw[INET6_ADDRSTRLEN];
if(!inet_ntop(AF_INET6, route->prefix,
addr_prefix, sizeof(addr_prefix)) ||
!inet_ntop(AF_INET6,route->gw, addr_gw, sizeof(addr_gw)) ||
!if_indextoname(route->ifindex, ifname)) {
fprintf(stderr,"Couldn't format kernel route for printing.");
// return;
}
fprintf(stderr,
"%s kernel route: dest: %s/%d gw: %s metric: %d if: %s(%d) \n",
add == RTM_ADD ? "Add" :
add == RTM_DELETE ? "Delete" : "Change",
addr_prefix, route->plen, addr_gw, route->metric, ifname,
route->ifindex
);
}
static int
parse_kernel_route(const struct rt_msghdr *rtm, struct kernel_route *route)
{
void *rta = (void*)rtm + sizeof(struct rt_msghdr);
struct sockaddr_in6 *sin6;
char addr[INET6_ADDRSTRLEN];
memset(route, 0, sizeof(*route));
route->metric = rtm->rtm_rmx.rmx_hopcount;
route->ifindex = rtm->rtm_index;
if(!rtm->rtm_addrs && RTA_DST)
return -1;
sin6 = (struct sockaddr_in6 *)rta;
if(IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)
|| IN6_IS_ADDR_MC_LINKLOCAL(&sin6->sin6_addr))
return -1;
if((rtm->rtm_flags & RTF_PROTO2) != 0)
return -1;
memcpy(&route->prefix, &sin6->sin6_addr, 16);
rta += ROUNDUP(sizeof(struct sockaddr_in6));
if(!rtm->rtm_addrs && RTA_GATEWAY)
return -1;
sin6 = (struct sockaddr_in6 *)rta;
if(IN6_IS_ADDR_LINKLOCAL (&sin6->sin6_addr)) {
route->ifindex = IN6_LINKLOCAL_IFINDEX(sin6->sin6_addr);
SET_IN6_LINKLOCAL_IFINDEX(sin6->sin6_addr, 0);
}
memcpy(&route->gw, &sin6->sin6_addr, 16);
rta += ROUNDUP(sizeof(struct sockaddr_in6));
if(!rtm->rtm_addrs && RTA_NETMASK) {
route->plen = 0;
} else {
sin6 = (struct sockaddr_in6 *)rta;
route->plen = mask2len(&sin6->sin6_addr);
inet_ntop(AF_INET6, &sin6->sin6_addr, addr, sizeof(addr));
rta += ROUNDUP(sizeof(struct sockaddr_in6));
}
if (rtm->rtm_flags & RTF_HOST)
route->plen = 128;
if(ifindex_lo < 0) {
ifindex_lo = if_nametoindex("lo0");
if(ifindex_lo <= 0)
return -1;
}
if(route->ifindex == ifindex_lo)
return -1;
return 0;
}
int
kernel_routes(struct kernel_route *routes, int maxroutes)
{
int mib[6];
char *buf, *p;
size_t len;
struct rt_msghdr *rtm;
int rc, i;
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0;
mib[3] = AF_INET6; /* Address family */
mib[4] = NET_RT_DUMP; /* Dump the kernel routing table */
mib[5] = 0; /* No flags */
rc = sysctl(mib, 6, NULL, &len, NULL, 0);
if (rc < 0) {
perror("kernel_routes(len)");
return -1;
}
buf = malloc(len);
if(!buf) {
perror("kernel_routes(malloc)");
return -1;
}
rc = sysctl(mib, 6, buf, &len, NULL, 0);
if (rc < 0) {
perror("kernel_routes(dump)");
goto fail;
}
i = 0;
p = buf;
while(p < buf + len && i < maxroutes) {
rtm = (struct rt_msghdr*)p;
rc = parse_kernel_route(rtm, &routes[i]);
if(rc)
goto cont;
if(debug > 2)
print_kernel_route(1,&routes[i]);
i++;
cont:
p += rtm->rtm_msglen;
}
free(buf);
return i;
fail:
free(buf);
return -1;
}
static int
socket_read(int sock)
{
int rc;
struct {
struct rt_msghdr rtm;
struct sockaddr_storage addr[RTAX_MAX];
} buf;
rc = read(sock, &buf, sizeof(buf));
if(rc <= 0) {
perror("kernel_callback(read)");
return 0;
}
if(buf.rtm.rtm_msglen != rc) {
kdebugf("kernel_callback(length)\n");
return -1;
}
if(buf.rtm.rtm_type == RTM_ADD ||
buf.rtm.rtm_type == RTM_DELETE ||
buf.rtm.rtm_type == RTM_CHANGE) {
struct kernel_route route;
if(buf.rtm.rtm_errno)
return 0;
rc = parse_kernel_route(&buf.rtm, &route);
if(rc < 0)
return 0;
if(debug > 2)
print_kernel_route(1,&route);
return 1;
}
return 0;
}
int
kernel_addresses(struct kernel_route *routes, int maxroutes)
{
errno = ENOSYS;
return -1;
}
int
kernel_callback(int (*fn)(int, void*), void *closure)
{
int rc;
if(kernel_socket < 0) kernel_setup_socket(1);
kdebugf("Reading kernel table modification.");
rc = socket_read(kernel_socket);
if(rc)
return fn(~0, closure);
return 0;
}
/* Local Variables: */
/* c-basic-offset: 4 */
/* indent-tabs-mode: nil */
/* End: */
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/local.c 0000664 0000000 0000000 00000013674 11073442770 0021235 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include "babel.h"
#include "network.h"
#include "source.h"
#include "neighbour.h"
#include "xroute.h"
#include "route.h"
#include "util.h"
#include "local.h"
#ifdef NO_LOCAL_INTERFACE
int dummy;
#else
int
local_read(int s)
{
int rc;
char buf[500];
/* Ignore anything that comes in, except for EOF */
rc = read(s, buf, 500);
if(rc <= 0)
return rc;
return 1;
}
static int
write_timeout(int fd, const void *buf, int len)
{
int n = 0, rc = 0;
const char *b = buf;
while(n < len) {
rc = write(fd, b + n, len - n);
if(rc < 0) {
if(errno == EAGAIN || errno == EINTR) {
rc = wait_for_fd(1, fd, 100);
if(rc > 0) {
rc = write(fd, b + n, len - n);
}
}
}
if(rc > 0)
n += rc;
else
break;
}
if(n >= len)
return 1;
else {
if(rc >= 0)
errno = EAGAIN;
return -1;
}
}
void
local_notify_self()
{
char buf[512];
int rc;
if(local_socket < 0)
return;
rc = snprintf(buf, 512, "add self alamakota id %s\n",
format_address(myid));
if(rc < 0 || rc >= 512)
goto fail;
rc = write_timeout(local_socket, buf, rc);
if(rc < 0)
goto fail;
return;
fail:
shutdown(local_socket, 1);
return;
}
static char *
local_kind(int kind)
{
switch(kind) {
case LOCAL_FLUSH: return "flush";
case LOCAL_CHANGE: return "change";
case LOCAL_ADD: return "add";
default: return "???";
}
}
void
local_notify_neighbour(struct neighbour *neigh, int kind)
{
char buf[512];
int rc;
if(local_socket < 0)
return;
rc = snprintf(buf, 512,
"%s neighbour %lx id %s address %s "
"if %s reach %04x rxcost %d txcost %d cost %d\n",
local_kind(kind),
/* Neighbours never move aroundin memory , so we can use the
address as a unique identifier. */
(unsigned long int)neigh,
format_address(neigh->id),
format_address(neigh->address),
neigh->network->ifname,
neigh->reach,
neighbour_rxcost(neigh),
neighbour_txcost(neigh),
neighbour_cost(neigh));
if(rc < 0 || rc >= 512)
goto fail;
rc = write_timeout(local_socket, buf, rc);
if(rc < 0)
goto fail;
return;
fail:
shutdown(local_socket, 1);
return;
}
void
local_notify_xroute(struct xroute *xroute, int kind)
{
char buf[512];
int rc;
if(local_socket < 0)
return;
rc = snprintf(buf, 512, "%s xroute %s prefix %s metric %d\n",
local_kind(kind),
format_prefix(xroute->prefix, xroute->plen),
format_prefix(xroute->prefix, xroute->plen),
xroute->metric);
if(rc < 0 || rc >= 512)
goto fail;
rc = write_timeout(local_socket, buf, rc);
if(rc < 0)
goto fail;
return;
fail:
shutdown(local_socket, 1);
return;
}
void
local_notify_route(struct route *route, int kind)
{
char buf[512];
int rc;
if(local_socket < 0)
return;
rc = snprintf(buf, 512,
"%s route %s-%s-%lx prefix %s installed %s "
"id %s metric %d refmetric %d via %s if %s neigh %s\n",
local_kind(kind),
format_prefix(route->src->prefix, route->src->plen),
format_address(route->src->id),
(unsigned long)route->neigh,
format_prefix(route->src->prefix, route->src->plen),
route->installed ? "yes" : "no",
format_address(route->src->id),
route->metric, route->refmetric,
format_address(route->neigh->address),
route->neigh->network->ifname,
format_address(route->neigh->id));
if(rc < 0 || rc >= 512)
goto fail;
rc = write_timeout(local_socket, buf, rc);
if(rc < 0)
goto fail;
return;
fail:
shutdown(local_socket, 1);
return;
}
void
local_dump()
{
int i, rc;
struct neighbour *neigh;
const char *header = "BABEL 0.0\n";
if(local_socket < 0)
return;
rc = write_timeout(local_socket, header, strlen(header));
if(rc < 0)
goto fail;
local_notify_self();
FOR_ALL_NEIGHBOURS(neigh) {
local_notify_neighbour(neigh, LOCAL_ADD);
}
for(i = 0; i < numxroutes; i++)
local_notify_xroute(&xroutes[i], LOCAL_ADD);
for(i = 0; i < numroutes; i++)
local_notify_route(&routes[i], LOCAL_ADD);
return;
fail:
shutdown(local_socket, 1);
return;
}
#endif
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/local.h 0000664 0000000 0000000 00000003260 11073442770 0021230 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
struct neighbour;
struct route;
struct xroute;
#define LOCAL_FLUSH 0
#define LOCAL_ADD 1
#define LOCAL_CHANGE 2
#ifndef NO_LOCAL_INTERFACE
int local_read(int s);
void local_notify_self(void);
void local_notify_neighbour(struct neighbour *neigh, int kind);
void local_notify_xroute(struct xroute *xroute, int kind);
void local_notify_route(struct route *route, int kind);
void local_dump(void);
#else
#define local_notify_self() do {} while(0)
#define local_notify_neighbour(n, k) do {} while(0)
#define local_notify_xroute(x, k) do {} while(0)
#define local_notify_route(r, k) do {} while(0)
#define local_dump() do {} while 0
#endif
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/message.c 0000664 0000000 0000000 00000102607 11073442770 0021562 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "net.h"
#include "network.h"
#include "source.h"
#include "neighbour.h"
#include "route.h"
#include "xroute.h"
#include "resend.h"
#include "message.h"
#include "filter.h"
struct timeval update_flush_timeout = {0, 0};
const unsigned char packet_header[8] = {42, 1};
int parasitic = 0;
int silent_time = 30;
int split_horizon = 1;
unsigned short myseqno = 0;
struct timeval seqno_time = {0, 0};
int seqno_interval = -1;
struct buffered_update {
unsigned char id[16];
unsigned char prefix[16];
unsigned char plen;
};
struct buffered_update buffered_updates[MAX_BUFFERED_UPDATES];
struct network *update_net = NULL;
int updates = 0;
#define UNICAST_BUFSIZE 1024
int unicast_buffered = 0;
unsigned char *unicast_buffer = NULL;
struct neighbour *unicast_neighbour = NULL;
struct timeval unicast_flush_timeout = {0, 0};
unsigned short
hash_id(const unsigned char *id)
{
int i;
unsigned short hash = 0;
for(i = 0; i < 8; i++)
hash ^= (id[2 * i] << 8) | id[2 * i + 1];
return hash;
}
void
parse_packet(const unsigned char *from, struct network *net,
const unsigned char *packet, int len)
{
int i, j;
const unsigned char *message;
unsigned char type, plen, hop_count;
unsigned short seqno, metric;
const unsigned char *address;
struct neighbour *neigh;
int have_current_source = 0;
unsigned char current_source[16];
if(from[0] != 0xFE || (from[1] & 0xC0) != 0x80) {
fprintf(stderr, "Received packet from non-local address %s.\n",
format_address(from));
return;
}
if(packet[0] != 42) {
fprintf(stderr, "Received malformed packet on %s from %s.\n",
net->ifname, format_address(from));
return;
}
if(packet[1] != 1) {
fprintf(stderr,
"Received packet with unknown version %d on %s from %s.\n",
packet[1], net->ifname, format_address(from));
return;
}
if(len % 24 != 8) {
fprintf(stderr, "Received malformed packet on %s from %s.\n",
net->ifname, format_address(from));
return;
}
j = 0;
for(i = 0; i < (len - 8) / 24; i++) {
message = packet + 8 + 24 * i;
type = message[0];
plen = message[1];
hop_count = message[3];
seqno = ntohs(*(uint16_t*)(message + 4));
metric = ntohs(*(uint16_t*)(message + 6));
address = message + 8;
if(type == 0) {
int changed;
if(memcmp(address, myid, 16) == 0)
continue;
debugf("Received hello (%d) on %s from %s (%s).\n",
metric, net->ifname,
format_address(address),
format_address(from));
net->activity_time = now.tv_sec;
update_hello_interval(net);
neigh = add_neighbour(address, from, net);
if(neigh == NULL)
continue;
changed = update_neighbour(neigh, seqno, metric);
if(changed)
update_neighbour_metric(neigh);
if(metric > 0)
schedule_neighbours_check(metric * 10, 0);
} else {
neigh = find_neighbour(from, net);
if(neigh == NULL) {
debugf("Received message from unknown neighbour %s.\n",
format_address(from));
continue;
}
net->activity_time = now.tv_sec;
if(type == 1) {
debugf("Received ihu %d for %s from %s (%s) %d.\n",
metric,
format_address(address),
format_address(neigh->id),
format_address(from), seqno);
if(memcmp(myid, address, 16) == 0) {
neigh->txcost = metric;
neigh->ihu_time = now;
neigh->ihu_interval = seqno;
update_neighbour_metric(neigh);
if(seqno > 0)
schedule_neighbours_check(seqno * 10 * 3, 0);
}
} else if(type == 2) {
debugf("Received request on %s from %s (%s) for %s "
"(%d hops).\n",
net->ifname,
format_address(neigh->id),
format_address(from),
plen == 0xFF ?
"any" :
format_prefix(address, plen),
hop_count);
if(plen == 0xFF) {
/* If a neighbour is requesting a full route dump from us,
we might as well send it an IHU. */
send_ihu(neigh, NULL);
send_update(neigh->network, 0, NULL, 0);
} else {
handle_request(neigh, address, plen,
hop_count, seqno, metric);
}
} else if(type == 3) {
if(plen == 0xFF)
debugf("Received update for %s/none on %s from %s (%s).\n",
format_address(address),
net->ifname,
format_address(neigh->id),
format_address(from));
else
debugf("Received update for %s on %s from %s (%s).\n",
format_prefix(address, plen),
net->ifname,
format_address(neigh->id),
format_address(from));
memcpy(current_source, address, 16);
have_current_source = 1;
if(memcmp(address, myid, 16) == 0)
continue;
if(plen <= 128) {
unsigned char prefix[16];
mask_prefix(prefix, address, plen);
update_route(address, prefix, plen, seqno, metric, neigh,
neigh->address);
}
} else if(type == 4) {
unsigned char prefix[16];
debugf("Received prefix %s on %s from %s (%s).\n",
format_prefix(address, plen),
net->ifname,
format_address(neigh->id),
format_address(from));
if(!have_current_source) {
fprintf(stderr, "Received prefix with no source "
"on %s from %s (%s).\n",
net->ifname,
format_address(neigh->id),
format_address(from));
continue;
}
if(memcmp(current_source, myid, 16) == 0)
continue;
mask_prefix(prefix, address, plen);
update_route(current_source, prefix, plen, seqno, metric,
neigh, neigh->address);
} else if(type == 5) {
unsigned char p4[16], prefix[16], nh[16];
if(!net->ipv4)
continue;
v4tov6(p4, message + 20);
v4tov6(nh, message + 16);
debugf("Received update for %s nh %s on %s from %s (%s).\n",
format_prefix(p4, plen + 96),
format_address(nh),
net->ifname,
format_address(neigh->id),
format_address(from));
if(plen > 32)
continue;
if(!have_current_source) {
fprintf(stderr, "Received IPv4 prefix with no source "
"on %s from %s (%s).\n",
net->ifname,
format_address(neigh->id),
format_address(from));
continue;
}
if(memcmp(current_source, myid, 16) == 0)
continue;
mask_prefix(prefix, p4, plen + 96);
update_route(current_source, prefix, plen + 96, seqno, metric,
neigh, nh);
} else {
debugf("Received unknown packet type %d from %s (%s).\n",
type, format_address(neigh->id), format_address(from));
}
}
}
return;
}
void
handle_request(struct neighbour *neigh, const unsigned char *prefix,
unsigned char plen, unsigned char hop_count,
unsigned short seqno, unsigned short router_hash)
{
struct xroute *xroute;
struct route *route;
struct neighbour *successor = NULL;
xroute = find_xroute(prefix, plen);
if(xroute) {
if(hop_count > 0 && router_hash == hash_id(myid)) {
if(seqno_compare(seqno, myseqno) > 0) {
if(seqno_minus(seqno, myseqno) > 100) {
/* Hopelessly out-of-date request */
return;
}
update_myseqno(1);
}
}
send_update(neigh->network, 1, prefix, plen);
return;
}
route = find_installed_route(prefix, plen);
if(route &&
(hop_count == 0 ||
(route->metric < INFINITY &&
(router_hash != hash_id(route->src->id) ||
seqno_compare(seqno, route->seqno) <= 0)))) {
/* We can satisfy this request straight away. Note that in the
hop_count=0 case, we do send a recent retraction, in order to
reply to nodes whose routes are about to expire. */
send_update(neigh->network, 1, prefix, plen);
return;
}
if(hop_count <= 1)
return;
if(route && router_hash == hash_id(route->src->id) &&
seqno_minus(seqno, route->seqno) > 100) {
/* Hopelessly out-of-date */
return;
}
if(request_redundant(neigh->network, prefix, plen, seqno, router_hash))
return;
/* Let's try to forward this request. */
if(route && route->metric < INFINITY)
successor = route->neigh;
if(!successor || successor == neigh) {
/* We were about to forward a request to its requestor. Try to
find a different neighbour to forward the request to. */
struct route *other_route;
other_route = find_best_route(prefix, plen, 0, neigh);
if(other_route && other_route->metric < INFINITY)
successor = other_route->neigh;
}
if(!successor || successor == neigh)
/* Give up */
return;
send_unicast_request(successor, prefix, plen, hop_count - 1,
seqno, router_hash);
record_resend(RESEND_REQUEST, prefix, plen, seqno, router_hash,
neigh->network, 0);
}
/* Under normal circumstances, there are enough moderation mechanisms
elsewhere in the protocol to make sure that this last-ditch check
should never trigger. But I'm supersticious. */
static int
check_bucket(struct network *net)
{
if(net->bucket <= 0) {
int seconds = now.tv_sec - net->bucket_time;
if(seconds > 0) {
net->bucket = MIN(BUCKET_TOKENS_MAX,
seconds * BUCKET_TOKENS_PER_SEC);
}
/* Reset bucket time unconditionally, in case clock is stepped. */
net->bucket_time = now.tv_sec;
}
if(net->bucket > 0) {
net->bucket--;
return 1;
} else {
return 0;
}
}
void
flushbuf(struct network *net)
{
int rc;
struct sockaddr_in6 sin6;
assert(net->buffered <= net->bufsize);
if(update_net == net)
flushupdates();
if(net->buffered > 0) {
debugf(" (flushing %d buffered bytes on %s)\n",
net->buffered, net->ifname);
if(check_bucket(net)) {
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
memcpy(&sin6.sin6_addr, protocol_group, 16);
sin6.sin6_port = htons(protocol_port);
sin6.sin6_scope_id = net->ifindex;
rc = babel_send(protocol_socket,
packet_header, sizeof(packet_header),
net->sendbuf, net->buffered,
(struct sockaddr*)&sin6, sizeof(sin6));
if(rc < 0)
perror("send");
} else {
fprintf(stderr, "Warning: bucket full, dropping packet to %s.\n",
net->ifname);
}
}
VALGRIND_MAKE_MEM_UNDEFINED(net->sendbuf, net->bufsize);
net->buffered = 0;
net->flush_timeout.tv_sec = 0;
net->flush_timeout.tv_usec = 0;
}
static void
schedule_flush(struct network *net)
{
int msecs = jitter(net, 0);
if(net->flush_timeout.tv_sec != 0 &&
timeval_minus_msec(&net->flush_timeout, &now) < msecs)
return;
net->flush_timeout.tv_usec = (now.tv_usec + msecs * 1000) % 1000000;
net->flush_timeout.tv_sec =
now.tv_sec + (now.tv_usec / 1000 + msecs) / 1000;
}
void
schedule_flush_now(struct network *net)
{
/* Almost now */
int msecs = roughly(10);
if(net->flush_timeout.tv_sec != 0 &&
timeval_minus_msec(&net->flush_timeout, &now) < msecs)
return;
net->flush_timeout.tv_usec = (now.tv_usec + msecs * 1000) % 1000000;
net->flush_timeout.tv_sec =
now.tv_sec + (now.tv_usec / 1000 + msecs) / 1000;
}
static void
schedule_unicast_flush(void)
{
int msecs;
if(!unicast_neighbour)
return;
msecs = jitter(unicast_neighbour->network, 1);
if(unicast_flush_timeout.tv_sec != 0 &&
timeval_minus_msec(&unicast_flush_timeout, &now) < msecs)
return;
unicast_flush_timeout.tv_usec = (now.tv_usec + msecs * 1000) % 1000000;
unicast_flush_timeout.tv_sec =
now.tv_sec + (now.tv_usec / 1000 + msecs) / 1000;
}
static void
start_message(struct network *net, int bytes)
{
assert(net->buffered % 24 == 0);
if(net->bufsize - net->buffered < bytes)
flushbuf(net);
}
static void
send_message(struct network *net,
unsigned char type, unsigned char plen, unsigned char hop_count,
unsigned short seqno, unsigned short metric,
const unsigned char *address)
{
unsigned char *buf;
int n;
if(!net->up)
return;
start_message(net, 24);
buf = net->sendbuf;
n = net->buffered;
buf[n++] = type;
buf[n++] = plen;
buf[n++] = 0;
buf[n++] = hop_count;
buf[n++] = (seqno >> 8) & 0xFF;
buf[n++] = seqno & 0xFF;
buf[n++] = (metric >> 8) & 0xFF;
buf[n++] = metric & 0xFF;
memcpy(buf + n, address, 16);
n += 16;
net->buffered = n;
schedule_flush(net);
}
/* Flush buffers if they contain any hellos. This avoids sending multiple
hellos in a single packet, which breaks link quality estimation. */
int
flush_hellos(struct network *net)
{
int i;
assert(net->buffered % 24 == 0);
for(i = 0; i < net->buffered / 24; i++) {
const unsigned char *message;
message = (const unsigned char*)(net->sendbuf + i * 24);
if(message[0] == 0) {
flushbuf(net);
return 1;
}
}
return 0;
}
void
send_hello_noupdate(struct network *net, unsigned interval)
{
debugf("Sending hello (%d) to %s.\n", interval, net->ifname);
net->hello_seqno = seqno_plus(net->hello_seqno, 1);
flush_hellos(net);
delay_jitter(&net->hello_time, &net->hello_timeout,
net->hello_interval);
send_message(net, 0, 0, 0, net->hello_seqno,
interval > 0xFFFF ? 0 : interval,
myid);
}
void
send_hello(struct network *net)
{
int changed;
changed = update_hello_interval(net);
send_hello_noupdate(net, (net->hello_interval + 9) / 10);
/* Send full IHU every 3 hellos, and marginal IHU each time */
if(changed || net->hello_seqno % 3 == 0)
send_ihu(NULL, net);
else
send_marginal_ihu(net);
}
void
send_request(struct network *net,
const unsigned char *prefix, unsigned char plen,
unsigned char hop_count, unsigned short seqno,
unsigned short router_hash)
{
if(net == NULL) {
struct network *n;
FOR_ALL_NETS(n) {
if(n->up)
continue;
send_request(n, prefix, plen, hop_count, seqno, router_hash);
}
return;
}
/* Make sure any buffered updates go out before this request. */
if(!net || update_net == net)
flushupdates();
debugf("Sending request to %s for %s (%d hops).\n",
net->ifname, prefix ? format_prefix(prefix, plen) : "any",
hop_count);
if(prefix)
send_message(net, 2, plen, hop_count, seqno, router_hash, prefix);
else
send_message(net, 2, 0xFF, 0, 0, 0, ones);
}
void
send_request_resend(struct neighbour *neigh,
const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash)
{
int delay;
if(neigh)
send_unicast_request(neigh, prefix, plen, 127, seqno, router_hash);
else
send_request(NULL, prefix, plen, 127, seqno, router_hash);
delay = 2000;
delay = MIN(delay, wireless_hello_interval / 2);
delay = MIN(delay, wired_hello_interval / 2);
delay = MAX(delay, 10);
record_resend(RESEND_REQUEST, prefix, plen, seqno, router_hash,
neigh ? neigh->network : NULL, delay);
}
void
flush_unicast(int dofree)
{
struct sockaddr_in6 sin6;
int rc;
if(unicast_buffered == 0)
goto done;
if(!unicast_neighbour->network->up)
goto done;
/* Preserve ordering of messages */
flushbuf(unicast_neighbour->network);
if(check_bucket(unicast_neighbour->network)) {
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
memcpy(&sin6.sin6_addr, unicast_neighbour->address, 16);
sin6.sin6_port = htons(protocol_port);
sin6.sin6_scope_id = unicast_neighbour->network->ifindex;
rc = babel_send(protocol_socket,
packet_header, sizeof(packet_header),
unicast_buffer, unicast_buffered,
(struct sockaddr*)&sin6, sizeof(sin6));
if(rc < 0)
perror("send(unicast)");
} else {
fprintf(stderr,
"Warning: bucket full, dropping unicast packet"
"to %s (%s) if %s.\n",
format_address(unicast_neighbour->id),
format_address(unicast_neighbour->address),
unicast_neighbour->network->ifname);
}
done:
VALGRIND_MAKE_MEM_UNDEFINED(unicast_buffer, UNICAST_BUFSIZE);
unicast_buffered = 0;
if(dofree && unicast_buffer) {
free(unicast_buffer);
unicast_buffer = NULL;
}
unicast_neighbour = NULL;
unicast_flush_timeout.tv_sec = 0;
unicast_flush_timeout.tv_usec = 0;
}
static void
send_unicast_message(struct neighbour *neigh,
unsigned char type,
unsigned char plen, unsigned char hop_count,
unsigned short seqno, unsigned short metric,
const unsigned char *address)
{
if(unicast_neighbour) {
if(neigh != unicast_neighbour ||
unicast_buffered + 24 >=
MIN(UNICAST_BUFSIZE, neigh->network->bufsize))
flush_unicast(0);
}
if(!unicast_buffer)
unicast_buffer = malloc(UNICAST_BUFSIZE);
if(!unicast_buffer) {
perror("malloc(unicast_buffer)");
return;
}
unicast_neighbour = neigh;
assert(unicast_buffered % 24 == 0);
unicast_buffer[unicast_buffered++] = type;
unicast_buffer[unicast_buffered++] = plen;
unicast_buffer[unicast_buffered++] = 0;
unicast_buffer[unicast_buffered++] = hop_count;
unicast_buffer[unicast_buffered++] = (seqno >> 8) & 0xFF;
unicast_buffer[unicast_buffered++] = seqno & 0xFF;
unicast_buffer[unicast_buffered++] = (metric >> 8) & 0xFF;
unicast_buffer[unicast_buffered++] = metric & 0xFF;
memcpy(unicast_buffer + unicast_buffered, address, 16);
unicast_buffered += 16;
schedule_unicast_flush();
}
void
send_unicast_request(struct neighbour *neigh,
const unsigned char *prefix, unsigned char plen,
unsigned char hop_count, unsigned short seqno,
unsigned short router_hash)
{
/* Make sure any buffered updates go out before this request. */
if(update_net == neigh->network)
flushupdates();
debugf("Sending unicast request to %s (%s) for %s (%d hops).\n",
format_address(neigh->id),
format_address(neigh->address),
prefix ? format_prefix(prefix, plen) : "any",
hop_count);
if(prefix)
send_unicast_message(neigh,
2, plen, hop_count, seqno, router_hash, prefix);
else
send_unicast_message(neigh, 2, 0xFF, 0, 0, 0, ones);
}
/* Return the source-id of the last buffered update message. */
static const unsigned char *
message_source_id(struct network *net)
{
int i;
assert(net->buffered % 24 == 0);
i = net->buffered / 24 - 1;
while(i >= 0) {
const unsigned char *message;
message = (const unsigned char*)(net->sendbuf + i * 24);
if(message[0] == 3)
return message + 8;
else if(message[0] == 4 || message[0] == 5)
i--;
else
break;
}
return NULL;
}
static void
really_send_update(struct network *net,
const unsigned char *id,
const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short metric)
{
int add_metric;
if(!net->up)
return;
add_metric = output_filter(id, prefix, plen, net->ifindex);
if(add_metric < INFINITY) {
metric = MIN(metric + add_metric, INFINITY);
if(plen >= 96 && v4mapped(prefix)) {
const unsigned char *sid;
unsigned char v4route[16];
if(!net->ipv4)
return;
memset(v4route, 0, 8);
memcpy(v4route + 8, net->ipv4, 4);
memcpy(v4route + 12, prefix + 12, 4);
start_message(net, 48);
sid = message_source_id(net);
if(sid == NULL || memcmp(id, sid, 16) != 0)
send_message(net, 3, 0xFF, 0, 0, 0xFFFF, id);
send_message(net, 5, plen - 96, 0, seqno, metric, v4route);
} else {
if(in_prefix(id, prefix, plen)) {
send_message(net, 3, plen, 0, seqno, metric, id);
} else {
const unsigned char *sid;
start_message(net, 48);
sid = message_source_id(net);
if(sid == NULL || memcmp(id, sid, 16) != 0)
send_message(net, 3, 0xFF, 0, 0, 0xFFFF, id);
send_message(net, 4, plen, 0, seqno, metric, prefix);
}
}
}
}
static int
compare_buffered_updates(const void *av, const void *bv)
{
const struct buffered_update *a = av, *b = bv;
int rc, v4a, v4b, ipa, ipb;
rc = memcmp(a->id, b->id, 16);
if(rc != 0)
return rc;
v4a = (a->plen >= 96 && v4mapped(a->prefix));
v4b = (b->plen >= 96 && v4mapped(b->prefix));
if(v4a > v4b)
return 1;
else if(v4a < v4b)
return -1;
ipa = in_prefix(a->id, a->prefix, a->plen);
ipb = in_prefix(b->id, b->prefix, b->plen);
if(ipa > ipb)
return -1;
else if(ipa < ipb)
return 1;
if(a->plen < b->plen)
return -1;
else if(a->plen > b->plen)
return 1;
return memcmp(a->prefix, b->prefix, 16);
}
void
flushupdates(void)
{
struct xroute *xroute;
struct route *route;
const unsigned char *last_prefix = NULL;
unsigned char last_plen = 0xFF;
int i;
if(updates > 0) {
int n = updates;
struct network *net = update_net;
updates = 0;
update_net = NULL;
debugf(" (flushing %d buffered updates)\n", n);
/* In order to send fewer update messages, we want to send updates
with the same router-id together, with IPv6 going out before IPv4. */
for(i = 0; i < n; i++) {
route = find_installed_route(buffered_updates[i].prefix,
buffered_updates[i].plen);
if(route)
memcpy(buffered_updates[i].id, route->src->id, 16);
else
memcpy(buffered_updates[i].id, myid, 16);
}
qsort(buffered_updates, n, sizeof(struct buffered_update),
compare_buffered_updates);
for(i = 0; i < n; i++) {
unsigned short seqno;
unsigned short metric;
/* The same update may be scheduled multiple times before it is
sent out. Since our buffer is now sorted, it is enough to
compare with the previous update. */
if(last_prefix) {
if(buffered_updates[i].plen == last_plen &&
memcmp(buffered_updates[i].prefix, last_prefix, 16) == 0)
continue;
}
xroute = find_xroute(buffered_updates[i].prefix,
buffered_updates[i].plen);
if(xroute) {
really_send_update(net, myid,
xroute->prefix, xroute->plen,
myseqno, xroute->metric);
last_prefix = xroute->prefix;
last_plen = xroute->plen;
continue;
}
route = find_installed_route(buffered_updates[i].prefix,
buffered_updates[i].plen);
if(route) {
seqno = route->seqno;
metric = route->metric;
if(metric < INFINITY)
satisfy_request(route->src->prefix, route->src->plen,
seqno, hash_id(route->src->id), net);
if(split_horizon && net->wired && route->neigh->network == net)
continue;
really_send_update(net, route->src->id,
route->src->prefix,
route->src->plen,
seqno, metric);
update_source(route->src, seqno, metric);
last_prefix = route->src->prefix;
last_plen = route->src->plen;
continue;
}
}
schedule_flush_now(net);
VALGRIND_MAKE_MEM_UNDEFINED(&buffered_updates,
sizeof(buffered_updates));
}
update_flush_timeout.tv_sec = 0;
update_flush_timeout.tv_usec = 0;
}
static void
schedule_update_flush(struct network *net, int urgent)
{
int msecs;
msecs = update_jitter(net, urgent);
if(update_flush_timeout.tv_sec != 0 &&
timeval_minus_msec(&update_flush_timeout, &now) < msecs)
return;
update_flush_timeout.tv_usec = (now.tv_usec + msecs * 1000) % 1000000;
update_flush_timeout.tv_sec =
now.tv_sec + (now.tv_usec / 1000 + msecs) / 1000;
}
static void
buffer_update(struct network *net,
const unsigned char *prefix, unsigned char plen)
{
if(update_net && update_net != net)
flushupdates();
update_net = net;
if(updates >= MAX_BUFFERED_UPDATES)
flushupdates();
memcpy(buffered_updates[updates].prefix, prefix, 16);
buffered_updates[updates].plen = plen;
updates++;
}
void
send_update(struct network *net, int urgent,
const unsigned char *prefix, unsigned char plen)
{
int i, selfonly;
struct resend *request;
if(prefix) {
/* This is needed here, since flushupdates only handles the
case where network is not null. */
request = find_request(prefix, plen, NULL);
if(request) {
struct route *route = find_installed_route(prefix, plen);
if(route && route->metric < INFINITY) {
urgent = 1;
satisfy_request(prefix, plen, route->seqno,
hash_id(route->src->id), net);
}
}
}
if(net == NULL) {
struct network *n;
FOR_ALL_NETS(n)
send_update(n, urgent, prefix, plen);
return;
}
if(!net->up)
return;
selfonly =
parasitic || (silent_time && now.tv_sec < reboot_time + silent_time);
if(!selfonly)
silent_time = 0;
if(prefix) {
if(!selfonly || find_xroute(prefix, plen)) {
debugf("Sending update to %s for %s.\n",
net->ifname, format_prefix(prefix, plen));
buffer_update(net, prefix, plen);
}
} else {
/* Don't send full route dumps more than ten times per second */
if(net->update_time.tv_sec > 0 &&
timeval_minus_msec(&now, &net->update_time) < 100)
return;
send_self_update(net, 0);
if(!selfonly) {
debugf("Sending update to %s for any.\n", net->ifname);
for(i = 0; i < numroutes; i++)
if(routes[i].installed)
buffer_update(net,
routes[i].src->prefix, routes[i].src->plen);
}
delay_jitter(&net->update_time, &net->update_timeout,
update_interval);
}
schedule_update_flush(net, urgent);
}
void
send_update_resend(struct network *net,
const unsigned char *prefix, unsigned char plen)
{
int delay;
assert(prefix != NULL);
send_update(net, 1, prefix, plen);
delay = 2000;
delay = MIN(delay, wireless_hello_interval / 2);
delay = MIN(delay, wired_hello_interval / 2);
delay = MAX(delay, 10);
record_resend(RESEND_UPDATE, prefix, plen, 0, 0, NULL, delay);
}
void
update_myseqno(int force)
{
if(force || timeval_minus_msec(&now, &seqno_time) >= seqno_interval) {
myseqno = seqno_plus(myseqno, 1);
seqno_time = now;
}
}
void
send_self_update(struct network *net, int force_seqno)
{
int i;
update_myseqno(force_seqno);
if(net == NULL) {
struct network *n;
FOR_ALL_NETS(n) {
if(n->up)
continue;
send_self_update(n, 0);
}
return;
}
debugf("Sending self update to %s.\n", net->ifname);
delay_jitter(&net->self_update_time, &net->self_update_timeout,
net->self_update_interval);
for(i = 0; i < numxroutes; i++) {
send_update(net, 0, xroutes[i].prefix, xroutes[i].plen);
}
}
void
send_ihu(struct neighbour *neigh, struct network *net)
{
if(neigh == NULL && net == NULL) {
struct network *n;
FOR_ALL_NETS(n) {
if(n->up)
continue;
send_ihu(NULL, n);
}
return;
}
if(neigh == NULL) {
struct neighbour *ngh;
FOR_ALL_NEIGHBOURS(ngh) {
if(ngh->network == net)
send_ihu(ngh, net);
}
} else {
int rxcost, interval;
if(net && neigh->network != net)
return;
net = neigh->network;
rxcost = neighbour_rxcost(neigh);
interval = (net->hello_interval * 3 + 9) / 10;
/* Conceptually, an IHU is a unicast message. We usually send
them as multicast, since this allows aggregation into
a single packet and avoids an ARP exchange. If we already
have a unicast message queued for this neighbour, however,
we might as well piggyback the IHU onto it. */
debugf("Sending %sihu %d on %s to %s (%s).\n",
unicast_neighbour == neigh ? "unicast " : "",
rxcost,
neigh->network->ifname,
format_address(neigh->id),
format_address(neigh->address));
if(unicast_neighbour == neigh) {
send_unicast_message(neigh, 1, 128, 0,
interval < 0xFFFF ? interval : 0,
rxcost, neigh->id);
} else {
send_message(net, 1, 128, 0,
interval < 0xFFFF ? interval : 0,
rxcost, neigh->id);
}
}
}
/* Send IHUs to all marginal neighbours */
void
send_marginal_ihu(struct network *net)
{
struct neighbour *neigh;
FOR_ALL_NEIGHBOURS(neigh) {
if(net && neigh->network != net)
continue;
if(neigh->txcost >= 384 || (neigh->reach & 0xF000) != 0xF000)
send_ihu(neigh, net);
}
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/message.h 0000664 0000000 0000000 00000006344 11073442770 0021570 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define MAX_BUFFERED_UPDATES 200
#define BUCKET_TOKENS_MAX 200
#define BUCKET_TOKENS_PER_SEC 40
extern unsigned short myseqno;
extern struct timeval seqno_time;
extern int seqno_interval;
extern int parasitic;
extern int silent_time;
extern int broadcast_ihu;
extern int split_horizon;
extern struct timeval update_flush_timeout;
extern const unsigned char packet_header[8];
extern struct neighbour *unicast_neighbour;
extern struct timeval unicast_flush_timeout;
unsigned short hash_id(const unsigned char *id) ATTRIBUTE ((pure));
void parse_packet(const unsigned char *from, struct network *net,
const unsigned char *packet, int len);
void handle_request(struct neighbour *neigh, const unsigned char *prefix,
unsigned char plen, unsigned char hop_count,
unsigned short seqno, unsigned short router_hash);
void flushbuf(struct network *net);
void send_hello_noupdate(struct network *net, unsigned interval);
void send_hello(struct network *net);
void send_request(struct network *net,
const unsigned char *prefix, unsigned char plen,
unsigned char hop_count, unsigned short seqno,
unsigned short router_hash);
void send_request_resend(struct neighbour *neigh,
const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash);
void flush_unicast(int dofree);
void send_unicast_request(struct neighbour *neigh,
const unsigned char *prefix, unsigned char plen,
unsigned char hop_count, unsigned short seqno,
unsigned short router_hash);
void send_update(struct network *net, int urgent,
const unsigned char *prefix, unsigned char plen);
void send_update_resend(struct network *net,
const unsigned char *prefix, unsigned char plen);
void update_myseqno(int force);
void send_self_update(struct network *net, int force_seqno);
void send_ihu(struct neighbour *neigh, struct network *net);
void send_marginal_ihu(struct network *net);
void schedule_flush_now(struct network *net);
void flushupdates(void);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/neighbour.c 0000664 0000000 0000000 00000025515 11073442770 0022122 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "network.h"
#include "neighbour.h"
#include "source.h"
#include "route.h"
#include "message.h"
#include "local.h"
struct neighbour *neighs = NULL;
struct neighbour *
find_neighbour(const unsigned char *address, struct network *net)
{
struct neighbour *neigh;
FOR_ALL_NEIGHBOURS(neigh) {
if(memcmp(address, neigh->address, 16) == 0 &&
neigh->network == net)
return neigh;
}
return NULL;
}
struct neighbour *
find_neighbour_by_id(const unsigned char *id, struct network *net)
{
struct neighbour *neigh;
FOR_ALL_NEIGHBOURS(neigh) {
if(memcmp(id, neigh->id, 16) == 0 && neigh->network == net)
return neigh;
}
return NULL;
}
void
flush_neighbour(struct neighbour *neigh)
{
flush_neighbour_routes(neigh);
if(unicast_neighbour == neigh)
flush_unicast(1);
if(neighs == neigh) {
neighs = neigh->next;
} else {
struct neighbour *previous = neighs;
while(previous->next != neigh)
previous = previous->next;
previous->next = neigh->next;
}
local_notify_neighbour(neigh, LOCAL_FLUSH);
free(neigh);
}
struct neighbour *
add_neighbour(const unsigned char *id, const unsigned char *address,
struct network *net)
{
struct neighbour *neigh;
const struct timeval zero = {0, 0};
neigh = find_neighbour(address, net);
if(neigh) {
if(memcmp(neigh->id, id, 16) == 0) {
return neigh;
} else {
fprintf(stderr, "Neighbour changed id (%s -> %s)!\n",
format_address(neigh->id), format_address(id));
flush_neighbour(neigh);
neigh = NULL;
}
}
neigh = find_neighbour_by_id(id, net);
if(neigh) {
if((neigh->reach & 0xE000) == 0) {
/* The other neighbour is probably obsolete. */
flush_neighbour(neigh);
neigh = NULL;
} else {
fprintf(stderr, "Duplicate neighbour %s (%s and %s)!\n",
format_address(id),
format_address(neigh->address),
format_address(address));
return NULL;
}
}
debugf("Creating neighbour %s (%s).\n",
format_address(id), format_address(address));
neigh = malloc(sizeof(struct neighbour));
if(neigh == NULL) {
perror("malloc(neighbour)");
return NULL;
}
neigh->hello_seqno = -1;
memcpy(neigh->id, id, 16);
memcpy(neigh->address, address, 16);
neigh->reach = 0;
neigh->txcost = INFINITY;
neigh->ihu_time = now;
neigh->hello_time = zero;
neigh->hello_interval = 0;
neigh->ihu_interval = 0;
neigh->network = net;
neigh->next = neighs;
neighs = neigh;
local_notify_neighbour(neigh, LOCAL_ADD);
send_hello(net);
return neigh;
}
/* Recompute a neighbour's rxcost. Return true if anything changed. */
int
update_neighbour(struct neighbour *neigh, int hello, int hello_interval)
{
int missed_hellos;
int rc = 0;
if(hello < 0) {
if(neigh->hello_interval <= 0)
return rc;
missed_hellos =
(timeval_minus_msec(&now, &neigh->hello_time) -
neigh->hello_interval * 7) /
(neigh->hello_interval * 10);
if(missed_hellos <= 0)
return rc;
timeval_plus_msec(&neigh->hello_time, &neigh->hello_time,
missed_hellos * neigh->hello_interval * 10);
} else {
if(neigh->hello_seqno >= 0 && neigh->reach > 0) {
missed_hellos = seqno_minus(hello, neigh->hello_seqno) - 1;
if(missed_hellos < -8) {
/* Probably a neighbour that rebooted and lost its seqno.
Reboot the universe. */
neigh->reach = 0;
missed_hellos = 0;
rc = 1;
} else if(missed_hellos < 0) {
if(hello_interval > neigh->hello_interval) {
/* This neighbour has increased its hello interval,
and we didn't notice. */
neigh->reach <<= -missed_hellos;
missed_hellos = 0;
} else {
/* Late hello. Probably due to the link layer buffering
packets during a link outage. Ignore it, but reset
the expected seqno. */
neigh->hello_seqno = hello;
hello = -1;
missed_hellos = 0;
}
rc = 1;
}
} else {
missed_hellos = 0;
}
neigh->hello_time = now;
neigh->hello_interval = hello_interval;
}
if(missed_hellos > 0) {
neigh->reach >>= missed_hellos;
neigh->hello_seqno = seqno_plus(neigh->hello_seqno, missed_hellos);
missed_hellos = 0;
rc = 1;
}
if(hello >= 0) {
neigh->hello_seqno = hello;
neigh->reach >>= 1;
neigh->reach |= 0x8000;
if((neigh->reach & 0xFC00) != 0xFC00)
rc = 1;
}
/* Make sure to give neighbours some feedback early after association */
if((neigh->reach & 0xBF00) == 0x8000) {
/* A new neighbour */
send_hello(neigh->network);
} else {
/* Don't send hellos, in order to avoid a positive feedback loop. */
int a = (neigh->reach & 0xC000);
int b = (neigh->reach & 0x3000);
if((a == 0xC000 && b == 0) || (a == 0 && b == 0x3000)) {
/* Reachability is either 1100 or 0011 */
send_self_update(neigh->network, 0);
}
}
if((neigh->reach & 0xFC00) == 0xC000) {
/* This is a newish neighbour. If we don't have another route to it,
request a full route dump. This assumes that the neighbour's id
is also its IP address and that it is exporting a route to itself. */
struct route *route = NULL;
send_ihu(neigh, NULL);
if(!martian_prefix(neigh->id, 128))
route = find_installed_route(neigh->id, 128);
if(!route || route->metric >= INFINITY || route->neigh == neigh)
send_unicast_request(neigh, NULL, 0, 0, 0, 0);
}
if(rc)
local_notify_neighbour(neigh, LOCAL_CHANGE);
return rc;
}
static int
reset_txcost(struct neighbour *neigh)
{
int delay;
delay = timeval_minus_msec(&now, &neigh->ihu_time);
if(neigh->ihu_interval > 0 && delay < neigh->ihu_interval * 10 * 3)
return 0;
/* If we're losing a lot of packets, we probably lost an IHU too */
if(delay >= 180000 || (neigh->reach & 0xFFF0) == 0 ||
(neigh->ihu_interval > 0 &&
delay >= neigh->ihu_interval * 10 * 10)) {
neigh->txcost = INFINITY;
neigh->ihu_time = now;
return 1;
}
return 0;
}
unsigned
neighbour_txcost(struct neighbour *neigh)
{
reset_txcost(neigh);
return neigh->txcost;
}
unsigned
check_neighbours()
{
struct neighbour *neigh;
int changed, delay;
int msecs = 50000;
debugf("Checking neighbours.\n");
neigh = neighs;
while(neigh) {
changed = update_neighbour(neigh, -1, 0);
if(neigh->reach == 0 ||
neigh->hello_time.tv_sec > now.tv_sec || /* clock stepped */
timeval_minus_msec(&now, &neigh->hello_time) > 300000) {
struct neighbour *old = neigh;
neigh = neigh->next;
flush_neighbour(old);
continue;
}
delay = timeval_minus_msec(&now, &neigh->ihu_time);
changed = changed || reset_txcost(neigh);
if(changed) {
update_neighbour_metric(neigh);
local_notify_neighbour(neigh, LOCAL_CHANGE);
}
if(neigh->hello_interval > 0)
msecs = MIN(msecs, neigh->hello_interval * 10);
if(neigh->ihu_interval > 0)
msecs = MIN(msecs, neigh->ihu_interval * 10);
neigh = neigh->next;
}
return msecs;
}
unsigned
neighbour_rxcost(struct neighbour *neigh)
{
int delay;
unsigned short reach = neigh->reach;
delay = timeval_minus_msec(&now, &neigh->hello_time);
if((reach & 0xFFF0) == 0 || delay >= 180000) {
return INFINITY;
} else if(neigh->network->wired) {
/* To lose one hello is a misfortune, to lose two is carelessness. */
if((reach & 0xC000) == 0xC000)
return neigh->network->cost;
else if((reach & 0xC000) == 0)
return INFINITY;
else if((reach & 0x2000))
return neigh->network->cost;
else
return INFINITY;
} else {
int sreach =
((reach & 0x8000) >> 2) +
((reach & 0x4000) >> 1) +
(reach & 0x3FFF);
/* 0 <= sreach <= 0x7FFF */
int cost = (0x8000 * neigh->network->cost) / (sreach + 1);
/* cost >= network->cost */
if(delay >= 40000)
cost = (cost * (delay - 20000) + 10000) / 20000;
return MIN(cost, INFINITY);
}
}
unsigned
neighbour_cost(struct neighbour *neigh)
{
unsigned a, b;
if(!neigh->network->up)
return INFINITY;
a = neighbour_txcost(neigh);
if(a >= INFINITY)
return INFINITY;
b = neighbour_rxcost(neigh);
if(b >= INFINITY)
return INFINITY;
if(neigh->network->wired || (a <= 256 && b <= 256)) {
return a;
} else {
/* a = 256/alpha, b = 256/beta, where alpha and beta are the expected
probabilities of a packet getting through in the direct and reverse
directions. */
a = MAX(a, 256);
b = MAX(b, 256);
/* 1/(alpha * beta), which is just plain ETX. */
/* Since a and b are capped to 16 bits, overflow is impossible. */
return (a * b + 128) >> 8;
}
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/neighbour.h 0000664 0000000 0000000 00000004573 11073442770 0022130 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
struct neighbour {
struct neighbour *next;
/* This is -1 when unknown, so don't make it unsigned */
int hello_seqno;
unsigned char id[16];
unsigned char address[16];
unsigned short reach;
unsigned short txcost;
struct timeval hello_time;
struct timeval ihu_time;
unsigned short hello_interval; /* in centiseconds */
unsigned short ihu_interval; /* in centiseconds */
struct network *network;
};
extern struct neighbour *neighs;
#define FOR_ALL_NEIGHBOURS(_neigh) \
for(_neigh = neighs; _neigh; _neigh = _neigh->next)
int neighbour_valid(struct neighbour *neigh);
void flush_neighbour(struct neighbour *neigh);
struct neighbour *find_neighbour(const unsigned char *address,
struct network *net);
struct neighbour *find_neighbour_by_id(const unsigned char *id,
struct network *net);
struct neighbour *add_neighbour(const unsigned char *id,
const unsigned char *address,
struct network *net);
int update_neighbour(struct neighbour *neigh, int hello, int hello_interval);
unsigned check_neighbours(void);
unsigned neighbour_txcost(struct neighbour *neigh);
unsigned neighbour_rxcost(struct neighbour *neigh);
unsigned neighbour_cost(struct neighbour *neigh);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/net.c 0000664 0000000 0000000 00000011605 11073442770 0020721 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "net.h"
int
babel_socket(int port)
{
struct sockaddr_in6 sin6;
int s, rc;
int saved_errno;
int one = 1, zero = 0;
s = socket(PF_INET6, SOCK_DGRAM, 0);
if(s < 0)
return -1;
rc = setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &one, sizeof(one));
if(rc < 0)
goto fail;
rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
if(rc < 0)
goto fail;
rc = setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
&zero, sizeof(zero));
if(rc < 0)
goto fail;
rc = setsockopt(s, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
&one, sizeof(one));
if(rc < 0)
goto fail;
rc = setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
&one, sizeof(one));
if(rc < 0)
goto fail;
rc = fcntl(s, F_GETFL, 0);
if(rc < 0)
goto fail;
rc = fcntl(s, F_SETFL, (rc | O_NONBLOCK));
if(rc < 0)
goto fail;
rc = fcntl(s, F_GETFD, 0);
if(rc < 0)
goto fail;
rc = fcntl(s, F_SETFD, rc | FD_CLOEXEC);
if(rc < 0)
goto fail;
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(port);
rc = bind(s, (struct sockaddr*)&sin6, sizeof(sin6));
if(rc < 0)
goto fail;
return s;
fail:
saved_errno = errno;
close(s);
errno = saved_errno;
return -1;
}
int
babel_recv(int s, void *buf, int buflen, struct sockaddr *sin, int slen)
{
struct iovec iovec;
struct msghdr msg;
int rc;
memset(&msg, 0, sizeof(msg));
iovec.iov_base = buf;
iovec.iov_len = buflen;
msg.msg_name = sin;
msg.msg_namelen = slen;
msg.msg_iov = &iovec;
msg.msg_iovlen = 1;
rc = recvmsg(s, &msg, 0);
return rc;
}
int
babel_send(int s,
const void *buf1, int buflen1, const void *buf2, int buflen2,
const struct sockaddr *sin, int slen)
{
struct iovec iovec[2];
struct msghdr msg;
int rc;
iovec[0].iov_base = (void*)buf1;
iovec[0].iov_len = buflen1;
iovec[1].iov_base = (void*)buf2;
iovec[1].iov_len = buflen2;
memset(&msg, 0, sizeof(msg));
msg.msg_name = (struct sockaddr*)sin;
msg.msg_namelen = slen;
msg.msg_iov = iovec;
msg.msg_iovlen = 2;
again:
rc = sendmsg(s, &msg, 0);
if(rc < 0) {
if(errno == EINTR)
goto again;
else if(errno == EAGAIN) {
int rc2;
rc2 = wait_for_fd(1, s, 5);
if(rc2 > 0)
goto again;
errno = EAGAIN;
}
}
return rc;
}
int
tcp_server_socket(int port, int local)
{
struct sockaddr_in6 sin6;
int s, rc, saved_errno;
int one = 1;
s = socket(PF_INET6, SOCK_STREAM, 0);
if(s < 0)
return -1;
rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
if(rc < 0)
goto fail;
rc = fcntl(s, F_GETFL, 0);
if(rc < 0)
goto fail;
rc = fcntl(s, F_SETFL, (rc | O_NONBLOCK));
if(rc < 0)
goto fail;
rc = fcntl(s, F_GETFD, 0);
if(rc < 0)
goto fail;
rc = fcntl(s, F_SETFD, rc | FD_CLOEXEC);
if(rc < 0)
goto fail;
memset(&sin6, 0, sizeof(sin6));
sin6.sin6_family = AF_INET6;
sin6.sin6_port = htons(port);
if(local) {
rc = inet_pton(AF_INET6, "::1", &sin6.sin6_addr);
if(rc < 0)
goto fail;
}
rc = bind(s, (struct sockaddr*)&sin6, sizeof(sin6));
if(rc < 0)
goto fail;
rc = listen(s, 2);
if(rc < 0)
goto fail;
return s;
fail:
saved_errno = errno;
close(s);
errno = saved_errno;
return -1;
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/net.h 0000664 0000000 0000000 00000002546 11073442770 0020732 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
int babel_socket(int port);
int babel_recv(int s, void *buf, int buflen, struct sockaddr *sin, int slen);
int babel_send(int s,
const void *buf1, int buflen1, const void *buf2, int buflen2,
const struct sockaddr *sin, int slen);
int tcp_server_socket(int port, int local);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/network.c 0000664 0000000 0000000 00000022574 11073442770 0021633 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "kernel.h"
#include "network.h"
#include "neighbour.h"
#include "message.h"
#include "route.h"
#include "filter.h"
struct network *networks = NULL;
static struct network *
last_network(void)
{
struct network *net = networks;
if(!net)
return NULL;
while(net->next)
net = net->next;
return net;
}
struct network *
add_network(char *ifname)
{
struct network *net;
net = malloc(sizeof(struct network));
if(net == NULL)
return NULL;
memset(net, 0, sizeof(struct network));
net->up = 0;
net->ifindex = 0;
net->ipv4 = NULL;
net->activity_time = now.tv_sec;
net->bufsize = 0;
strncpy(net->ifname, ifname, IF_NAMESIZE);
net->sendbuf = NULL;
net->buffered = 0;
net->bucket_time = now.tv_sec;
net->bucket = BUCKET_TOKENS_MAX;
net->hello_seqno = (random() & 0xFFFF);
if(networks == NULL)
networks = net;
else
last_network()->next = net;
return net;
}
int
network_idle(struct network *net)
{
return (idle_hello_interval > 0 &&
net->activity_time < now.tv_sec - idle_time);
}
int
update_hello_interval(struct network *net)
{
int rc = 0;
if(network_idle(net)) {
if(net->hello_interval != idle_hello_interval) {
net->hello_interval = idle_hello_interval;
rc = 1;
}
} else if(net->wired) {
if(net->hello_interval != wired_hello_interval) {
net->hello_interval = wired_hello_interval;
rc = 1;
}
} else {
if(net->hello_interval != wireless_hello_interval) {
net->hello_interval = wireless_hello_interval;
rc = 1;
}
}
net->self_update_interval =
MAX(update_interval / 2, net->hello_interval);
return rc;
}
/* This should be no more than half the hello interval, so that hellos
aren't sent late. The result is in milliseconds. */
unsigned int
jitter(struct network *net, int urgent)
{
unsigned interval = net->hello_interval;
if(urgent)
interval = MIN(interval, 100);
else
interval = MIN(interval, 4000);
return roughly(interval) / 4;
}
unsigned int
update_jitter(struct network *net, int urgent)
{
unsigned interval = net->hello_interval;
if(urgent)
interval = MIN(interval, 100);
else
interval = MIN(interval, 4000);
return roughly(interval);
}
void
delay_jitter(struct timeval *time, struct timeval *timeout, int msecs)
{
*time = now;
timeval_plus_msec(timeout, &now, roughly(msecs));
}
static int
check_network_ipv4(struct network *net)
{
unsigned char ipv4[4];
int rc;
if(net->ifindex > 0)
rc = kernel_interface_ipv4(net->ifname, net->ifindex, ipv4);
else
rc = 0;
if(rc > 0) {
if(!net->ipv4 || memcmp(ipv4, net->ipv4, 4) != 0) {
debugf("Noticed IPv4 change for %s.\n", net->ifname);
if(!net->ipv4)
net->ipv4 = malloc(4);
if(net->ipv4)
memcpy(net->ipv4, ipv4, 4);
return 1;
}
} else {
debugf("Noticed IPv4 change for %s.\n", net->ifname);
if(net->ipv4) {
free(net->ipv4);
net->ipv4 = NULL;
return 1;
}
}
return 0;
}
int
network_up(struct network *net, int up)
{
int mtu, rc, wired;
struct ipv6_mreq mreq;
if(up == net->up)
return 0;
net->up = up;
if(up) {
if(net->ifindex <= 0) {
fprintf(stderr,
"Upping unknown interface %s.\n", net->ifname);
return network_up(net, 0);
}
rc = kernel_setup_interface(1, net->ifname, net->ifindex);
if(rc < 0) {
fprintf(stderr, "kernel_setup_interface(%s, %d) failed.\n",
net->ifname, net->ifindex);
return network_up(net, 0);
}
mtu = kernel_interface_mtu(net->ifname, net->ifindex);
if(mtu < 0) {
fprintf(stderr, "Warning: couldn't get MTU of interface %s (%d).\n",
net->ifname, net->ifindex);
mtu = 1280;
}
/* We need to be able to fit at least two messages into a packet,
so MTUs below 116 require lower layer fragmentation. */
/* In IPv6, the minimum MTU is 1280, and every host must be able
to reassemble up to 1500 bytes, but I'd rather not rely on this. */
if(mtu < 128) {
fprintf(stderr, "Suspiciously low MTU %d on interface %s (%d).\n",
mtu, net->ifname, net->ifindex);
mtu = 128;
}
if(net->sendbuf)
free(net->sendbuf);
/* 40 for IPv6 header, 8 for UDP header, 12 for good luck. */
net->bufsize = mtu - sizeof(packet_header) - 60;
net->sendbuf = malloc(net->bufsize);
if(net->sendbuf == NULL) {
fprintf(stderr, "Couldn't allocate sendbuf.\n");
net->bufsize = 0;
return network_up(net, 0);
}
resize_receive_buffer(mtu);
if(all_wireless) {
wired = 0;
} else {
rc = kernel_interface_wireless(net->ifname, net->ifindex);
if(rc < 0) {
fprintf(stderr,
"Warning: couldn't determine whether %s (%d) "
"is a wireless interface.\n",
net->ifname, net->ifindex);
wired = 0;
} else {
wired = !rc;
}
}
net->wired = wired;
net->cost = wired ? 96 : 256;
update_hello_interval(net);
memset(&mreq, 0, sizeof(mreq));
memcpy(&mreq.ipv6mr_multiaddr, protocol_group, 16);
mreq.ipv6mr_interface = net->ifindex;
rc = setsockopt(protocol_socket, IPPROTO_IPV6, IPV6_JOIN_GROUP,
(char*)&mreq, sizeof(mreq));
if(rc < 0) {
perror("setsockopt(IPV6_JOIN_GROUP)");
/* This is probably due to a missing link-local address,
so down this network, and wait until the main loop
tries to up it again. */
return network_up(net, 0);
}
delay_jitter(&net->hello_time, &net->hello_timeout,
net->hello_interval);
delay_jitter(&net->self_update_time, &net->self_update_timeout,
net->self_update_interval);
delay_jitter(&net->update_time, &net->update_timeout,
update_interval);
send_hello(net);
send_request(net, NULL, 0, 0, 0, 0);
} else {
net->buffered = 0;
net->bufsize = 0;
free(net->sendbuf);
net->sendbuf = NULL;
if(net->ifindex > 0) {
memset(&mreq, 0, sizeof(mreq));
memcpy(&mreq.ipv6mr_multiaddr, protocol_group, 16);
mreq.ipv6mr_interface = net->ifindex;
rc = setsockopt(protocol_socket, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
(char*)&mreq, sizeof(mreq));
if(rc < 0)
perror("setsockopt(IPV6_LEAVE_GROUP)");
kernel_setup_interface(0, net->ifname, net->ifindex);
}
}
update_network_metric(net);
rc = check_network_ipv4(net);
if(up && rc > 0)
send_update(net, 0, NULL, 0);
return 1;
}
void
check_networks(void)
{
struct network *net;
int rc, ifindex, ifindex_changed = 0;
FOR_ALL_NETS(net) {
ifindex = if_nametoindex(net->ifname);
if(ifindex != net->ifindex) {
debugf("Noticed ifindex change for %s.\n", net->ifname);
net->ifindex = 0;
network_up(net, 0);
net->ifindex = ifindex;
ifindex_changed = 1;
}
if(net->ifindex > 0)
rc = kernel_interface_operational(net->ifname, net->ifindex);
else
rc = 0;
if((rc > 0) != net->up) {
debugf("Noticed status change for %s.\n", net->ifname);
network_up(net, rc > 0);
}
rc = check_network_ipv4(net);
if(rc > 0) {
send_request(net, NULL, 0, 0, 0, 0);
send_update(net, 0, NULL, 0);
}
}
if(ifindex_changed)
renumber_filters();
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/network.h 0000664 0000000 0000000 00000004332 11073442770 0021630 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
struct network {
struct network *next;
int up;
unsigned int ifindex;
int wired;
unsigned short cost;
struct timeval hello_time;
struct timeval hello_timeout;
struct timeval self_update_time;
struct timeval self_update_timeout;
struct timeval update_time;
struct timeval update_timeout;
char ifname[IF_NAMESIZE];
unsigned char *ipv4;
int buffered;
struct timeval flush_timeout;
int bufsize;
unsigned char *sendbuf;
time_t bucket_time;
unsigned int bucket;
time_t activity_time;
unsigned short hello_seqno;
unsigned int hello_interval;
unsigned int self_update_interval;
};
extern struct network *networks;
extern int numnets;
#define FOR_ALL_NETS(_net) for(_net = networks; _net; _net = _net->next)
struct network *add_network(char *ifname);
int network_idle(struct network *net);
int update_hello_interval(struct network *net);
unsigned int jitter(struct network *net, int urgent);
unsigned int update_jitter(struct network *net, int urgent);
void delay_jitter(struct timeval *time, struct timeval *timeout, int msecs);
int network_up(struct network *net, int up);
void check_networks(void);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/resend.c 0000664 0000000 0000000 00000020574 11073442770 0021420 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "neighbour.h"
#include "resend.h"
#include "message.h"
#include "network.h"
#include "filter.h"
struct timeval resend_time = {0, 0};
struct resend *to_resend = NULL;
static int
resend_match(struct resend *resend,
int kind, const unsigned char *prefix, unsigned char plen)
{
return (resend->kind == kind &&
resend->plen == plen && memcmp(resend->prefix, prefix, 16) == 0);
}
static struct resend *
find_resend(int kind, const unsigned char *prefix, unsigned char plen,
struct resend **previous_return)
{
struct resend *current, *previous;
previous = NULL;
current = to_resend;
while(current) {
if(resend_match(current, kind, prefix, plen)) {
if(previous_return)
*previous_return = previous;
return current;
}
previous = current;
current = current->next;
}
return NULL;
}
struct resend *
find_request(const unsigned char *prefix, unsigned char plen,
struct resend **previous_return)
{
return find_resend(RESEND_REQUEST, prefix, plen, previous_return);
}
int
record_resend(int kind, const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash,
struct network *network, int delay)
{
struct resend *resend;
unsigned int ifindex = network ? network->ifindex : 0;
if((kind == RESEND_REQUEST &&
input_filter(NULL, prefix, plen, NULL, ifindex) >= INFINITY) ||
(kind == RESEND_UPDATE &&
output_filter(NULL, prefix, plen, ifindex) >= INFINITY))
return 0;
if(delay >= 0xFFFF)
delay = 0xFFFF;
resend = find_resend(kind, prefix, plen, NULL);
if(resend) {
if(resend->delay && delay)
resend->delay = MIN(resend->delay, delay);
else if(delay)
resend->delay = delay;
resend->time = now;
resend->max = kind == RESEND_REQUEST ? 128 : UPDATE_MAX;
if(resend->router_hash == router_hash &&
seqno_compare(resend->seqno, seqno) > 0) {
return 0;
}
resend->router_hash = router_hash;
resend->seqno = seqno;
if(resend->network != network)
resend->network = NULL;
} else {
resend = malloc(sizeof(struct resend));
if(resend == NULL)
return -1;
resend->kind = kind;
resend->max = kind == RESEND_REQUEST ? 128 : UPDATE_MAX;
resend->delay = delay;
memcpy(resend->prefix, prefix, 16);
resend->plen = plen;
resend->seqno = seqno;
resend->router_hash = router_hash;
resend->network = network;
resend->time = now;
resend->next = to_resend;
to_resend = resend;
}
if(resend->delay) {
struct timeval timeout;
timeval_plus_msec(&timeout, &resend->time, resend->delay);
timeval_min(&resend_time, &timeout);
}
return 1;
}
static int
resend_expired(struct resend *resend)
{
switch(resend->kind) {
case RESEND_REQUEST:
return timeval_minus_msec(&now, &resend->time) >= REQUEST_TIMEOUT;
default:
return resend->max <= 0;
}
}
int
unsatisfied_request(const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash)
{
struct resend *request;
request = find_request(prefix, plen, NULL);
if(request == NULL || resend_expired(request))
return 0;
if(request->router_hash != router_hash ||
seqno_compare(request->seqno, seqno) <= 0)
return 1;
return 0;
}
/* Determine whether a given request should be forwarded. */
int
request_redundant(struct network *net,
const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash)
{
struct resend *request;
request = find_request(prefix, plen, NULL);
if(request == NULL || resend_expired(request))
return 0;
if(request->router_hash == router_hash &&
seqno_compare(request->seqno, seqno) > 0)
return 0;
if(request->network != NULL && request->network != net)
return 0;
if(request->max > 0)
/* Will be resent. */
return 1;
if(timeval_minus_msec(&now, &request->time) <
(net ? MIN(net->hello_interval, 1000) : 1000))
/* Fairly recent. */
return 1;
return 0;
}
int
satisfy_request(const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash,
struct network *network)
{
struct resend *request, *previous;
request = find_request(prefix, plen, &previous);
if(request == NULL)
return 0;
if(network != NULL && request->network != network)
return 0;
if(request->router_hash != router_hash ||
seqno_compare(request->seqno, seqno) <= 0) {
/* We cannot remove the request, as we may be walking the list right
now. Mark it as expired, so that expire_resend will remove it. */
request->max = 0;
request->time.tv_sec = 0;
recompute_resend_time();
return 1;
}
return 0;
}
void
expire_resend()
{
struct resend *current, *previous;
int recompute = 0;
previous = NULL;
current = to_resend;
while(current) {
if(resend_expired(current)) {
if(previous == NULL) {
to_resend = current->next;
free(current);
current = to_resend;
} else {
previous->next = current->next;
free(current);
current = previous->next;
}
recompute = 1;
} else {
current = current->next;
}
}
if(recompute)
recompute_resend_time();
}
void
recompute_resend_time()
{
struct resend *request;
struct timeval resend = {0, 0};
request = to_resend;
while(request) {
if(!resend_expired(request) && request->delay > 0 && request->max > 0) {
struct timeval timeout;
timeval_plus_msec(&timeout, &request->time, request->delay);
timeval_min(&resend_time, &timeout);
}
request = request->next;
}
resend_time = resend;
}
void
do_resend()
{
struct resend *resend;
resend = to_resend;
while(resend) {
if(!resend_expired(resend) && resend->delay > 0 && resend->max > 0) {
struct timeval timeout;
timeval_plus_msec(&timeout, &resend->time, resend->delay);
if(timeval_compare(&now, &timeout) >= 0) {
switch(resend->kind) {
case RESEND_REQUEST:
send_request(resend->network,
resend->prefix, resend->plen, 127,
resend->seqno, resend->router_hash);
break;
case RESEND_UPDATE:
send_update(resend->network, 1,
resend->prefix, resend->plen);
break;
default: abort();
}
resend->delay = MIN(0xFFFF, resend->delay * 2);
resend->max--;
}
}
resend = resend->next;
}
recompute_resend_time();
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/resend.h 0000664 0000000 0000000 00000004605 11073442770 0021422 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define REQUEST_TIMEOUT 65000
#define UPDATE_MAX 4
#define RESEND_REQUEST 1
#define RESEND_UPDATE 2
struct resend {
unsigned char kind;
unsigned char max;
unsigned short delay;
struct timeval time;
unsigned char prefix[16];
unsigned char plen;
unsigned short seqno;
unsigned short router_hash;
struct network *network;
struct resend *next;
};
extern struct timeval resend_time;
struct resend *find_request(const unsigned char *prefix, unsigned char plen,
struct resend **previous_return);
int record_resend(int kind, const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash,
struct network *net, int delay);
int unsatisfied_request(const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash);
int request_redundant(struct network *net,
const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash);
int satisfy_request(const unsigned char *prefix, unsigned char plen,
unsigned short seqno, unsigned short router_hash,
struct network *net);
void expire_resend(void);
void recompute_resend_time(void);
void do_resend(void);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/route.c 0000664 0000000 0000000 00000043756 11073442770 0021305 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "kernel.h"
#include "network.h"
#include "source.h"
#include "neighbour.h"
#include "route.h"
#include "xroute.h"
#include "message.h"
#include "resend.h"
#include "filter.h"
#include "local.h"
struct route *routes = NULL;
int numroutes = 0, maxroutes = 0;
unsigned kernel_metric = 0;
int route_timeout_delay = 160;
int route_gc_delay = 180;
struct route *
find_route(const unsigned char *prefix, unsigned char plen,
struct neighbour *neigh, const unsigned char *nexthop)
{
int i;
for(i = 0; i < numroutes; i++) {
if(routes[i].neigh == neigh &&
memcmp(routes[i].nexthop, nexthop, 16) == 0 &&
source_match(routes[i].src, prefix, plen))
return &routes[i];
}
return NULL;
}
struct route *
find_installed_route(const unsigned char *prefix, unsigned char plen)
{
int i;
for(i = 0; i < numroutes; i++) {
if(routes[i].installed && source_match(routes[i].src, prefix, plen))
return &routes[i];
}
return NULL;
}
void
flush_route(struct route *route)
{
int n;
struct source *src;
unsigned oldmetric;
int lost = 0;
n = route - routes;
assert(n >= 0 && n < numroutes);
oldmetric = route->metric;
if(route->installed) {
uninstall_route(route);
lost = 1;
}
local_notify_route(route, LOCAL_FLUSH);
src = route->src;
if(n != numroutes - 1)
memcpy(routes + n, routes + numroutes - 1, sizeof(struct route));
numroutes--;
VALGRIND_MAKE_MEM_UNDEFINED(routes + numroutes, sizeof(struct route));
if(numroutes == 0) {
free(routes);
routes = NULL;
maxroutes = 0;
} else if(maxroutes > 8 && numroutes < maxroutes / 4) {
struct route *new_routes;
int n = maxroutes / 2;
new_routes = realloc(routes, n * sizeof(struct route));
if(new_routes == NULL)
return;
routes = new_routes;
maxroutes = n;
}
if(lost)
route_lost(src, oldmetric);
}
void
flush_neighbour_routes(struct neighbour *neigh)
{
int i;
i = 0;
while(i < numroutes) {
if(routes[i].neigh == neigh) {
flush_route(&routes[i]);
continue;
}
i++;
}
}
unsigned
metric_to_kernel(unsigned metric)
{
if(metric >= INFINITY)
return KERNEL_INFINITY;
else
return MIN((metric + 255) / 256 + kernel_metric, KERNEL_INFINITY);
}
void
install_route(struct route *route)
{
int rc;
if(route->installed)
return;
rc = kernel_route(ROUTE_ADD, route->src->prefix, route->src->plen,
route->nexthop,
route->neigh->network->ifindex,
metric_to_kernel(route->metric), NULL, 0, 0);
if(rc < 0) {
perror("kernel_route(ADD)");
if(errno != EEXIST)
return;
}
route->installed = 1;
local_notify_route(route, LOCAL_CHANGE);
}
void
uninstall_route(struct route *route)
{
int rc;
if(!route->installed)
return;
rc = kernel_route(ROUTE_FLUSH, route->src->prefix, route->src->plen,
route->nexthop,
route->neigh->network->ifindex,
metric_to_kernel(route->metric), NULL, 0, 0);
if(rc < 0)
perror("kernel_route(FLUSH)");
route->installed = 0;
local_notify_route(route, LOCAL_CHANGE);
}
/* This is equivalent to uninstall_route followed with install_route,
but without the race condition. The destination of both routes
must be the same. */
void
switch_routes(struct route *old, struct route *new)
{
int rc;
if(!old) {
install_route(new);
return;
}
if(!old->installed)
return;
rc = kernel_route(ROUTE_MODIFY, old->src->prefix, old->src->plen,
old->nexthop, old->neigh->network->ifindex,
metric_to_kernel(old->metric),
new->nexthop, new->neigh->network->ifindex,
metric_to_kernel(new->metric));
if(rc >= 0) {
old->installed = 0;
new->installed = 1;
}
local_notify_route(old, LOCAL_CHANGE);
local_notify_route(new, LOCAL_CHANGE);
}
void
change_route_metric(struct route *route, unsigned newmetric)
{
int rc;
if(route->metric == newmetric)
return;
if(route->installed) {
rc = kernel_route(ROUTE_MODIFY,
route->src->prefix, route->src->plen,
route->nexthop,
route->neigh->network->ifindex,
metric_to_kernel(route->metric),
route->nexthop,
route->neigh->network->ifindex,
metric_to_kernel(newmetric));
if(rc < 0) {
perror("kernel_route(MODIFY)");
return;
}
}
route->metric = newmetric;
local_notify_route(route, LOCAL_CHANGE);
}
int
route_feasible(struct route *route)
{
return update_feasible(route->src->id,
route->src->prefix, route->src->plen,
route->seqno, route->refmetric);
}
int
update_feasible(const unsigned char *id,
const unsigned char *p, unsigned char plen,
unsigned short seqno, unsigned short refmetric)
{
struct source *src = find_source(id, p, plen, 0, 0);
if(src == NULL)
return 1;
if(src->time < now.tv_sec - SOURCE_GC_TIME)
/* Never mind what is probably stale data */
return 1;
if(refmetric >= INFINITY)
/* Retractions are always feasible */
return 1;
return (seqno_compare(seqno, src->seqno) > 0 ||
(src->seqno == seqno && refmetric < src->metric));
}
/* This returns the feasible route with the smallest metric. */
struct route *
find_best_route(const unsigned char *prefix, unsigned char plen, int feasible,
struct neighbour *exclude)
{
struct route *route = NULL;
int i;
for(i = 0; i < numroutes; i++) {
if(!source_match(routes[i].src, prefix, plen))
continue;
if(routes[i].time < now.tv_sec - route_timeout_delay)
continue;
if(feasible && !route_feasible(&routes[i]))
continue;
if(exclude && routes[i].neigh == exclude)
continue;
if(route && route->metric <= routes[i].metric)
continue;
route = &routes[i];
}
return route;
}
void
update_route_metric(struct route *route)
{
int oldmetric;
int newmetric;
oldmetric = route->metric;
if(route->time < now.tv_sec - route_timeout_delay) {
if(route->refmetric < INFINITY) {
route->seqno = seqno_plus(route->src->seqno, 1);
route->refmetric = INFINITY;
}
newmetric = INFINITY;
} else {
newmetric = MIN(route->refmetric + neighbour_cost(route->neigh),
INFINITY);
}
if(newmetric != oldmetric) {
change_route_metric(route, newmetric);
route_changed(route, route->src, oldmetric);
}
}
void
update_neighbour_metric(struct neighbour *neigh)
{
int i;
i = 0;
while(i < numroutes) {
if(routes[i].neigh == neigh)
update_route_metric(&routes[i]);
i++;
}
}
void
update_network_metric(struct network *net)
{
int i;
i = 0;
while(i < numroutes) {
if(routes[i].neigh->network == net)
update_route_metric(&routes[i]);
i++;
}
}
/* This is called whenever we receive an update. */
struct route *
update_route(const unsigned char *a, const unsigned char *p, unsigned char plen,
unsigned short seqno, unsigned short refmetric,
struct neighbour *neigh, const unsigned char *nexthop)
{
struct route *route;
struct source *src;
int metric, feasible;
int add_metric;
if(martian_prefix(p, plen)) {
fprintf(stderr, "Rejecting martian route to %s through %s.\n",
format_prefix(p, plen), format_address(a));
return NULL;
}
add_metric = input_filter(a, p, plen, neigh->id, neigh->network->ifindex);
if(add_metric >= INFINITY)
return NULL;
src = find_source(a, p, plen, 1, seqno);
if(src == NULL)
return NULL;
feasible = update_feasible(a, p, plen, seqno, refmetric);
route = find_route(p, plen, neigh, nexthop);
metric = MIN((int)refmetric + neighbour_cost(neigh) + add_metric, INFINITY);
if(route) {
struct source *oldsrc;
unsigned short oldseqno;
unsigned short oldmetric;
int lost = 0;
oldsrc = route->src;
oldseqno = route->seqno;
oldmetric = route->metric;
/* If a successor switches sources, we must accept his update even
if it makes a route unfeasible in order to break any routing loops
in a timely manner. If the source remains the same, we ignore
the update but send a request for a new seqno. */
if(!feasible && route->installed) {
debugf("Unfeasible update for installed route to %s "
"(%s %d %d -> %s %d %d).\n",
format_prefix(src->prefix, src->plen),
format_address(route->src->id),
route->seqno, route->refmetric,
format_address(src->id), seqno, refmetric);
if(src == route->src) {
send_unfeasible_request(neigh, 1, seqno, metric, a, p, plen);
return route;
}
uninstall_route(route);
lost = 1;
}
route->src = src;
if(feasible && refmetric < INFINITY)
route->time = now.tv_sec;
route->seqno = seqno;
route->refmetric = refmetric;
change_route_metric(route, metric);
if(feasible)
route_changed(route, oldsrc, oldmetric);
else
send_unfeasible_request(neigh, 0, seqno, metric, a, p, plen);
if(lost)
route_lost(oldsrc, oldmetric);
} else {
if(!feasible) {
send_unfeasible_request(neigh, 0, seqno, metric, a, p, plen);
return NULL;
}
if(refmetric >= INFINITY)
/* Somebody's retracting a route we never saw. */
return NULL;
if(numroutes >= maxroutes) {
struct route *new_routes;
int n = maxroutes < 1 ? 8 : 2 * maxroutes;
new_routes = routes == NULL ?
malloc(n * sizeof(struct route)) :
realloc(routes, n * sizeof(struct route));
if(new_routes == NULL)
return NULL;
maxroutes = n;
routes = new_routes;
}
route = &routes[numroutes];
route->src = src;
route->refmetric = refmetric;
route->seqno = seqno;
route->metric = metric;
route->neigh = neigh;
memcpy(route->nexthop, nexthop, 16);
route->time = now.tv_sec;
route->installed = 0;
numroutes++;
local_notify_route(route, LOCAL_ADD);
consider_route(route);
}
return route;
}
/* We just received an unfeasible update. If it's any good, send
a request for a new seqno. */
void
send_unfeasible_request(struct neighbour *neigh, int force,
unsigned short seqno, unsigned short metric,
const unsigned char *a,
const unsigned char *prefix, unsigned char plen)
{
struct route *route = find_installed_route(prefix, plen);
struct source *src = find_source(a, prefix, plen, 0, 0);
if(src == NULL)
return;
if(seqno_minus(src->seqno, seqno) > 100) {
/* Probably a source that lost its seqno. Let it time-out. */
return;
}
if(force || !route || route->metric >= metric + 256) {
send_request_resend(neigh, prefix, plen,
src->metric >= INFINITY ?
src->seqno : seqno_plus(src->seqno, 1),
hash_id(src->id));
}
}
/* This takes a feasible route and decides whether to install it. */
void
consider_route(struct route *route)
{
struct route *installed;
if(route->installed)
return;
if(!route_feasible(route))
return;
if(find_xroute(route->src->prefix, route->src->plen))
return;
installed = find_installed_route(route->src->prefix, route->src->plen);
if(installed == NULL)
goto install;
if(route->metric >= INFINITY)
return;
if(installed->metric >= INFINITY)
goto install;
if(installed->metric >= route->metric + 192)
goto install;
/* Avoid switching sources */
if(installed->src != route->src)
return;
if(installed->metric >= route->metric + 64)
goto install;
return;
install:
switch_routes(installed, route);
if(installed && route->installed)
send_triggered_update(route, installed->src, installed->metric);
else
send_update(NULL, 1, route->src->prefix, route->src->plen);
return;
}
void
send_triggered_update(struct route *route, struct source *oldsrc,
unsigned oldmetric)
{
int urgent = 0;
unsigned newmetric, diff;
if(!route->installed)
return;
newmetric = route->metric;
diff =
newmetric >= oldmetric ? newmetric - oldmetric : oldmetric - newmetric;
if(route->src != oldsrc || (oldmetric < INFINITY && newmetric >= INFINITY))
/* Switching sources can cause transient routing loops.
Retractions are always urgent. */
urgent = 2;
else if(newmetric >= 6 * 256 && oldmetric >= 6 * 256)
/* Don't be noisy about far-away nodes */
urgent = -1;
else if(diff >= 512)
urgent = 1;
/* Make sure that requests are satisfied speedily */
if(urgent < 1) {
if(unsatisfied_request(route->src->prefix, route->src->plen,
route->seqno, hash_id(route->src->id)))
urgent = 1;
}
if(urgent < 0 || (!urgent && diff < 256))
/* Never mind. */
return;
if(urgent >= 2)
send_update_resend(NULL, route->src->prefix, route->src->plen);
else
send_update(NULL, urgent, route->src->prefix, route->src->plen);
if(oldmetric < INFINITY) {
if(newmetric >= oldmetric + 384) {
send_request_resend(NULL, route->src->prefix, route->src->plen,
route->src->metric >= INFINITY ?
route->src->seqno :
seqno_plus(route->src->seqno, 1),
hash_id(route->src->id));
} else if(newmetric >= oldmetric + 288) {
send_request(NULL, route->src->prefix, route->src->plen,
0, 0, 0);
}
}
}
/* A route has just changed. Decide whether to switch to a different route or
send an update. */
void
route_changed(struct route *route,
struct source *oldsrc, unsigned short oldmetric)
{
if(route->installed) {
if(route->metric > oldmetric) {
struct route *better_route;
better_route =
find_best_route(route->src->prefix, route->src->plen, 1, NULL);
if(better_route && better_route->metric <= route->metric - 96)
consider_route(better_route);
}
if(route->installed)
send_triggered_update(route, oldsrc, oldmetric);
} else {
/* Reconsider routes even when their metric didn't decrease,
they may not have been feasible before. */
consider_route(route);
}
}
/* We just lost the installed route to a given destination. */
void
route_lost(struct source *src, unsigned oldmetric)
{
struct route *new_route;
new_route = find_best_route(src->prefix, src->plen, 1, NULL);
if(new_route) {
consider_route(new_route);
} else if(oldmetric < INFINITY) {
/* Complain loudly. */
send_update_resend(NULL, src->prefix, src->plen);
send_request_resend(NULL, src->prefix, src->plen,
src->metric >= INFINITY ?
src->seqno : seqno_plus(src->seqno, 1),
hash_id(src->id));
}
}
void
expire_routes(void)
{
int i;
debugf("Expiring old routes.\n");
i = 0;
while(i < numroutes) {
struct route *route = &routes[i];
if(route->time > now.tv_sec || /* clock stepped */
route->time < now.tv_sec - route_gc_delay) {
flush_route(route);
continue;
}
update_route_metric(route);
if(route->installed && route->refmetric < INFINITY) {
if(route->time < now.tv_sec - MAX(10, route_timeout_delay * 7 / 8))
send_unicast_request(route->neigh,
route->src->prefix, route->src->plen,
0, 0, 0);
}
i++;
}
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/route.h 0000664 0000000 0000000 00000007075 11073442770 0021304 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
struct route {
struct source *src;
unsigned short metric;
unsigned short refmetric;
unsigned short seqno;
struct neighbour *neigh;
unsigned char nexthop[16];
time_t time;
int installed;
};
extern struct route *routes;
extern int numroutes, maxroutes;
extern unsigned kernel_metric;
extern int route_timeout_delay;
extern int route_gc_delay;
struct route *find_route(const unsigned char *prefix, unsigned char plen,
struct neighbour *neigh, const unsigned char *nexthop);
struct route *find_installed_route(const unsigned char *prefix,
unsigned char plen);
void flush_route(struct route *route);
void flush_neighbour_routes(struct neighbour *neigh);
unsigned metric_to_kernel(unsigned metric);
void install_route(struct route *route);
void uninstall_route(struct route *route);
void switch_route(struct route *old, struct route *new);
void change_route_metric(struct route *route, unsigned newmetric);
int route_feasible(struct route *route);
int update_feasible(const unsigned char *id,
const unsigned char *p, unsigned char plen,
unsigned short seqno, unsigned short refmetric);
struct route *find_best_route(const unsigned char *prefix, unsigned char plen,
int feasible, struct neighbour *exclude);
struct route *install_best_route(const unsigned char prefix[16],
unsigned char plen);
void update_neighbour_metric(struct neighbour *neigh);
void update_network_metric(struct network *net);
void update_route_metric(struct route *route);
struct route *update_route(const unsigned char *a,
const unsigned char *p, unsigned char plen,
unsigned short seqno, unsigned short refmetric,
struct neighbour *neigh,
const unsigned char *nexthop);
void send_unfeasible_request(struct neighbour *neigh, int force,
unsigned short seqno, unsigned short metric,
const unsigned char *a,
const unsigned char *prefix, unsigned char plen);
void consider_route(struct route *route);
void send_triggered_update(struct route *route,
struct source *oldsrc, unsigned oldmetric);
void route_changed(struct route *route,
struct source *oldsrc, unsigned short oldmetric);
void route_lost(struct source *src, unsigned oldmetric);
void expire_routes(void);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/source.c 0000664 0000000 0000000 00000007216 11073442770 0021436 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include "babel.h"
#include "util.h"
#include "source.h"
#include "network.h"
#include "route.h"
struct source *srcs = NULL;
struct source*
find_source(const unsigned char *id, const unsigned char *p, unsigned char plen,
int create, unsigned short seqno)
{
struct source *src;
for(src = srcs; src; src = src->next) {
/* This should really be a hash table. For now, check the
last byte first. */
if(src->id[15] != id[15])
continue;
if(memcmp(src->id, id, 16) != 0)
continue;
if(source_match(src, p, plen))
return src;
}
if(!create)
return NULL;
src = malloc(sizeof(struct source));
if(src == NULL) {
perror("malloc(source)");
return NULL;
}
memcpy(src->id, id, 16);
memcpy(src->prefix, p, 16);
src->plen = plen;
src->seqno = seqno;
src->metric = INFINITY;
src->time = now.tv_sec;
src->next = srcs;
srcs = src;
return src;
}
int
flush_source(struct source *src)
{
int i;
/* This is absolutely horrible -- it makes expire_sources quadratic.
But it's not called very often. */
for(i = 0; i < numroutes; i++) {
if(routes[i].src == src)
return 0;
}
if(srcs == src) {
srcs = src->next;
} else {
struct source *previous = srcs;
while(previous->next != src)
previous = previous->next;
previous->next = src->next;
}
free(src);
return 1;
}
int
source_match(struct source *src,
const unsigned char *p, unsigned char plen)
{
if(src->plen != plen)
return 0;
if(src->prefix[15] != p[15])
return 0;
if(memcmp(src->prefix, p, 16) != 0)
return 0;
return 1;
}
void
update_source(struct source *src,
unsigned short seqno, unsigned short metric)
{
if(metric >= INFINITY)
return;
if(src->time < now.tv_sec - SOURCE_GC_TIME ||
seqno_compare(src->seqno, seqno) < 0 ||
(src->seqno == seqno && src->metric > metric)) {
src->seqno = seqno;
src->metric = metric;
}
src->time = now.tv_sec;
}
void
expire_sources()
{
struct source *src;
src = srcs;
while(src) {
if(src->time > now.tv_sec)
/* clock stepped */
src->time = now.tv_sec;
if(src->time < now.tv_sec - SOURCE_GC_TIME) {
struct source *old = src;
src = src->next;
flush_source(old);
continue;
}
src = src->next;
}
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/source.h 0000664 0000000 0000000 00000003366 11073442770 0021445 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#define SOURCE_GC_TIME 200
struct source {
struct source *next;
unsigned char id[16];
unsigned char prefix[16];
unsigned char plen;
unsigned short seqno;
unsigned short metric;
time_t time;
};
int source_match(struct source *src,
const unsigned char *p, unsigned char plen);
struct source *find_source(const unsigned char *id,
const unsigned char *p,
unsigned char plen,
int create, unsigned short seqno);
int flush_source(struct source *src);
void update_source(struct source *src,
unsigned short seqno, unsigned short metric);
void expire_sources(void);
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/util.c 0000664 0000000 0000000 00000023177 11073442770 0021117 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "babel.h"
#include "util.h"
int
seqno_compare(unsigned short s1, unsigned short s2)
{
if(s1 == s2)
return 0;
else if(((s2 - s1) & 0xFFFF) < 0x8000)
return -1;
else
return 1;
}
int
seqno_minus(unsigned short s1, unsigned short s2)
{
if(s1 == s2)
return 0;
else if(((s2 - s1) & 0xFFFF) < 0x8000)
return -(int)((s2 - s1) & 0xFFFF);
else
return ((s1 - s2) & 0xFFFF);
}
unsigned short
seqno_plus(unsigned short s, int plus)
{
return ((s + plus) & 0xFFFF);
}
int
roughly(int value)
{
return value * 3 / 4 + random() % (value / 2);
}
void
timeval_minus(struct timeval *d,
const struct timeval *s1, const struct timeval *s2)
{
if(s1->tv_usec > s2->tv_usec) {
d->tv_usec = s1->tv_usec - s2->tv_usec;
d->tv_sec = s1->tv_sec - s2->tv_sec;
} else {
d->tv_usec = s1->tv_usec + 1000000 - s2->tv_usec;
d->tv_sec = s1->tv_sec - s2->tv_sec - 1;
}
}
int
timeval_minus_msec(const struct timeval *s1, const struct timeval *s2)
{
/* Avoid overflow. This may happen if the clock is changed */
if(s1->tv_sec - s2->tv_sec > 2000000)
return 2000000000;
else if(s1->tv_sec - s2->tv_sec < -2000000)
return -2000000000;
return (s1->tv_sec - s2->tv_sec) * 1000 +
(s1->tv_usec - s2->tv_usec) / 1000;
}
void
timeval_plus_msec(struct timeval *d, const struct timeval *s, int msecs)
{
int usecs;
d->tv_sec = s->tv_sec + msecs / 1000;
usecs = s->tv_usec + (msecs % 1000) * 1000;
if(usecs < 1000000) {
d->tv_usec = usecs;
} else {
d->tv_usec = usecs - 1000000;
d->tv_sec++;
}
}
int
timeval_compare(const struct timeval *s1, const struct timeval *s2)
{
if(s1->tv_sec < s2->tv_sec)
return -1;
else if(s1->tv_sec > s2->tv_sec)
return 1;
else if(s1->tv_usec < s2->tv_usec)
return -1;
else if(s1->tv_usec > s2->tv_usec)
return 1;
else
return 0;
}
/* {0, 0} represents infinity */
void
timeval_min(struct timeval *d, const struct timeval *s)
{
if(s->tv_sec == 0)
return;
if(d->tv_sec == 0 || timeval_compare(d, s) > 0) {
*d = *s;
}
}
void
timeval_min_sec(struct timeval *d, time_t secs)
{
if(d->tv_sec == 0 || d->tv_sec > secs) {
d->tv_sec = secs;
d->tv_usec = random() % 1000000;
}
}
int
parse_msec(const char *string)
{
unsigned int in, fl;
int i, j;
in = fl = 0;
i = 0;
while(string[i] == ' ' || string[i] == '\t')
i++;
while(string[i] >= '0' && string[i] <= '9') {
in = in * 10 + string[i] - '0';
i++;
}
if(string[i] == '.') {
i++;
j = 0;
while(string[i] >= '0' && string[i] <= '9') {
fl = fl * 10 + string[i] - '0';
i++;
j++;
}
while(j > 3) {
fl /= 10;
j--;
}
while(j < 3) {
fl *= 10;
j++;
}
}
while(string[i] == ' ' || string[i] == '\t')
i++;
if(string[i] == '\0')
return in * 1000 + fl;
return -1;
}
void
do_debugf(int level, const char *format, ...)
{
va_list args;
va_start(args, format);
if(debug >= level)
vfprintf(stderr, format, args);
va_end(args);
fflush(stderr);
}
int
in_prefix(const unsigned char *address,
const unsigned char *prefix, unsigned char plen)
{
unsigned char m;
if(plen > 128)
plen = 128;
if(memcmp(address, prefix, plen / 8) != 0)
return 0;
m = 0xFF << (8 - (plen % 8));
return ((address[plen / 8] & m) == (prefix[plen / 8] & m));
}
const unsigned char *
mask_prefix(unsigned char *ret,
const unsigned char *prefix, unsigned char plen)
{
if(plen > 128)
plen = 128;
memset(ret, 0, 16);
memcpy(ret, prefix, plen / 8);
if(plen % 8 != 0)
ret[plen / 8] = (prefix[plen / 8] & (0xFF << (8 - (plen % 8))));
return (const unsigned char *)ret;
}
static const unsigned char v4prefix[16] =
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 };
const char *
format_address(const unsigned char *address)
{
static char buf[4][INET6_ADDRSTRLEN];
static int i = 0;
i = (i + 1) % 4;
if(v4mapped(address))
inet_ntop(AF_INET, address + 12, buf[i], INET6_ADDRSTRLEN);
else
inet_ntop(AF_INET6, address, buf[i], INET6_ADDRSTRLEN);
return buf[i];
}
const char *
format_prefix(const unsigned char *prefix, unsigned char plen)
{
static char buf[4][INET6_ADDRSTRLEN + 4];
static int i = 0;
int n;
i = (i + 1) % 4;
if(plen >= 96 && v4mapped(prefix)) {
inet_ntop(AF_INET, prefix + 12, buf[i], INET6_ADDRSTRLEN);
n = strlen(buf[i]);
snprintf(buf[i] + n, INET6_ADDRSTRLEN + 4 - n, "/%d", plen - 96);
} else {
inet_ntop(AF_INET6, prefix, buf[i], INET6_ADDRSTRLEN);
n = strlen(buf[i]);
snprintf(buf[i] + n, INET6_ADDRSTRLEN + 4 - n, "/%d", plen);
}
return buf[i];
}
int
parse_address(const char *address, unsigned char *addr_r, int *af_r)
{
struct in_addr ina;
struct in6_addr ina6;
int rc;
rc = inet_pton(AF_INET, address, &ina);
if(rc > 0) {
memcpy(addr_r, v4prefix, 12);
memcpy(addr_r + 12, &ina, 4);
if(af_r) *af_r = AF_INET;
return 0;
}
rc = inet_pton(AF_INET6, address, &ina6);
if(rc > 0) {
memcpy(addr_r, &ina6, 16);
if(af_r) *af_r = AF_INET6;
return 0;
}
return -1;
}
int
parse_net(const char *net, unsigned char *prefix_r, unsigned char *plen_r,
int *af_r)
{
char buf[INET6_ADDRSTRLEN];
char *slash, *end;
unsigned char prefix[16];
long plen;
int af;
struct in_addr ina;
struct in6_addr ina6;
int rc;
if(strcmp(net, "default") == 0) {
memset(prefix, 0, 16);
plen = 0;
} else {
slash = strchr(net, '/');
if(slash == NULL) {
rc = parse_address(net, prefix, &af);
if(rc < 0)
return rc;
plen = 128;
} else {
if(slash - net >= INET6_ADDRSTRLEN)
return -1;
memcpy(buf, net, slash - net);
buf[slash - net] = '\0';
rc = inet_pton(AF_INET, buf, &ina);
if(rc > 0) {
memcpy(prefix, v4prefix, 12);
memcpy(prefix + 12, &ina, 4);
plen = strtol(slash + 1, &end, 0);
if(*end != '\0' || plen < 0 || plen > 32)
return -1;
plen += 96;
af = AF_INET;
} else {
rc = inet_pton(AF_INET6, buf, &ina6);
if(rc > 0) {
memcpy(prefix, &ina6, 16);
plen = strtol(slash + 1, &end, 0);
if(*end != '\0' || plen < 0 || plen > 128)
return -1;
af = AF_INET6;
} else {
return -1;
}
}
}
}
mask_prefix(prefix_r, prefix, plen);
*plen_r = plen;
if(af_r) *af_r = af;
return 0;
}
int
wait_for_fd(int direction, int fd, int msecs)
{
fd_set fds;
int rc;
struct timeval tv;
tv.tv_sec = msecs / 1000;
tv.tv_usec = (msecs % 1000) * 1000;
FD_ZERO(&fds);
FD_SET(fd, &fds);
if(direction)
rc = select(fd + 1, NULL, &fds, NULL, &tv);
else
rc = select(fd + 1, &fds, NULL, NULL, &tv);
return rc;
}
int
martian_prefix(const unsigned char *prefix, int plen)
{
return
(plen >= 8 && prefix[0] == 0xFF) ||
(plen >= 10 && prefix[0] == 0xFE && (prefix[1] & 0xC0) == 0x80) ||
(plen >= 128 && memcmp(prefix, zeroes, 15) == 0 &&
(prefix[15] == 0 || prefix[15] == 1)) ||
(plen >= 96 && v4mapped(prefix) &&
((plen >= 104 && (prefix[12] == 127 || prefix[12] == 0)) ||
(plen >= 100 &&
((prefix[12] & 0xF0) == 0xF0 || (prefix[12] & 0xF0) == 0xE0))));
}
int
v4mapped(const unsigned char *address)
{
return in_prefix(address, v4prefix, 96);
}
void
v4tov6(unsigned char *dst, const unsigned char *src)
{
memcpy(dst, v4prefix, 12);
memcpy(dst + 12, src, 4);
}
int
daemonise()
{
int rc;
fflush(stdout);
fflush(stderr);
rc = fork();
if(rc < 0)
return -1;
if(rc > 0)
exit(0);
rc = setsid();
if(rc < 0)
return -1;
return 1;
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/util.h 0000664 0000000 0000000 00000007231 11073442770 0021115 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
int seqno_compare(unsigned short s1, unsigned short s2)
ATTRIBUTE ((const));
int seqno_minus(unsigned short s1, unsigned short s2)
ATTRIBUTE ((const));
unsigned short seqno_plus(unsigned short s, int plus)
ATTRIBUTE ((const));
int roughly(int value);
void timeval_minus(struct timeval *d,
const struct timeval *s1, const struct timeval *s2);
int timeval_minus_msec(const struct timeval *s1, const struct timeval *s2)
ATTRIBUTE ((pure));
void timeval_plus_msec(struct timeval *d,
const struct timeval *s, int msecs);
int timeval_compare(const struct timeval *s1, const struct timeval *s2)
ATTRIBUTE ((pure));
void timeval_min(struct timeval *d, const struct timeval *s);
void timeval_min_sec(struct timeval *d, time_t secs);
int parse_msec(const char *string) ATTRIBUTE ((pure));
void do_debugf(int leve, const char *format, ...)
ATTRIBUTE ((format (printf, 2, 3)));
int in_prefix(const unsigned char *address,
const unsigned char *prefix, unsigned char plen)
ATTRIBUTE ((pure));
const unsigned char *mask_prefix(unsigned char *ret,
const unsigned char *prefix,
unsigned char plen);
const char *format_address(const unsigned char *address);
const char *format_prefix(const unsigned char *address, unsigned char prefix);
int parse_address(const char *address, unsigned char *addr_r, int *af_r);
int parse_net(const char *net, unsigned char *prefix_r, unsigned char *plen_r,
int *af_r);
int wait_for_fd(int direction, int fd, int msecs);
int martian_prefix(const unsigned char *prefix, int plen) ATTRIBUTE ((pure));
int v4mapped(const unsigned char *address) ATTRIBUTE ((pure));
void v4tov6(unsigned char *dst, const unsigned char *src);
int daemonise(void);
/* If debugging is disabled, we want to avoid calling format_address
for every omitted debugging message. So debug is a macro. But
vararg macros are not portable. */
#if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L
#define debugf(...) \
do { \
if(debug >= 2) do_debugf(2, __VA_ARGS__); \
} while(0)
#define kdebugf(...) \
do { \
if(debug >= 3) do_debugf(3, __VA_ARGS__); \
} while(0)
#elif defined __GNUC__
#define debugf(_args...) \
do { \
if(debug >= 2) do_debugf(2, _args); \
} while(0)
#define kdebugf(_args...) \
do { \
if(debug >= 3) do_debugf(3, _args); \
} while(0)
#else
/* Disable debugging code */
static void debugf(const char *format, ...) { return; }
static void kdebugf(const char *format, ...) { return; }
#endif
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/xroute.c 0000664 0000000 0000000 00000016203 11073442770 0021460 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include
#include
#include
#include
#include
#include
#include "babel.h"
#include "kernel.h"
#include "neighbour.h"
#include "message.h"
#include "route.h"
#include "xroute.h"
#include "util.h"
#include "filter.h"
#include "network.h"
#include "local.h"
struct xroute *xroutes;
int numxroutes = 0;
int maxxroutes = 0;
struct xroute *
find_xroute(const unsigned char *prefix, unsigned char plen)
{
int i;
for(i = 0; i < numxroutes; i++) {
if(xroutes[i].plen == plen &&
memcmp(xroutes[i].prefix, prefix, 16) == 0)
return &xroutes[i];
}
return NULL;
}
void
flush_xroute(struct xroute *xroute)
{
int n;
n = xroute - xroutes;
assert(n >= 0 && n < numxroutes);
local_notify_xroute(xroute, LOCAL_FLUSH);
if(n != numxroutes - 1)
memcpy(xroutes + n, xroutes + numxroutes - 1, sizeof(struct xroute));
numxroutes--;
VALGRIND_MAKE_MEM_UNDEFINED(xroutes + numxroutes, sizeof(struct xroute));
if(numxroutes == 0) {
free(xroutes);
xroutes = NULL;
maxxroutes = 0;
} else if(maxxroutes > 8 && numxroutes < maxxroutes / 4) {
struct xroute *new_xroutes;
int n = maxxroutes / 2;
new_xroutes = realloc(xroutes, n * sizeof(struct xroute));
if(new_xroutes == NULL)
return;
xroutes = new_xroutes;
maxxroutes = n;
}
}
int
add_xroute(unsigned char prefix[16], unsigned char plen,
unsigned short metric, unsigned int ifindex, int proto)
{
struct xroute *xroute = find_xroute(prefix, plen);
if(xroute) {
if(xroute->metric <= metric)
return 0;
xroute->metric = metric;
local_notify_xroute(xroute, LOCAL_CHANGE);
return 1;
}
if(numxroutes >= maxxroutes) {
struct xroute *new_xroutes;
int n = maxxroutes < 1 ? 8 : 2 * maxxroutes;
new_xroutes = xroutes == NULL ?
malloc(n * sizeof(struct xroute)) :
realloc(xroutes, n * sizeof(struct xroute));
if(new_xroutes == NULL)
return -1;
maxxroutes = n;
xroutes = new_xroutes;
}
memcpy(xroutes[numxroutes].prefix, prefix, 16);
xroutes[numxroutes].plen = plen;
xroutes[numxroutes].metric = metric;
xroutes[numxroutes].ifindex = ifindex;
xroutes[numxroutes].proto = proto;
numxroutes++;
local_notify_xroute(&xroutes[numxroutes - 1], LOCAL_ADD);
return 1;
}
int
check_xroutes(int send_updates)
{
int i, j, metric, export, change = 0, rc;
struct kernel_route *routes;
int numroutes;
static int maxroutes = 8;
const int maxmaxroutes = 16 * 1024;
debugf("\nChecking kernel routes.\n");
again:
routes = malloc(maxroutes * sizeof(struct kernel_route));
if(routes == NULL)
return -1;
rc = kernel_addresses(routes, maxroutes);
if(rc < 0) {
perror("kernel_addresses");
numroutes = 0;
} else {
numroutes = rc;
}
if(numroutes >= maxroutes)
goto resize;
rc = kernel_routes(routes + numroutes, maxroutes - numroutes);
if(rc < 0)
fprintf(stderr, "Couldn't get kernel routes.\n");
else
numroutes += rc;
if(numroutes >= maxroutes)
goto resize;
/* Check for any routes that need to be flushed */
i = 0;
while(i < numxroutes) {
export = 0;
metric = redistribute_filter(xroutes[i].prefix, xroutes[i].plen,
xroutes[i].ifindex, xroutes[i].proto);
if((metric < INFINITY && metric == xroutes[i].metric) ||
metric == METRIC_INHERIT) {
for(j = 0; j < numroutes; j++) {
if(xroutes[i].plen == routes[j].plen &&
memcmp(xroutes[i].prefix, routes[j].prefix, 16) == 0 &&
xroutes[i].ifindex == routes[j].ifindex &&
xroutes[i].proto == routes[j].proto) {
if(metric < INFINITY) {
export = 1;
break;
} else if(metric == METRIC_INHERIT &&
xroutes[i].metric == routes[j].metric * 256) {
export = 1;
break;
}
}
}
}
if(!export) {
unsigned char prefix[16], plen;
struct route *route;
memcpy(prefix, xroutes[i].prefix, 16);
plen = xroutes[i].plen;
flush_xroute(&xroutes[i]);
route = find_best_route(prefix, plen, 1, NULL);
if(route)
install_route(route);
/* send_update_resend only records the prefix, so the update
will only be sent after we perform all of the changes. */
if(send_updates)
send_update_resend(NULL, prefix, plen);
change = 1;
} else {
i++;
}
}
/* Add any new routes */
for(i = 0; i < numroutes; i++) {
if(martian_prefix(routes[i].prefix, routes[i].plen))
continue;
metric = redistribute_filter(routes[i].prefix, routes[i].plen,
routes[i].ifindex, routes[i].proto);
if(metric == METRIC_INHERIT)
metric = routes[i].metric * 256;
if(metric < INFINITY) {
rc = add_xroute(routes[i].prefix, routes[i].plen,
metric, routes[i].ifindex, routes[i].proto);
if(rc) {
struct route *route;
route = find_installed_route(routes[i].prefix, routes[i].plen);
if(route)
uninstall_route(route);
change = 1;
if(send_updates)
send_update(NULL, 0, routes[i].prefix, routes[i].plen);
}
}
}
free(routes);
/* Set up maxroutes for the next call. */
maxroutes = MIN(numroutes + 8, maxmaxroutes);
return change;
resize:
free(routes);
if(maxroutes >= maxmaxroutes)
return -1;
maxroutes = MIN(maxmaxroutes, 2 * maxroutes);
goto again;
}
babeld-123f9ffbf6fb0f9b1e21992d914187d5aed89727/xroute.h 0000664 0000000 0000000 00000003127 11073442770 0021466 0 ustar 00root root 0000000 0000000 /*
Copyright (c) 2007, 2008 by Juliusz Chroboczek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* These should come in decreasing order of priority. */
struct xroute {
unsigned char prefix[16];
unsigned char plen;
unsigned short metric;
unsigned int ifindex;
int proto;
};
extern struct xroute *xroutes;
extern int numxroutes;
struct xroute *find_xroute(const unsigned char *prefix, unsigned char plen);
void flush_xroute(struct xroute *xroute);
int add_xroute(unsigned char prefix[16], unsigned char plen,
unsigned short metric, unsigned int ifindex, int proto);
int check_xroutes(int send_updates);