summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.cvsignore1
-rw-r--r--.gitignore12
-rw-r--r--Makefile.in33
-rw-r--r--NEWS16
-rw-r--r--README156
-rw-r--r--client/birdcl.c2
-rw-r--r--client/util.c4
-rw-r--r--conf/Makefile3
-rw-r--r--conf/cf-lex.l5
-rw-r--r--conf/conf.c11
-rw-r--r--conf/conf.h10
-rw-r--r--conf/confbase.Y8
-rw-r--r--configure.in13
-rw-r--r--doc/Makefile11
-rw-r--r--doc/bird.sgml1292
-rw-r--r--doc/sbase/dist/birddoc/groff/mapping144
-rw-r--r--doc/sbase/dist/birddoc/html/mapping72
-rw-r--r--doc/sbase/dist/birddoc/latex2e/mapping63
-rw-r--r--doc/sbase/dist/fmt_latex2e.pl4
-rw-r--r--doc/sbase/dtd/birddoc.dtd112
-rw-r--r--filter/Makefile4
-rw-r--r--filter/config.Y258
-rw-r--r--filter/filter.c245
-rw-r--r--filter/filter.h49
-rw-r--r--filter/filter_test.c87
-rw-r--r--filter/test.conf1396
-rw-r--r--filter/test.conf.inc6
-rw-r--r--filter/test.conf294
-rw-r--r--filter/test6.conf182
-rw-r--r--filter/tree.c17
-rw-r--r--filter/tree_test.c304
-rw-r--r--filter/trie.c10
-rw-r--r--filter/trie_test.c185
-rw-r--r--lib/Doc1
-rw-r--r--lib/Makefile6
-rw-r--r--lib/birdlib.h5
-rw-r--r--lib/bitops.h2
-rw-r--r--lib/bitops_test.c123
-rw-r--r--lib/buffer.h16
-rw-r--r--lib/buffer_test.c147
-rw-r--r--lib/checksum_test.c94
-rw-r--r--lib/event_test.c88
-rw-r--r--lib/fletcher16_test.c169
-rw-r--r--lib/hash.h29
-rw-r--r--lib/hash_test.c305
-rw-r--r--lib/heap_test.c186
-rw-r--r--lib/idm.c2
-rw-r--r--lib/ip.c2
-rw-r--r--lib/ip.h1
-rw-r--r--lib/ip_test.c161
-rw-r--r--lib/lists.c12
-rw-r--r--lib/lists.h1
-rw-r--r--lib/lists_test.c287
-rw-r--r--lib/mac.c289
-rw-r--r--lib/mac.h121
-rw-r--r--lib/mac_test.c1159
-rw-r--r--lib/md5.c81
-rw-r--r--lib/md5.h21
-rw-r--r--lib/net.c18
-rw-r--r--lib/net.h2
-rw-r--r--lib/patmatch_test.c149
-rw-r--r--lib/printf.c2
-rw-r--r--lib/printf_test.c70
-rw-r--r--lib/sha1.c95
-rw-r--r--lib/sha1.h30
-rw-r--r--lib/sha256.c150
-rw-r--r--lib/sha256.h42
-rw-r--r--lib/sha512.c150
-rw-r--r--lib/sha512.h44
-rw-r--r--lib/slist_test.c384
-rw-r--r--lib/slists.c82
-rw-r--r--lib/socket.h2
-rw-r--r--lib/string.h30
-rw-r--r--lib/unaligned.h18
-rw-r--r--misc/bird.spec2
-rw-r--r--nest/Makefile4
-rw-r--r--nest/a-path.c465
-rw-r--r--nest/a-path_test.c214
-rw-r--r--nest/a-set.c219
-rw-r--r--nest/a-set_test.c260
-rw-r--r--nest/attrs.h110
-rw-r--r--nest/bfd.h2
-rw-r--r--nest/cmds.c1
-rw-r--r--nest/config.Y34
-rw-r--r--nest/iface.h1
-rw-r--r--nest/locks.c3
-rw-r--r--nest/password.c17
-rw-r--r--nest/password.h11
-rw-r--r--nest/proto.c10
-rw-r--r--nest/protocol.h12
-rw-r--r--nest/route.h29
-rw-r--r--nest/rt-attr.c49
-rw-r--r--nest/rt-table.c86
-rw-r--r--proto/babel/babel.c163
-rw-r--r--proto/babel/babel.h8
-rw-r--r--proto/babel/config.Y9
-rw-r--r--proto/babel/packets.c111
-rw-r--r--proto/bfd/Makefile2
-rw-r--r--proto/bfd/bfd.c8
-rw-r--r--proto/bfd/bfd.h19
-rw-r--r--proto/bfd/config.Y46
-rw-r--r--proto/bfd/io.c2
-rw-r--r--proto/bfd/packets.c249
-rw-r--r--proto/bgp/Makefile2
-rw-r--r--proto/bgp/attrs.c2571
-rw-r--r--proto/bgp/bgp.c1369
-rw-r--r--proto/bgp/bgp.h422
-rw-r--r--proto/bgp/config.Y132
-rw-r--r--proto/bgp/packets.c2679
-rw-r--r--proto/ospf/Makefile2
-rw-r--r--proto/ospf/config.Y14
-rw-r--r--proto/ospf/hello.c7
-rw-r--r--proto/ospf/iface.c28
-rw-r--r--proto/ospf/lsalib.c2
-rw-r--r--proto/ospf/lsupd.c8
-rw-r--r--proto/ospf/ospf.h23
-rw-r--r--proto/ospf/packet.c115
-rw-r--r--proto/ospf/rt.c6
-rw-r--r--proto/ospf/topology.c5
-rw-r--r--proto/pipe/Makefile2
-rw-r--r--proto/pipe/pipe.c2
-rw-r--r--proto/radv/Makefile2
-rw-r--r--proto/radv/packets.c6
-rw-r--r--proto/radv/radv.c4
-rw-r--r--proto/rip/Makefile2
-rw-r--r--proto/rip/config.Y24
-rw-r--r--proto/rip/packets.c77
-rw-r--r--proto/rip/rip.c16
-rw-r--r--proto/rip/rip.h2
-rw-r--r--proto/static/Makefile2
-rw-r--r--proto/static/static.c11
-rw-r--r--sysdep/autoconf.h.in3
-rw-r--r--sysdep/bsd/Makefile1
-rw-r--r--sysdep/bsd/krt-sock.c13
-rw-r--r--sysdep/bsd/krt-sys.h1
-rw-r--r--sysdep/bsd/sysio.h18
-rw-r--r--sysdep/config.h2
-rw-r--r--sysdep/linux/Makefile2
-rw-r--r--sysdep/linux/krt-sys.h6
-rw-r--r--sysdep/linux/netlink.Y10
-rw-r--r--sysdep/linux/netlink.c436
-rw-r--r--sysdep/linux/syspriv.h9
-rw-r--r--sysdep/unix/Makefile3
-rw-r--r--sysdep/unix/io.c47
-rw-r--r--sysdep/unix/krt.Y18
-rw-r--r--sysdep/unix/krt.c6
-rw-r--r--sysdep/unix/log.c27
-rw-r--r--sysdep/unix/main.c70
-rw-r--r--test/Makefile3
-rw-r--r--test/birdtest.c502
-rw-r--r--test/birdtest.h179
-rw-r--r--test/bt-utils.c223
-rw-r--r--test/bt-utils.h35
153 files changed, 14796 insertions, 5884 deletions
diff --git a/.cvsignore b/.cvsignore
deleted file mode 100644
index dc557db3..00000000
--- a/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-bird.conf
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..52510836
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,12 @@
+/autom4te.cache/
+/doc/*.html
+/obj/
+/Makefile
+/bird
+/birdc
+/birdcl
+/config.log
+/config.status
+/configure
+/bird.conf
+/bird.log
diff --git a/Makefile.in b/Makefile.in
index 6d82c8e4..a5e80ff4 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -23,7 +23,7 @@ INSTALL_DATA=@INSTALL_DATA@
client=$(addprefix $(exedir)/,@CLIENT@)
daemon=$(exedir)/bird
-protocols = @protocols@
+protocols=@protocols@
prefix=@prefix@
exec_prefix=@exec_prefix@
@@ -50,9 +50,10 @@ else
endif
# Meta rules
-cleangoals := clean distclean
docgoals := docs userdocs progdocs
-.PHONY: all daemon cli $(cleangoals) $(docgoals) tags
+testgoals := check test tests tests_run
+cleangoals := clean distclean testsclean
+.PHONY: all daemon cli $(docgoals) $(testgoals) $(cleangoals) tags
all: daemon cli
daemon: $(daemon)
@@ -61,15 +62,16 @@ cli: $(client)
$(daemon): LIBS += $(DAEMON_LIBS)
# Include directories
-dirs := client conf doc filter lib nest $(addprefix proto/,$(protocols)) @sysdep_dirs@
+dirs := client conf doc filter lib nest test $(addprefix proto/,$(protocols)) @sysdep_dirs@
conf-y-targets := $(addprefix $(objdir)/conf/,cf-parse.y keywords.h commands.h)
cf-local = $(conf-y-targets): $(s)config.Y
src-o-files = $(patsubst %.c,$(o)%.o,$(src))
+tests-target-files = $(patsubst %.c,$(o)%,$(tests_src))
-all-daemon = $(exedir)/bird: $(obj)
-all-client = $(exedir)/birdc $(exedir)/birdcl: $(obj)
+all-daemon = $(daemon): $(obj)
+all-client = $(client): $(obj)
s = $(dir $(lastword $(MAKEFILE_LIST)))
ifeq ($(srcdir),.)
@@ -112,6 +114,22 @@ $(objdir)/sysdep/paths.h: Makefile
echo >>$@ "#define PATH_CONTROL_SOCKET \"@CONTROL_SOCKET@\""
if test -n "@iproutedir@" ; then echo >>$@ "#define PATH_IPROUTE_DIR \"@iproutedir@\"" ; fi
+# Unit tests rules
+
+tests_targets_ok = $(addsuffix .ok,$(tests_targets))
+
+$(tests_targets): %: %.o $(tests_objs)
+ $(E)echo LD $(LDFLAGS) -o $@ $^ $(LIBS)
+ $(Q)$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
+
+$(tests_targets_ok): %.ok: %
+ $(Q)$* 2>/dev/null && touch $*.ok
+
+test: testsclean check
+check: tests tests_run
+tests: $(tests_targets)
+tests_run: $(tests_targets_ok)
+
# Finally include the computed dependencies
ifneq ($(filter-out $(cleangoals),$(MAKECMDGOALS)),)
@@ -150,6 +168,9 @@ clean::
rm -f $(addprefix $(exedir)/,bird birdc birdcl)
find $(objdir) -name "*.[od]" -exec rm -f '{}' '+'
+testsclean:
+ rm -f $(tests_targets_ok)
+
ifeq ($(objdir),obj)
distclean: clean
rm -rf $(objdir)
diff --git a/NEWS b/NEWS
index f689d195..26314d82 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,19 @@
+Version 1.6.2 (2016-09-29)
+ o Fixes serious bug introduced in the previous version
+
+Version 1.6.1 (2016-09-22)
+ o Support for IPv6 ECMP
+ o Better handling of IPv6 tentative addresses
+ o Several updates and fixes in Babel protocol
+ o Filter: New !~ operator
+ o Filter: ASN ranges in bgpmask
+ o KRT: New kernel protocol option 'metric'
+ o KRT: New route attribute 'krt_scope'
+ o Improved BIRD help messages
+ o Fixes memory leak in BGP multipath
+ o Fixes handling of empty path segments in BGP AS_PATH
+ o Several bug fixes
+
Version 1.6.0 (2016-04-29)
o Major RIP protocol redesign
o New Babel routing protocol
diff --git a/README b/README
index 5d4bd9b2..5a6d934d 100644
--- a/README
+++ b/README
@@ -1,82 +1,114 @@
- BIRD Internet Routing Daemon
+ BIRD Internet Routing Daemon
- (c) 1998--2008 Martin Mares <mj@ucw.cz>
+ Home page http://bird.network.cz/
+ Mailing list bird-users@network.cz
+
+ (c) 1998--2008 Martin Mares <mj@ucw.cz>
(c) 1998--2000 Pavel Machek <pavel@ucw.cz>
(c) 1998--2008 Ondrej Filip <feela@network.cz>
- (c) 2009--2013 CZ.NIC z.s.p.o.
+ (c) 2009--2016 CZ.NIC z.s.p.o.
================================================================================
-The BIRD project is an attempt to create a routing daemon running on UNIX-like
-systems (but not necessarily limited to them) with full support of all modern
-routing protocols, easy to use configuration interface and powerful route
-filtering language.
-
-If you want to help us debugging, enhancing and porting BIRD or just lurk
-around to see what's going to develop from this strange creature, feel free
-to subscribe to the BIRD users mailing list (bird-users@bird.network.cz),
-send subscribes to majordomo at the same machine). Bug reports, suggestions,
-feature requests (: and code :) are welcome.
+The BIRD project aims to develop a dynamic IP routing daemon with full support
+of all modern routing protocols, easy to use configuration interface and
+powerful route filtering language, primarily targeted on (but not limited to)
+Linux and other UNIX-like systems and distributed under the GNU General
+Public License.
-You can download the latest version from ftp://bird.network.cz/pub/bird/
-and look at the BIRD home page at http://bird.network.cz/.
+What do we support
+==================
-BIRD development started as a student project at the Faculty of Math
-and Physics, Charles University, Prague, Czech Republic under supervision
-of RNDr. Libor Forst <forst@cuni.cz>. BIRD has been developed and supported
-by CZ.NIC z.s.p.o. http://www.nic.cz/ since 2009.
+ o Both IPv4 and IPv6 (use --enable-ipv6 when configuring)
+ o Multiple routing tables
+ o Border Gateway Protocol (BGPv4)
+ o Routing Information Protocol (RIPv2, RIPng)
+ o Open Shortest Path First protocol (OSPFv2, OSPFv3)
+ o Babel Routing Protocol (Babel)
+ o Bidirectional Forwarding Detection (BFD)
+ o IPv6 router advertisements
+ o Static routes
+ o Inter-table protocol
+ o Command-line interface allowing on-line control and inspection of
+ status of the daemon
+ o Soft reconfiguration, no need to use complex online commands to
+ change the configuration, just edit the configuration file and notify
+ BIRD to re-read it and it will smoothly switch itself to the new
+ configuration, not disturbing routing protocols unless they are
+ affected by the configuration changes
+ o Powerful language for route filtering, see doc/bird.conf.example
+ o Linux, FreeBSD, NetBSD and OpenBSD ports
+
+How to install BIRD
+===================
+
+ o From standard distribution package of your OS (recommended)
+ o From official binary packages for Debian and Red Hat Linux
+ ftp://bird.network.cz/pub/bird/debian/
+ ftp://bird.network.cz/pub/bird/redhat/
+ o From source code of the latest stable release version
+ ftp://bird.network.cz/pub/bird/
+ o From source code of the actual development version
+ git://git.nic.cz/bird.git
+ https://gitlab.labs.nic.cz/labs/bird/
+
+How to install BIRD from source code
+------------------------------------
+
+ $ ./configure
+ $ make
+ $ su
+ # make install
+ # vi /usr/local/etc/bird.conf
+
+See the file INSTALL for more information about installation from source code.
+
+Documentation
+=============
+
+Online documentation is available at http://bird.network.cz/?get_doc or as HTML
+files in the doc directory, you can install it by `make install-docs' and
+rebuild it by `make docs', but you'll need SGMLtools and LaTeX to be installed
+on your machine. You can also download a neatly formatted PostScript version as
+a separate archive (bird-doc-*.tar.gz) from ftp://bird.network.cz/pub/bird/
+
+User support
+============
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
+If you want to help us debugging, enhancing and porting BIRD or just lurk
+around to see what's going to develop, feel free to subscribe to the BIRD
+users mailing list bird-users@network.cz, just send `subscribe' to
+bird-request@network.cz. Bug reports, suggestions, feature requests and
+code are welcome! We don't use gitlab issues for reporting, sorry.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+Subscribe: http://bird.network.cz/mailman/listinfo/bird-users/
+Archive: http://bird.network.cz/pipermail/bird-users/
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+Licence
+=======
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or
+(at your option) any later version.
-How to install BIRD:
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
- ./configure
- make
- make install
- vi /usr/local/etc/bird.conf
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-Online documentation is available as HTML files in the doc directory,
-you can install it by `make install-docs' and rebuild it by `make docs',
-but for the latter you need SGMLtools and LaTeX to be installed on your
-machine. You can also download a neatly formatted PostScript version
-as a separate archive (bird-doc-*.tar.gz).
+History
+=======
-What do we support:
+BIRD development started as a student project at the Faculty of Math
+and Physics, Charles University, Prague, Czech Republic under supervision
+of RNDr. Libor Forst <forst@cuni.cz>. BIRD has been developed and supported
+by CZ.NIC z.s.p.o. http://www.nic.cz/ since 2009.
- o Both IPv4 and IPv6 (use --enable-ipv6 when configuring)
- o Multiple routing tables
- o BGP
- o RIP
- o OSPF
- o Static routes
- o Inter-table protocol
- o IPv6 router advertisements
- o Bidirectional Forwarding Detection (BFD)
- o Command-line interface (using the `birdc' client; to get
- some help, just press `?')
- o Soft reconfiguration -- no online commands for changing the
- configuration in very limited ways, just edit the configuration
- file and issue a `configure' command or send SIGHUP and BIRD
- will start using the new configuration, possibly restarting
- protocols affected by the configuration changes.
- o Powerful language for route filtering (see doc/bird.conf.example).
-
-What is missing:
-
- o See the TODO list
Good Luck and enjoy the BIRD :)
The BIRD Team
diff --git a/client/birdcl.c b/client/birdcl.c
index 7b567a9f..4508185c 100644
--- a/client/birdcl.c
+++ b/client/birdcl.c
@@ -125,7 +125,7 @@ more_end(void)
}
static void
-sig_handler(int signal)
+sig_handler(int signal UNUSED)
{
cleanup();
exit(0);
diff --git a/client/util.c b/client/util.c
index c35cf8f4..1d83e518 100644
--- a/client/util.c
+++ b/client/util.c
@@ -24,7 +24,7 @@ vlog(const char *msg, va_list args)
int n = vsnprintf(buf, sizeof(buf), msg, args);
if (n < 0)
snprintf(buf, sizeof(buf), "???");
- if (n >= sizeof(buf))
+ else if (n >= (int) sizeof(buf))
snprintf(buf + sizeof(buf) - 100, 100, " ... <too long>");
fputs(buf, stderr);
fputc('\n', stderr);
@@ -40,6 +40,7 @@ bug(const char *msg, ...)
fputs("Internal error: ", stderr);
vlog(msg, args);
vfprintf(stderr, msg, args);
+ va_end(args);
exit(1);
}
@@ -51,5 +52,6 @@ die(const char *msg, ...)
va_start(args, msg);
cleanup();
vlog(msg, args);
+ va_end(args);
exit(1);
}
diff --git a/conf/Makefile b/conf/Makefile
index c1a906e3..cc2b13c6 100644
--- a/conf/Makefile
+++ b/conf/Makefile
@@ -3,6 +3,8 @@ obj := $(src-o-files)
$(all-daemon)
+tests_objs := $(tests_objs) $(src-o-files)
+
ifdef DEBUG
BISON_DEBUG=-t
#FLEX_DEBUG=-d
@@ -24,6 +26,7 @@ $(o)cf-lex.c: $(s)cf-lex.l
$(FLEX) $(FLEX_DEBUG) -s -B -8 -Pcf_ -o$@ $<
$(o)cf-lex.o: $(o)cf-parse.tab.h $(o)keywords.h
+$(o)cf-lex.o: CFLAGS+=-Wno-sign-compare -Wno-unused-function
$(addprefix $(o), cf-parse.y keywords.h commands.h cf-parse.tab.h cf-parse.tab.c cf-lex.c): $(objdir)/.dir-stamp
diff --git a/conf/cf-lex.l b/conf/cf-lex.l
index dd99b497..bd6dfff2 100644
--- a/conf/cf-lex.l
+++ b/conf/cf-lex.l
@@ -30,6 +30,7 @@
#include <errno.h>
#include <stdlib.h>
#include <stdarg.h>
+#include <stdint.h>
#include <unistd.h>
#include <libgen.h>
#include <glob.h>
@@ -202,6 +203,7 @@ else: {
["][^"\n]*["] {
yytext[yyleng-1] = 0;
cf_lval.t = cfg_strdup(yytext+1);
+ yytext[yyleng-1] = '"';
return TEXT;
}
@@ -233,6 +235,7 @@ else: {
<CCOMM>.
\!\= return NEQ;
+\!\~ return NMA;
\<\= return LEQ;
\>\= return GEQ;
\&\& return AND;
@@ -575,7 +578,7 @@ cf_lex_init(int is_cli, struct config *c)
cf_lex_init_kh();
ifs_head = ifs = push_ifs(NULL);
- if (!is_cli)
+ if (!is_cli)
{
ifs->file_name = c->file_name;
ifs->fd = c->file_fd;
diff --git a/conf/conf.c b/conf/conf.c
index 8d4d28e3..a2837886 100644
--- a/conf/conf.c
+++ b/conf/conf.c
@@ -56,6 +56,7 @@
#include "conf/conf.h"
#include "filter/filter.h"
+
static jmp_buf conf_jmpbuf;
struct config *config, *new_config;
@@ -85,7 +86,7 @@ int undo_available; /* Undo was not requested from last reconfiguration */
* further use. Returns a pointer to the structure.
*/
struct config *
-config_alloc(byte *name)
+config_alloc(const char *name)
{
pool *p = rp_new(&root_pool, "Config");
linpool *l = lp_new(p, 4080);
@@ -96,6 +97,7 @@ config_alloc(byte *name)
char *ndup = lp_allocu(l, nlen);
memcpy(ndup, name, nlen);
+ init_list(&c->tests);
c->mrtdump_file = -1; /* Hack, this should be sysdep-specific */
c->pool = p;
c->mem = l;
@@ -405,7 +407,7 @@ config_confirm(void)
* if it's been queued due to another reconfiguration being in progress now,
* %CONF_UNQUEUED if a scheduled reconfiguration is removed, %CONF_NOTHING
* if there is no relevant configuration to undo (the previous config request
- * was config_undo() too) or %CONF_SHUTDOWN if BIRD is in shutdown mode and
+ * was config_undo() too) or %CONF_SHUTDOWN if BIRD is in shutdown mode and
* no new configuration changes are accepted.
*/
int
@@ -450,7 +452,7 @@ config_undo(void)
extern void cmd_reconfig_undo_notify(void);
static void
-config_timeout(struct timer *t)
+config_timeout(struct timer *t UNUSED)
{
log(L_INFO "Config timeout expired, starting undo");
cmd_reconfig_undo_notify();
@@ -512,6 +514,7 @@ cf_error(const char *msg, ...)
va_start(args, msg);
if (bvsnprintf(buf, sizeof(buf), msg, args) < 0)
strcpy(buf, "<bug: error message too long>");
+ va_end(args);
new_config->err_msg = cfg_strdup(buf);
new_config->err_lino = ifs->lino;
new_config->err_file_name = ifs->file_name;
@@ -529,7 +532,7 @@ cf_error(const char *msg, ...)
* and we want to preserve it for further use.
*/
char *
-cfg_strdup(char *c)
+cfg_strdup(const char *c)
{
int l = strlen(c) + 1;
char *z = cfg_allocu(l);
diff --git a/conf/conf.h b/conf/conf.h
index 03fecd32..4b245e00 100644
--- a/conf/conf.h
+++ b/conf/conf.h
@@ -9,6 +9,8 @@
#ifndef _BIRD_CONF_H_
#define _BIRD_CONF_H_
+#include "sysdep/config.h"
+#include "lib/ip.h"
#include "lib/resource.h"
#include "sysdep/unix/timer.h"
@@ -20,7 +22,8 @@ struct config {
linpool *mem; /* Linear pool containing configuration data */
list protos; /* Configured protocol instances (struct proto_config) */
list tables; /* Configured routing tables (struct rtable_config) */
- list logfiles; /* Configured log fils (sysdep) */
+ list logfiles; /* Configured log files (sysdep) */
+ list tests; /* Configured unit tests (f_bt_test_suite) */
int mrtdump_file; /* Configured MRTDump file (sysdep, fd in unix) */
char *syslog_name; /* Name used for syslog (NULL -> no syslog) */
@@ -60,7 +63,7 @@ struct config {
extern struct config *config; /* Currently active configuration */
extern struct config *new_config; /* Configuration being parsed */
-struct config *config_alloc(byte *name);
+struct config *config_alloc(const char *name);
int config_parse(struct config *);
int cli_parse(struct config *);
void config_free(struct config *);
@@ -94,7 +97,7 @@ extern linpool *cfg_mem;
#define cfg_alloc(size) lp_alloc(cfg_mem, size)
#define cfg_allocu(size) lp_allocu(cfg_mem, size)
#define cfg_allocz(size) lp_allocz(cfg_mem, size)
-char *cfg_strdup(char *c);
+char *cfg_strdup(const char *c);
void cfg_copy_list(list *dest, list *src, unsigned node_size);
/* Lexer */
@@ -161,6 +164,7 @@ static inline int cf_symbol_is_constant(struct symbol *sym)
/* Parser */
+extern char *cf_text;
int cf_parse(void);
/* Sysdep hooks */
diff --git a/conf/confbase.Y b/conf/confbase.Y
index e64d7593..094c81b5 100644
--- a/conf/confbase.Y
+++ b/conf/confbase.Y
@@ -87,7 +87,7 @@ CF_DECLS
%nonassoc PREFIX_DUMMY
%left AND OR
-%nonassoc '=' '<' '>' '~' GEQ LEQ NEQ PO PC
+%nonassoc '=' '<' '>' '~' GEQ LEQ NEQ NMA PO PC
%left '+' '-'
%left '*' '/' '%'
%left '!'
@@ -143,7 +143,7 @@ expr_us:
/* Switches */
bool:
- expr {$$ = !!$1; }
+ expr { $$ = !!$1; }
| ON { $$ = 1; }
| YES { $$ = 1; }
| OFF { $$ = 0; }
@@ -202,7 +202,7 @@ net_roa4_: net_ip4_ MAX NUM AS NUM
{
$$ = cfg_alloc(sizeof(net_addr_roa4));
net_fill_roa4($$, net4_prefix(&$1), net4_pxlen(&$1), $3, $5);
- if ($3 < net4_pxlen(&$1) || $3 > IP4_MAX_PREFIX_LENGTH)
+ if ($3 < (int) net4_pxlen(&$1) || $3 > IP4_MAX_PREFIX_LENGTH)
cf_error("Invalid max prefix length %d", $3);
};
@@ -210,7 +210,7 @@ net_roa6_: net_ip6_ MAX NUM AS NUM
{
$$ = cfg_alloc(sizeof(net_addr_roa6));
net_fill_roa6($$, net6_prefix(&$1), net6_pxlen(&$1), $3, $5);
- if ($3 < net6_pxlen(&$1) || $3 > IP6_MAX_PREFIX_LENGTH)
+ if ($3 < (int) net6_pxlen(&$1) || $3 > IP6_MAX_PREFIX_LENGTH)
cf_error("Invalid max prefix length %d", $3);
};
diff --git a/configure.in b/configure.in
index 3c9df3a9..32344d1f 100644
--- a/configure.in
+++ b/configure.in
@@ -57,7 +57,7 @@ if test "$ac_test_CFLAGS" != set ; then
bird_cflags_default=yes
fi
-AC_PROG_CC
+AC_PROG_CC_C99
if test -z "$GCC" ; then
AC_MSG_ERROR([This program requires the GNU C Compiler.])
fi
@@ -104,11 +104,13 @@ fi
if test "$bird_cflags_default" = yes ; then
BIRD_CHECK_GCC_OPTION(bird_cv_c_option_wno_pointer_sign, -Wno-pointer-sign, -Wall)
+ BIRD_CHECK_GCC_OPTION(bird_cv_c_option_wno_missing_init, -Wno-missing-field-initializers, -Wall -Wextra)
BIRD_CHECK_GCC_OPTION(bird_cv_c_option_fno_strict_aliasing, -fno-strict-aliasing)
BIRD_CHECK_GCC_OPTION(bird_cv_c_option_fno_strict_overflow, -fno-strict-overflow)
- CFLAGS="$CFLAGS -Wall -Wstrict-prototypes -Wno-parentheses"
+ CFLAGS="$CFLAGS -Wall -Wextra -Wstrict-prototypes -Wno-parentheses"
BIRD_ADD_GCC_OPTION(bird_cv_c_option_wno_pointer_sign, -Wno-pointer-sign)
+ BIRD_ADD_GCC_OPTION(bird_cv_c_option_wno_missing_init, -Wno-missing-field-initializers)
BIRD_ADD_GCC_OPTION(bird_cv_c_option_fno_strict_aliasing, -fno-strict-aliasing)
BIRD_ADD_GCC_OPTION(bird_cv_c_option_fno_strict_overflow, -fno-strict-overflow)
fi
@@ -183,8 +185,8 @@ fi
AC_SUBST(iproutedir)
-# all_protocols="$proto_bfd babel bgp ospf pipe radv rip static"
-all_protocols="$proto_bfd ospf pipe radv rip $proto_rpki static "
+# all_protocols="$proto_bfd babel bgp ospf pipe radv rip $proto_rpki static"
+all_protocols="$proto_bfd bgp ospf pipe radv rip $proto_rpki static "
all_protocols=`echo $all_protocols | sed 's/ /,/g'`
@@ -234,6 +236,9 @@ BIRD_CHECK_STRUCT_IP_MREQN
if test "$enable_debug" = yes ; then
AC_DEFINE(DEBUGGING)
+ AC_CHECK_HEADER(execinfo.h, [AC_SEARCH_LIBS([backtrace, backtrace_symbols], [c execinfo], [AC_DEFINE(HAVE_EXECINFO_H)])])
+ LDFLAGS="$LDFLAGS -rdynamic"
+ CFLAGS="$CFLAGS -O0 -ggdb -g3 -gdwarf-4"
if test "$enable_memcheck" = yes ; then
AC_CHECK_LIB(dmalloc, dmalloc_debug)
if test $ac_cv_lib_dmalloc_dmalloc_debug != yes ; then
diff --git a/doc/Makefile b/doc/Makefile
index 3ff73389..4e7e91eb 100644
--- a/doc/Makefile
+++ b/doc/Makefile
@@ -25,6 +25,9 @@ $(o)%.sgml: $(s)%.sgml $(objdir)/.dir-stamp
$(o)%.html: $(o)%.sgml
cd $(dir $@) && $(sgml2)html $(notdir $<)
+$(o)%.tex: $(o)%.sgml
+ cd $(dir $@) && $(sgml2)latex --output=tex $(notdir $<)
+
$(o)%.dvi: $(o)%.tex
cd $(dir $@) && TEXINPUTS=$(TEXINPUTS):$(doc-srcdir)/tex latex $(notdir $<)
cd $(dir $@) && TEXINPUTS=$(TEXINPUTS):$(doc-srcdir)/tex latex $(notdir $<)
@@ -32,11 +35,9 @@ $(o)%.dvi: $(o)%.tex
$(o)%.ps: $(o)%.dvi
dvips -D600 -ta4 -o $@ $<
-$(o)%.pdf: $(o)%.ps
- ps2pdf $< $@
-
-$(o)%.tex: $(o)%.sgml
- cd $(dir $@) && $(sgml2)latex --output=tex $(notdir $<)
+$(o)%.pdf: $(o)%.tex
+ pdflatex -output-directory=$(dir $@) $<
+ pdflatex -output-directory=$(dir $@) $<
$(o)%.txt: $(o)%.sgml
cd $(dir $@) && $(sgml2)txt $(notdir $<)
diff --git a/doc/bird.sgml b/doc/bird.sgml
index 53998a76..a734b2ff 100644
--- a/doc/bird.sgml
+++ b/doc/bird.sgml
@@ -39,11 +39,12 @@ This document contains user documentation for the BIRD Internet Routing Daemon p
<chapt>Introduction
+<label id="intro">
<sect>What is BIRD
+<label id="what-is-bird">
-<p><label id="intro">
-The name `BIRD' is actually an acronym standing for `BIRD Internet Routing
+<p>The name `BIRD' is actually an acronym standing for `BIRD Internet Routing
Daemon'. Let's take a closer look at the meaning of the name:
<p><em/BIRD/: Well, we think we have already explained that. It's an acronym
@@ -72,8 +73,8 @@ running on background which does the dynamic part of Internet routing, that is
it communicates with the other routers, calculates routing tables and sends them
to the OS kernel which does the actual packet forwarding. There already exist
other such routing daemons: routed (RIP only), GateD (non-free),
-Zebra <HTMLURL URL="http://www.zebra.org"> and
-MRTD <HTMLURL URL="http://sourceforge.net/projects/mrt">,
+<HTMLURL URL="http://www.zebra.org" name="Zebra"> and
+<HTMLURL URL="http://sourceforge.net/projects/mrt" name="MRTD">,
but their capabilities are limited and they are relatively hard to configure
and maintain.
@@ -118,6 +119,7 @@ files, tools ...).
<sect>Installing BIRD
+<label id="install">
<p>On a recent UNIX system with GNU development tools (GCC, binutils, m4, make)
and Perl, installing BIRD should be as easy as:
@@ -138,52 +140,60 @@ BIRD executable by configuring out routing protocols you don't use, and
<sect>Running BIRD
+<label id="argv">
<p>You can pass several command-line options to bird:
<descrip>
- <tag>-c <m/config name/</tag>
+ <tag><label id="argv-config">-c <m/config name/</tag>
use given configuration file instead of <it/prefix/<file>/etc/bird.conf</file>.
- <tag>-d</tag>
+ <tag><label id="argv-debug">-d</tag>
enable debug messages and run bird in foreground.
- <tag>-D <m/filename of debug log/</tag>
+ <tag><label id="argv-log-file">-D <m/filename of debug log/</tag>
log debugging information to given file instead of stderr.
- <tag>-p</tag>
- just parse the config file and exit. Return value is zero if the config
- file is valid, nonzero if there are some errors.
-
- <tag>-s <m/name of communication socket/</tag>
- use given filename for a socket for communications with the client,
- default is <it/prefix/<file>/var/run/bird.ctl</file>.
-
- <tag>-P <m/name of PID file/</tag>
- create a PID file with given filename.
-
- <tag>-u <m/user/</tag>
- drop privileges and use that user ID, see the next section for details.
+ <tag><label id="argv-foreground">-f</tag>
+ run bird in foreground.
- <tag>-g <m/group/</tag>
+ <tag><label id="argv-group">-g <m/group/</tag>
use that group ID, see the next section for details.
- <tag>-f</tag>
- run bird in foreground.
+ <tag><label id="argv-help">-h, --help</tag>
+ display command-line options to bird.
- <tag>-l</tag>
+ <tag><label id="argv-local">-l</tag>
look for a configuration file and a communication socket in the current
working directory instead of in default system locations. However, paths
specified by options <cf/-c/, <cf/-s/ have higher priority.
- <tag>-R</tag>
+ <tag><label id="argv-parse">-p</tag>
+ just parse the config file and exit. Return value is zero if the config
+ file is valid, nonzero if there are some errors.
+
+ <tag><label id="argv-pid">-P <m/name of PID file/</tag>
+ create a PID file with given filename.
+
+ <tag><label id="argv-recovery">-R</tag>
apply graceful restart recovery after start.
+
+ <tag><label id="argv-socket">-s <m/name of communication socket/</tag>
+ use given filename for a socket for communications with the client,
+ default is <it/prefix/<file>/var/run/bird.ctl</file>.
+
+ <tag><label id="argv-user">-u <m/user/</tag>
+ drop privileges and use that user ID, see the next section for details.
+
+ <tag><label id="argv-version">--version</tag>
+ display bird version.
</descrip>
<p>BIRD writes messages about its work to log files or syslog (according to config).
<sect>Privileges
+<label id="privileges">
<p>BIRD, as a routing daemon, uses several privileged operations (like setting
routing table and using raw sockets). Traditionally, BIRD is executed and runs
@@ -208,6 +218,7 @@ the config file and create the control socket and the CAP_NET_* capabilities.
<chapt>About routing tables
+<label id="routing-tables">
<p>BIRD has one or more routing tables which may or may not be synchronized with
OS kernel and which may or may not be synchronized with each other (see the Pipe
@@ -245,7 +256,7 @@ network. Note that although most protocols are interested in receiving just
selected routes, some protocols (e.g. the <cf/Pipe/ protocol) receive and
process all entries in routing tables (accepted by filters).
-<p><label id="dsc-sorted">Usually, a routing table just chooses a selected route
+<p><label id="dsc-table-sorted">Usually, a routing table just chooses a selected route
from a list of entries for one network. But if the <cf/sorted/ option is
activated, these lists of entries are kept completely sorted (according to
preference or some protocol-dependent metric). This is needed for some features
@@ -259,6 +270,7 @@ is that it is slightly more computationally expensive.
<sect>Graceful restart
+<label id="graceful-restart">
<p>When BIRD is started after restart or crash, it repopulates routing tables in
an uncoordinated manner, like after clean start. This may be impractical in some
@@ -274,8 +286,10 @@ particular boot by option <cf/-R/.
<chapt>Configuration
+<label id="config">
<sect>Introduction
+<label id="config-intro">
<p>BIRD is configured using a text configuration file. Upon startup, BIRD reads
<it/prefix/<file>/etc/bird.conf</file> (unless the <tt/-c/ command line option
@@ -319,17 +333,18 @@ protocol rip {
<sect>Global options
+<label id="global-opts">
<p><descrip>
- <tag>include "<m/filename/"</tag>
+ <tag><label id="opt-include">include "<m/filename/"</tag>
This statement causes inclusion of a new file. <m/Filename/ could also
be a wildcard, in that case matching files are included in alphabetic
order. The maximal depth is 8. Note that this statement could be used
anywhere in the config file, not just as a top-level option.
- <tag><label id="dsc-log">log "<m/filename/"|syslog [name <m/name/]|stderr all|{ <m/list of classes/ }</tag>
+ <tag><label id="opt-log">log "<m/filename/"|syslog [name <m/name/]|stderr all|{ <m/list of classes/ }</tag>
Set logging of messages having the given class (either <cf/all/ or
- <cf/{ error, trace }/ etc.) into selected destination (a file specified
+ <cf/{ error|trace [, <m/.../] }/ etc.) into selected destination (a file specified
as a filename string, syslog with optional name argument, or the stderr
output). Classes are:
<cf/info/, <cf/warning/, <cf/error/ and <cf/fatal/ for messages about local problems,
@@ -341,48 +356,48 @@ protocol rip {
You may specify more than one <cf/log/ line to establish logging to
multiple destinations. Default: log everything to the system log.
- <tag>debug protocols all|off|{ states, routes, filters, interfaces, events, packets }</tag>
+ <tag><label id="opt-debug-protocols">debug protocols all|off|{ states|routes|filters|interfaces|events|packets [, <m/.../] }</tag>
Set global defaults of protocol debugging options. See <cf/debug/ in the
following section. Default: off.
- <tag>debug commands <m/number/</tag>
+ <tag><label id="opt-debug-commands">debug commands <m/number/</tag>
Control logging of client connections (0 for no logging, 1 for logging
of connects and disconnects, 2 and higher for logging of all client
commands). Default: 0.
- <tag>debug latency <m/switch/</tag>
+ <tag><label id="opt-debug-latency">debug latency <m/switch/</tag>
Activate tracking of elapsed time for internal events. Recent events
could be examined using <cf/dump events/ command. Default: off.
- <tag>debug latency limit <m/time/</tag>
+ <tag><label id="opt-debug-latency-limit">debug latency limit <m/time/</tag>
If <cf/debug latency/ is enabled, this option allows to specify a limit
for elapsed time. Events exceeding the limit are logged. Default: 1 s.
- <tag>watchdog warning <m/time/</tag>
+ <tag><label id="opt-watchdog-warn">watchdog warning <m/time/</tag>
Set time limit for I/O loop cycle. If one iteration took more time to
complete, a warning is logged. Default: 5 s.
- <tag>watchdog timeout <m/time/</tag>
+ <tag><label id="opt-watchdog-timeout">watchdog timeout <m/time/</tag>
Set time limit for I/O loop cycle. If the limit is breached, BIRD is
killed by abort signal. The timeout has effective granularity of
seconds, zero means disabled. Default: disabled (0).
- <tag>mrtdump "<m/filename/"</tag>
+ <tag><label id="opt-mrtdump">mrtdump "<m/filename/"</tag>
Set MRTdump file name. This option must be specified to allow MRTdump
feature. Default: no dump file.
- <tag>mrtdump protocols all|off|{ states, messages }</tag>
+ <tag><label id="opt-mrtdump-protocols">mrtdump protocols all|off|{ states|messages [, <m/.../] }</tag>
Set global defaults of MRTdump options. See <cf/mrtdump/ in the
following section. Default: off.
- <tag>filter <m/name local variables/{ <m/commands/ }</tag>
+ <tag><label id="opt-filter">filter <m/name local variables/{ <m/commands/ }</tag>
Define a filter. You can learn more about filters in the following
chapter.
- <tag>function <m/name/ (<m/parameters/) <m/local variables/ { <m/commands/ }</tag>
+ <tag><label id="opt-function">function <m/name/ (<m/parameters/) <m/local variables/ { <m/commands/ }</tag>
Define a function. You can learn more about functions in the following chapter.
- <tag>protocol rip|ospf|bgp|... [<m/name/ [from <m/name2/]] { <m>protocol options</m> }</tag>
+ <tag><label id="opt-protocol">protocol rip|ospf|bgp|<m/.../ [<m/name/ [from <m/name2/]] { <m>protocol options</m> }</tag>
Define a protocol instance called <cf><m/name/</cf> (or with a name like
"rip5" generated automatically if you don't specify any
<cf><m/name/</cf>). You can learn more about configuring protocols in
@@ -391,7 +406,7 @@ protocol rip {
<cf><m/name2/</cf> You can run more than one instance of most protocols
(like RIP or BGP). By default, no instances are configured.
- <tag>template rip|bgp|... [<m/name/ [from <m/name2/]] { <m>protocol options</m> }</tag>
+ <tag><label id="opt-template">template rip|bgp|<m/.../ [<m/name/ [from <m/name2/]] { <m>protocol options</m> }</tag>
Define a protocol template instance called <m/name/ (or with a name like
"bgp1" generated automatically if you don't specify any <m/name/).
Protocol templates can be used to group common options when many
@@ -400,25 +415,25 @@ protocol rip {
expression and the name of the template. At the moment templates (and
<cf/from/ expression) are not implemented for OSPF protocol.
- <tag>define <m/constant/ = <m/expression/</tag>
+ <tag><label id="opt-define">define <m/constant/ = <m/expression/</tag>
Define a constant. You can use it later in every place you could use a
value of the same type. Besides, there are some predefined numeric
constants based on /etc/iproute2/rt_* files. A list of defined constants
can be seen (together with other symbols) using 'show symbols' command.
- <tag>router id <m/IPv4 address/</tag>
- Set BIRD's router ID. It's a world-wide unique identification of your
+ <tag><label id="opt-router-id">router id <m/IPv4 address/</tag>
+ Set BIRD's router ID. It's a world-wide unique identification of your
router, usually one of router's IPv4 addresses. Default: in IPv4
version, the lowest IP address of a non-loopback interface. In IPv6
version, this option is mandatory.
- <tag>router id from [-] [ "<m/mask/" ] [ <m/prefix/ ] [, ...]</tag>
+ <tag><label id="opt-router-id-from">router id from [-] [ "<m/mask/" ] [ <m/prefix/ ] [, <m/.../]</tag>
Set BIRD's router ID based on an IP address of an interface specified by
an interface pattern. The option is applicable for IPv4 version only.
- See <ref id="dsc-iface" name="interface"> section for detailed
+ See <ref id="proto-iface" name="interface"> section for detailed
description of interface patterns with extended clauses.
- <tag>listen bgp [address <m/address/] [port <m/port/] [dual]</tag>
+ <tag><label id="opt-listen-bgp">listen bgp [address <m/address/] [port <m/port/] [dual]</tag>
This option allows to specify address and port where BGP protocol should
listen. It is global option as listening socket is common to all BGP
instances. Default is to listen on all addresses (0.0.0.0) and port 179.
@@ -427,13 +442,13 @@ protocol rip {
BIRD would accept IPv6 routes only). Such behavior was default in older
versions of BIRD.
- <tag>graceful restart wait <m/number/</tag>
+ <tag><label id="opt-graceful-restart">graceful restart wait <m/number/</tag>
During graceful restart recovery, BIRD waits for convergence of routing
protocols. This option allows to specify a timeout for the recovery to
prevent waiting indefinitely if some protocols cannot converge. Default:
240 seconds.
- <tag>timeformat route|protocol|base|log "<m/format1/" [<m/limit/ "<m/format2/"]</tag>
+ <tag><label id="opt-timeformat">timeformat route|protocol|base|log "<m/format1/" [<m/limit/ "<m/format2/"]</tag>
This option allows to specify a format of date/time used by BIRD. The
first argument specifies for which purpose such format is used.
<cf/route/ is a format used in 'show route' command output,
@@ -459,32 +474,33 @@ protocol rip {
hh:mm:ss) for <cf/base/ and <cf/log/. These timeformats could be set by
<cf/old short/ and <cf/old long/ compatibility shorthands.
- <tag>table <m/name/ [sorted]</tag>
+ <tag><label id="opt-table">table <m/name/ [sorted]</tag>
Create a new routing table. The default routing table is created
implicitly, other routing tables have to be added by this command.
Option <cf/sorted/ can be used to enable sorting of routes, see
- <ref id="dsc-sorted" name="sorted table"> description for details.
+ <ref id="dsc-table-sorted" name="sorted table"> description for details.
- <tag>roa table <m/name/ [ { roa table options ... } ]</tag>
+ <tag><label id="opt-roa-table">roa table <m/name/ [ { <m/roa table options .../ } ]</tag>
Create a new ROA (Route Origin Authorization) table. ROA tables can be
used to validate route origination of BGP routes. A ROA table contains
ROA entries, each consist of a network prefix, a max prefix length and
- an AS (Autonomous System) number. A ROA entry specifies prefixes which could be originated
- by that AS number. ROA tables could be filled with data from RPKI (RFC
- 6480) or from public databases like Whois. ROA tables are examined by
- <cf/roa_check()/ operator in filters.
+ an AS number. A ROA entry specifies prefixes which could be originated
+ by that AS number. ROA tables could be filled with data from RPKI (<rfc
+ id="6480">) or from public databases like Whois. ROA tables are
+ examined by <cf/roa_check()/ operator in filters.
Currently, there is just one option, <cf>roa <m/prefix/ max <m/num/ as
<m/num/</cf>, which can be used to populate the ROA table with static
ROA entries. The option may be used multiple times. Other entries can be
added dynamically by <cf/add roa/ command.
- <tag>eval <m/expr/</tag>
+ <tag><label id="opt-eval">eval <m/expr/</tag>
Evaluates given filter expression. It is used by us for testing of filters.
</descrip>
<sect>Protocol options
+<label id="protocol-opts">
<p>For each protocol instance, you can configure a bunch of options. Some of
them (those described in this section) are generic, some are specific to the
@@ -497,16 +513,16 @@ disable it. An empty <m/switch/ is equivalent to <cf/on/ ("silence means
agreement").
<descrip>
- <tag>preference <m/expr/</tag>
+ <tag><label id="proto-preference">preference <m/expr/</tag>
Sets the preference of routes generated by this protocol. Default:
protocol dependent.
- <tag>disabled <m/switch/</tag>
+ <tag><label id="proto-disabled">disabled <m/switch/</tag>
Disables the protocol. You can change the disable/enable status from the
command line interface without needing to touch the configuration.
Disabled protocols are not activated. Default: protocol is enabled.
- <tag>debug all|off|{ states, routes, filters, interfaces, events, packets }</tag>
+ <tag><label id="proto-debug">debug all|off|{ states|routes|filters|interfaces|events|packets [, <m/.../] }</tag>
Set protocol debugging options. If asked, each protocol is capable of
writing trace messages about its work to the log (with category
<cf/trace/). You can either request printing of <cf/all/ trace messages
@@ -517,7 +533,7 @@ agreement").
protocol, <cf/events/ for events internal to the protocol and <cf/packets/
for packets sent and received by the protocol. Default: off.
- <tag>mrtdump all|off|{ states, messages }</tag>
+ <tag><label id="proto-mrtdump">mrtdump all|off|{ states|messages [, <m/.../] }</tag>
Set protocol MRTdump flags. MRTdump is a standard binary format for
logging information from routing protocols and daemons. These flags
control what kind of information is logged from the protocol to the
@@ -527,27 +543,27 @@ agreement").
BGP protocol, <cf/states/ logs BGP state changes and <cf/messages/ logs
received BGP messages. Other protocols does not support MRTdump yet.
- <tag>router id <m/IPv4 address/</tag>
+ <tag><label id="proto-router-id">router id <m/IPv4 address/</tag>
This option can be used to override global router id for a given
protocol. Default: uses global router id.
- <tag>import all | none | filter <m/name/ | filter { <m/filter commands/ } | where <m/filter expression/</tag>
+ <tag><label id="proto-import">import all | none | filter <m/name/ | filter { <m/filter commands/ } | where <m/filter expression/</tag>
Specify a filter to be used for filtering routes coming from the
protocol to the routing table. <cf/all/ is shorthand for <cf/where true/
and <cf/none/ is shorthand for <cf/where false/. Default: <cf/all/.
- <tag>export <m/filter/</tag>
+ <tag><label id="proto-export">export <m/filter/</tag>
This is similar to the <cf>import</cf> keyword, except that it works in
the direction from the routing table to the protocol. Default: <cf/none/.
- <tag>import keep filtered <m/switch/</tag>
+ <tag><label id="proto-import-keep-filtered">import keep filtered <m/switch/</tag>
Usually, if an import filter rejects a route, the route is forgotten.
When this option is active, these routes are kept in the routing table,
but they are hidden and not propagated to other protocols. But it is
possible to show them using <cf/show route filtered/. Note that this
option does not work for the pipe protocol. Default: off.
- <tag><label id="import-limit">import limit [<m/number/ | off ] [action warn | block | restart | disable]</tag>
+ <tag><label id="proto-import-limit">import limit [<m/number/ | off ] [action warn | block | restart | disable]</tag>
Specify an import route limit (a maximum number of routes imported from
the protocol) and optionally the action to be taken when the limit is
hit. Warn action just prints warning log message. Block action discards
@@ -556,7 +572,7 @@ agreement").
action if an action is not explicitly specified. Note that limits are
reset during protocol reconfigure, reload or restart. Default: <cf/off/.
- <tag>receive limit [<m/number/ | off ] [action warn | block | restart | disable]</tag>
+ <tag><label id="proto-receive-limit">receive limit [<m/number/ | off ] [action warn | block | restart | disable]</tag>
Specify an receive route limit (a maximum number of routes received from
the protocol and remembered). It works almost identically to <cf>import
limit</cf> option, the only difference is that if <cf/import keep
@@ -566,7 +582,7 @@ agreement").
on the contrary, counts accepted routes only and routes blocked by the
limit are handled like filtered routes. Default: <cf/off/.
- <tag>export limit [ <m/number/ | off ] [action warn | block | restart | disable]</tag>
+ <tag><label id="proto-export-limit">export limit [ <m/number/ | off ] [action warn | block | restart | disable]</tag>
Specify an export route limit, works similarly to the <cf>import
limit</cf> option, but for the routes exported to the protocol. This
option is experimental, there are some problems in details of its
@@ -576,18 +592,18 @@ agreement").
updates of already accepted routes -- and these details will probably
change in the future. Default: <cf/off/.
- <tag>description "<m/text/"</tag>
+ <tag><label id="proto-description">description "<m/text/"</tag>
This is an optional description of the protocol. It is displayed as a
part of the output of 'show route all' command.
- <tag>table <m/name/</tag>
+ <tag><label id="proto-table">table <m/name/</tag>
Connect this protocol to a non-default routing table.
</descrip>
<p>There are several options that give sense only with certain protocols:
<descrip>
- <tag><label id="dsc-iface">interface [-] [ "<m/mask/" ] [ <m/prefix/ ] [, ...] [ { <m/option/ ; [...] } ]</tag>
+ <tag><label id="proto-iface">interface [-] [ "<m/mask/" ] [ <m/prefix/ ] [, <m/.../] [ { <m/option/; [<m/.../] } ]</tag>
Specifies a set of interfaces on which the protocol is activated with
given interface-specific options. A set of interfaces specified by one
interface option is described using an interface pattern. The interface
@@ -610,8 +626,8 @@ agreement").
options, in that case for given interface the first matching interface
option is used.
- This option is allowed in BFD, Direct, OSPF, RAdv and RIP protocols, but
- in OSPF protocol it is used in the <cf/area/ subsection.
+ This option is allowed in Babel, BFD, Direct, OSPF, RAdv and RIP
+ protocols, but in OSPF protocol it is used in the <cf/area/ subsection.
Default: none.
@@ -634,7 +650,7 @@ agreement").
<cf>interface "eth*" 192.168.1.0/24;</cf> - start the protocol on all
ethernet interfaces that have address from 192.168.1.0/24.
- <tag><label id="dsc-prio">tx class|dscp <m/num/</tag>
+ <tag><label id="proto-tx-class">tx class|dscp <m/num/</tag>
This option specifies the value of ToS/DS/Class field in IP headers of
the outgoing protocol packets. This may affect how the protocol packets
are processed by the network relative to the other network traffic. With
@@ -643,51 +659,64 @@ agreement").
keyword, the value (0-63) is used just for the DS field in the octet.
Default value is 0xc0 (DSCP 0x30 - CS6).
- <tag>tx priority <m/num/</tag>
+ <tag><label id="proto-tx-priority">tx priority <m/num/</tag>
This option specifies the local packet priority. This may affect how the
protocol packets are processed in the local TX queues. This option is
Linux specific. Default value is 7 (highest priority, privileged traffic).
- <tag><label id="dsc-pass">password "<m/password/" [ { id <m/num/; generate from <m/time/; generate to <m/time/; accept from <m/time/; accept to <m/time/; } ]</tag>
- Specifies a password that can be used by the protocol. Password option
- can be used more times to specify more passwords. If more passwords are
- specified, it is a protocol-dependent decision which one is really
- used. Specifying passwords does not mean that authentication is enabled,
- authentication can be enabled by separate, protocol-dependent
- <cf/authentication/ option.
+ <tag><label id="proto-pass">password "<m/password/" [ { <m>password options</m> } ]</tag>
+ Specifies a password that can be used by the protocol as a shared secret
+ key. Password option can be used more times to specify more passwords.
+ If more passwords are specified, it is a protocol-dependent decision
+ which one is really used. Specifying passwords does not mean that
+ authentication is enabled, authentication can be enabled by separate,
+ protocol-dependent <cf/authentication/ option.
- This option is allowed in OSPF and RIP protocols. BGP has also
+ This option is allowed in BFD, OSPF and RIP protocols. BGP has also
<cf/password/ option, but it is slightly different and described
separately.
-
Default: none.
</descrip>
<p>Password option can contain section with some (not necessary all) password sub-options:
<descrip>
- <tag>id <M>num</M></tag>
- ID of the password, (0-255). If it's not used, BIRD will choose ID based
+ <tag><label id="proto-pass-id">id <M>num</M></tag>
+ ID of the password, (1-255). If it is not used, BIRD will choose ID based
on an order of the password item in the interface. For example, second
password item in one interface will have default ID 2. ID is used by
some routing protocols to identify which password was used to
authenticate protocol packets.
- <tag>generate from "<m/time/"</tag>
+ <tag><label id="proto-pass-gen-from">generate from "<m/time/"</tag>
The start time of the usage of the password for packet signing.
The format of <cf><m/time/</cf> is <tt>dd-mm-yyyy HH:MM:SS</tt>.
- <tag>generate to "<m/time/"</tag>
+ <tag><label id="proto-pass-gen-to">generate to "<m/time/"</tag>
The last time of the usage of the password for packet signing.
- <tag>accept from "<m/time/"</tag>
+ <tag><label id="proto-pass-accept-from">accept from "<m/time/"</tag>
The start time of the usage of the password for packet verification.
- <tag>accept to "<m/time/"</tag>
+ <tag><label id="proto-pass-accept-to">accept to "<m/time/"</tag>
The last time of the usage of the password for packet verification.
+
+ <tag><label id="proto-pass-from">from "<m/time/"</tag>
+ Shorthand for setting both <cf/generate from/ and <cf/accept from/.
+
+ <tag><label id="proto-pass-to">to "<m/time/"</tag>
+ Shorthand for setting both <cf/generate to/ and <cf/accept to/.
+
+ <tag><label id="proto-pass-algorithm">algorithm ( keyed md5 | keyed sha1 | hmac sha1 | hmac sha256 | hmac sha384 | hmac sha512 )</tag>
+ The message authentication algorithm for the password when cryptographic
+ authentication is enabled. The default value depends on the protocol.
+ For RIP and OSPFv2 it is Keyed-MD5 (for compatibility), for OSPFv3
+ protocol it is HMAC-SHA-256.
+
</descrip>
<chapt>Remote control
+<label id="remote-control">
<p>You can use the command-line client <file>birdc</file> to talk with a running
BIRD. Communication is done using a <file/bird.ctl/ UNIX domain socket (unless
@@ -713,26 +742,26 @@ This argument can be omitted if there exists only a single instance.
<p>Here is a brief list of supported functions:
<descrip>
- <tag>show status</tag>
+ <tag><label id="cli-show-status">show status</tag>
Show router status, that is BIRD version, uptime and time from last
reconfiguration.
- <tag>show interfaces [summary]</tag>
+ <tag><label id="cli-show-interfaces">show interfaces [summary]</tag>
Show the list of interfaces. For each interface, print its type, state,
MTU and addresses assigned.
- <tag>show protocols [all]</tag>
+ <tag><label id="cli-show-protocols">show protocols [all]</tag>
Show list of protocol instances along with tables they are connected to
and protocol status, possibly giving verbose information, if <cf/all/ is
specified.
- <tag>show ospf interface [<m/name/] ["<m/interface/"]</tag>
+ <tag><label id="cli-show-ospf-iface">show ospf interface [<m/name/] ["<m/interface/"]</tag>
Show detailed information about OSPF interfaces.
- <tag>show ospf neighbors [<m/name/] ["<m/interface/"]</tag>
+ <tag><label id="cli-show-ospf-neighbors">show ospf neighbors [<m/name/] ["<m/interface/"]</tag>
Show a list of OSPF neighbors and a state of adjacency to them.
- <tag>show ospf state [all] [<m/name/]</tag>
+ <tag><label id="cli-show-ospf-state">show ospf state [all] [<m/name/]</tag>
Show detailed information about OSPF areas based on a content of the
link-state database. It shows network topology, stub networks,
aggregated networks and routers from other areas and external routes.
@@ -740,31 +769,31 @@ This argument can be omitted if there exists only a single instance.
<cf/all/ to show information about all network nodes in the link-state
database.
- <tag>show ospf topology [all] [<m/name/]</tag>
+ <tag><label id="cli-show-ospf-topology">show ospf topology [all] [<m/name/]</tag>
Show a topology of OSPF areas based on a content of the link-state
database. It is just a stripped-down version of 'show ospf state'.
- <tag>show ospf lsadb [global | area <m/id/ | link] [type <m/num/] [lsid <m/id/] [self | router <m/id/] [<m/name/] </tag>
+ <tag><label id="cli-show-ospf-lsadb">show ospf lsadb [global | area <m/id/ | link] [type <m/num/] [lsid <m/id/] [self | router <m/id/] [<m/name/] </tag>
Show contents of an OSPF LSA database. Options could be used to filter
entries.
- <tag>show rip interfaces [<m/name/] ["<m/interface/"]</tag>
+ <tag><label id="cli-show-rip-interfaces">show rip interfaces [<m/name/] ["<m/interface/"]</tag>
Show detailed information about RIP interfaces.
- <tag>show rip neighbors [<m/name/] ["<m/interface/"]</tag>
+ <tag><label id="cli-show-rip-neighbors">show rip neighbors [<m/name/] ["<m/interface/"]</tag>
Show a list of RIP neighbors and associated state.
- <tag>show static [<m/name/]</tag>
+ <tag><label id="cli-show-static">show static [<m/name/]</tag>
Show detailed information about static routes.
- <tag>show bfd sessions [<m/name/]</tag>
+ <tag><label id="cli-show-bfd-sessions">show bfd sessions [<m/name/]</tag>
Show information about BFD sessions.
- <tag>show symbols [table|filter|function|protocol|template|roa|<m/symbol/]</tag>
+ <tag><label id="cli-show-symbols">show symbols [table|filter|function|protocol|template|roa|<m/symbol/]</tag>
Show the list of symbols defined in the configuration (names of
protocols, routing tables etc.).
- <tag>show route [[for] <m/prefix/|<m/IP/] [table <m/sym/] [filter <m/f/|where <m/c/] [(export|preexport|noexport) <m/p/] [protocol <m/p/] [<m/options/]</tag>
+ <tag><label id="cli-show-route">show route [[for] <m/prefix/|<m/IP/] [table <m/t/] [filter <m/f/|where <m/c/] [(export|preexport|noexport) <m/p/] [protocol <m/p/] [<m/options/]</tag>
Show contents of a routing table (by default of the main one or the
table attached to a respective protocol), that is routes, their metrics
and (in case the <cf/all/ switch is given) all their attributes.
@@ -799,7 +828,7 @@ This argument can be omitted if there exists only a single instance.
number of networks, number of routes before and after filtering). If
you use <cf/count/ instead, only the statistics will be printed.
- <tag>show roa [<m/prefix/ | in <m/prefix/ | for <m/prefix/] [as <m/num/] [table <m/t/>]</tag>
+ <tag><label id="cli-show-roa">show roa [<m/prefix/ | in <m/prefix/ | for <m/prefix/] [as <m/num/] [table <m/t/]</tag>
Show contents of a ROA table (by default of the first one). You can
specify a <m/prefix/ to print ROA entries for a specific network. If you
use <cf>for <m/prefix/</cf>, you'll get all entries relevant for route
@@ -808,19 +837,19 @@ This argument can be omitted if there exists only a single instance.
entries covered by the network prefix. You could also use <cf/as/ option
to show just entries for given AS.
- <tag>add roa <m/prefix/ max <m/num/] as <m/num/ [table <m/t/>]</tag>
+ <tag><label id="cli-add-roa">add roa <m/prefix/ max <m/num/ as <m/num/ [table <m/t/]</tag>
Add a new ROA entry to a ROA table. Such entry is called <it/dynamic/
compared to <it/static/ entries specified in the config file. These
dynamic entries survive reconfiguration.
- <tag>delete roa <m/prefix/ max <m/num/] as <m/num/ [table <m/t/>]</tag>
+ <tag><label id="cli-delete-roa">delete roa <m/prefix/ max <m/num/ as <m/num/ [table <m/t/]</tag>
Delete the specified ROA entry from a ROA table. Only dynamic ROA
entries (i.e., the ones added by <cf/add roa/ command) can be deleted.
- <tag>flush roa [table <m/t/>]</tag>
+ <tag><label id="cli-flush-roa">flush roa [table <m/t/]</tag>
Remove all dynamic ROA entries from a ROA table.
- <tag>configure [soft] ["<m/config file/"] [timeout [<m/num/]]</tag>
+ <tag><label id="cli-configure">configure [soft] ["<m/config file/"] [timeout [<m/num/]]</tag>
Reload configuration from a given file. BIRD will smoothly switch itself
to the new configuration, protocols are reconfigured if possible,
restarted otherwise. Changes in filters usually lead to restart of
@@ -839,11 +868,11 @@ This argument can be omitted if there exists only a single instance.
config timeout expiration is equivalent to <cf/configure undo/
command. The timeout duration could be specified, default is 300 s.
- <tag>configure confirm</tag>
+ <tag><label id="cli-configure-confirm">configure confirm</tag>
Deactivate the config undo timer and therefore confirm the current
configuration.
- <tag>configure undo</tag>
+ <tag><label id="cli-configure-undo">configure undo</tag>
Undo the last configuration change and smoothly switch back to the
previous (stored) configuration. If the last configuration change was
soft, the undo change is also soft. There is only one level of undo, but
@@ -851,15 +880,15 @@ This argument can be omitted if there exists only a single instance.
immediately in a row and the intermediate ones are skipped then the undo
also skips them back.
- <tag>configure check ["<m/config file/"]</tag>
+ <tag><label id="cli-configure-check">configure check ["<m/config file/"]</tag>
Read and parse given config file, but do not use it. useful for checking
syntactic and some semantic validity of an config file.
- <tag>enable|disable|restart <m/name/|"<m/pattern/"|all</tag>
+ <tag><label id="cli-enable-disable-restart">enable|disable|restart <m/name/|"<m/pattern/"|all</tag>
Enable, disable or restart a given protocol instance, instances matching
the <cf><m/pattern/</cf> or <cf/all/ instances.
- <tag>reload [in|out] <m/name/|"<m/pattern/"|all</tag>
+ <tag><label id="cli-reload">reload [in|out] <m/name/|"<m/pattern/"|all</tag>
Reload a given protocol instance, that means re-import routes from the
protocol instance and re-export preferred routes to the instance. If
<cf/in/ or <cf/out/ options are used, the command is restricted to one
@@ -876,27 +905,29 @@ This argument can be omitted if there exists only a single instance.
pipe protocol, both directions are always reloaded together (<cf/in/ or
<cf/out/ options are ignored in that case).
- <tag/down/
+ <tag><label id="cli-down">down</tag>
Shut BIRD down.
- <tag>debug <m/protocol/|<m/pattern/|all all|off|{ states | routes | filters | events | packets }</tag>
+ <tag><label id="cli-debug">debug <m/protocol/|<m/pattern/|all all|off|{ states|routes|filters|events|packets [, <m/.../] }</tag>
Control protocol debugging.
- <tag>dump resources|sockets|interfaces|neighbors|attributes|routes|protocols</tag>
+ <tag><label id="cli-dump">dump resources|sockets|interfaces|neighbors|attributes|routes|protocols</tag>
Dump contents of internal data structures to the debugging output.
- <tag>echo all|off|{ <m/list of log classes/ } [ <m/buffer-size/ ]</tag>
+ <tag><label id="cli-echo">echo all|off|{ <m/list of log classes/ } [ <m/buffer-size/ ]</tag>
Control echoing of log messages to the command-line output.
- See <ref id="dsc-log" name="log option"> for a list of log classes.
+ See <ref id="opt-log" name="log option"> for a list of log classes.
- <tag>eval <m/expr/</tag>
+ <tag><label id="cli-eval">eval <m/expr/</tag>
Evaluate given expression.
</descrip>
<chapt>Filters
+<label id="filters">
<sect>Introduction
+<label id="filters-intro">
<p>BIRD contains a simple programming language. (No, it can't yet read mail :-).
There are two objects in this language: filters and functions. Filters are
@@ -984,43 +1015,44 @@ bird>
<sect>Data types
+<label id="data-types">
<p>Each variable and each value has certain type. Booleans, integers and enums
are incompatible with each other (that is to prevent you from shooting in the
foot).
<descrip>
- <tag/bool/
+ <tag><label id="type-bool">bool</tag>
This is a boolean type, it can have only two values, <cf/true/ and
<cf/false/. Boolean is the only type you can use in <cf/if/ statements.
- <tag/int/
+ <tag><label id="type-int">int</tag>
This is a general integer type. It is an unsigned 32bit type; i.e., you
can expect it to store values from 0 to 4294967295. Overflows are not
checked. You can use <cf/0x1234/ syntax to write hexadecimal values.
- <tag/pair/
+ <tag><label id="type-pair">pair</tag>
This is a pair of two short integers. Each component can have values
from 0 to 65535. Literals of this type are written as <cf/(1234,5678)/.
The same syntax can also be used to construct a pair from two arbitrary
integer expressions (for example <cf/(1+2,a)/).
- <tag/quad/
+ <tag><label id="type-quad">quad</tag>
This is a dotted quad of numbers used to represent router IDs (and
others). Each component can have a value from 0 to 255. Literals of
this type are written like IPv4 addresses.
- <tag/string/
+ <tag><label id="type-string">string</tag>
This is a string of characters. There are no ways to modify strings in
filters. You can pass them between functions, assign them to variables
of type <cf/string/, print such variables, use standard string
comparison operations (e.g. <cf/=, !=, &lt;, &gt;, &lt;=, &gt;=/), but
you can't concatenate two strings. String literals are written as
- <cf/"This is a string constant"/. Additionally matching <cf/&tilde;/
- operator could be used to match a string value against a shell pattern
- (represented also as a string).
+ <cf/"This is a string constant"/. Additionally matching (<cf/&tilde;,
+ !&tilde;/) operators could be used to match a string value against
+ a shell pattern (represented also as a string).
- <tag/ip/
+ <tag><label id="type-ip">ip</tag>
This type can hold a single IP address. Depending on the compile-time
configuration of BIRD you are using, it is either an IPv4 or IPv6
address. IP addresses are written in the standard notation
@@ -1029,15 +1061,15 @@ foot).
first <cf><M>num</M></cf> bits from the IP address. So
<cf/1.2.3.4.mask(8) = 1.0.0.0/ is true.
- <tag/prefix/
+ <tag><label id="type-prefix">prefix</tag>
This type can hold a network prefix consisting of IP address and prefix
length. Prefix literals are written as <cf><m/ipaddress//<m/pxlen/</cf>,
or <cf><m>ipaddress</m>/<m>netmask</m></cf>. There are two special
operators on prefixes: <cf/.ip/ which extracts the IP address from the
pair, and <cf/.len/, which separates prefix length from the pair.
- So <cf>1.2.0.0/16.pxlen = 16</cf> is true.
+ So <cf>1.2.0.0/16.len = 16</cf> is true.
- <tag/ec/
+ <tag><label id="type-ec">ec</tag>
This is a specialized type used to represent BGP extended community
values. It is essentially a 64bit value, literals of this type are
usually written as <cf>(<m/kind/, <m/key/, <m/value/)</cf>, where
@@ -1048,7 +1080,16 @@ foot).
for <cf/key/ and <cf/value/ parts, (e.g. <cf/(ro, myas, 3*10)/, where
<cf/myas/ is an integer variable).
- <tag/int|pair|quad|ip|prefix|ec|enum set/
+ <tag><label id="type-lc">lc</tag>
+ This is a specialized type used to represent BGP large community
+ values. It is essentially a triplet of 32bit values, where the first
+ value is reserved for the AS number of the issuer, while meaning of
+ remaining parts is defined by the issuer. Literals of this type are
+ written as <cf/(123, 456, 789)/, with any integer values. Similarly to
+ pairs, LCs can be constructed using expressions for its parts, (e.g.
+ <cf/(myas, 10+20, 3*10)/, where <cf/myas/ is an integer variable).
+
+ <tag><label id="type-set">int|pair|quad|ip|prefix|ec|lc|enum set</tag>
Filters recognize four types of sets. Sets are similar to strings: you
can pass them around but you can't modify them. Literals of type <cf>int
set</cf> look like <cf> [ 1, 2, 5..7 ]</cf>. As you can see, both simple
@@ -1067,9 +1108,15 @@ foot).
(like <cf/(rt, *, 3)/) are not allowed (as they usually have 4B range
for ASNs).
- You can also use expressions for int, pair and EC set values. However it
- must be possible to evaluate these expressions before daemon boots. So
- you can use only constants inside them. E.g.
+ Also LC sets use similar expressions like pair sets. You can use ranges
+ and wildcards, but if one field uses that, more specific (later) fields
+ must be wildcards. E.g., <cf/(10, 20..30, *)/ or <cf/(10, 20, 30..40)/
+ is valid, while <cf/(10, *, 20..30)/ or <cf/(10, 20..30, 40)/ is not
+ valid.
+
+ You can also use expressions for int, pair, EC and LC set values.
+ However, it must be possible to evaluate these expressions before daemon
+ boots. So you can use only constants inside them. E.g.
<code>
define one=1;
@@ -1118,12 +1165,12 @@ foot).
<cf>192.168.0.0/16{16,24}</cf> and <cf>192.168.0.0/16 ge 24</cf> as
<cf>192.168.0.0/16{24,32}</cf>.
- <tag/enum/
+ <tag><label id="type-enum">enum</tag>
Enumeration types are fixed sets of possibilities. You can't define your
own variables of such type, but some route attributes are of enumeration
type. Enumeration types are incompatible with each other.
- <tag/bgppath/
+ <tag><label id="type-bgppath">bgppath</tag>
BGP path is a list of autonomous system numbers. You can't write
literals of this type. There are several special operators on bgppaths:
@@ -1156,7 +1203,7 @@ foot).
<cf><m/P/.prepend(<m/A/);</cf> if <m/P/ is appropriate route attribute
(for example <cf/bgp_path/). Similarly for <cf/delete/ and <cf/filter/.
- <tag/bgpmask/
+ <tag><label id="type-bgpmask">bgpmask</tag>
BGP masks are patterns used for BGP path matching (using <cf>path
&tilde; [= 2 3 5 * =]</cf> syntax). The masks resemble wildcard patterns
as used by UNIX shells. Autonomous system numbers match themselves,
@@ -1165,10 +1212,12 @@ foot).
is 4 3 2 1, then: <tt>bgp_path &tilde; [= * 4 3 * =]</tt> is true,
but <tt>bgp_path &tilde; [= * 4 5 * =]</tt> is false. BGP mask
expressions can also contain integer expressions enclosed in parenthesis
- and integer variables, for example <tt>[= * 4 (1+2) a =]</tt>. There is
- also old syntax that uses / .. / instead of [= .. =] and ? instead of *.
+ and integer variables, for example <tt>[= * 4 (1+2) a =]</tt>. You can
+ also use ranges, for example <tt>[= * 3..5 2 100..200 * =]</tt>.
+ There is also old (deprecated) syntax that uses / .. / instead of [= .. =]
+ and ? instead of *.
- <tag/clist/
+ <tag><label id="type-clist">clist</tag>
Clist is similar to a set, except that unlike other sets, it can be
modified. The type is used for community list (a set of pairs) and for
cluster list (a set of quads). There exist no literals of this type.
@@ -1197,38 +1246,46 @@ foot).
<cf><m/C/.add(<m/P/);</cf> if <m/C/ is appropriate route attribute (for
example <cf/bgp_community/). Similarly for <cf/delete/ and <cf/filter/.
- <tag/eclist/
+ <tag><label id="type-eclist">eclist</tag>
Eclist is a data type used for BGP extended community lists. Eclists
are very similar to clists, but they are sets of ECs instead of pairs.
- The same operations (like <cf/add/, <cf/delete/, or <cf/&tilde;/
- membership operator) can be used to modify or test eclists, with ECs
- instead of pairs as arguments.
+ The same operations (like <cf/add/, <cf/delete/ or <cf/&tilde;/ and
+ <cf/!&tilde;/ membership operators) can be used to modify or test
+ eclists, with ECs instead of pairs as arguments.
+
+ <tag><label id="type-lclist">lclist/</tag>
+ Lclist is a data type used for BGP large community lists. Like eclists,
+ lclists are very similar to clists, but they are sets of LCs instead of
+ pairs. The same operations (like <cf/add/, <cf/delete/ or <cf/&tilde;/
+ and <cf/!&tilde;/ membership operators) can be used to modify or test
+ lclists, with LCs instead of pairs as arguments.
</descrip>
<sect>Operators
+<label id="operators">
<p>The filter language supports common integer operators <cf>(+,-,*,/)</cf>,
parentheses <cf/(a*(b+c))/, comparison <cf/(a=b, a!=b, a&lt;b, a&gt;=b)/.
Logical operations include unary not (<cf/!/), and (<cf/&amp;&amp;/) and or
-(<cf/&verbar;&verbar;/). Special operators include <cf/&tilde;/ for "is element
-of a set" operation - it can be used on element and set of elements of the same
-type (returning true if element is contained in the given set), or on two
-strings (returning true if first string matches a shell-like pattern stored in
-second string) or on IP and prefix (returning true if IP is within the range
-defined by that prefix), or on prefix and prefix (returning true if first prefix
-is more specific than second one) or on bgppath and bgpmask (returning true if
-the path matches the mask) or on number and bgppath (returning true if the
-number is in the path) or on bgppath and int (number) set (returning true if any
-ASN from the path is in the set) or on pair/quad and clist (returning true if
-the pair/quad is element of the clist) or on clist and pair/quad set (returning
-true if there is an element of the clist that is also a member of the pair/quad
-set).
+(<cf/&verbar;&verbar;/). Special operators include (<cf/&tilde;/,
+<cf/!&tilde;/) for "is (not) element of a set" operation - it can be used on
+element and set of elements of the same type (returning true if element is
+contained in the given set), or on two strings (returning true if first string
+matches a shell-like pattern stored in second string) or on IP and prefix
+(returning true if IP is within the range defined by that prefix), or on prefix
+and prefix (returning true if first prefix is more specific than second one) or
+on bgppath and bgpmask (returning true if the path matches the mask) or on
+number and bgppath (returning true if the number is in the path) or on bgppath
+and int (number) set (returning true if any ASN from the path is in the set) or
+on pair/quad and clist (returning true if the pair/quad is element of the
+clist) or on clist and pair/quad set (returning true if there is an element of
+the clist that is also a member of the pair/quad set).
<p>There is one operator related to ROA infrastructure - <cf/roa_check()/. It
-examines a ROA table and does RFC 6483 route origin validation for a given
-network prefix. The basic usage is <cf>roa_check(<m/table/)</cf>, which checks
-current route (which should be from BGP to have AS_PATH argument) in the
+examines a ROA table and does <rfc id="6483"> route origin validation for a
+given network prefix. The basic usage is <cf>roa_check(<m/table/)</cf>, which
+checks current route (which should be from BGP to have AS_PATH argument) in the
specified ROA table and returns ROA_UNKNOWN if there is no relevant ROA,
ROA_VALID if there is a matching ROA, or ROA_INVALID if there are some relevant
ROAs but none of them match. There is also an extended variant
@@ -1237,6 +1294,7 @@ prefix and an ASN as arguments.
<sect>Control structures
+<label id="control-structures">
<p>Filters support two control structures: conditions and case switches.
@@ -1272,6 +1330,7 @@ if 1234 = i then printn "."; else {
<sect>Route attributes
+<label id="route-attributes">
<p>A filter is implicitly passed a route, and it can access its attributes just
like it accesses variables. Attempts to access undefined attribute result in a
@@ -1281,11 +1340,11 @@ rule are attributes of clist type, where undefined value is regarded as empty
clist for most purposes.
<descrip>
- <tag><m/prefix/ net</tag>
+ <tag><label id="rta-net"><m/prefix/ net</tag>
Network the route is talking about. Read-only. (See the chapter about
routing tables.)
- <tag><m/enum/ scope</tag>
+ <tag><label id="rta-scope"><m/enum/ scope</tag>
The scope of the route. Possible values: <cf/SCOPE_HOST/ for routes
local to this host, <cf/SCOPE_LINK/ for those specific for a physical
link, <cf/SCOPE_SITE/ and <cf/SCOPE_ORGANIZATION/ for private routes and
@@ -1293,33 +1352,33 @@ clist for most purposes.
interpreted by BIRD and can be used to mark routes in filters. The
default value for new routes is <cf/SCOPE_UNIVERSE/.
- <tag><m/int/ preference</tag>
+ <tag><label id="rta-preference"><m/int/ preference</tag>
Preference of the route. Valid values are 0-65535. (See the chapter
about routing tables.)
- <tag><m/ip/ from</tag>
+ <tag><label id="rta-from"><m/ip/ from</tag>
The router which the route has originated from.
- <tag><m/ip/ gw</tag>
+ <tag><label id="rta-gw"><m/ip/ gw</tag>
Next hop packets routed using this route should be forwarded to.
- <tag><m/string/ proto</tag>
+ <tag><label id="rta-proto"><m/string/ proto</tag>
The name of the protocol which the route has been imported from.
Read-only.
- <tag><m/enum/ source</tag>
+ <tag><label id="rta-source"><m/enum/ source</tag>
what protocol has told me about this route. Possible values:
<cf/RTS_DUMMY/, <cf/RTS_STATIC/, <cf/RTS_INHERIT/, <cf/RTS_DEVICE/,
<cf/RTS_STATIC_DEVICE/, <cf/RTS_REDIRECT/, <cf/RTS_RIP/, <cf/RTS_OSPF/,
<cf/RTS_OSPF_IA/, <cf/RTS_OSPF_EXT1/, <cf/RTS_OSPF_EXT2/, <cf/RTS_BGP/,
- <cf/RTS_PIPE/.
+ <cf/RTS_PIPE/, <cf/RTS_BABEL/.
- <tag><m/enum/ cast</tag>
+ <tag><label id="rta-cast"><m/enum/ cast</tag>
Route type (Currently <cf/RTC_UNICAST/ for normal routes,
<cf/RTC_BROADCAST/, <cf/RTC_MULTICAST/, <cf/RTC_ANYCAST/ will be used in
the future for broadcast, multicast and anycast routes). Read-only.
- <tag><m/enum/ dest</tag>
+ <tag><label id="rta-dest"><m/enum/ dest</tag>
Type of destination the packets should be sent to
(<cf/RTD_ROUTER/ for forwarding to a neighboring router,
<cf/RTD_DEVICE/ for routing to a directly-connected network,
@@ -1330,18 +1389,18 @@ clist for most purposes.
messages). Can be changed, but only to <cf/RTD_BLACKHOLE/,
<cf/RTD_UNREACHABLE/ or <cf/RTD_PROHIBIT/.
- <tag><m/string/ ifname</tag>
+ <tag><label id="rta-ifname"><m/string/ ifname</tag>
Name of the outgoing interface. Sink routes (like blackhole, unreachable
or prohibit) and multipath routes have no interface associated with
them, so <cf/ifname/ returns an empty string for such routes. Read-only.
- <tag><m/int/ ifindex</tag>
+ <tag><label id="rta-ifindex"><m/int/ ifindex</tag>
Index of the outgoing interface. System wide index of the interface. May
be used for interface matching, however indexes might change on interface
creation/removal. Zero is returned for routes with undefined outgoing
interfaces. Read-only.
- <tag><m/int/ igp_metric</tag>
+ <tag><label id="rta-igp-metric"><m/int/ igp_metric</tag>
The optional attribute that can be used to specify a distance to the
network for routes that do not have a native protocol metric attribute
(like <cf/ospf_metric1/ for OSPF routes). It is used mainly by BGP to
@@ -1355,40 +1414,45 @@ corresponding protocol sections.
<sect>Other statements
+<label id="other-statements">
<p>The following statements are available:
<descrip>
- <tag><m/variable/ = <m/expr/</tag>
+ <tag><label id="assignment"><m/variable/ = <m/expr/</tag>
Set variable to a given value.
- <tag>accept|reject [ <m/expr/ ]</tag>
+ <tag><label id="filter-accept-reject">accept|reject [ <m/expr/ ]</tag>
Accept or reject the route, possibly printing <cf><m>expr</m></cf>.
- <tag>return <m/expr/</tag>
+ <tag><label id="return">return <m/expr/</tag>
Return <cf><m>expr</m></cf> from the current function, the function ends
at this point.
- <tag>print|printn <m/expr/ [<m/, expr.../]</tag>
+ <tag><label id="print">print|printn <m/expr/ [<m/, expr.../]</tag>
Prints given expressions; useful mainly while debugging filters. The
<cf/printn/ variant does not terminate the line.
- <tag>quitbird</tag>
+ <tag><label id="quitbird">quitbird</tag>
Terminates BIRD. Useful when debugging the filter interpreter.
</descrip>
<chapt>Protocols
+<label id="protocols">
<sect>Babel
+<label id="babel">
<sect1>Introduction
+<label id="babel-intro">
-<p>The Babel protocol (RFC6126) is a loop-avoiding distance-vector routing
-protocol that is robust and efficient both in ordinary wired networks and in
-wireless mesh networks. Babel is conceptually very simple in its operation and
-"just works" in its default configuration, though some configuration is possible
-and in some cases desirable.
+<p>The Babel protocol
+(<rfc id="6126">) is a loop-avoiding distance-vector routing protocol that is
+robust and efficient both in ordinary wired networks and in wireless mesh
+networks. Babel is conceptually very simple in its operation and "just works"
+in its default configuration, though some configuration is possible and in some
+cases desirable.
<p>While the Babel protocol is dual stack (i.e., can carry both IPv4 and IPv6
routes over the same IPv6 transport), BIRD presently implements only the IPv6
@@ -1399,6 +1463,7 @@ just ignore extension messages).
<p>The Babel protocol implementation in BIRD is currently in alpha stage.
<sect1>Configuration
+<label id="babel-config">
<p>Babel supports no global configuration options apart from those common to all
other protocols, but supports the following per-interface configuration options:
@@ -1421,7 +1486,7 @@ protocol babel [<name>] {
</code>
<descrip>
- <tag>type wired|wireless </tag>
+ <tag><label id="babel-type">type wired|wireless </tag>
This option specifies the interface type: Wired or wireless. Wired
interfaces are considered more reliable, and so the default hello
interval is higher, and a neighbour is considered unreachable after only
@@ -1432,41 +1497,41 @@ protocol babel [<name>] {
when packets are lost rather than the more binary up/down mechanism of
wired type links. Default: <cf/wired/.
- <tag>rxcost <m/num/</tag>
+ <tag><label id="babel-rxcost">rxcost <m/num/</tag>
This specifies the RX cost of the interface. The route metrics will be
computed from this value with a mechanism determined by the interface
<cf/type/. Default: 96 for wired interfaces, 256 for wireless.
- <tag>hello interval <m/num/</tag>
+ <tag><label id="babel-hello">hello interval <m/num/</tag>
Interval at which periodic "hello" messages are sent on this interface,
in seconds. Default: 4 seconds.
- <tag>update interval <m/num/</tag>
+ <tag><label id="babel-update">update interval <m/num/</tag>
Interval at which periodic (full) updates are sent. Default: 4 times the
hello interval.
- <tag>port <m/number/</tag>
+ <tag><label id="babel-port">port <m/number/</tag>
This option selects an UDP port to operate on. The default is to operate
on port 6696 as specified in the Babel RFC.
- <tag>tx class|dscp|priority <m/number/</tag>
+ <tag><label id="babel-tx-class">tx class|dscp|priority <m/number/</tag>
These options specify the ToS/DiffServ/Traffic class/Priority of the
- outgoing Babel packets. See <ref id="dsc-prio" name="tx class"> common
+ outgoing Babel packets. See <ref id="proto-tx-class" name="tx class"> common
option for detailed description.
- <tag>rx buffer <m/number/</tag>
+ <tag><label id="babel-rx-buffer">rx buffer <m/number/</tag>
This option specifies the size of buffers used for packet processing.
The buffer size should be bigger than maximal size of received packets.
The default value is the interface MTU, and the value will be clamped to a
minimum of 512 bytes + IP packet overhead.
- <tag>tx length <m/number/</tag>
+ <tag><label id="babel-tx-length">tx length <m/number/</tag>
This option specifies the maximum length of generated Babel packets. To
avoid IP fragmentation, it should not exceed the interface MTU value.
The default value is the interface MTU value, and the value will be
clamped to a minimum of 512 bytes + IP packet overhead.
- <tag>check link <m/switch/</tag>
+ <tag><label id="babel-check-link">check link <m/switch/</tag>
If set, the hardware link state (as reported by OS) is taken into
consideration. When the link disappears (e.g. an ethernet cable is
unplugged), neighbors are immediately considered unreachable and all
@@ -1475,10 +1540,42 @@ protocol babel [<name>] {
yes.
</descrip>
+<sect1>Attributes
+<label id="babel-attr">
+
+<p>Babel defines just one attribute: the internal babel metric of the route. It
+is exposed as the <cf/babel_metric/ attribute and has range from 1 to infinity
+(65535).
-<sect><label id="sect-bfd">BFD
+<sect1>Example
+<label id="babel-exam">
+
+<p><code>
+protocol babel {
+ interface "eth*" {
+ type wired;
+ };
+ interface "wlan0", "wlan1" {
+ type wireless;
+ hello interval 1;
+ rxcost 512;
+ };
+ interface "tap0";
+
+ # This matches the default of babeld: redistribute all addresses
+ # configured on local interfaces, plus re-distribute all routes received
+ # from other babel peers.
+
+ export where (source = RTS_DEVICE) || (source = RTS_BABEL);
+}
+</code>
+
+
+<sect>BFD
+<label id="bfd">
<sect1>Introduction
+<label id="bfd-intro">
<p>Bidirectional Forwarding Detection (BFD) is not a routing protocol itself, it
is an independent tool providing liveness and failure detection. Routing
@@ -1497,14 +1594,10 @@ addresses and associated interfaces. When a session changes its state, these
protocols are notified and act accordingly (e.g. break an OSPF adjacency when
the BFD session went down).
-<p>BIRD implements basic BFD behavior as defined in
-RFC 5880<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5880.txt">
-(some advanced features like the echo mode or authentication are not implemented),
-IP transport for BFD as defined in
-RFC 5881<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5881.txt"> and
-RFC 5883<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5883.txt">
-and interaction with client protocols as defined in
-RFC 5882<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5882.txt">.
+<p>BIRD implements basic BFD behavior as defined in <rfc id="5880"> (some
+advanced features like the echo mode or authentication are not implemented), IP
+transport for BFD as defined in <rfc id="5881"> and <rfc id="5883"> and
+interaction with client protocols as defined in <rfc id="5882">.
<p>Note that BFD implementation in BIRD is currently a new feature in
development, expect some rough edges and possible UI and configuration changes
@@ -1516,6 +1609,7 @@ default a bit different dynamic port range than the IANA approved one
<cf>/proc/sys/net/ipv4/ip_local_port_range</cf>
<sect1>Configuration
+<label id="bfd-config">
<p>BFD configuration consists mainly of multiple definitions of interfaces.
Most BFD config options are session specific. When a new session is requested
@@ -1543,6 +1637,19 @@ protocol bfd [&lt;name&gt;] {
idle tx interval &lt;time&gt;;
multiplier &lt;num&gt;;
passive &lt;switch&gt;;
+ authentication none;
+ authentication simple;
+ authentication [meticulous] keyed md5|sha1;
+ password "&lt;text&gt;";
+ password "&lt;text&gt;" {
+ id &lt;num&gt;;
+ generate from "&lt;date&gt;";
+ generate to "&lt;date&gt;";
+ accept from "&lt;date&gt;";
+ accept to "&lt;date&gt;";
+ from "&lt;date&gt;";
+ to "&lt;date&gt;";
+ };
};
multihop {
interval &lt;time&gt;;
@@ -1557,22 +1664,22 @@ protocol bfd [&lt;name&gt;] {
</code>
<descrip>
- <tag>interface <m/pattern [, ...]/ { <m/options/ }</tag>
+ <tag><label id="bfd-iface">interface <m/pattern/ [, <m/.../] { <m/options/ }</tag>
Interface definitions allow to specify options for sessions associated
with such interfaces and also may contain interface specific options.
- See <ref id="dsc-iface" name="interface"> common option for a detailed
+ See <ref id="proto-iface" name="interface"> common option for a detailed
description of interface patterns. Note that contrary to the behavior of
<cf/interface/ definitions of other protocols, BFD protocol would accept
sessions (in default configuration) even on interfaces not covered by
such definitions.
- <tag>multihop { <m/options/ }</tag>
+ <tag><label id="bfd-multihop">multihop { <m/options/ }</tag>
Multihop definitions allow to specify options for multihop BFD sessions,
in the same manner as <cf/interface/ definitions are used for directly
connected sessions. Currently only one such definition (for all multihop
sessions) could be used.
- <tag>neighbor <m/ip/ [dev "<m/interface/"] [local <m/ip/] [multihop <m/switch/]</tag>
+ <tag><label id="bfd-neighbor">neighbor <m/ip/ [dev "<m/interface/"] [local <m/ip/] [multihop <m/switch/]</tag>
BFD sessions are usually created on demand as requested by other
protocols (like OSPF or BGP). This option allows to explicitly add
a BFD session to the specified neighbor regardless of such requests.
@@ -1587,33 +1694,33 @@ protocol bfd [&lt;name&gt;] {
<p>Session specific options (part of <cf/interface/ and <cf/multihop/ definitions):
<descrip>
- <tag>interval <m/time/</tag>
+ <tag><label id="bfd-interval">interval <m/time/</tag>
BFD ensures availability of the forwarding path associated with the
session by periodically sending BFD control packets in both
directions. The rate of such packets is controlled by two options,
<cf/min rx interval/ and <cf/min tx interval/ (see below). This option
is just a shorthand to set both of these options together.
- <tag>min rx interval <m/time/</tag>
+ <tag><label id="bfd-min-rx-interval">min rx interval <m/time/</tag>
This option specifies the minimum RX interval, which is announced to the
neighbor and used there to limit the neighbor's rate of generated BFD
control packets. Default: 10 ms.
- <tag>min tx interval <m/time/</tag>
+ <tag><label id="bfd-min-tx-interval">min tx interval <m/time/</tag>
This option specifies the desired TX interval, which controls the rate
of generated BFD control packets (together with <cf/min rx interval/
announced by the neighbor). Note that this value is used only if the BFD
session is up, otherwise the value of <cf/idle tx interval/ is used
instead. Default: 100 ms.
- <tag>idle tx interval <m/time/</tag>
+ <tag><label id="bfd-idle-tx-interval">idle tx interval <m/time/</tag>
In order to limit unnecessary traffic in cases where a neighbor is not
available or not running BFD, the rate of generated BFD control packets
is lower when the BFD session is not up. This option specifies the
desired TX interval in such cases instead of <cf/min tx interval/.
Default: 1 s.
- <tag>multiplier <m/num/</tag>
+ <tag><label id="bfd-multiplier">multiplier <m/num/</tag>
Failure detection time for BFD sessions is based on established rate of
BFD control packets (<cf>min rx/tx interval</cf>) multiplied by this
multiplier, which is essentially (ignoring jitter) a number of missed
@@ -1621,14 +1728,41 @@ protocol bfd [&lt;name&gt;] {
multipliers could be different in each direction of a BFD session.
Default: 5.
- <tag>passive <m/switch/</tag>
+ <tag><label id="bfd-passive">passive <m/switch/</tag>
Generally, both BFD session endpoints try to establish the session by
sending control packets to the other side. This option allows to enable
passive mode, which means that the router does not send BFD packets
until it has received one from the other side. Default: disabled.
+
+ <tag>authentication none</tag>
+ No passwords are sent in BFD packets. This is the default value.
+
+ <tag>authentication simple</tag>
+ Every packet carries 16 bytes of password. Received packets lacking this
+ password are ignored. This authentication mechanism is very weak.
+
+ <tag>authentication [meticulous] keyed md5|sha1</tag>
+ An authentication code is appended to each packet. The cryptographic
+ algorithm is keyed MD5 or keyed SHA-1. Note that the algorithm is common
+ for all keys (on one interface), in contrast to OSPF or RIP, where it
+ is a per-key option. Passwords (keys) are not sent open via network.
+
+ The <cf/meticulous/ variant means that cryptographic sequence numbers
+ are increased for each sent packet, while in the basic variant they are
+ increased about once per second. Generally, the <cf/meticulous/ variant
+ offers better resistance to replay attacks but may require more
+ computation.
+
+ <tag>password "<M>text</M>"</tag>
+ Specifies a password used for authentication. See <ref id="dsc-pass"
+ name="password"> common option for detailed description. Note that
+ password option <cf/algorithm/ is not available in BFD protocol. The
+ algorithm is selected by <cf/authentication/ option for all passwords.
+
</descrip>
<sect1>Example
+<label id="bfd-exam">
<p><code>
protocol bfd {
@@ -1655,6 +1789,7 @@ protocol bfd {
<sect>BGP
+<label id="bgp">
<p>The Border Gateway Protocol is the routing protocol used for backbone level
routing in the today's Internet. Contrary to other protocols, its convergence
@@ -1678,33 +1813,19 @@ the packet will travel through if it uses the particular route) in order to
avoid routing loops.
<p>BIRD supports all requirements of the BGP4 standard as defined in
-RFC 4271<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4271.txt">
-It also supports the community attributes
-(RFC 1997<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc1997.txt">),
-capability negotiation
-(RFC 5492<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5492.txt">),
-MD5 password authentication
-(RFC 2385<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc2385.txt">),
-extended communities
-(RFC 4360<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4360.txt">),
-route reflectors
-(RFC 4456<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4456.txt">),
-graceful restart
-(RFC 4724<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4724.txt">),
-multiprotocol extensions
-(RFC 4760<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4760.txt">),
-4B AS numbers
-(RFC 4893<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4893.txt">),
-and 4B AS numbers in extended communities
-(RFC 5668<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5668.txt">).
+<rfc id="4271"> It also supports the community attributes (<rfc id="1997">),
+capability negotiation (<rfc id="5492">), MD5 password authentication (<rfc
+id="2385">), extended communities (<rfc id="4360">), route reflectors (<rfc
+id="4456">), graceful restart (<rfc id="4724">), multiprotocol extensions
+(<rfc id="4760">), 4B AS numbers (<rfc id="4893">), and 4B AS numbers in
+extended communities (<rfc id="5668">).
For IPv6, it uses the standard multiprotocol extensions defined in
-RFC 4760<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4760.txt">
-and applied to IPv6 according to
-RFC 2545<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc2545.txt">.
+<rfc id="4760"> and applied to IPv6 according to <rfc id="2545">.
<sect1>Route selection rules
+<label id="bgp-route-select-rules">
<p>BGP doesn't have any simple metric, so the rules for selection of an optimal
route among multiple BGP routes with the same preference are a bit more complex
@@ -1724,6 +1845,7 @@ choose among them and so on.
</itemize>
<sect1>IGP routing table
+<label id="bgp-igp-routing-table">
<p>BGP is mainly concerned with global network reachability and with routes to
other autonomous systems. When such routes are redistributed to routers in the
@@ -1734,13 +1856,14 @@ boundary routers for the purpose of BGP route selection. In BIRD, there is
usually one routing table used for both IGP routes and BGP routes.
<sect1>Configuration
+<label id="bgp-config">
<p>Each instance of the BGP corresponds to one neighboring router. This allows
to set routing policy and all the other parameters differently for each neighbor
using the following configuration parameters:
<descrip>
- <tag>local [<m/ip/] as <m/number/</tag>
+ <tag><label id="bgp-local">local [<m/ip/] as <m/number/</tag>
Define which AS we are part of. (Note that contrary to other IP routers,
BIRD is able to act as a router located in multiple AS'es simultaneously,
but in such cases you need to tweak the BGP paths manually in the filters
@@ -1748,7 +1871,7 @@ using the following configuration parameters:
address, equivalent to the <cf/source address/ option (see below). This
parameter is mandatory.
- <tag>neighbor [<m/ip/] [port <m/number/] [as <m/number/]</tag>
+ <tag><label id="bgp-neighbor">neighbor [<m/ip/] [port <m/number/] [as <m/number/]</tag>
Define neighboring router this instance will be talking to and what AS
it is located in. In case the neighbor is in the same AS as we are, we
automatically switch to iBGP. Optionally, the remote port may also be
@@ -1757,20 +1880,20 @@ using the following configuration parameters:
<cf/neighbor 10.0.0.1; neighbor as 65000;/ are valid). This parameter is
mandatory.
- <tag>interface <m/string/</tag>
+ <tag><label id="bgp-iface">interface <m/string/</tag>
Define interface we should use for link-local BGP IPv6 sessions.
Interface can also be specified as a part of <cf/neighbor address/
(e.g., <cf/neighbor fe80::1234%eth0 as 65000;/). It is an error to use
this parameter for non link-local sessions.
- <tag>direct</tag>
+ <tag><label id="bgp-direct">direct</tag>
Specify that the neighbor is directly connected. The IP address of the
neighbor must be from a directly reachable IP range (i.e. associated
with one of your router's interfaces), otherwise the BGP session
wouldn't start but it would wait for such interface to appear. The
alternative is the <cf/multihop/ option. Default: enabled for eBGP.
- <tag>multihop [<m/number/]</tag>
+ <tag><label id="bgp-multihop">multihop [<m/number/]</tag>
Configure multihop BGP session to a neighbor that isn't directly
connected. Accurately, this option should be used if the configured
neighbor IP address does not match with any local network subnets. Such
@@ -1782,22 +1905,22 @@ using the following configuration parameters:
path is counted; i.e., if two BGP speakers are separated by one router,
the number of hops is 2. Default: enabled for iBGP.
- <tag>source address <m/ip/</tag>
+ <tag><label id="bgp-source-address">source address <m/ip/</tag>
Define local address we should use for next hop calculation and as a
source address for the BGP session. Default: the address of the local
end of the interface our neighbor is connected to.
- <tag>next hop self</tag>
+ <tag><label id="bgp-next-hop-self">next hop self</tag>
Avoid calculation of the Next Hop attribute and always advertise our own
source address as a next hop. This needs to be used only occasionally to
circumvent misconfigurations of other routers. Default: disabled.
- <tag>next hop keep</tag>
+ <tag><label id="bgp-next-hop-keep">next hop keep</tag>
Forward the received Next Hop attribute even in situations where the
local address should be used instead, like when the route is sent to an
interface with a different subnet. Default: disabled.
- <tag>missing lladdr self|drop|ignore</tag>
+ <tag><label id="bgp-missing-lladdr">missing lladdr self|drop|ignore</tag>
Next Hop attribute in BGP-IPv6 sometimes contains just the global IPv6
address, but sometimes it has to contain both global and link-local IPv6
addresses. This option specifies what to do if BIRD have to send both
@@ -1811,7 +1934,7 @@ using the following configuration parameters:
route server (option <cf/rs client/), in that case default is <cf/ignore/,
because route servers usually do not forward packets themselves.
- <tag>gateway direct|recursive</tag>
+ <tag><label id="bgp-gateway">gateway direct|recursive</tag>
For received routes, their <cf/gw/ (immediate next hop) attribute is
computed from received <cf/bgp_next_hop/ attribute. This option
specifies how it is computed. Direct mode means that the IP address from
@@ -1826,45 +1949,45 @@ using the following configuration parameters:
standard. Direct mode is simpler, does not require any routes in a
routing table, and was used in older versions of BIRD, but does not
handle well nontrivial iBGP setups and multihop. Recursive mode is
- incompatible with <ref id="dsc-sorted" name="sorted tables">. Default:
+ incompatible with <ref id="dsc-table-sorted" name="sorted tables">. Default:
<cf/direct/ for direct sessions, <cf/recursive/ for multihop sessions.
- <tag>igp table <m/name/</tag>
+ <tag><label id="bgp-igp-table">igp table <m/name/</tag>
Specifies a table that is used as an IGP routing table. Default: the
same as the table BGP is connected to.
- <tag>check link <M>switch</M></tag>
+ <tag><label id="bgp-check-link">check link <M>switch</M></tag>
BGP could use hardware link state into consideration. If enabled,
BIRD tracks the link state of the associated interface and when link
disappears (e.g. an ethernet cable is unplugged), the BGP session is
immediately shut down. Note that this option cannot be used with
multihop BGP. Default: disabled.
- <tag>bfd <M>switch</M></tag>
+ <tag><label id="bgp-bfd">bfd <M>switch</M></tag>
BGP could use BFD protocol as an advisory mechanism for neighbor
liveness and failure detection. If enabled, BIRD setups a BFD session
for the BGP neighbor and tracks its liveness by it. This has an
advantage of an order of magnitude lower detection times in case of
failure. Note that BFD protocol also has to be configured, see
- <ref id="sect-bfd" name="BFD"> section for details. Default: disabled.
+ <ref id="bfd" name="BFD"> section for details. Default: disabled.
- <tag>ttl security <m/switch/</tag>
- Use GTSM (RFC 5082 - the generalized TTL security mechanism). GTSM
+ <tag><label id="bgp-ttl-security">ttl security <m/switch/</tag>
+ Use GTSM (<rfc id="5082"> - the generalized TTL security mechanism). GTSM
protects against spoofed packets by ignoring received packets with a
smaller than expected TTL. To work properly, GTSM have to be enabled on
- both sides of a BGP session. If both <cf/ttl security/ and <cf/multihop/
- options are enabled, <cf/multihop/ option should specify proper hop
- value to compute expected TTL. Kernel support required: Linux: 2.6.34+
- (IPv4), 2.6.35+ (IPv6), BSD: since long ago, IPv4 only. Note that full
- (ICMP protection, for example) RFC 5082 support is provided by Linux
- only. Default: disabled.
-
- <tag>password <m/string/</tag>
- Use this password for MD5 authentication of BGP sessions (RFC 2385).
- When used on BSD systems, see also <cf/setkey/ option below. Default:
- no authentication.
-
- <tag>setkey <m/switch/</tag>
+ both sides of a BGP session. If both <cf/ttl security/ and
+ <cf/multihop/ options are enabled, <cf/multihop/ option should specify
+ proper hop value to compute expected TTL. Kernel support required:
+ Linux: 2.6.34+ (IPv4), 2.6.35+ (IPv6), BSD: since long ago, IPv4 only.
+ Note that full (ICMP protection, for example) <rfc id="5082"> support is
+ provided by Linux only. Default: disabled.
+
+ <tag><label id="bgp-pass">password <m/string/</tag>
+ Use this password for MD5 authentication of BGP sessions (<rfc id="2385">). When
+ used on BSD systems, see also <cf/setkey/ option below. Default: no
+ authentication.
+
+ <tag><label id="bgp-setkey">setkey <m/switch/</tag>
On BSD systems, keys for TCP MD5 authentication are stored in the global
SA/SP database, which can be accessed by external utilities (e.g.
setkey(8)). BIRD configures security associations in the SA/SP database
@@ -1875,16 +1998,16 @@ using the following configuration parameters:
set manually by an external utility on NetBSD and OpenBSD. Default:
enabled (ignored on non-FreeBSD).
- <tag>passive <m/switch/</tag>
+ <tag><label id="bgp-passive">passive <m/switch/</tag>
Standard BGP behavior is both initiating outgoing connections and
accepting incoming connections. In passive mode, outgoing connections
are not initiated. Default: off.
- <tag>rr client</tag>
+ <tag><label id="bgp-rr-client">rr client</tag>
Be a route reflector and treat the neighbor as a route reflection
client. Default: disabled.
- <tag>rr cluster id <m/IPv4 address/</tag>
+ <tag><label id="bgp-rr-cluster-id">rr cluster id <m/IPv4 address/</tag>
Route reflectors use cluster id to avoid route reflection loops. When
there is one route reflector in a cluster it usually uses its router id
as a cluster id, but when there are more route reflectors in a cluster,
@@ -1892,26 +2015,26 @@ using the following configuration parameters:
id. Clients in a cluster need not know their cluster id and this option
is not allowed for them. Default: the same as router id.
- <tag>rs client</tag>
+ <tag><label id="bgp-rs-client">rs client</tag>
Be a route server and treat the neighbor as a route server client.
A route server is used as a replacement for full mesh EBGP routing in
Internet exchange points in a similar way to route reflectors used in
- IBGP routing. BIRD does not implement obsoleted RFC 1863, but uses
- ad-hoc implementation, which behaves like plain EBGP but reduces
+ IBGP routing. BIRD does not implement obsoleted <rfc id="1863">, but
+ uses ad-hoc implementation, which behaves like plain EBGP but reduces
modifications to advertised route attributes to be transparent (for
- example does not prepend its AS number to AS PATH attribute and keeps
- MED attribute). Default: disabled.
+ example does not prepend its AS number to AS PATH attribute and
+ keeps MED attribute). Default: disabled.
- <tag>secondary <m/switch/</tag>
+ <tag><label id="bgp-secondary">secondary <m/switch/</tag>
Usually, if an export filter rejects a selected route, no other route is
propagated for that network. This option allows to try the next route in
order until one that is accepted is found or all routes for that network
are rejected. This can be used for route servers that need to propagate
different tables to each client but do not want to have these tables
explicitly (to conserve memory). This option requires that the connected
- routing table is <ref id="dsc-sorted" name="sorted">. Default: off.
+ routing table is <ref id="dsc-table-sorted" name="sorted">. Default: off.
- <tag>add paths <m/switch/|rx|tx</tag>
+ <tag><label id="bgp-add-paths">add paths <m/switch/|rx|tx</tag>
Standard BGP can propagate only one path (route) per destination network
(usually the selected one). This option controls the add-path protocol
extension, which allows to advertise any number of paths to a
@@ -1920,7 +2043,7 @@ using the following configuration parameters:
TX direction. When active, all available routes accepted by the export
filter are advertised to the neighbor. Default: off.
- <tag>allow local as [<m/number/]</tag>
+ <tag><label id="bgp-allow-local-as">allow local as [<m/number/]</tag>
BGP prevents routing loops by rejecting received routes with the local
AS number in the AS path. This option allows to loose or disable the
check. Optional <cf/number/ argument can be used to specify the maximum
@@ -1929,51 +2052,52 @@ using the following configuration parameters:
completely disabled and you should ensure loop-free behavior by some
other means. Default: 0 (no local AS number allowed).
- <tag>enable route refresh <m/switch/</tag>
+ <tag><label id="bgp-enable-route-refresh">enable route refresh <m/switch/</tag>
After the initial route exchange, BGP protocol uses incremental updates
to keep BGP speakers synchronized. Sometimes (e.g., if BGP speaker
changes its import filter, or if there is suspicion of inconsistency) it
is necessary to do a new complete route exchange. BGP protocol extension
- Route Refresh (RFC 2918) allows BGP speaker to request re-advertisement
- of all routes from its neighbor. BGP protocol extension Enhanced Route
- Refresh (RFC 7313) specifies explicit begin and end for such exchanges,
- therefore the receiver can remove stale routes that were not advertised
- during the exchange. This option specifies whether BIRD advertises these
- capabilities and supports related procedures. Note that even when
- disabled, BIRD can send route refresh requests. Default: on.
-
- <tag>graceful restart <m/switch/|aware</tag>
+ Route Refresh (<rfc id="2918">) allows BGP speaker to request
+ re-advertisement of all routes from its neighbor. BGP protocol
+ extension Enhanced Route Refresh (<rfc id="7313">) specifies explicit
+ begin and end for such exchanges, therefore the receiver can remove
+ stale routes that were not advertised during the exchange. This option
+ specifies whether BIRD advertises these capabilities and supports
+ related procedures. Note that even when disabled, BIRD can send route
+ refresh requests. Default: on.
+
+ <tag><label id="bgp-graceful-restart">graceful restart <m/switch/|aware</tag>
When a BGP speaker restarts or crashes, neighbors will discard all
received paths from the speaker, which disrupts packet forwarding even
- when the forwarding plane of the speaker remains intact. RFC 4724
- specifies an optional graceful restart mechanism to alleviate this
- issue. This option controls the mechanism. It has three states:
- Disabled, when no support is provided. Aware, when the graceful restart
- support is announced and the support for restarting neighbors is
- provided, but no local graceful restart is allowed (i.e. receiving-only
- role). Enabled, when the full graceful restart support is provided
- (i.e. both restarting and receiving role). Note that proper support for
- local graceful restart requires also configuration of other protocols.
- Default: aware.
-
- <tag>graceful restart time <m/number/</tag>
+ when the forwarding plane of the speaker remains intact. <rfc
+ id="4724"> specifies an optional graceful restart mechanism to
+ alleviate this issue. This option controls the mechanism. It has three
+ states: Disabled, when no support is provided. Aware, when the graceful
+ restart support is announced and the support for restarting neighbors
+ is provided, but no local graceful restart is allowed (i.e.
+ receiving-only role). Enabled, when the full graceful restart
+ support is provided (i.e. both restarting and receiving role). Note
+ that proper support for local graceful restart requires also
+ configuration of other protocols. Default: aware.
+
+ <tag><label id="bgp-graceful-restart-time">graceful restart time <m/number/</tag>
The restart time is announced in the BGP graceful restart capability
and specifies how long the neighbor would wait for the BGP session to
re-establish after a restart before deleting stale routes. Default:
120 seconds.
- <tag>interpret communities <m/switch/</tag>
- RFC 1997 demands that BGP speaker should process well-known communities
- like no-export (65535, 65281) or no-advertise (65535, 65282). For
- example, received route carrying a no-adverise community should not be
- advertised to any of its neighbors. If this option is enabled (which is
- by default), BIRD has such behavior automatically (it is evaluated when
- a route is exported to the BGP protocol just before the export filter).
- Otherwise, this integrated processing of well-known communities is
- disabled. In that case, similar behavior can be implemented in the
- export filter. Default: on.
-
- <tag>enable as4 <m/switch/</tag>
+ <tag><label id="bgp-interpret-communities">interpret communities <m/switch/</tag>
+ <rfc id="1997"> demands that BGP speaker should process well-known
+ communities like no-export (65535, 65281) or no-advertise (65535,
+ 65282). For example, received route carrying a no-adverise community
+ should not be advertised to any of its neighbors. If this option is
+ enabled (which is by default), BIRD has such behavior automatically (it
+ is evaluated when a route is exported to the BGP protocol just before
+ the export filter). Otherwise, this integrated processing of
+ well-known communities is disabled. In that case, similar behavior can
+ be implemented in the export filter. Default: on.
+
+ <tag><label id="bgp-enable-as4">enable as4 <m/switch/</tag>
BGP protocol was designed to use 2B AS numbers and was extended later to
allow 4B AS number. BIRD supports 4B AS extension, but by disabling this
option it can be persuaded not to advertise it and to maintain old-style
@@ -1981,12 +2105,12 @@ using the following configuration parameters:
in neighbor's implementation of 4B AS extension. Even when disabled
(off), BIRD behaves internally as AS4-aware BGP router. Default: on.
- <tag>enable extended messages <m/switch/</tag>
+ <tag><label id="bgp-enable-extended-messages">enable extended messages <m/switch/</tag>
The BGP protocol uses maximum message length of 4096 bytes. This option
provides an extension to allow extended messages with length up
to 65535 bytes. Default: off.
- <tag>capabilities <m/switch/</tag>
+ <tag><label id="bgp-capabilities">capabilities <m/switch/</tag>
Use capability advertisement to advertise optional capabilities. This is
standard behavior for newer BGP implementations, but there might be some
older BGP implementations that reject such connection attempts. When
@@ -1994,64 +2118,64 @@ using the following configuration parameters:
disabled. Default: on, with automatic fallback to off when received
capability-related error.
- <tag>advertise ipv4 <m/switch/</tag>
+ <tag><label id="bgp-advertise-ipv4">advertise ipv4 <m/switch/</tag>
Advertise IPv4 multiprotocol capability. This is not a correct behavior
- according to the strict interpretation of RFC 4760, but it is widespread
- and required by some BGP implementations (Cisco and Quagga). This option
- is relevant to IPv4 mode with enabled capability advertisement
- only. Default: on.
+ according to the strict interpretation of <rfc id="4760">, but it is
+ widespread and required by some BGP implementations (Cisco and Quagga).
+ This option is relevant to IPv4 mode with enabled capability
+ advertisement only. Default: on.
- <tag>route limit <m/number/</tag>
+ <tag><label id="bgp-route-limit">route limit <m/number/</tag>
The maximal number of routes that may be imported from the protocol. If
the route limit is exceeded, the connection is closed with an error.
Limit is currently implemented as <cf>import limit <m/number/ action
restart</cf>. This option is obsolete and it is replaced by
- <ref id="import-limit" name="import limit option">. Default: no limit.
+ <ref id="proto-import-limit" name="import limit option">. Default: no limit.
- <tag>disable after error <m/switch/</tag>
+ <tag><label id="bgp-disable-after-error">disable after error <m/switch/</tag>
When an error is encountered (either locally or by the other side),
disable the instance automatically and wait for an administrator to fix
the problem manually. Default: off.
- <tag>hold time <m/number/</tag>
+ <tag><label id="bgp-hold-time">hold time <m/number/</tag>
Time in seconds to wait for a Keepalive message from the other side
before considering the connection stale. Default: depends on agreement
with the neighboring router, we prefer 240 seconds if the other side is
willing to accept it.
- <tag>startup hold time <m/number/</tag>
+ <tag><label id="bgp-startup-hold-time">startup hold time <m/number/</tag>
Value of the hold timer used before the routers have a chance to exchange
open messages and agree on the real value. Default: 240 seconds.
- <tag>keepalive time <m/number/</tag>
+ <tag><label id="bgp-keepalive-time">keepalive time <m/number/</tag>
Delay in seconds between sending of two consecutive Keepalive messages.
Default: One third of the hold time.
- <tag>connect delay time <m/number/</tag>
+ <tag><label id="bgp-connect-delay-time">connect delay time <m/number/</tag>
Delay in seconds between protocol startup and the first attempt to
connect. Default: 5 seconds.
- <tag>connect retry time <m/number/</tag>
+ <tag><label id="bgp-connect-retry-time">connect retry time <m/number/</tag>
Time in seconds to wait before retrying a failed attempt to connect.
Default: 120 seconds.
- <tag>error wait time <m/number/,<m/number/</tag>
+ <tag><label id="bgp-error-wait-time">error wait time <m/number/,<m/number/</tag>
Minimum and maximum delay in seconds between a protocol failure (either
local or reported by the peer) and automatic restart. Doesn't apply
when <cf/disable after error/ is configured. If consecutive errors
happen, the delay is increased exponentially until it reaches the
maximum. Default: 60, 300.
- <tag>error forget time <m/number/</tag>
+ <tag><label id="bgp-error-forget-time">error forget time <m/number/</tag>
Maximum time in seconds between two protocol failures to treat them as a
error sequence which makes <cf/error wait time/ increase exponentially.
Default: 300 seconds.
- <tag>path metric <m/switch/</tag>
+ <tag><label id="bgp-path-metric">path metric <m/switch/</tag>
Enable comparison of path lengths when deciding which BGP route is the
best one. Default: on.
- <tag>med metric <m/switch/</tag>
+ <tag><label id="bgp-med-metric">med metric <m/switch/</tag>
Enable comparison of MED attributes (during best route selection) even
between routes received from different ASes. This may be useful if all
MED attributes contain some consistent metric, perhaps enforced in
@@ -2059,35 +2183,35 @@ using the following configuration parameters:
attributes are compared only if routes are received from the same AS
(which is the standard behavior). Default: off.
- <tag>deterministic med <m/switch/</tag>
+ <tag><label id="bgp-deterministic-med">deterministic med <m/switch/</tag>
BGP route selection algorithm is often viewed as a comparison between
individual routes (e.g. if a new route appears and is better than the
current best one, it is chosen as the new best one). But the proper
- route selection, as specified by RFC 4271, cannot be fully implemented
- in that way. The problem is mainly in handling the MED attribute. BIRD,
- by default, uses an simplification based on individual route comparison,
- which in some cases may lead to temporally dependent behavior (i.e. the
- selection is dependent on the order in which routes appeared). This
- option enables a different (and slower) algorithm implementing proper
- RFC 4271 route selection, which is deterministic. Alternative way how to
- get deterministic behavior is to use <cf/med metric/ option. This option
- is incompatible with <ref id="dsc-sorted" name="sorted tables">.
- Default: off.
-
- <tag>igp metric <m/switch/</tag>
+ route selection, as specified by <rfc id="4271">, cannot be fully
+ implemented in that way. The problem is mainly in handling the MED
+ attribute. BIRD, by default, uses an simplification based on individual
+ route comparison, which in some cases may lead to temporally dependent
+ behavior (i.e. the selection is dependent on the order in which routes
+ appeared). This option enables a different (and slower) algorithm
+ implementing proper <rfc id="4271"> route selection, which is
+ deterministic. Alternative way how to get deterministic behavior is to
+ use <cf/med metric/ option. This option is incompatible with <ref
+ id="dsc-table-sorted" name="sorted tables">. Default: off.
+
+ <tag><label id="bgp-igp-metric">igp metric <m/switch/</tag>
Enable comparison of internal distances to boundary routers during best
route selection. Default: on.
- <tag>prefer older <m/switch/</tag>
+ <tag><label id="bgp-prefer-older">prefer older <m/switch/</tag>
Standard route selection algorithm breaks ties by comparing router IDs.
This changes the behavior to prefer older routes (when both are external
- and from different peer). For details, see RFC 5004. Default: off.
+ and from different peer). For details, see <rfc id="5004">. Default: off.
- <tag>default bgp_med <m/number/</tag>
+ <tag><label id="bgp-default-med">default bgp_med <m/number/</tag>
Value of the Multiple Exit Discriminator to be used during route
selection when the MED attribute is missing. Default: 0.
- <tag>default bgp_local_pref <m/number/</tag>
+ <tag><label id="bgp-default-local-pref">default bgp_local_pref <m/number/</tag>
A default value for the Local Preference attribute. It is used when
a new Local Preference attribute is attached to a route by the BGP
protocol itself (for example, if a route is received through eBGP and
@@ -2096,23 +2220,24 @@ using the following configuration parameters:
</descrip>
<sect1>Attributes
+<label id="bgp-attr">
<p>BGP defines several route attributes. Some of them (those marked with
`<tt/I/' in the table below) are available on internal BGP connections only,
some of them (marked with `<tt/O/') are optional.
<descrip>
- <tag>bgppath <cf/bgp_path/</tag>
+ <tag><label id="rta-bgp-path">bgppath bgp_path/</tag>
Sequence of AS numbers describing the AS path the packet will travel
through when forwarded according to the particular route. In case of
internal BGP it doesn't contain the number of the local AS.
- <tag>int <cf/bgp_local_pref/ [I]</tag>
+ <tag><label id="rta-bgp-local-pref">int bgp_local_pref/ [I]</tag>
Local preference value used for selection among multiple BGP routes (see
the selection rules above). It's used as an additional metric which is
propagated through the whole local AS.
- <tag>int <cf/bgp_med/ [O]</tag>
+ <tag><label id="rta-bgp-med">int bgp_med/ [O]</tag>
The Multiple Exit Discriminator of the route is an optional attribute
which is used on external (inter-AS) links to convey to an adjacent AS
the optimal entry point into the local AS. The received attribute is
@@ -2120,23 +2245,23 @@ some of them (marked with `<tt/O/') are optional.
when a route is exported to an external BGP instance to ensure that the
attribute received from a neighboring AS is not propagated to other
neighboring ASes. A new value might be set in the export filter of an
- external BGP instance. See RFC 4451<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4451.txt">
- for further discussion of BGP MED attribute.
+ external BGP instance. See <rfc id="4451"> for further discussion of
+ BGP MED attribute.
- <tag>enum <cf/bgp_origin/</tag>
+ <tag><label id="rta-bgp-origin">enum bgp_origin/</tag>
Origin of the route: either <cf/ORIGIN_IGP/ if the route has originated
in an interior routing protocol or <cf/ORIGIN_EGP/ if it's been imported
from the <tt>EGP</tt> protocol (nowadays it seems to be obsolete) or
<cf/ORIGIN_INCOMPLETE/ if the origin is unknown.
- <tag>ip <cf/bgp_next_hop/</tag>
+ <tag><label id="rta-bgp-next-hop">ip bgp_next_hop/</tag>
Next hop to be used for forwarding of packets to this destination. On
internal BGP connections, it's an address of the originating router if
it's inside the local AS or a boundary router the packet will leave the
AS through if it's an exterior route, so each BGP speaker within the AS
has a chance to use the shortest interior path possible to this point.
- <tag>void <cf/bgp_atomic_aggr/ [O]</tag>
+ <tag><label id="rta-bgp-atomic-aggr">void bgp_atomic_aggr/ [O]</tag>
This is an optional attribute which carries no value, but the sole
presence of which indicates that the route has been aggregated from
multiple routes by some router on the path from the originator.
@@ -2144,7 +2269,7 @@ some of them (marked with `<tt/O/') are optional.
<!-- we don't handle aggregators right since they are of a very obscure type
<tag>bgp_aggregator</tag>
-->
- <tag>clist <cf/bgp_community/ [O]</tag>
+ <tag><label id="rta-bgp-community">clist bgp_community/ [O]</tag>
List of community values associated with the route. Each such value is a
pair (represented as a <cf/pair/ data type inside the filters) of 16-bit
integers, the first of them containing the number of the AS which
@@ -2155,24 +2280,33 @@ some of them (marked with `<tt/O/') are optional.
freedom about which community attributes it defines and what will their
semantics be.
- <tag>eclist <cf/bgp_ext_community/ [O]</tag>
+ <tag><label id="rta-bgp-ext-community">eclist bgp_ext_community/ [O]</tag>
List of extended community values associated with the route. Extended
communities have similar usage as plain communities, but they have an
extended range (to allow 4B ASNs) and a nontrivial structure with a type
field. Individual community values are represented using an <cf/ec/ data
type inside the filters.
- <tag>quad <cf/bgp_originator_id/ [I, O]</tag>
+ <tag><label id="rta-bgp-large-community">lclist <cf/bgp_large_community/ [O]</tag>
+ List of large community values associated with the route. Large BGP
+ communities is another variant of communities, but contrary to extended
+ communities they behave very much the same way as regular communities,
+ just larger -- they are uniform untyped triplets of 32bit numbers.
+ Individual community values are represented using an <cf/lc/ data type
+ inside the filters.
+
+ <tag><label id="rta-bgp-originator-id">quad bgp_originator_id/ [I, O]</tag>
This attribute is created by the route reflector when reflecting the
route and contains the router ID of the originator of the route in the
local AS.
- <tag>clist <cf/bgp_cluster_list/ [I, O]</tag>
+ <tag><label id="rta-bgp-cluster-list">clist bgp_cluster_list/ [I, O]</tag>
This attribute contains a list of cluster IDs of route reflectors. Each
route reflector prepends its cluster ID when reflecting the route.
</descrip>
<sect1>Example
+<label id="bgp-exam">
<p><code>
protocol bgp {
@@ -2198,6 +2332,7 @@ protocol bgp {
<sect>Device
+<label id="device">
<p>The Device protocol is not a real routing protocol. It doesn't generate any
routes and it only serves as a module for getting information about network
@@ -2208,17 +2343,18 @@ protocol in the configuration since almost all other protocols require network
interfaces to be defined for them to work with.
<sect1>Configuration
+<label id="device-config">
<p><descrip>
- <tag>scan time <m/number/</tag>
+ <tag><label id="device-scan-time">scan time <m/number/</tag>
Time in seconds between two scans of the network interface list. On
systems where we are notified about interface status changes
asynchronously (such as newer versions of Linux), we need to scan the
list only in order to avoid confusion by lost notification messages,
so the default time is set to a large value.
- <tag>primary [ "<m/mask/" ] <m/prefix/</tag>
+ <tag><label id="device-primary">primary [ "<m/mask/" ] <m/prefix/</tag>
If a network interface has more than one network address, BIRD has to
choose one of them as a primary one. By default, BIRD chooses the
lexicographically smallest address as the primary one.
@@ -2246,6 +2382,7 @@ protocol device {
<sect>Direct
+<label id="direct">
<p>The Direct protocol is a simple generator of device routes for all the
directly connected networks according to the list of interfaces provided by the
@@ -2271,16 +2408,16 @@ on Linux systems BIRD cannot change non-BIRD route in the kernel routing table.
<p>There are just few configuration options for the Direct protocol:
<p><descrip>
- <tag>interface <m/pattern [, ...]/</tag>
+ <tag><label id="direct-iface">interface <m/pattern/ [, <m/.../]</tag>
By default, the Direct protocol will generate device routes for all the
interfaces available. If you want to restrict it to some subset of
interfaces or addresses (e.g. if you're using multiple routing tables
for policy routing and some of the policy domains don't contain all
- interfaces), just use this clause. See <ref id="dsc-iface" name="interface">
+ interfaces), just use this clause. See <ref id="proto-iface" name="interface">
common option for detailed description. The Direct protocol uses
extended interface clauses.
- <tag>check link <m/switch/</tag>
+ <tag><label id="direct-check-link">check link <m/switch/</tag>
If enabled, a hardware link state (reported by OS) is taken into
consideration. Routes for directly connected networks are generated only
if link up is reported and they are withdrawn when link disappears
@@ -2299,6 +2436,7 @@ protocol direct {
<sect>Kernel
+<label id="krt">
<p>The Kernel protocol is not a real routing protocol. Instead of communicating
with other routers in the network, it performs synchronization of BIRD's routing
@@ -2331,40 +2469,52 @@ kernel protocols to the same routing table and changing route destination
limitations can be overcome using another routing table and the pipe protocol.
<sect1>Configuration
+<label id="krt-config">
<p><descrip>
- <tag>persist <m/switch/</tag>
+ <tag><label id="krt-persist">persist <m/switch/</tag>
Tell BIRD to leave all its routes in the routing tables when it exits
(instead of cleaning them up).
- <tag>scan time <m/number/</tag>
+ <tag><label id="krt-scan-time">scan time <m/number/</tag>
Time in seconds between two consecutive scans of the kernel routing
table.
- <tag>learn <m/switch/</tag>
+ <tag><label id="krt-learn">learn <m/switch/</tag>
Enable learning of routes added to the kernel routing tables by other
routing daemons or by the system administrator. This is possible only on
systems which support identification of route authorship.
- <tag>device routes <m/switch/</tag>
+ <tag><label id="krt-device-routes">device routes <m/switch/</tag>
Enable export of device routes to the kernel routing table. By default,
such routes are rejected (with the exception of explicitly configured
device routes from the static protocol) regardless of the export filter
to protect device routes in kernel routing table (managed by OS itself)
from accidental overwriting or erasing.
- <tag>kernel table <m/number/</tag>
+ <tag><label id="krt-kernel-table">kernel table <m/number/</tag>
Select which kernel table should this particular instance of the Kernel
protocol work with. Available only on systems supporting multiple
routing tables.
- <tag>graceful restart <m/switch/</tag>
+ <tag><label id="krt-metric">metric <m/number/</tag> (Linux)
+ Use specified value as a kernel metric (priority) for all routes sent to
+ the kernel. When multiple routes for the same network are in the kernel
+ routing table, the Linux kernel chooses one with lower metric. Also,
+ routes with different metrics do not clash with each other, therefore
+ using dedicated metric value is a reliable way to avoid overwriting
+ routes from other sources (e.g. kernel device routes). Metric 0 has a
+ special meaning of undefined metric, in which either OS default is used,
+ or per-route metric can be set using <cf/krt_metric/ attribute. Default:
+ 0 (undefined).
+
+ <tag><label id="krt-graceful-restart">graceful restart <m/switch/</tag>
Participate in graceful restart recovery. If this option is enabled and
a graceful restart recovery is active, the Kernel protocol will defer
synchronization of routing tables until the end of the recovery. Note
that import of kernel routes to BIRD is not affected.
- <tag>merge paths <M>switch</M> [limit <M>number</M>]</tag>
+ <tag><label id="krt-merge-paths">merge paths <M>switch</M> [limit <M>number</M>]</tag>
Usually, only best routes are exported to the kernel protocol. With path
merging enabled, both best routes and equivalent non-best routes are
merged during export to generate one ECMP (equal-cost multipath) route
@@ -2378,28 +2528,40 @@ limitations can be overcome using another routing table and the pipe protocol.
</descrip>
<sect1>Attributes
+<label id="krt-attr">
<p>The Kernel protocol defines several attributes. These attributes are
translated to appropriate system (and OS-specific) route attributes. We support
these attributes:
<descrip>
- <tag>int <cf/krt_source/</tag>
+ <tag><label id="rta-krt-source">int krt_source/</tag>
The original source of the imported kernel route. The value is
system-dependent. On Linux, it is a value of the protocol field of the
route. See /etc/iproute2/rt_protos for common values. On BSD, it is
based on STATIC and PROTOx flags. The attribute is read-only.
- <tag>int <cf/krt_metric/</tag>
+ <tag><label id="rta-krt-metric">int krt_metric/</tag> (Linux)
The kernel metric of the route. When multiple same routes are in a
kernel routing table, the Linux kernel chooses one with lower metric.
+ Note that preferred way to set kernel metric is to use protocol option
+ <cf/metric/, unless per-route metric values are needed.
- <tag>ip <cf/krt_prefsrc/</tag> (Linux)
+ <tag><label id="rta-krt-prefsrc">ip krt_prefsrc/</tag> (Linux)
The preferred source address. Used in source address selection for
outgoing packets. Has to be one of the IP addresses of the router.
- <tag>int <cf/krt_realm/</tag> (Linux)
+ <tag><label id="rta-krt-realm">int krt_realm/</tag> (Linux)
The realm of the route. Can be used for traffic classification.
+
+ <tag><label id="rta-krt-scope">int krt_scope/</tag> (Linux IPv4)
+ The scope of the route. Valid values are 0-254, although Linux kernel
+ may reject some values depending on route type and nexthop. It is
+ supposed to represent `indirectness' of the route, where nexthops of
+ routes are resolved through routes with a higher scope, but in current
+ kernels anything below <it/link/ (253) is treated as <it/global/ (0).
+ When not present, global scope is implied for all routes except device
+ routes, where link scope is used by default.
</descrip>
<p>In Linux, there is also a plenty of obscure route attributes mostly focused
@@ -2417,6 +2579,7 @@ Supported attributes are:
<cf/krt_feature_ecn/, <cf/krt_feature_allfrag/
<sect1>Example
+<label id="krt-exam">
<p>A simple configuration can look this way:
@@ -2446,19 +2609,19 @@ protocol kernel { # Secondary routing table
<sect>OSPF
+<label id="ospf">
<sect1>Introduction
+<label id="ospf-intro">
<p>Open Shortest Path First (OSPF) is a quite complex interior gateway
-protocol. The current IPv4 version (OSPFv2) is defined in RFC 2328
-<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc2328.txt">
-and the current IPv6 version (OSPFv3) is defined in RFC 5340
-<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc5340.txt">
-It's a link state (a.k.a. shortest path first) protocol -- each router maintains
-a database describing the autonomous system's topology. Each participating
-router has an identical copy of the database and all routers run the same
-algorithm calculating a shortest path tree with themselves as a root. OSPF
-chooses the least cost path as the best path.
+protocol. The current IPv4 version (OSPFv2) is defined in <rfc id="2328"> and
+the current IPv6 version (OSPFv3) is defined in <rfc id="5340"> It's a link
+state (a.k.a. shortest path first) protocol -- each router maintains a database
+describing the autonomous system's topology. Each participating router has an
+identical copy of the database and all routers run the same algorithm
+calculating a shortest path tree with themselves as a root. OSPF chooses the
+least cost path as the best path.
<p>In OSPF, the autonomous system can be split to several areas in order to
reduce the amount of resources consumed for exchanging the routing information
@@ -2482,6 +2645,7 @@ identical by flooding updates. The flooding process is reliable and ensures that
each router detects all changes.
<sect1>Configuration
+<label id="ospf-config">
<p>In the main part of configuration, there can be multiple definitions of OSPF
areas, each with a different id. These definitions includes many other switches
@@ -2547,7 +2711,7 @@ protocol ospf &lt;name&gt; {
ttl security [&lt;switch&gt;; | tx only]
tx class|dscp &lt;num&gt;;
tx priority &lt;num&gt;;
- authentication [none|simple|cryptographic];
+ authentication none|simple|cryptographic;
password "&lt;text&gt;";
password "&lt;text&gt;" {
id &lt;num&gt;;
@@ -2555,6 +2719,9 @@ protocol ospf &lt;name&gt; {
generate to "&lt;date&gt;";
accept from "&lt;date&gt;";
accept to "&lt;date&gt;";
+ from "&lt;date&gt;";
+ to "&lt;date&gt;";
+ algorithm ( keyed md5 | keyed sha1 | hmac sha1 | hmac sha256 | hmac sha384 | hmac sha512 );
};
neighbors {
&lt;ip&gt;;
@@ -2567,20 +2734,29 @@ protocol ospf &lt;name&gt; {
wait &lt;num&gt;;
dead count &lt;num&gt;;
dead &lt;num&gt;;
- authentication [none|simple|cryptographic];
+ authentication none|simple|cryptographic;
password "&lt;text&gt;";
+ password "&lt;text&gt;" {
+ id &lt;num&gt;;
+ generate from "&lt;date&gt;";
+ generate to "&lt;date&gt;";
+ accept from "&lt;date&gt;";
+ accept to "&lt;date&gt;";
+ from "&lt;date&gt;";
+ to "&lt;date&gt;";
+ algorithm ( keyed md5 | keyed sha1 | hmac sha1 | hmac sha256 | hmac sha384 | hmac sha512 );
+ };
};
};
}
</code>
<descrip>
- <tag>rfc1583compat <M>switch</M></tag>
+ <tag><label id="ospf-rfc1583compat">rfc1583compat <M>switch</M></tag>
This option controls compatibility of routing table calculation with
- RFC 1583 <htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc1583.txt">.
- Default value is no.
+ <rfc id="1583">. Default value is no.
- <tag>instance id <m/num/</tag>
+ <tag><label id="ospf-instance-id">instance id <m/num/</tag>
When multiple OSPF protocol instances are active on the same links, they
should use different instance IDs to distinguish their packets. Although
it could be done on per-interface basis, it is often preferred to set
@@ -2590,22 +2766,21 @@ protocol ospf &lt;name&gt; {
interfaces of the OSPF instance. Note that this option, if used, must
precede interface definitions. Default value is 0.
- <tag>stub router <M>switch</M></tag>
+ <tag><label id="ospf-stub-router">stub router <M>switch</M></tag>
This option configures the router to be a stub router, i.e., a router
that participates in the OSPF topology but does not allow transit
traffic. In OSPFv2, this is implemented by advertising maximum metric
for outgoing links. In OSPFv3, the stub router behavior is announced by
- clearing the R-bit in the router LSA. See RFC 6987
- <htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc6987.txt"> for
- details. Default value is no.
+ clearing the R-bit in the router LSA. See <rfc id="6987"> for details.
+ Default value is no.
- <tag>tick <M>num</M></tag>
+ <tag><label id="ospf-tick">tick <M>num</M></tag>
The routing table calculation and clean-up of areas' databases is not
performed when a single link state change arrives. To lower the CPU
utilization, it's processed later at periodical intervals of <m/num/
seconds. The default value is 1.
- <tag>ecmp <M>switch</M> [limit <M>number</M>]</tag>
+ <tag><label id="ospf-ecmp">ecmp <M>switch</M> [limit <M>number</M>]</tag>
This option specifies whether OSPF is allowed to generate ECMP
(equal-cost multipath) routes. Such routes are used when there are
several directions to the destination, each with the same (computed)
@@ -2613,7 +2788,7 @@ protocol ospf &lt;name&gt; {
nexthops in one route. By default, ECMP is disabled. If enabled,
default value of the limit is 16.
- <tag>merge external <M>switch</M></tag>
+ <tag><label id="ospf-merge-external">merge external <M>switch</M></tag>
This option specifies whether OSPF should merge external routes from
different routers/LSAs for the same destination. When enabled together
with <cf/ecmp/, equal-cost external routes will be combined to multipath
@@ -2621,18 +2796,18 @@ protocol ospf &lt;name&gt; {
from different LSAs are treated as separate even if they represents the
same destination. Default value is no.
- <tag>area <M>id</M></tag>
+ <tag><label id="ospf-area">area <M>id</M></tag>
This defines an OSPF area with given area ID (an integer or an IPv4
address, similarly to a router ID). The most important area is the
backbone (ID 0) to which every other area must be connected.
- <tag>stub</tag>
+ <tag><label id="ospf-stub">stub</tag>
This option configures the area to be a stub area. External routes are
not flooded into stub areas. Also summary LSAs can be limited in stub
areas (see option <cf/summary/). By default, the area is not a stub
area.
- <tag>nssa</tag>
+ <tag><label id="ospf-nssa">nssa</tag>
This option configures the area to be a NSSA (Not-So-Stubby Area). NSSA
is a variant of a stub area which allows a limited way of external route
propagation. Global external routes are not propagated into a NSSA, but
@@ -2640,7 +2815,7 @@ protocol ospf &lt;name&gt; {
(and possibly translated and/or aggregated on area boundary). By
default, the area is not NSSA.
- <tag>summary <M>switch</M></tag>
+ <tag><label id="ospf-summary">summary <M>switch</M></tag>
This option controls propagation of summary LSAs into stub or NSSA
areas. If enabled, summary LSAs are propagated as usual, otherwise just
the default summary route (0.0.0.0/0) is propagated (this is sometimes
@@ -2648,43 +2823,43 @@ protocol ospf &lt;name&gt; {
routers, propagating summary LSAs could lead to more efficient routing
at the cost of larger link state database. Default value is no.
- <tag>default nssa <M>switch</M></tag>
+ <tag><label id="ospf-default-nssa">default nssa <M>switch</M></tag>
When <cf/summary/ option is enabled, default summary route is no longer
propagated to the NSSA. In that case, this option allows to originate
default route as NSSA-LSA to the NSSA. Default value is no.
- <tag>default cost <M>num</M></tag>
+ <tag><label id="ospf-default-cost">default cost <M>num</M></tag>
This option controls the cost of a default route propagated to stub and
NSSA areas. Default value is 1000.
- <tag>default cost2 <M>num</M></tag>
+ <tag><label id="ospf-default-cost2">default cost2 <M>num</M></tag>
When a default route is originated as NSSA-LSA, its cost can use either
type 1 or type 2 metric. This option allows to specify the cost of a
default route in type 2 metric. By default, type 1 metric (option
<cf/default cost/) is used.
- <tag>translator <M>switch</M></tag>
+ <tag><label id="ospf-translator">translator <M>switch</M></tag>
This option controls translation of NSSA-LSAs into external LSAs. By
default, one translator per NSSA is automatically elected from area
boundary routers. If enabled, this area boundary router would
unconditionally translate all NSSA-LSAs regardless of translator
election. Default value is no.
- <tag>translator stability <M>num</M></tag>
+ <tag><label id="ospf-translator-stability">translator stability <M>num</M></tag>
This option controls the translator stability interval (in seconds).
When the new translator is elected, the old one keeps translating until
the interval is over. Default value is 40.
- <tag>networks { <m/set/ }</tag>
+ <tag><label id="ospf-networks">networks { <m/set/ }</tag>
Definition of area IP ranges. This is used in summary LSA origination.
Hidden networks are not propagated into other areas.
- <tag>external { <m/set/ }</tag>
+ <tag><label id="ospf-external">external { <m/set/ }</tag>
Definition of external area IP ranges for NSSAs. This is used for
NSSA-LSA translation. Hidden networks are not translated into external
LSAs. Networks can have configured route tag.
- <tag>stubnet <m/prefix/ { <m/options/ }</tag>
+ <tag><label id="ospf-stubnet">stubnet <m/prefix/ { <m/options/ }</tag>
Stub networks are networks that are not transit networks between OSPF
routers. They are also propagated through an OSPF area as a part of a
link state database. By default, BIRD generates a stub network record
@@ -2700,67 +2875,66 @@ protocol ospf &lt;name&gt; {
that are subnetworks of given stub network are suppressed. This might be
used, for example, to aggregate generated stub networks.
- <tag>interface <M>pattern</M> [instance <m/num/]</tag>
+ <tag><label id="ospf-iface">interface <M>pattern</M> [instance <m/num/]</tag>
Defines that the specified interfaces belong to the area being defined.
- See <ref id="dsc-iface" name="interface"> common option for detailed
+ See <ref id="proto-iface" name="interface"> common option for detailed
description. In OSPFv2, extended interface clauses are used, because
each network prefix is handled as a separate virtual interface.
You can specify alternative instance ID for the interface definition,
therefore it is possible to have several instances of that interface
- with different options or even in different areas. For OSPFv2,
- instance ID support is an extension (RFC 6549
- <htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc6549.txt">) and is
- supposed to be set per-protocol. For OSPFv3, it is an integral feature.
+ with different options or even in different areas. For OSPFv2, instance
+ ID support is an extension (<rfc id="6549">) and is supposed to be set
+ per-protocol. For OSPFv3, it is an integral feature.
- <tag>virtual link <M>id</M> [instance <m/num/]</tag>
+ <tag><label id="ospf-virtual-link">virtual link <M>id</M> [instance <m/num/]</tag>
Virtual link to router with the router id. Virtual link acts as a
point-to-point interface belonging to backbone. The actual area is used
as a transport area. This item cannot be in the backbone. Like with
<cf/interface/ option, you could also use several virtual links to one
destination with different instance IDs.
- <tag>cost <M>num</M></tag>
+ <tag><label id="ospf-cost">cost <M>num</M></tag>
Specifies output cost (metric) of an interface. Default value is 10.
- <tag>stub <M>switch</M></tag>
+ <tag><label id="ospf-stub-iface">stub <M>switch</M></tag>
If set to interface it does not listen to any packet and does not send
any hello. Default value is no.
- <tag>hello <M>num</M></tag>
+ <tag><label id="ospf-hello">hello <M>num</M></tag>
Specifies interval in seconds between sending of Hello messages. Beware,
all routers on the same network need to have the same hello interval.
Default value is 10.
- <tag>poll <M>num</M></tag>
+ <tag><label id="ospf-poll">poll <M>num</M></tag>
Specifies interval in seconds between sending of Hello messages for some
neighbors on NBMA network. Default value is 20.
- <tag>retransmit <M>num</M></tag>
+ <tag><label id="ospf-retransmit">retransmit <M>num</M></tag>
Specifies interval in seconds between retransmissions of unacknowledged
updates. Default value is 5.
- <tag>priority <M>num</M></tag>
+ <tag><label id="ospf-priority">priority <M>num</M></tag>
On every multiple access network (e.g., the Ethernet) Designated Router
and Backup Designated router are elected. These routers have some special
functions in the flooding process. Higher priority increases preferences
in this election. Routers with priority 0 are not eligible. Default
value is 1.
- <tag>wait <M>num</M></tag>
+ <tag><label id="ospf-wait">wait <M>num</M></tag>
After start, router waits for the specified number of seconds between
starting election and building adjacency. Default value is 4*<m/hello/.
- <tag>dead count <M>num</M></tag>
+ <tag><label id="ospf-dead-count">dead count <M>num</M></tag>
When the router does not receive any messages from a neighbor in
<m/dead count/*<m/hello/ seconds, it will consider the neighbor down.
- <tag>dead <M>num</M></tag>
+ <tag><label id="ospf-dead">dead <M>num</M></tag>
When the router does not receive any messages from a neighbor in
<m/dead/ seconds, it will consider the neighbor down. If both directives
<cf/dead count/ and <cf/dead/ are used, <cf/dead/ has precedence.
- <tag>secondary <M>switch</M></tag>
+ <tag><label id="ospf-secondary">secondary <M>switch</M></tag>
On BSD systems, older versions of BIRD supported OSPFv2 only for the
primary IP address of an interface, other IP ranges on the interface
were handled as stub networks. Since v1.4.1, regular operation on
@@ -2770,14 +2944,14 @@ protocol ospf &lt;name&gt; {
behavior will be changed. On Linux systems, the option is irrelevant, as
operation on non-primary addresses is already the regular behavior.
- <tag>rx buffer <M>num</M></tag>
+ <tag><label id="ospf-rx-buffer">rx buffer <M>num</M></tag>
This option allows to specify the size of buffers used for packet
processing. The buffer size should be bigger than maximal size of any
packets. By default, buffers are dynamically resized as needed, but a
fixed value could be specified. Value <cf/large/ means maximal allowed
packet size - 65535.
- <tag>tx length <M>num</M></tag>
+ <tag><label id="ospf-tx-length">tx length <M>num</M></tag>
Transmitted OSPF messages that contain large amount of information are
segmented to separate OSPF packets to avoid IP fragmentation. This
option specifies the soft ceiling for the length of generated OSPF
@@ -2785,7 +2959,7 @@ protocol ospf &lt;name&gt; {
larger OSPF packets may still be generated if underlying OSPF messages
cannot be splitted (e.g. when one large LSA is propagated).
- <tag>type broadcast|bcast</tag>
+ <tag><label id="ospf-type-bcast">type broadcast|bcast</tag>
BIRD detects a type of a connected network automatically, but sometimes
it's convenient to force use of a different type manually. On broadcast
networks (like ethernet), flooding and Hello messages are sent using
@@ -2795,7 +2969,7 @@ protocol ospf &lt;name&gt; {
on physically NBMA networks and on unnumbered networks (networks without
proper IP prefix).
- <tag>type pointopoint|ptp</tag>
+ <tag><label id="ospf-type-ptp">type pointopoint|ptp</tag>
Point-to-point networks connect just 2 routers together. No election is
performed and no network LSA is originated, which makes it simpler and
faster to establish. This network type is useful not only for physically
@@ -2803,31 +2977,31 @@ protocol ospf &lt;name&gt; {
as PtP links. This network type cannot be used on physically NBMA
networks.
- <tag>type nonbroadcast|nbma</tag>
+ <tag><label id="ospf-type-nbma">type nonbroadcast|nbma</tag>
On NBMA networks, the packets are sent to each neighbor separately
because of lack of multicast capabilities. Like on broadcast networks,
a designated router is elected, which plays a central role in propagation
of LSAs. This network type cannot be used on unnumbered networks.
- <tag>type pointomultipoint|ptmp</tag>
+ <tag><label id="ospf-type-ptmp">type pointomultipoint|ptmp</tag>
This is another network type designed to handle NBMA networks. In this
case the NBMA network is treated as a collection of PtP links. This is
useful if not every pair of routers on the NBMA network has direct
communication, or if the NBMA network is used as an (possibly
unnumbered) PtP link.
- <tag>link lsa suppression <m/switch/</tag>
+ <tag><label id="ospf-link-lsa-suppression">link lsa suppression <m/switch/</tag>
In OSPFv3, link LSAs are generated for each link, announcing link-local
IPv6 address of the router to its local neighbors. These are useless on
PtP or PtMP networks and this option allows to suppress the link LSA
origination for such interfaces. The option is ignored on other than PtP
or PtMP interfaces. Default value is no.
- <tag>strict nonbroadcast <m/switch/</tag>
+ <tag><label id="ospf-strict-nonbroadcast">strict nonbroadcast <m/switch/</tag>
If set, don't send hello to any undefined neighbor. This switch is
ignored on other than NBMA or PtMP interfaces. Default value is no.
- <tag>real broadcast <m/switch/</tag>
+ <tag><label id="ospf-real-broadcast">real broadcast <m/switch/</tag>
In <cf/type broadcast/ or <cf/type ptp/ network configuration, OSPF
packets are sent as IP multicast packets. This option changes the
behavior to using old-fashioned IP broadcast packets. This may be useful
@@ -2835,7 +3009,7 @@ protocol ospf &lt;name&gt; {
not work reliably. This is a non-standard option and probably is not
interoperable with other OSPF implementations. Default value is no.
- <tag>ptp netmask <m/switch/</tag>
+ <tag><label id="ospf-ptp-netmask">ptp netmask <m/switch/</tag>
In <cf/type ptp/ network configurations, OSPFv2 implementations should
ignore received netmask field in hello packets and should send hello
packets with zero netmask field on unnumbered PtP links. But some OSPFv2
@@ -2845,7 +3019,7 @@ protocol ospf &lt;name&gt; {
compatibility problems related to this issue. Default value is no for
unnumbered PtP links, yes otherwise.
- <tag>check link <M>switch</M></tag>
+ <tag><label id="ospf-check-link">check link <M>switch</M></tag>
If set, a hardware link state (reported by OS) is taken into consideration.
When a link disappears (e.g. an ethernet cable is unplugged), neighbors
are immediately considered unreachable and only the address of the iface
@@ -2853,15 +3027,15 @@ protocol ospf &lt;name&gt; {
some hardware drivers or platforms do not implement this feature.
Default value is no.
- <tag>bfd <M>switch</M></tag>
+ <tag><label id="ospf-bfd">bfd <M>switch</M></tag>
OSPF could use BFD protocol as an advisory mechanism for neighbor
liveness and failure detection. If enabled, BIRD setups a BFD session
for each OSPF neighbor and tracks its liveness by it. This has an
advantage of an order of magnitude lower detection times in case of
failure. Note that BFD protocol also has to be configured, see
- <ref id="sect-bfd" name="BFD"> section for details. Default value is no.
+ <ref id="bfd" name="BFD"> section for details. Default value is no.
- <tag>ttl security [<m/switch/ | tx only]</tag>
+ <tag><label id="ospf-ttl-security">ttl security [<m/switch/ | tx only]</tag>
TTL security is a feature that protects routing protocols from remote
spoofed packets by using TTL 255 instead of TTL 1 for protocol packets
destined to neighbors. Because TTL is decremented when packets are
@@ -2874,35 +3048,38 @@ protocol ospf &lt;name&gt; {
set to <cf/tx only/, TTL 255 is used for sent packets, but is not
checked for received packets. Default value is no.
- <tag>tx class|dscp|priority <m/num/</tag>
+ <tag><label id="ospf-tx-class">tx class|dscp|priority <m/num/</tag>
These options specify the ToS/DiffServ/Traffic class/Priority of the
- outgoing OSPF packets. See <ref id="dsc-prio" name="tx class"> common
+ outgoing OSPF packets. See <ref id="proto-tx-class" name="tx class"> common
option for detailed description.
- <tag>ecmp weight <M>num</M></tag>
+ <tag><label id="ospf-ecmp-weight">ecmp weight <M>num</M></tag>
When ECMP (multipath) routes are allowed, this value specifies a
relative weight used for nexthops going through the iface. Allowed
values are 1-256. Default value is 1.
- <tag>authentication none</tag>
+ <tag><label id="ospf-auth-none">authentication none</tag>
No passwords are sent in OSPF packets. This is the default value.
- <tag>authentication simple</tag>
+ <tag><label id="ospf-auth-simple">authentication simple</tag>
Every packet carries 8 bytes of password. Received packets lacking this
password are ignored. This authentication mechanism is very weak.
-
- <tag>authentication cryptographic</tag>
- 16-byte long MD5 digest is appended to every packet. For the digest
- generation 16-byte long passwords are used. Those passwords are not sent
- via network, so this mechanism is quite secure. Packets can still be
- read by an attacker.
-
- <tag>password "<M>text</M>"</tag>
- An 8-byte or 16-byte password used for authentication. See
- <ref id="dsc-pass" name="password"> common option for detailed
+ This option is not available in OSPFv3.
+
+ <tag><label id="ospf-auth-cryptographic">authentication cryptographic</tag>
+ An authentication code is appended to every packet. The specific
+ cryptographic algorithm is selected by option <cf/algorithm/ for each
+ key. The default cryptographic algorithm for OSPFv2 keys is Keyed-MD5
+ and for OSPFv3 keys is HMAC-SHA-256. Passwords are not sent open via
+ network, so this mechanism is quite secure. Packets can still be read by
+ an attacker.
+
+ <tag><label id="ospf-pass">password "<M>text</M>"</tag>
+ Specifies a password used for authentication. See
+ <ref id="proto-pass" name="password"> common option for detailed
description.
- <tag>neighbors { <m/set/ } </tag>
+ <tag><label id="ospf-neighbors">neighbors { <m/set/ } </tag>
A set of neighbors to which Hello messages on NBMA or PtMP networks are
to be sent. For NBMA networks, some of them could be marked as eligible.
In OSPFv3, link-local addresses should be used, using global ones is
@@ -2911,6 +3088,7 @@ protocol ospf &lt;name&gt; {
</descrip>
<sect1>Attributes
+<label id="ospf-attr">
<p>OSPF defines four route attributes. Each internal route has a <cf/metric/.
@@ -2930,6 +3108,7 @@ network. This attribute is read-only. Default is <cf/ospf_metric2 = 10000/ and
<cf/ospf_tag = 0/.
<sect1>Example
+<label id="ospf-exam">
<p><code>
protocol ospf MyOSPF {
@@ -2958,11 +3137,13 @@ protocol ospf MyOSPF {
id 1;
generate to "22-04-2003 11:00:06";
accept from "17-01-2001 12:01:05";
+ algorithm hmac sha384;
};
password "def" {
id 2;
generate to "22-07-2005 17:03:21";
accept from "22-02-2001 11:34:06";
+ algorithm hmac sha512;
};
};
interface "arc0" {
@@ -2996,8 +3177,10 @@ protocol ospf MyOSPF {
<sect>Pipe
+<label id="pipe">
<sect1>Introduction
+<label id="pipe-intro">
<p>The Pipe protocol serves as a link between two routing tables, allowing
routes to be passed from a table declared as primary (i.e., the one the pipe is
@@ -3032,21 +3215,24 @@ routes appear in which tables and also you can employ the Pipe protocol for
exporting a selected subset of one table to another one.
<sect1>Configuration
+<label id="pipe-config">
<p><descrip>
- <tag>peer table <m/table/</tag>
+ <tag><label id="pipe-peer-table">peer table <m/table/</tag>
Defines secondary routing table to connect to. The primary one is
selected by the <cf/table/ keyword.
- <tag>mode opaque|transparent</tag>
+ <tag><label id="pipe-mode">mode opaque|transparent</tag>
Specifies the mode for the pipe to work in. Default is transparent.
</descrip>
<sect1>Attributes
+<label id="pipe-attr">
<p>The Pipe protocol doesn't define any route attributes.
<sect1>Example
+<label id="pipe-exam">
<p>Let's consider a router which serves as a boundary router of two different
autonomous systems, each of them connected to a subset of interfaces of the
@@ -3117,8 +3303,10 @@ protocol pipe { # The Pipe
<sect>RAdv
+<label id="radv">
<sect1>Introduction
+<label id="radv-intro">
<p>The RAdv protocol is an implementation of Router Advertisements, which are
used in the IPv6 stateless autoconfiguration. IPv6 routers send (in irregular
@@ -3126,23 +3314,22 @@ time intervals or as an answer to a request) advertisement packets to connected
networks. These packets contain basic information about a local network (e.g. a
list of network prefixes), which allows network hosts to autoconfigure network
addresses and choose a default route. BIRD implements router behavior as defined
-in RFC 4861<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc4861.txt">
-and also the DNS extensions from
-RFC 6106<htmlurl url="ftp://ftp.rfc-editor.org/in-notes/rfc6106.txt">.
+in <rfc id="4861"> and also the DNS extensions from <rfc id="6106">.
<sect1>Configuration
+<label id="radv-config">
<p>There are several classes of definitions in RAdv configuration -- interface
definitions, prefix definitions and DNS definitions:
<descrip>
- <tag>interface <m/pattern [, ...]/ { <m/options/ }</tag>
+ <tag><label id="radv-iface">interface <m/pattern/ [, <m/.../] { <m/options/ }</tag>
Interface definitions specify a set of interfaces on which the
protocol is activated and contain interface specific options.
- See <ref id="dsc-iface" name="interface"> common options for
+ See <ref id="proto-iface" name="interface"> common options for
detailed description.
- <tag>prefix <m/prefix/ { <m/options/ }</tag>
+ <tag><label id="radv-prefix">prefix <m/prefix/ { <m/options/ }</tag>
Prefix definitions allow to modify a list of advertised prefixes. By
default, the advertised prefixes are the same as the network prefixes
assigned to the interface. For each network prefix, the matching prefix
@@ -3156,7 +3343,7 @@ definitions, prefix definitions and DNS definitions:
prefix definition is matching if the network prefix is a subnet of the
prefix in prefix definition.
- <tag>rdnss { <m/options/ }</tag>
+ <tag><label id="radv-rdnss">rdnss { <m/options/ }</tag>
RDNSS definitions allow to specify a list of advertised recursive DNS
servers together with their options. As options are seldom necessary,
there is also a short variant <cf>rdnss <m/address/</cf> that just
@@ -3164,15 +3351,15 @@ definitions, prefix definitions and DNS definitions:
definitions may also be interface-specific when used inside interface
options. By default, interface uses both global and interface-specific
options, but that can be changed by <cf/rdnss local/ option.
-
- <tag>dnssl { <m/options/ }</tag>
+dsc-iface
+ <tag><label id="radv-dnssl">dnssl { <m/options/ }</tag>
DNSSL definitions allow to specify a list of advertised DNS search
domains together with their options. Like <cf/rdnss/ above, multiple
definitions are cumulative, they can be used also as interface-specific
options and there is a short variant <cf>dnssl <m/domain/</cf> that just
specifies one DNS search domain.
- <label id="dsc-trigger"> <tag>trigger <m/prefix/</tag>
+ <tag><label id="radv-trigger">trigger <m/prefix/</tag>
RAdv protocol could be configured to change its behavior based on
availability of routes. When this option is used, the protocol waits in
suppressed state until a <it/trigger route/ (for the specified network)
@@ -3194,99 +3381,99 @@ definitions, prefix definitions and DNS definitions:
<p>Interface specific options:
<descrip>
- <tag>max ra interval <m/expr/</tag>
+ <tag><label id="radv-iface-max-ra-interval">max ra interval <m/expr/</tag>
Unsolicited router advertisements are sent in irregular time intervals.
This option specifies the maximum length of these intervals, in seconds.
Valid values are 4-1800. Default: 600
- <tag>min ra interval <m/expr/</tag>
+ <tag><label id="radv-iface-min-ra-interval">min ra interval <m/expr/</tag>
This option specifies the minimum length of that intervals, in seconds.
Must be at least 3 and at most 3/4 * <cf/max ra interval/. Default:
about 1/3 * <cf/max ra interval/.
- <tag>min delay <m/expr/</tag>
+ <tag><label id="radv-iface-min-delay">min delay <m/expr/</tag>
The minimum delay between two consecutive router advertisements, in
seconds. Default: 3
- <tag>managed <m/switch/</tag>
+ <tag><label id="radv-iface-managed">managed <m/switch/</tag>
This option specifies whether hosts should use DHCPv6 for IP address
configuration. Default: no
- <tag>other config <m/switch/</tag>
+ <tag><label id="radv-iface-other-config">other config <m/switch/</tag>
This option specifies whether hosts should use DHCPv6 to receive other
configuration information. Default: no
- <tag>link mtu <m/expr/</tag>
+ <tag><label id="radv-iface-link-mtu">link mtu <m/expr/</tag>
This option specifies which value of MTU should be used by hosts. 0
means unspecified. Default: 0
- <tag>reachable time <m/expr/</tag>
+ <tag><label id="radv-iface-reachable-time">reachable time <m/expr/</tag>
This option specifies the time (in milliseconds) how long hosts should
assume a neighbor is reachable (from the last confirmation). Maximum is
3600000, 0 means unspecified. Default 0.
- <tag>retrans timer <m/expr/</tag>
+ <tag><label id="radv-iface-retrans-timer">retrans timer <m/expr/</tag>
This option specifies the time (in milliseconds) how long hosts should
wait before retransmitting Neighbor Solicitation messages. 0 means
unspecified. Default 0.
- <tag>current hop limit <m/expr/</tag>
+ <tag><label id="radv-iface-current-hop-limit">current hop limit <m/expr/</tag>
This option specifies which value of Hop Limit should be used by
hosts. Valid values are 0-255, 0 means unspecified. Default: 64
- <tag>default lifetime <m/expr/ [sensitive <m/switch/]</tag>
+ <tag><label id="radv-iface-default-lifetime">default lifetime <m/expr/ [sensitive <m/switch/]</tag>
This option specifies the time (in seconds) how long (after the receipt
of RA) hosts may use the router as a default router. 0 means do not use
- as a default router. For <cf/sensitive/ option, see <ref id="dsc-trigger" name="trigger">.
+ as a default router. For <cf/sensitive/ option, see <ref id="radv-trigger" name="trigger">.
Default: 3 * <cf/max ra interval/, <cf/sensitive/ yes.
- <tag>default preference low|medium|high</tag>
+ <tag><label id="radv-iface-default-preference-low">default preference low|medium|high</tag>
This option specifies the Default Router Preference value to advertise
to hosts. Default: medium.
- <tag>rdnss local <m/switch/</tag>
+ <tag><label id="radv-iface-rdnss-local">rdnss local <m/switch/</tag>
Use only local (interface-specific) RDNSS definitions for this
interface. Otherwise, both global and local definitions are used. Could
also be used to disable RDNSS for given interface if no local definitons
are specified. Default: no.
- <tag>dnssl local <m/switch/</tag>
+ <tag><label id="radv-iface-dnssl-local">dnssl local <m/switch/</tag>
Use only local DNSSL definitions for this interface. See <cf/rdnss local/
option above. Default: no.
</descrip>
-<p>Prefix specific options:
+<p>Prefix specific options
<descrip>
- <tag>skip <m/switch/</tag>
+ <tag><label id="radv-prefix-skip">skip <m/switch/</tag>
This option allows to specify that given prefix should not be
advertised. This is useful for making exceptions from a default policy
of advertising all prefixes. Note that for withdrawing an already
advertised prefix it is more useful to advertise it with zero valid
lifetime. Default: no
- <tag>onlink <m/switch/</tag>
+ <tag><label id="radv-prefix-onlink">onlink <m/switch/</tag>
This option specifies whether hosts may use the advertised prefix for
onlink determination. Default: yes
- <tag>autonomous <m/switch/</tag>
+ <tag><label id="radv-prefix-autonomous">autonomous <m/switch/</tag>
This option specifies whether hosts may use the advertised prefix for
stateless autoconfiguration. Default: yes
- <tag>valid lifetime <m/expr/ [sensitive <m/switch/]</tag>
+ <tag><label id="radv-prefix-valid-lifetime">valid lifetime <m/expr/ [sensitive <m/switch/]</tag>
This option specifies the time (in seconds) how long (after the
receipt of RA) the prefix information is valid, i.e., autoconfigured
IP addresses can be assigned and hosts with that IP addresses are
considered directly reachable. 0 means the prefix is no longer
- valid. For <cf/sensitive/ option, see <ref id="dsc-trigger" name="trigger">.
+ valid. For <cf/sensitive/ option, see <ref id="radv-trigger" name="trigger">.
Default: 86400 (1 day), <cf/sensitive/ no.
- <tag>preferred lifetime <m/expr/ [sensitive <m/switch/]</tag>
+ <tag><label id="radv-prefix-preferred-lifetime">preferred lifetime <m/expr/ [sensitive <m/switch/]</tag>
This option specifies the time (in seconds) how long (after the
receipt of RA) IP addresses generated from the prefix using stateless
autoconfiguration remain preferred. For <cf/sensitive/ option,
- see <ref id="dsc-trigger" name="trigger">. Default: 14400 (4 hours),
+ see <ref id="radv-trigger" name="trigger">. Default: 14400 (4 hours),
<cf/sensitive/ no.
</descrip>
@@ -3294,12 +3481,12 @@ definitions, prefix definitions and DNS definitions:
<p>RDNSS specific options:
<descrip>
- <tag>ns <m/address/</tag>
+ <tag><label id="radv-rdnss-ns">ns <m/address/</tag>
This option specifies one recursive DNS server. Can be used multiple
times for multiple servers. It is mandatory to have at least one
<cf/ns/ option in <cf/rdnss/ definition.
- <tag>lifetime [mult] <m/expr/</tag>
+ <tag><label id="radv-rdnss-lifetime">lifetime [mult] <m/expr/</tag>
This option specifies the time how long the RDNSS information may be
used by clients after the receipt of RA. It is expressed either in
seconds or (when <cf/mult/ is used) in multiples of <cf/max ra
@@ -3312,12 +3499,12 @@ definitions, prefix definitions and DNS definitions:
<p>DNSSL specific options:
<descrip>
- <tag>domain <m/address/</tag>
+ <tag><label id="radv-dnssl-domain">domain <m/address/</tag>
This option specifies one DNS search domain. Can be used multiple times
for multiple domains. It is mandatory to have at least one <cf/domain/
option in <cf/dnssl/ definition.
- <tag>lifetime [mult] <m/expr/</tag>
+ <tag><label id="radv-dnssl-lifetime">lifetime [mult] <m/expr/</tag>
This option specifies the time how long the DNSSL information may be
used by clients after the receipt of RA. Details are the same as for
RDNSS <cf/lifetime/ option above. Default: 3 * <cf/max ra interval/.
@@ -3325,6 +3512,7 @@ definitions, prefix definitions and DNS definitions:
<sect1>Example
+<label id="radv-exam">
<p><code>
protocol radv {
@@ -3364,8 +3552,10 @@ protocol radv {
<sect>RIP
+<label id="rip">
<sect1>Introduction
+<label id="rip-intro">
<p>The RIP protocol (also sometimes called Rest In Pieces) is a simple protocol,
where each router broadcasts (to all its neighbors) distances to all networks it
@@ -3379,18 +3569,15 @@ counting to infinity is necessary, because it is slow. Due to infinity being 16,
you can't use RIP on networks where maximal distance is higher than 15
hosts.
-<p>BIRD supports RIPv1
-(RFC 1058<htmlurl url="http://www.rfc-editor.org/rfc/rfc1058.txt">),
-RIPv2 (RFC 2453<htmlurl url="http://www.rfc-editor.org/rfc/rfc2453.txt">),
-RIPng (RFC 2080<htmlurl url="http://www.rfc-editor.org/rfc/rfc2080.txt">),
-and RIP cryptographic authentication (SHA-1 not implemented)
-(RFC 4822<htmlurl url="http://www.rfc-editor.org/rfc/rfc4822.txt">).
+<p>BIRD supports RIPv1 (<rfc id="1058">), RIPv2 (<rfc id="2453">), RIPng (<rfc
+id="2080">), and RIP cryptographic authentication (<rfc id="4822">).
<p>RIP is a very simple protocol, and it has a lot of shortcomings. Slow
convergence, big network load and inability to handle larger networks makes it
pretty much obsolete. It is still usable on very small networks.
<sect1>Configuration
+<label id="rip-config">
<p>RIP configuration consists mainly of common protocol options and interface
definitions, most RIP options are interface specific.
@@ -3427,17 +3614,20 @@ protocol rip [&lt;name&gt;] {
generate to "&lt;date&gt;";
accept from "&lt;date&gt;";
accept to "&lt;date&gt;";
+ from "&lt;date&gt;";
+ to "&lt;date&gt;";
+ algorithm ( keyed md5 | keyed sha1 | hmac sha1 | hmac sha256 | hmac sha384 | hmac sha512 );
};
};
}
</code>
<descrip>
- <tag>infinity <M>number</M></tag>
+ <tag><label id="rip-infinity">infinity <M>number</M></tag>
Selects the distance of infinity. Bigger values will make
protocol convergence even slower. The default value is 16.
- <tag>ecmp <M>switch</M> [limit <M>number</M>]</tag>
+ <tag><label id="rip-ecmp">ecmp <M>switch</M> [limit <M>number</M>]</tag>
This option specifies whether RIP is allowed to generate ECMP
(equal-cost multipath) routes. Such routes are used when there are
several directions to the destination, each with the same (computed)
@@ -3445,42 +3635,42 @@ protocol rip [&lt;name&gt;] {
nexthops in one route. By default, ECMP is disabled. If enabled,
default value of the limit is 16.
- <tag>interface <m/pattern [, ...]/ { <m/options/ }</tag>
+ <tag><label id="rip-iface">interface <m/pattern/ [, <m/.../] { <m/options/ }</tag>
Interface definitions specify a set of interfaces on which the
protocol is activated and contain interface specific options.
- See <ref id="dsc-iface" name="interface"> common options for
+ See <ref id="proto-iface" name="interface"> common options for
detailed description.
</descrip>
<p>Interface specific options:
<descrip>
- <tag>metric <m/num/</tag>
+ <tag><label id="rip-iface-metric">metric <m/num/</tag>
This option specifies the metric of the interface. When a route is
received from the interface, its metric is increased by this value
before further processing. Valid values are 1-255, but values higher
than infinity has no further meaning. Default: 1.
- <tag>mode multicast|broadcast</tag>
+ <tag><label id="rip-iface-mode">mode multicast|broadcast</tag>
This option selects the mode for RIP to use on the interface. The
default is multicast mode for RIPv2 and broadcast mode for RIPv1.
RIPng always uses the multicast mode.
- <tag>passive <m/switch/</tag>
+ <tag><label id="rip-iface-passive">passive <m/switch/</tag>
Passive interfaces receive routing updates but do not transmit any
messages. Default: no.
- <tag>address <m/ip/</tag>
+ <tag><label id="rip-iface-address">address <m/ip/</tag>
This option specifies a destination address used for multicast or
broadcast messages, the default is the official RIP (224.0.0.9) or RIPng
(ff02::9) multicast address, or an appropriate broadcast address in the
broadcast mode.
- <tag>port <m/number/</tag>
+ <tag><label id="rip-iface-port">port <m/number/</tag>
This option selects an UDP port to operate on, the default is the
official RIP (520) or RIPng (521) port.
- <tag>version 1|2</tag>
+ <tag><label id="rip-iface-version">version 1|2</tag>
This option selects the version of RIP used on the interface. For RIPv1,
automatic subnet aggregation is not implemented, only classful network
routes and host routes are propagated. Note that BIRD allows RIPv1 to be
@@ -3489,12 +3679,12 @@ protocol rip [&lt;name&gt;] {
RIP, the option is not supported for RIPng, as no further versions are
defined.
- <tag>version only <m/switch/</tag>
+ <tag><label id="rip-iface-version-only">version only <m/switch/</tag>
Regardless of RIP version configured for the interface, BIRD accepts
incoming packets of any RIP version. This option restrict accepted
packets to the configured version. Default: no.
- <tag>split horizon <m/switch/</tag>
+ <tag><label id="rip-iface-split-horizon">split horizon <m/switch/</tag>
Split horizon is a scheme for preventing routing loops. When split
horizon is active, routes are not regularly propagated back to the
interface from which they were received. They are either not propagated
@@ -3503,52 +3693,54 @@ protocol rip [&lt;name&gt;] {
on the interface will not consider the router as a part of an
independent path to the destination of the route. Default: yes.
- <tag>poison reverse <m/switch/</tag>
+ <tag><label id="rip-iface-poison-reverse">poison reverse <m/switch/</tag>
When split horizon is active, this option specifies whether the poisoned
reverse variant (propagating routes back with an infinity metric) is
used. The poisoned reverse has some advantages in faster convergence,
but uses more network traffic. Default: yes.
- <tag>check zero <m/switch/</tag>
+ <tag><label id="rip-iface-check-zero">check zero <m/switch/</tag>
Received RIPv1 packets with non-zero values in reserved fields should
be discarded. This option specifies whether the check is performed or
such packets are just processed as usual. Default: yes.
- <tag>update time <m/number/</tag>
+ <tag><label id="rip-iface-update-time">update time <m/number/</tag>
Specifies the number of seconds between periodic updates. A lower number
will mean faster convergence but bigger network load. Default: 30.
- <tag>timeout time <m/number/</tag>
+ <tag><label id="rip-iface-timeout-time">timeout time <m/number/</tag>
Specifies the time interval (in seconds) between the last received route
announcement and the route expiration. After that, the network is
considered unreachable, but still is propagated with infinity distance.
Default: 180.
- <tag>garbage time <m/number/</tag>
+ <tag><label id="rip-iface-garbage-time">garbage time <m/number/</tag>
Specifies the time interval (in seconds) between the route expiration
and the removal of the unreachable network entry. The garbage interval,
when a route with infinity metric is propagated, is used for both
internal (after expiration) and external (after withdrawal) routes.
Default: 120.
- <tag>ecmp weight <m/number/</tag>
+ <tag><label id="rip-iface-ecmp-weight">ecmp weight <m/number/</tag>
When ECMP (multipath) routes are allowed, this value specifies a
relative weight used for nexthops going through the iface. Valid
values are 1-256. Default value is 1.
- <tag>authentication none|plaintext|cryptographic</tag>
+ <tag><label id="rip-iface-auth">authentication none|plaintext|cryptographic</tag>
Selects authentication method to be used. <cf/none/ means that packets
are not authenticated at all, <cf/plaintext/ means that a plaintext
password is embedded into each packet, and <cf/cryptographic/ means that
- packets are authenticated using a MD5 cryptographic hash. If you set
+ packets are authenticated using some cryptographic hash function
+ selected by option <cf/algorithm/ for each key. The default
+ cryptographic algorithm for RIP keys is Keyed-MD5. If you set
authentication to not-none, it is a good idea to add <cf>password</cf>
section. Default: none.
- <tag>password "<m/text/"</tag>
- Specifies a password used for authentication. See <ref id="dsc-pass"
+ <tag><label id="rip-iface-pass">password "<m/text/"</tag>
+ Specifies a password used for authentication. See <ref id="proto-pass"
name="password"> common option for detailed description.
- <tag>ttl security [<m/switch/ | tx only]</tag>
+ <tag><label id="rip-iface-ttl-security">ttl security [<m/switch/ | tx only]</tag>
TTL security is a feature that protects routing protocols from remote
spoofed packets by using TTL 255 instead of TTL 1 for protocol packets
destined to neighbors. Because TTL is decremented when packets are
@@ -3562,34 +3754,36 @@ protocol rip [&lt;name&gt;] {
compatibility with neighbors regardless of whether they use ttl
security.
- For RIPng, TTL security is a standard behavior (required by RFC 2080)
- and therefore default value is yes. For IPv4 RIP, default value is no.
+ For RIPng, TTL security is a standard behavior (required by <rfc
+ id="2080">) and therefore default value is yes. For IPv4 RIP, default
+ value is no.
- <tag>tx class|dscp|priority <m/number/</tag>
+ <tag><label id="rip-iface-tx-class">tx class|dscp|priority <m/number/</tag>
These options specify the ToS/DiffServ/Traffic class/Priority of the
- outgoing RIP packets. See <ref id="dsc-prio" name="tx class"> common
+ outgoing RIP packets. See <ref id="proto-tx-class" name="tx class"> common
option for detailed description.
- <tag>rx buffer <m/number/</tag>
+ <tag><label id="rip-iface-rx-buffer">rx buffer <m/number/</tag>
This option specifies the size of buffers used for packet processing.
The buffer size should be bigger than maximal size of received packets.
The default value is 532 for IPv4 RIP and interface MTU value for RIPng.
- <tag>tx length <m/number/</tag>
+ <tag><label id="rip-iface-tx-length">tx length <m/number/</tag>
This option specifies the maximum length of generated RIP packets. To
avoid IP fragmentation, it should not exceed the interface MTU value.
The default value is 532 for IPv4 RIP and interface MTU value for RIPng.
- <tag>check link <m/switch/</tag>
+ <tag><label id="rip-iface-check-link">check link <m/switch/</tag>
If set, the hardware link state (as reported by OS) is taken into
consideration. When the link disappears (e.g. an ethernet cable is
unplugged), neighbors are immediately considered unreachable and all
routes received from them are withdrawn. It is possible that some
- hardware drivers or platforms do not implement this feature. Default:
- no.
+ hardware drivers or platforms do not implement this feature.
+ Default: no.
</descrip>
<sect1>Attributes
+<label id="rip-attr">
<p>RIP defines two route attributes:
@@ -3600,7 +3794,7 @@ protocol rip [&lt;name&gt;] {
preference, BIRD prefers the route with lowest <cf/rip_metric/. When a
non-RIP route is exported to RIP, the default metric is 1.
- <tag>int <cf/rip_tag/</tag>
+ <tag><label id="rta-rip-tag">int rip_tag/</tag>
RIP route tag: a 16-bit number which can be used to carry additional
information with the route (for example, an originating AS number in
case of external routes). When a non-RIP route is exported to RIP, the
@@ -3608,6 +3802,7 @@ protocol rip [&lt;name&gt;] {
</descrip>
<sect1>Example
+<label id="rip-exam">
<p><code>
protocol rip {
@@ -3616,8 +3811,9 @@ protocol rip {
period 12;
garbage time 60;
interface "eth0" { metric 3; mode multicast; };
- interface "eth*" { metric 2; mode broadcast; };
- authentication none;
+ interface "eth*" { metric 2; mode broadcast; };
+ authentication cryptographic;
+ password "secret-shared-key" { algorithm hmac sha256; };
import filter { print "importing"; accept; };
export filter { print "exporting"; accept; };
}
@@ -3803,6 +3999,7 @@ protocol rpki {
<sect>Static
+<label id="static">
<p>The Static protocol doesn't communicate with other routers in the network,
but instead it allows you to define routes manually. This is often used for
@@ -3831,14 +4028,14 @@ definition of the protocol contains mainly a list of static routes.
<p>Global options:
<descrip>
- <tag>check link <m/switch/</tag>
+ <tag><label id="static-check-link">check link <m/switch/</tag>
If set, hardware link states of network interfaces are taken into
consideration. When link disappears (e.g. ethernet cable is unplugged),
static routes directing to that interface are removed. It is possible
that some hardware drivers or platforms do not implement this feature.
Default: off.
- <tag>igp table <m/name/</tag>
+ <tag><label id="static-igp-table">igp table <m/name/</tag>
Specifies a table that is used for route table lookups of recursive
routes. Default: the same table as the protocol is connected to.
</descrip>
@@ -3846,24 +4043,24 @@ definition of the protocol contains mainly a list of static routes.
<p>Route definitions (each may also contain a block of per-route options):
<descrip>
- <tag>route <m/prefix/ via <m/ip/</tag>
+ <tag><label id="static-route-via-ip">route <m/prefix/ via <m/ip/</tag>
Static route through a neighboring router. For link-local next hops,
interface can be specified as a part of the address (e.g.,
<cf/via fe80::1234%eth0/).
- <tag>route <m/prefix/ multipath via <m/ip/ [weight <m/num/] [bfd <m/switch/] [via ...]</tag>
+ <tag><label id="static-route-via-mpath">route <m/prefix/ multipath via <m/ip/ [weight <m/num/] [bfd <m/switch/] [via <m/.../]</tag>
Static multipath route. Contains several nexthops (gateways), possibly
with their weights.
- <tag>route <m/prefix/ via <m/"interface"/</tag>
+ <tag><label id="static-route-via-iface">route <m/prefix/ via <m/"interface"/</tag>
Static device route through an interface to hosts on a directly
connected network.
- <tag>route <m/prefix/ recursive <m/ip/</tag>
+ <tag><label id="static-route-recursive">route <m/prefix/ recursive <m/ip/</tag>
Static recursive route, its nexthop depends on a route table lookup for
given IP address.
- <tag>route <m/prefix/ blackhole|unreachable|prohibit</tag>
+ <tag><label id="static-route-drop">route <m/prefix/ blackhole|unreachable|prohibit</tag>
Special routes specifying to silently drop the packet, return it as
unreachable or return it as administratively prohibited. First two
targets are also known as <cf/drop/ and <cf/reject/.
@@ -3872,7 +4069,7 @@ definition of the protocol contains mainly a list of static routes.
<p>Per-route options:
<descrip>
- <tag>bfd <m/switch/</tag>
+ <tag><label id="static-route-bfd">bfd <m/switch/</tag>
The Static protocol could use BFD protocol for next hop liveness
detection. If enabled, a BFD session to the route next hop is created
and the static route is BFD-controlled -- the static route is announced
@@ -3885,9 +4082,9 @@ definition of the protocol contains mainly a list of static routes.
This option can be used for static routes with a direct next hop, or
also for for individual next hops in a static multipath route (see
above). Note that BFD protocol also has to be configured, see
- <ref id="sect-bfd" name="BFD"> section for details. Default value is no.
+ <ref id="bfd" name="BFD"> section for details. Default value is no.
- <tag><m/filter expression/</tag>
+ <tag><label id="static-route-filter"><m/filter expression/</tag>
This is a special option that allows filter expressions to be configured
on per-route basis. Can be used multiple times. These expressions are
evaluated when the route is originated, similarly to the import filter
@@ -3924,8 +4121,10 @@ protocol static {
<chapt>Conclusions
+<label id="conclusion">
<sect>Future work
+<label id="future-work">
<p>Although BIRD supports all the commonly used routing protocols, there are
still some features which would surely deserve to be implemented in future
@@ -3941,6 +4140,7 @@ versions of BIRD:
<sect>Getting more help
+<label id="help">
<p>If you use BIRD, you're welcome to join the bird-users mailing list
(<HTMLURL URL="mailto:bird-users@network.cz" name="bird-users@network.cz">)
diff --git a/doc/sbase/dist/birddoc/groff/mapping b/doc/sbase/dist/birddoc/groff/mapping
index 71d2c935..3861a28d 100644
--- a/doc/sbase/dist/birddoc/groff/mapping
+++ b/doc/sbase/dist/birddoc/groff/mapping
@@ -6,7 +6,7 @@
% Based on qwertz replacement file by Tom Gordon
% linuxdoc mods by mdw
-% Groff dependencies are few. To port to another roff:
+% Groff dependencies are few. To port to another roff:
% 1. Check and modify, if necessary, font changes. (e.g. In psroff the
% same fonts have other names.)
% 2. Check the code for including Encapsulated PostScript, generated
@@ -19,13 +19,13 @@
% Hacked by mdw
".nr PI 3n\n"
- ".ds CF \\\\n\%\n"
+ ".ds CF \\\\n\%\n"
".ds CH \\&\n"
".ds dR $\n" % dollar, to avoid EQN conflicts
% Start with no TOC
".ds printtoc\n"
-
+
% Footnote style
".nr FF 1\n"
@@ -51,16 +51,16 @@
".nr HM 0i\n"
".nr FM 0i\n"
- % Turn off right-margin filling
+ % Turn off right-margin filling
".na\n"
-
+
% h is 1 if first paragraph after heading
- ".nr h 0\n"
+ ".nr h 0\n"
% initialize heading level
-
- ".nr il 1\n"
+
+ ".nr il 1\n"
% Number registers for list
@@ -68,20 +68,20 @@
".nr ll 0\n" % list level, stores current level
".nr el 0\n" % current enumeration level
- % Not all list levels are enumerations, as
+ % Not all list levels are enumerations, as
% itemizations can be embedded within enumerations
% and vice versa
-
+
% type of list level is in \n(t\n(ll, where
% 0 : itemize, 1 : enumerate, 2: description
% enumerator for an enumeration level is in
% \n(e\n(el -- i.e. \n(e1=2 means current item of
% enumeration level 1 is 2
-
+
% context-sensitive paragraph macro
-% Bug: There's some problem using this to re-start paragraphs after the
+% Bug: There's some problem using this to re-start paragraphs after the
% </verb> and </code>, so after verb and code I insert .LP. That's fine
% except that is loses indentation when using verb or code inside of a list.
@@ -95,21 +95,21 @@
% for this enumeration level
".if \\\\n(t\\\\n(ll=1 \\{.IP \\\\n+(e\\\\n(el.\\}\n"
% if first par element of descrip, do nothing
-".\\}\n"
+".\\}\n"
".el .sp \n" % subsequent par element of item
".\\}\n"
".el \\{\\\n" % not within list
-".ie \\\\nh=1 \\{\\\n" % first par after heading
-".LP\n"
+".ie \\\\nh=1 \\{\\\n" % first par after heading
+".LP\n"
".nr h 0\n" % reset h flag
-".\\}\n"
+".\\}\n"
".el .LP \n" % Changed from .PP, mdw
".\\}\n"
".nh\n"
-"..\n"
+"..\n"
+
+
-
-
% for each level, a number register is created
% to store its type and current item number, where
% -1=bullet of an itemized list.
@@ -141,7 +141,7 @@
% set initial level of headings, in register il
<article> + ".nr il 0" +
-</article> + ".if '\\*[printtoc]'true' .PX\n"
+</article> + ".if '\\*[printtoc]'true' .PX\n"
<report> + ".nr il 1" +
</report> + ".bp\n"
@@ -153,23 +153,23 @@
".bp\n"
".TC" +
-<notes>
+<notes>
</notes>
<manpage> + ".nr il -1" +
-</manpage>
+</manpage>
<progdoc>
</progdoc>
% Hacked up titlepag stuff to look more reasonable. Titles and author
% names are now stored in strings, printed by the end of </titlepag>.
-% Wake up! This uses groff-like long string names. You must use groff
+% Wake up! This uses groff-like long string names. You must use groff
% to format this.
<titlepag> + ".ds mdwtitle\n"
".ds mdwsubtitle\n"
- ".ds mdwdate\n"
+ ".ds mdwdate\n"
".de printabstract\n"
"..\n" +
</titlepag> + "\\*[mdwtitle]\n"
@@ -181,10 +181,10 @@
"\\*[mdwdate]\n"
".br\n"
".printabstract\n"
- ".br\n"
+ ".br\n"
%<title> + ".TL" +
-%</title>
+%</title>
<title> + ".ds mdwtitle "
</title> +
@@ -194,13 +194,13 @@
% ".SM" +
%</subtitle> + ".LG" +
-<subtitle> + ".ds mdwsubtitle "
+<subtitle> + ".ds mdwsubtitle "
</subtitle> +
-<date> + ".ds mdwdate "
+<date> + ".ds mdwdate "
</date> +
-<abstract> + ".de printabstract\n"
+<abstract> + ".de printabstract\n"
".LP\n"
</abstract> + ".." +
@@ -215,10 +215,10 @@
<name> + ".br" +
</name>
-<and>
+<and>
</and>
-<thanks> "\\**\n"
+<thanks> "\\**\n"
".FS" +
</thanks> + ".FE" +
@@ -229,11 +229,11 @@
<newline> + ".br"
</newline>
-<label>
-</label>
+<label>
+</label>
-<header>
-</header>
+<header>
+</header>
<lhead> + ".EH '"
</lhead> "'''" +
@@ -263,13 +263,13 @@
<toc>
</toc>
-<lof>
+<lof>
</lof>
-<lot>
+<lot>
</lot>
-<chapt> + ".bp\n"
+<chapt> + ".bp\n"
".NH \\n(il " +
</chapt>
@@ -283,7 +283,7 @@
</sect2>
<sect3> + ".NH 4+\\n(il" +
-</sect3>
+</sect3>
<sect4> + ".NH 5+\\n(il" +
</sect4>
@@ -292,10 +292,10 @@
</heading> + "\\*h\n"
".XS \\n%\n"
"\\*(SN \\*h\n"
- ".XE\n"
+ ".XE\n"
".nr h 1\n" % set heading flag to true
-<p> + ".Pp" +
+<p> + ".Pp" +
</p>
<itemize> + ".nr ll +1\n" % increment list level
@@ -309,9 +309,9 @@
".af e\\n(el \\*(f\\n(el\n" % style of enumerator
".if \\n(ll>1 .RS" +
</enum> + ".if \\n(ll>1 .RE\n"
- ".br\n"
+ ".br\n"
".nr el -1\n" % decrement enumeration level
- ".nr ll -1\n" % decrement list level
+ ".nr ll -1\n" % decrement list level
<descrip> + ".RS\n"
".nr ll +1\n" % increment list level
@@ -324,7 +324,7 @@
% If bi=1 then the paragraph is the first one of the item.
<item> + ".nr bi 1\n.Pp" +
-</item>
+</item>
<tag> + ".IP \"\\fB"
</tag> "\\fR\"\n"
@@ -337,12 +337,12 @@
</cf> ""
<cite> + ".\[\n[ID]\n.\]" +
-</cite>
+</cite>
<ncite> + ".\[\n[ID]\n.\]\n([NOTE])"
</ncite>
-<footnote> " (-- "
+<footnote> " (-- "
</footnote> "--)" +
<sq> "\\*Q"
@@ -353,20 +353,20 @@
</lq> + ".nr LL \\n(LL+\\n(PI\n"
".RE" +
-<em> "\\fI"
-</em> "\\fP"
+<em> "\\fI"
+</em> "\\fP"
-<bf> "\\fB"
-</bf> "\\fR"
+<bf> "\\fB"
+</bf> "\\fR"
-<it> "\\fI"
-</it> "\\fR"
+<it> "\\fI"
+</it> "\\fR"
-<sf> "\\fR"
-</sf> "\\fR"
+<sf> "\\fR"
+</sf> "\\fR"
-<sl> "\\fI"
-</sl> "\\fR"
+<sl> "\\fI"
+</sl> "\\fR"
% Changed by mdw
<tt> "\\fC"
@@ -394,10 +394,10 @@
<pageref> "??"
</pageref>
-<x>
+<x>
</x>
-<mc>
+<mc>
</mc>
<biblio> + ".\[\n"
@@ -423,7 +423,7 @@
% ".Pp" + % continue previous paragraph (changed mdw)
".LP"
-% tscreen added by mdw
+% tscreen added by mdw
<tscreen> + ".br\n"
".po 0.75i\n"
".ll 6.0i\n"
@@ -487,8 +487,8 @@
% mathematics -- this nroff version needs work.
-<f>
-</f>
+<f>
+</f>
<dm> + ".DS L" +
</dm> + ".DE" +
@@ -496,8 +496,8 @@
<eq> + ".DS L" +
</eq> + ".DE" +
-<fr>
-</fr>
+<fr>
+</fr>
<nu> "{"
</nu> "} over "
@@ -505,7 +505,7 @@
<de> "{"
</de> "}"
-<lim>
+<lim>
</lim>
<op>
@@ -527,7 +527,7 @@
</in>
<sum> " sum "
-</sum>
+</sum>
% limitation: eqn only does square roots!
@@ -539,7 +539,7 @@
"[ca]." +
</ar> + ".TE" +
-<arr> "\n"
+<arr> "\n"
</arr>
<arc> "|"
@@ -567,8 +567,8 @@
% limitation: no calligraphic characters, using helvetica italics instead. Is there a better font?
-<fi> "\\fI"
-</fi> "\\fP"
+<fi> "\\fI"
+</fi> "\\fP"
<phr> " roman }"
</phr> "}"
@@ -584,12 +584,12 @@
<eps> + ".if t .PSPIC [file].ps\n"
".if n .sp 4" +
-</eps>
-
+</eps>
+
% Are TeX units properly handled by this translation of ph?
<ph> + ".sp [VSPACE]" +
-</ph>
+</ph>
<caption> + ".sp\n.ce" +
</caption>
@@ -619,7 +619,7 @@
<slides> + ".nr PS 18" +
</slides>
-<slide>
+<slide>
</slide> + ".bp\n\\&" +
% letters -- replacement for email, using mh format.
diff --git a/doc/sbase/dist/birddoc/html/mapping b/doc/sbase/dist/birddoc/html/mapping
index 353d7774..1f05070c 100644
--- a/doc/sbase/dist/birddoc/html/mapping
+++ b/doc/sbase/dist/birddoc/html/mapping
@@ -21,7 +21,7 @@
</notes> + "<@@enddoc>" +
% Manual Pages are expected to be formatted using nroff (or groff), unless
-% they are included as sections of other qwertz documents.
+% they are included as sections of other qwertz documents.
<manpage>
</manpage>
@@ -35,7 +35,7 @@
<title> + "<@@title>"
</title>
-<subtitle> + "<H2>"
+<subtitle> + "<H2>"
</subtitle> "</H2>" +
<author>
@@ -48,26 +48,27 @@
</and>
<thanks> + "Thanks "
-</thanks>
+</thanks>
<inst> + "<H3>"
</inst> "</H3>" +
<newline> "<BR>"
-
+
<label> + "<@@label>[ID]" +
-
-<header>
-</header>
+</label>
+
+<header>
+</header>
<lhead> + "<!-- "
-</lhead> " -->" +
+</lhead> " -->" +
<rhead> + "<!-- "
</rhead> " -->" +
<comment> + "<H4>Comment</H4>" +
-</comment>
+</comment>
<abstract> + "<P><HR>\n<EM>"
</abstract> "</EM>\n<HR>" +
@@ -99,7 +100,7 @@
<sect3> + "<@@head>"
</sect3>
-<sect4> + "<@@head>"
+<sect4> + "<@@head>"
</sect4>
<heading>
@@ -134,6 +135,9 @@
<ncite> "[<I>[NOTE] ([ID])</I>]"
</ncite>
+<file> "<CODE>"
+</file> "</CODE>"
+
<footnote> + "<BLOCKQUOTE>"
</footnote> "</BLOCKQUOTE>" +
@@ -198,12 +202,14 @@
"<@@endurl>" +
</url>
-<htmlurl> + "<@@url>[URL]\n"
- "[NAME]</A>\n"
- "<@@endurl>" +
+<htmlurl> "<A HREF=\"[URL]\">[NAME]</A>"
</htmlurl>
-% ref modified to have an optional name field
+<rfc> "<A HREF=\"http://www.rfc-editor.org/info/rfc[ID]\">RFC [ID]</A>"
+</rfc>
+
+
+% ref modified to have an optional name field
<ref> + "<@@ref>[ID]\n"
"[NAME]</A>\n"
"<@@endref>" +
@@ -228,7 +234,7 @@
</mc> "</MC>"
<biblio> + "<BIBLIO STYLE=\"[STYLE]\" FILES=\"[FILES]\">" +
-</biblio>
+</biblio>
<code> + "<HR>\n<PRE>" +
</code> + "</PRE>\n<HR>" +
@@ -244,28 +250,28 @@
% theorems and such
-<def> + "<DEF>"
+<def> + "<DEF>"
</def> + "</DEF>" +
-<prop> + "<PROP>"
+<prop> + "<PROP>"
</prop> + "</PROP>" +
-<lemma> + "<LEMMA>"
+<lemma> + "<LEMMA>"
</lemma> + "</LEMMA>" +
-<coroll> + "<COROLL>"
+<coroll> + "<COROLL>"
</coroll> + "</COROLL>" +
-<proof> + "<PROOF>"
+<proof> + "<PROOF>"
</proof> + "</PROOF>" +
-<theorem> + "<THEOREM>"
+<theorem> + "<THEOREM>"
</theorem> + "</THEOREM>" +
<thtag> "<THTAG>"
</thtag> "</THTAG>"
-% mathematics
+% mathematics
<f>
</f>
@@ -315,11 +321,11 @@
<ar> "<AR>"
</ar> "</AR>"
-<arr> "<ARR>"
-</arr>
+<arr> "<ARR>"
+</arr>
<arc> "<ARC>"
-</arc>
+</arc>
<sup> "<SUP>"
</sup> "</SUP>"
@@ -354,13 +360,13 @@
</figure> + "</FIGURE>" +
<eps> + "<EPS FILE=\"[FILE]\">" +
-</eps>
-
+</eps>
+
<img> + "<IMG SRC=\"[SRC]\">" +
</img>
<ph> + "<PH VSPACE=\"[VSPACE]\">" +
-</ph>
+</ph>
<caption> + "<CAPTION>"
</caption> "</CAPTION>" +
@@ -403,7 +409,7 @@
</opening> "</OPENING>" +
-<from> + "<FROM>"
+<from> + "<FROM>"
</from> + "</FROM>" +
@@ -419,7 +425,7 @@
<email> + "<EMAIL>"
</email> "</EMAIL>" +
-<phone> + "<PHONE>"
+<phone> + "<PHONE>"
</phone> "</PHONE>" +
@@ -430,16 +436,16 @@
</subject> "</SUBJECT>" +
-<sref> + "<SREF>"
+<sref> + "<SREF>"
</sref> "</SREF>" +
-<rref> + "<RREF>"
+<rref> + "<RREF>"
</rref> "</RREF>" +
<rdate> + "<RDATE>"
</rdate> "</RDATE>" +
-<closing> + "<CLOSING>"
+<closing> + "<CLOSING>"
</closing> "</CLOSING>" +
<cc> + "<CC>"
diff --git a/doc/sbase/dist/birddoc/latex2e/mapping b/doc/sbase/dist/birddoc/latex2e/mapping
index 747d0d33..f53bbbe4 100644
--- a/doc/sbase/dist/birddoc/latex2e/mapping
+++ b/doc/sbase/dist/birddoc/latex2e/mapping
@@ -2,7 +2,9 @@
% birddoc to LaTeX replacement file
% The \relax is there to avoid sgml2latex rewriting the class
-<book> + "\\relax\\documentclass\[a4paper,10pt,openany\]{book}\n"
+<book> + "\\relax\\documentclass\[a4paper,10pt,openany,oneside\]{book}\n"
+ "\\usepackage\[colorlinks=true,linkcolor=blue,pdftitle={BIRD User's Guide}\]{hyperref}\n"
+ "\\usepackage{enumitem}\n"
"\\usepackage{birddoc}\n"
"\\usepackage{qwertz}\n"
"\\usepackage{url}\n"
@@ -14,7 +16,7 @@
</book> + "\\end{document}" +
% Manual Pages are expected to be formatted using nroff (or groff), unless
-% they are included as sections of other qwertz documents.
+% they are included as sections of other qwertz documents.
<manpage>
</manpage>
@@ -26,17 +28,17 @@
</titlepag> + "\n\n\\begin{document}\n"
"\\maketitle\n" +
-<title> + "\\title{"
+<title> + "\\title{"
</title> "}" +
<subtitle> "\\\\\n"
"{\\large "
</subtitle> "}" +
-<author> + "\\author{"
+<author> + "\\author{"
</author> "}" +
-<name>
+<name>
</name>
<and> "\\and " +
@@ -51,14 +53,14 @@
<date> + "\\date{"
</date> "}" +
-<newline> "\\\\ "
+<newline> "\\\\ "
</newline>
<label> "\\label{[ID]}"
-</label>
+</label>
<header> + "\\markboth"
-</header>
+</header>
<lhead> "{"
</lhead> "}"
@@ -73,7 +75,7 @@
</comment> "}"
% Hacked by mdw to use linuxdoc-sgml \abstract{...}
-<abstract> + "\\abstract{"
+<abstract> + "\\abstract{"
</abstract> "}" +
<appendix> + "\n \\appendix \n" +
@@ -101,15 +103,15 @@
</sect2>
<sect3> + "\n\\paragraph"
-</sect3>
+</sect3>
<sect4> + "\n\\subparagraph"
</sect4>
<heading> "{"
-</heading> "}\n\n"
+</heading> "}\n\n"
-<p>
+<p> "\\phantomsection{}"
</p> "\n\n"
<itemize> + "\\begin{itemize}" +
@@ -121,13 +123,13 @@
<list> + "\\begin{list}{}{}\n" +
</list> + "\\end{list}" +
-<descrip> + "\\begin{description}" +
+<descrip> + "\\begin{description}\[style=unboxed\]" +
</descrip> + "\\end{description}" +
<item> + "\\item "
</item>
-<tag> + "\\item\[{\\ttfamily "
+<tag> + "\\phantomsection\\item\[{\\ttfamily "
</tag> "}\] \\hfil\\break\n" +
<tagp> + "\\item\[ "
@@ -154,7 +156,7 @@
% The idea here is to automatically insert soft hyphens after every slash in
% the filename, so long filenames will break naturally. The url{} macro is
% a kluge but it works,
-<file> "\\url{"
+<file> "{\\tt "
</file> "}"
<footnote> "\\footnote{"
@@ -223,29 +225,32 @@
<cparam> "\\cparam{"
</cparam> "}"
-<ref> "\\ref{[ID]} {([NAME])}"
+<ref> "\\hyperref\[[ID]\]{[NAME]} (p.\\,\\getpagerefnumber{[ID]})"
</ref>
<pageref> "\\pageref{[ID]}"
</pageref>
%url added by HG
-<url> "\\nameurl{[URL]}{[NAME]}"
+<url> "\\href{[URL]}{[NAME]}"
</url>
-<htmlurl> "\\onlynameurl{[NAME]}"
+<htmlurl> "\\href{[URL]}{[NAME]}"
</htmlurl>
-<x>
+<rfc> "\\href{http://www.rfc-editor.org/info/rfc[ID]}{RFC [ID]}"
+</rfc>
+
+<x>
</x>
-<mc>
+<mc>
</mc>
<biblio> + "\\bibliographystyle{[STYLE]}\n"
"\\bibliography{[FILES]}\n"
"\\addbibtoc{}" +
-</biblio>
+</biblio>
% <macro> + "\\macro{[ID]}{\\qw[ID]}"
% </macro>
@@ -300,19 +305,19 @@
<thtag> "\["
</thtag> "\]" +
-% mathematics
+% mathematics
<f> "$"
</f> "$"
-<dm> + "\\\["
+<dm> + "\\\["
</dm> "\\\]" +
<eq> + "\\begin{equation}" +
</eq> + "\\end{equation}\n" +
<fr> "\\frac"
-</fr>
+</fr>
<nu> "{"
</nu> "}"
@@ -320,7 +325,7 @@
<de> "{"
</de> "}"
-<lim>
+<lim>
</lim>
<op>
@@ -342,7 +347,7 @@
</in>
<sum> "\\sum"
-</sum>
+</sum>
<root> "\\sqrt\[[n]\]{"
</root> "}"
@@ -390,11 +395,11 @@
</figure> + "\\end{figure}\n" +
<eps> + "\\centerline{\\epsfig{file=[FILE],height=[HEIGHT],angle=[ANGLE]}}" +
-</eps>
-
+</eps>
+
<ph> + "\\vspace{[VSPACE]}\n\\par" +
-</ph>
+</ph>
<caption> + "\\caption{"
</caption> "}" +
diff --git a/doc/sbase/dist/fmt_latex2e.pl b/doc/sbase/dist/fmt_latex2e.pl
index 1f121743..d0656b7d 100644
--- a/doc/sbase/dist/fmt_latex2e.pl
+++ b/doc/sbase/dist/fmt_latex2e.pl
@@ -284,11 +284,11 @@ $latex2e->{postASP} = sub
# for nameurl
if ( /\\nameurl/ )
{
- ($urlid, $urlnam) = ($_ =~ /\\nameurl{(.*)}{(.*)}/);
+ ($urlid, $urlnam) = ($_ =~ /\\nameurl\{(.*)\}\{(.*)\}/);
print $urlnum . ": " . $urlid . "\n" if ( $global->{debug} );
$urldef = latex2e_defnam($urlnum) . "url";
- s/\\nameurl{.*}{.*}/{\\em $urlnam} {\\tt \\$urldef}/;
+ s/\\nameurl\{.*\}\{.*\}/{\\em $urlnam} {\\tt \\$urldef}/;
push @urlnames, $_;
push @urldefines, "\\urldef{\\$urldef} \\url{$urlid}\n";
$urlnum++;
diff --git a/doc/sbase/dtd/birddoc.dtd b/doc/sbase/dtd/birddoc.dtd
index 9cedcacc..1db2af6c 100644
--- a/doc/sbase/dtd/birddoc.dtd
+++ b/doc/sbase/dtd/birddoc.dtd
@@ -1,6 +1,6 @@
<!-- This is a DTD, but will be read as -*- sgml -*- -->
<!-- ================================================= -->
-<!-- $Id$
+<!-- $Id$
This was heavilly modified for use with bird! Don't you dare to use it
anywhere else. <pavel@ucw.cz>
@@ -79,7 +79,7 @@ anywhere else. <pavel@ucw.cz>
weren't in the original linuxdoc 1.3 DTD, and are
superseded by the new if/unless facility. -->
<!-- BK/97/05/09: this is the original Linuxdoc DTD,
- as of SGML Tools 0.99.0. It is not longer
+ as of SGML Tools 0.99.0. It is not longer
supported. Use only if in dire need, for backwards
compabitlity. Backend support for undocumented
QWERTZ leftovers not in the strict Linuxdoc DTD's
@@ -92,36 +92,36 @@ anywhere else. <pavel@ucw.cz>
any changes to this, just replacing. -->
<!-- ================================================= -->
-<!entity % emph
+<!entity % emph
" em|it|bf|sf|sl|tt|cf|m|cparam|const|func|struct|param|type|funcdef " >
<!entity % index "idx|cdx|nidx|ncdx" >
<!-- url added by HG; htmlurl added by esr -->
<!entity % xref
- " label|ref|pageref|cite|url|htmlurl|ncite " >
+ " label|ref|pageref|cite|url|htmlurl|rfc|ncite " >
-<!entity % inline
+<!entity % inline
" (#pcdata | f| x| %emph; |sq| %xref | %index | file )* " >
-<!entity % list
+<!entity % list
" list | itemize | enum | descrip " >
-<!entity % par
+<!entity % par
" %list; | comment | lq | quote | tscreen | hrule " >
<!entity % mathpar " dm | eq " >
-<!entity % thrm
+<!entity % thrm
" def | prop | lemma | coroll | proof | theorem " >
<!entity % litprog " code | verb " >
-<!entity % sectpar
- " %par; | figure | tabular | table | %mathpar; |
+<!entity % sectpar
+ " %par; | figure | tabular | table | %mathpar; |
%thrm; | %litprog; | function ">
-<!element birddoc o o
- (sect | chapt | article | report |
+<!element birddoc o o
+ (sect | chapt | article | report |
book | letter | telefax | slides | notes | manpage ) >
<!-- `general' entity replaced with ISO entities - kwm -->
@@ -150,7 +150,7 @@ anywhere else. <pavel@ucw.cz>
<!element hrule - - EMPTY>
<!shortref pmap
- "&#RS;B" null
+ "&#RS;B" null
"&#RS;B&#RE;" psplit
"&#RS;&#RE;" psplit
-- '"' qtag --
@@ -189,7 +189,7 @@ anywhere else. <pavel@ucw.cz>
<!entity ftag '<f>' -- formula begin -- >
<!entity qendtag '</sq>'>
-<!shortref sqmap
+<!shortref sqmap
"&#RS;B" null
-- '"' qendtag --
"[" lsqb
@@ -249,7 +249,7 @@ anywhere else. <pavel@ucw.cz>
<!shortref bodymap
"&#RS;B&#RE;" ptag
"&#RS;&#RE;" ptag
- '"' qtag
+ '"' qtag
"[" lsqb
"~" nbsp
"_" lowbar
@@ -285,7 +285,7 @@ anywhere else. <pavel@ucw.cz>
<!shortref oneline
"B&#RE;" space
- "&#RS;&#RE;" null
+ "&#RS;&#RE;" null
"&#RS;B&#RE;" null
-- '"' qtag --
"[" ftag
@@ -302,7 +302,7 @@ anywhere else. <pavel@ucw.cz>
<!usemap oneline caption>
<!entity % tabrow "(%inline, (colsep, %inline)*)" >
-<!element tabular - -
+<!element tabular - -
(hline?, %tabrow, (rowsep, hline?, %tabrow)*, caption?) >
<!attlist tabular
@@ -323,7 +323,7 @@ anywhere else. <pavel@ucw.cz>
"B&#RE;" null
"BB" space
"@" rowsep
- "|" colsep
+ "|" colsep
"[" ftag
-- '"' qtag --
"_" thinsp
@@ -344,7 +344,7 @@ anywhere else. <pavel@ucw.cz>
<!shortref ttmap -- also on one-line --
"B&#RE;" space
- "&#RS;&#RE;" null
+ "&#RS;&#RE;" null
"&#RS;B&#RE;" null
"&#RS;B" null
'#' num
@@ -365,14 +365,14 @@ anywhere else. <pavel@ucw.cz>
<!entity % limits "pr|in|sum" >
<!entity % fbu "fr|lim|ar|root" >
<!entity % fph "unl|ovl|sup|inf" >
-<!entity % fbutxt "(%fbu;) | (%limits;) |
+<!entity % fbutxt "(%fbu;) | (%limits;) |
(%fcstxt;)|(%fscs;)|(%fph;)" >
<!entity % fphtxt "p|#pcdata" >
<!element f - - ((%fbutxt;)*) >
<!entity fendtag '</f>' -- formula end -- >
-<!shortref fmap
+<!shortref fmap
"&#RS;B" null
"&#RS;B&#RE;" null
"&#RS;&#RE;" null
@@ -432,7 +432,7 @@ anywhere else. <pavel@ucw.cz>
<!shortref arrmap
"&#RE;" space
"@" arr
- "|" arc
+ "|" arc
"_" thinsp
"~" nbsp
"#" num
@@ -448,7 +448,7 @@ anywhere else. <pavel@ucw.cz>
<!element ovl - - ((%fbutxt;)*) >
<!element rf - o (#pcdata) >
<!element phr - o ((%fphtxt;)*) >
-<!element v - o ((%fcstxt;)*)
+<!element v - o ((%fcstxt;)*)
-(tu|%limits;|%fbu;|%fph;) >
<!element fi - o (#pcdata) >
<!element tu - o empty >
@@ -468,7 +468,7 @@ anywhere else. <pavel@ucw.cz>
<!shortref global
"&#RS;B" null -- delete leading blanks --
- -- '"' qtag --
+ -- '"' qtag --
"[" ftag
"~" nbsp
"_" lowbar
@@ -485,22 +485,26 @@ anywhere else. <pavel@ucw.cz>
<!-- ref modified to have an optional name field HG -->
<!element ref - o empty>
-<!attlist ref
+<!attlist ref
id cdata #required
name cdata "&refnam">
<!-- url entity added to have direct url references HG -->
<!element url - o empty>
-<!attlist url
+<!attlist url
url cdata #required
name cdata "&urlnam" >
<!-- htmlurl entity added to have quieter url references esr -->
<!element htmlurl - o empty>
-<!attlist htmlurl
+<!attlist htmlurl
url cdata #required
name cdata "&urlnam" >
+<!element rfc - o empty>
+<!attlist rfc
+ id cdata #required>
+
<!element pageref - o empty>
<!attlist pageref
id cdata #required>
@@ -510,22 +514,22 @@ anywhere else. <pavel@ucw.cz>
<!-- Hacked by mdw to exclude abstract; abstract now part of titlepag -->
<!element article - -
- (titlepag, header?,
- toc?, lof?, lot?, p*, sect*,
+ (titlepag, header?,
+ toc?, lof?, lot?, p*, sect*,
(appendix, sect+)?, biblio?) +(footnote)>
<!attlist article
opts cdata "null">
<!-- Hacked by mdw to exclude abstract; abstract now part of titlepag -->
-<!element report - -
+<!element report - -
(titlepag, header?, toc?, lof?, lot?, p*,
chapt*, (appendix, chapt+)?, biblio?) +(footnote)>
<!attlist report
opts cdata "null">
-<!element book - -
- (titlepag, header?, toc?, lof?, lot?, p*, chapt*,
+<!element book - -
+ (titlepag, header?, toc?, lof?, lot?, p*, chapt*,
(appendix, chapt+)?, biblio?) +(footnote) >
<!attlist book
@@ -536,7 +540,7 @@ anywhere else. <pavel@ucw.cz>
<!element title - o (%inline, subtitle?) +(newline)>
<!element subtitle - o (%inline)>
<!usemap oneline titlepag>
-<!element author - o (name, thanks?, inst?,
+<!element author - o (name, thanks?, inst?,
(and, name, thanks?, inst?)*)>
<!element name o o (%inline) +(newline)>
<!element and - o empty>
@@ -545,9 +549,9 @@ anywhere else. <pavel@ucw.cz>
<!element date - o (#pcdata) >
<!usemap global thanks>
-
+
<!element newline - o empty >
-<!entity nl "<newline>">
+<!entity nl "<newline>">
<!element progdoc - o empty>
@@ -564,9 +568,9 @@ anywhere else. <pavel@ucw.cz>
<!element rhead - o (%inline)>
<!entity % sect "heading, header?, p* " >
<!element heading o o (%inline)>
-<!element chapt - o (%sect, sect*) +(footnote)>
+<!element chapt - o (%sect, sect*) +(footnote)>
<!element sect - o (%sect, sect1*) +(footnote)>
-<!element sect1 - o (%sect, sect2*)>
+<!element sect1 - o (%sect, sect2*) +(footnote)>
<!element sect2 - o (%sect, sect3*)>
<!element sect3 - o (%sect, sect4*)>
<!element sect4 - o (%sect)>
@@ -575,11 +579,11 @@ anywhere else. <pavel@ucw.cz>
<!element footnote - - (%inline)>
<!usemap global footnote>
<!element cite - o empty>
-<!attlist cite
+<!attlist cite
id cdata #required>
<!element ncite - o empty>
-<!attlist ncite
+<!attlist ncite
id cdata #required
note cdata #required>
@@ -599,41 +603,41 @@ anywhere else. <pavel@ucw.cz>
<!attlist slides
opts cdata "null">
<!element slide - o (title?, p+) >
-<!entity % addr "(address?, email?, phone?, fax?)" >
-
-<!element letter - -
+<!entity % addr "(address?, email?, phone?, fax?)" >
+
+<!element letter - -
(from, %addr, to, %addr, cc?, subject?, sref?, rref?,
rdate?, opening, p+, closing, encl?, ps?)>
<!attlist letter
opts cdata "null">
-
+
<!element from - o (#pcdata) >
<!element to - o (#pcdata) >
-
+
<!usemap oneline (from,to)>
-
+
<!element address - o (#pcdata) +(newline) >
<!element email - o (#pcdata) >
<!element phone - o (#pcdata) >
<!element fax - o (#pcdata) >
-
+
<!element subject - o (%inline;) >
<!element sref - o (#pcdata) >
<!element rref - o (#pcdata) >
<!element rdate - o (#pcdata) >
-
+
<!element opening - o (%inline;) >
<!usemap oneline opening>
-
+
<!element closing - o (%inline;) >
<!element cc - o (%inline;) +(newline) >
<!element encl - o (%inline;) +(newline) >
-
+
<!element ps - o (p+) >
-<!element telefax - -
- (from, %addr, to, address, email?,
+<!element telefax - -
+ (from, %addr, to, address, email?,
phone?, fax, cc?, subject?,
opening, p+, closing, ps?)>
@@ -644,8 +648,8 @@ anywhere else. <pavel@ucw.cz>
<!element notes - - (title?, p+) >
<!attlist notes
opts cdata "null" >
-<!element manpage - - (sect1*)
- -(sect2 | f | %mathpar | figure | tabular |
+<!element manpage - - (sect1*)
+ -(sect2 | f | %mathpar | figure | tabular |
table | %xref | %thrm )>
@@ -673,5 +677,5 @@ anywhere else. <pavel@ucw.cz>
<!--
Local Variables:
mode: sgml
- End: -->
+ End: -->
<!-- ================================================= -->
diff --git a/filter/Makefile b/filter/Makefile
index f27befdf..6bada8ca 100644
--- a/filter/Makefile
+++ b/filter/Makefile
@@ -2,3 +2,7 @@ src := filter.c f-util.c tree.c trie.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_src := tree_test.c filter_test.c trie_test.c
+tests_targets := $(tests_targets) $(tests-target-files)
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/filter/config.Y b/filter/config.Y
index 79247ac9..7b4178be 100644
--- a/filter/config.Y
+++ b/filter/config.Y
@@ -36,6 +36,7 @@ f_valid_set_type(int type)
case T_ENUM:
case T_IP:
case T_EC:
+ case T_LC:
return 1;
default:
@@ -66,6 +67,14 @@ f_merge_items(struct f_tree *a, struct f_tree *b)
static inline struct f_tree *
f_new_pair_item(int fa, int ta, int fb, int tb)
{
+ check_u16(fa);
+ check_u16(ta);
+ check_u16(fb);
+ check_u16(tb);
+
+ if ((ta < fa) || (tb < fb))
+ cf_error( "From value cannot be higher that To value in pair sets");
+
struct f_tree *t = f_new_tree();
t->right = t;
t->from.type = t->to.type = T_PAIR;
@@ -77,22 +86,26 @@ f_new_pair_item(int fa, int ta, int fb, int tb)
static inline struct f_tree *
f_new_pair_set(int fa, int ta, int fb, int tb)
{
- struct f_tree *lst = NULL;
- int i;
+ check_u16(fa);
+ check_u16(ta);
+ check_u16(fb);
+ check_u16(tb);
- if ((fa == ta) || ((fb == 0) && (tb == 0xFFFF)))
- return f_new_pair_item(fa, ta, fb, tb);
-
if ((ta < fa) || (tb < fb))
cf_error( "From value cannot be higher that To value in pair sets");
+ struct f_tree *lst = NULL;
+ int i;
+
for (i = fa; i <= ta; i++)
lst = f_merge_items(lst, f_new_pair_item(i, i, fb, tb));
return lst;
}
+#define CC_ALL 0xFFFF
#define EC_ALL 0xFFFFFFFF
+#define LC_ALL 0xFFFFFFFF
static struct f_tree *
f_new_ec_item(u32 kind, u32 ipv4_used, u32 key, u32 vf, u32 vt)
@@ -132,6 +145,17 @@ f_new_ec_item(u32 kind, u32 ipv4_used, u32 key, u32 vf, u32 vt)
return t;
}
+static struct f_tree *
+f_new_lc_item(u32 f1, u32 t1, u32 f2, u32 t2, u32 f3, u32 t3)
+{
+ struct f_tree *t = f_new_tree();
+ t->right = t;
+ t->from.type = t->to.type = T_LC;
+ t->from.val.lc = (lcomm) {f1, f2, f3};
+ t->to.val.lc = (lcomm) {t1, t2, t3};
+ return t;
+}
+
static inline struct f_inst *
f_generate_empty(struct f_inst *dyn)
{
@@ -148,6 +172,9 @@ f_generate_empty(struct f_inst *dyn)
case EAF_TYPE_EC_SET:
e->aux = T_ECLIST;
break;
+ case EAF_TYPE_LC_SET:
+ e->aux = T_LCLIST;
+ break;
default:
cf_error("Can't empty that attribute");
}
@@ -266,14 +293,108 @@ f_generate_ec(u16 kind, struct f_inst *tk, struct f_inst *tv)
return rv;
}
+static inline struct f_inst *
+f_generate_lc(struct f_inst *t1, struct f_inst *t2, struct f_inst *t3)
+{
+ struct f_inst *rv;
+ if ((t1->code == 'c') && (t2->code == 'c') && (t3->code == 'c')) {
+ if ((t1->aux != T_INT) || (t2->aux != T_INT) || (t3->aux != T_INT))
+ cf_error( "LC - Can't operate with value of non-integer type in tuple constructor");
+
+ rv = f_new_inst();
+ rv->code = 'C';
+
+ NEW_F_VAL;
+ rv->a1.p = val;
+ val->type = T_LC;
+ val->val.lc = (lcomm) { t1->a2.i, t2->a2.i, t3->a2.i };
+ }
+ else
+ {
+ rv = cfg_allocz(sizeof(struct f_inst3));
+ rv->lineno = ifs->lino;
+ rv->code = P('m','l');
+ rv->a1.p = t1;
+ rv->a2.p = t2;
+ INST3(rv).p = t3;
+ }
+
+ return rv;
+}
+
+/*
+ * Remove all new lines and doubled whitespaces
+ * and convert all tabulators to spaces
+ * and return a copy of string
+ */
+char *
+assert_copy_expr(const char *start, size_t len)
+{
+ /* XXX: Allocates maybe a little more memory than we really finally need */
+ char *str = cfg_alloc(len + 1);
+
+ char *dst = str;
+ const char *src = start - 1;
+ const char *end = start + len;
+ while (++src < end)
+ {
+ if (*src == '\n')
+ continue;
+
+ /* Skip doubled whitespaces */
+ if (src != start)
+ {
+ const char *prev = src - 1;
+ if ((*src == ' ' || *src == '\t') && (*prev == ' ' || *prev == '\t'))
+ continue;
+ }
+
+ if (*src == '\t')
+ *dst = ' ';
+ else
+ *dst = *src;
+
+ dst++;
+ }
+ *dst = '\0';
+
+ return str;
+}
+
+/*
+ * assert_done - create f_instruction of bt_assert
+ * @expr: expression in bt_assert()
+ * @start: pointer to first char of test expression
+ * @end: pointer to the last char of test expression
+ */
+static struct f_inst *
+assert_done(struct f_inst *expr, const char *start, const char *end)
+{
+ struct f_inst *i;
+ i = f_new_inst();
+ i->code = P('a','s');
+ i->a1.p = expr;
+
+ if (end >= start)
+ {
+ i->a2.p = assert_copy_expr(start, end - start + 1);
+ }
+ else
+ {
+ /* this is a break of lexer buffer */
+ i->a2.p = "???";
+ }
+
+ return i;
+}
CF_DECLS
CF_KEYWORDS(FUNCTION, PRINT, PRINTN, UNSET, RETURN,
ACCEPT, REJECT, ERROR, QUITBIRD,
- INT, BOOL, IP, PREFIX, PAIR, QUAD, EC,
- SET, STRING, BGPMASK, BGPPATH, CLIST, ECLIST,
+ INT, BOOL, IP, PREFIX, PAIR, QUAD, EC, LC,
+ SET, STRING, BGPMASK, BGPPATH, CLIST, ECLIST, LCLIST,
IF, THEN, ELSE, CASE,
TRUE, FALSE, RT, RO, UNKNOWN, GENERIC,
FROM, GW, NET, MASK, PROTO, SOURCE, SCOPE, CAST, DEST, IFNAME, IFINDEX,
@@ -284,21 +405,23 @@ CF_KEYWORDS(FUNCTION, PRINT, PRINTN, UNSET, RETURN,
ADD, DELETE, CONTAINS, RESET,
PREPEND, FIRST, LAST, LAST_NONAGGREGATED, MATCH,
EMPTY,
- FILTER, WHERE, EVAL)
+ FILTER, WHERE, EVAL,
+ BT_ASSERT, BT_TEST_SUITE, FORMAT)
%nonassoc THEN
%nonassoc ELSE
%type <x> term block cmds cmds_int cmd function_body constant constructor print_one print_list var_list var_listn dynamic_attr static_attr function_call symbol bgp_path_expr
%type <f> filter filter_body where_filter
-%type <i> type break_command pair_expr ec_kind
-%type <i32> pair_atom ec_expr
-%type <e> pair_item ec_item set_item switch_item set_items switch_items switch_body
+%type <i> type break_command ec_kind
+%type <i32> cnum
+%type <e> pair_item ec_item lc_item set_item switch_item set_items switch_items switch_body
%type <trie> fprefix_set
%type <v> set_atom switch_atom fipa
%type <px> fprefix
%type <s> decls declsn one_decl function_params
%type <h> bgp_path bgp_path_tail1 bgp_path_tail2
+%type <t> get_cf_position
CF_GRAMMAR
@@ -318,6 +441,21 @@ filter_eval:
EVAL term { f_eval_int($2); }
;
+CF_ADDTO(conf, bt_test_suite)
+bt_test_suite:
+ BT_TEST_SUITE '(' SYM ',' text ')' {
+ if (!($3->class & SYM_FUNCTION))
+ cf_error("Function expected");
+
+ struct f_bt_test_suite *t = cfg_alloc(sizeof(struct f_bt_test_suite));
+ t->fn = $3->def;
+ t->fn_name = $3->name;
+ t->dsc = $5;
+
+ add_tail(&new_config->tests, &t->n);
+ }
+ ;
+
type:
INT { $$ = T_INT; }
| BOOL { $$ = T_BOOL; }
@@ -326,17 +464,20 @@ type:
| PAIR { $$ = T_PAIR; }
| QUAD { $$ = T_QUAD; }
| EC { $$ = T_EC; }
+ | LC { $$ = T_LC; }
| STRING { $$ = T_STRING; }
| BGPMASK { $$ = T_PATH_MASK; }
| BGPPATH { $$ = T_PATH; }
| CLIST { $$ = T_CLIST; }
| ECLIST { $$ = T_ECLIST; }
- | type SET {
+ | LCLIST { $$ = T_LCLIST; }
+ | type SET {
switch ($1) {
case T_INT:
case T_PAIR:
case T_QUAD:
case T_EC:
+ case T_LC:
case T_IP:
$$ = T_SET;
break;
@@ -445,7 +586,7 @@ function_def:
} function_params function_body {
$2->def = $5;
$2->aux2 = $4;
- DBG("Hmm, we've got one function here - %s\n", $2->name);
+ DBG("Hmm, we've got one function here - %s\n", $2->name);
cf_pop_scope();
}
;
@@ -511,30 +652,23 @@ switch_atom:
| ENUM { $$.type = pair_a($1); $$.val.i = pair_b($1); }
;
-pair_expr:
- term { $$ = f_eval_int($1); check_u16($$); }
-
-pair_atom:
- pair_expr { $$ = pair($1, $1); }
- | pair_expr DDOT pair_expr { $$ = pair($1, $3); }
- | '*' { $$ = 0xFFFF; }
- ;
+cnum:
+ term { $$ = f_eval_int($1); }
pair_item:
- '(' pair_atom ',' pair_atom ')' {
- $$ = f_new_pair_set(pair_a($2), pair_b($2), pair_a($4), pair_b($4));
- }
- | '(' pair_atom ',' pair_atom ')' DDOT '(' pair_expr ',' pair_expr ')' {
- /* Hack: $2 and $4 should be pair_expr, but that would cause shift/reduce conflict */
- if ((pair_a($2) != pair_b($2)) || (pair_a($4) != pair_b($4)))
- cf_error("syntax error");
- $$ = f_new_pair_item(pair_b($2), $8, pair_b($4), $10);
- }
+ '(' cnum ',' cnum ')' { $$ = f_new_pair_item($2, $2, $4, $4); }
+ | '(' cnum ',' cnum DDOT cnum ')' { $$ = f_new_pair_item($2, $2, $4, $6); }
+ | '(' cnum ',' '*' ')' { $$ = f_new_pair_item($2, $2, 0, CC_ALL); }
+ | '(' cnum DDOT cnum ',' cnum ')' { $$ = f_new_pair_set($2, $4, $6, $6); }
+ | '(' cnum DDOT cnum ',' cnum DDOT cnum ')' { $$ = f_new_pair_set($2, $4, $6, $8); }
+ | '(' cnum DDOT cnum ',' '*' ')' { $$ = f_new_pair_item($2, $4, 0, CC_ALL); }
+ | '(' '*' ',' cnum ')' { $$ = f_new_pair_set(0, CC_ALL, $4, $4); }
+ | '(' '*' ',' cnum DDOT cnum ')' { $$ = f_new_pair_set(0, CC_ALL, $4, $6); }
+ | '(' '*' ',' '*' ')' { $$ = f_new_pair_item(0, CC_ALL, 0, CC_ALL); }
+ | '(' cnum ',' cnum ')' DDOT '(' cnum ',' cnum ')'
+ { $$ = f_new_pair_item($2, $8, $4, $10); }
;
-ec_expr:
- term { $$ = f_eval_int($1); }
-
ec_kind:
RT { $$ = EC_RT; }
| RO { $$ = EC_RO; }
@@ -543,14 +677,27 @@ ec_kind:
;
ec_item:
- '(' ec_kind ',' ec_expr ',' ec_expr ')' { $$ = f_new_ec_item($2, 0, $4, $6, $6); }
- | '(' ec_kind ',' ec_expr ',' ec_expr DDOT ec_expr ')' { $$ = f_new_ec_item($2, 0, $4, $6, $8); }
- | '(' ec_kind ',' ec_expr ',' '*' ')' { $$ = f_new_ec_item($2, 0, $4, 0, EC_ALL); }
+ '(' ec_kind ',' cnum ',' cnum ')' { $$ = f_new_ec_item($2, 0, $4, $6, $6); }
+ | '(' ec_kind ',' cnum ',' cnum DDOT cnum ')' { $$ = f_new_ec_item($2, 0, $4, $6, $8); }
+ | '(' ec_kind ',' cnum ',' '*' ')' { $$ = f_new_ec_item($2, 0, $4, 0, EC_ALL); }
;
+lc_item:
+ '(' cnum ',' cnum ',' cnum ')' { $$ = f_new_lc_item($2, $2, $4, $4, $6, $6); }
+ | '(' cnum ',' cnum ',' cnum DDOT cnum ')' { $$ = f_new_lc_item($2, $2, $4, $4, $6, $8); }
+ | '(' cnum ',' cnum ',' '*' ')' { $$ = f_new_lc_item($2, $2, $4, $4, 0, LC_ALL); }
+ | '(' cnum ',' cnum DDOT cnum ',' '*' ')' { $$ = f_new_lc_item($2, $2, $4, $6, 0, LC_ALL); }
+ | '(' cnum ',' '*' ',' '*' ')' { $$ = f_new_lc_item($2, $2, 0, LC_ALL, 0, LC_ALL); }
+ | '(' cnum DDOT cnum ',' '*' ',' '*' ')' { $$ = f_new_lc_item($2, $4, 0, LC_ALL, 0, LC_ALL); }
+ | '(' '*' ',' '*' ',' '*' ')' { $$ = f_new_lc_item(0, LC_ALL, 0, LC_ALL, 0, LC_ALL); }
+ | '(' cnum ',' cnum ',' cnum ')' DDOT '(' cnum ',' cnum ',' cnum ')'
+ { $$ = f_new_lc_item($2, $10, $4, $12, $6, $14); }
+;
+
set_item:
pair_item
| ec_item
+ | lc_item
| set_atom { $$ = f_new_item($1, $1); }
| set_atom DDOT set_atom { $$ = f_new_item($1, $3); }
;
@@ -558,6 +705,7 @@ set_item:
switch_item:
pair_item
| ec_item
+ | lc_item
| switch_atom { $$ = f_new_item($1, $1); }
| switch_atom DDOT switch_atom { $$ = f_new_item($1, $3); }
;
@@ -608,7 +756,7 @@ switch_body: /* EMPTY */ { $$ = NULL; }
/* CONST '(' expr ')' { $$ = f_new_inst(); $$->code = 'c'; $$->aux = T_INT; $$->a2.i = $3; } */
bgp_path_expr:
- symbol { $$ = $1; }
+ symbol { $$ = $1; }
| '(' term ')' { $$ = $2; }
;
@@ -618,16 +766,17 @@ bgp_path:
;
bgp_path_tail1:
- NUM bgp_path_tail1 { $$ = cfg_alloc(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASN; $$->val = $1; }
- | '*' bgp_path_tail1 { $$ = cfg_alloc(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASTERISK; $$->val = 0; }
- | '?' bgp_path_tail1 { $$ = cfg_alloc(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_QUESTION; $$->val = 0; }
- | bgp_path_expr bgp_path_tail1 { $$ = cfg_alloc(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASN_EXPR; $$->val = (uintptr_t) $1; }
- | { $$ = NULL; }
+ NUM bgp_path_tail1 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASN; $$->val = $1; }
+ | NUM DDOT NUM bgp_path_tail1 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $4; $$->kind = PM_ASN_RANGE; $$->val = $1; $$->val2 = $3; }
+ | '*' bgp_path_tail1 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASTERISK; }
+ | '?' bgp_path_tail1 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_QUESTION; }
+ | bgp_path_expr bgp_path_tail1 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASN_EXPR; $$->val = (uintptr_t) $1; }
+ | { $$ = NULL; }
;
bgp_path_tail2:
- NUM bgp_path_tail2 { $$ = cfg_alloc(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASN; $$->val = $1; }
- | '?' bgp_path_tail2 { $$ = cfg_alloc(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASTERISK; $$->val = 0; }
+ NUM bgp_path_tail2 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASN; $$->val = $1; }
+ | '?' bgp_path_tail2 { $$ = cfg_allocz(sizeof(struct f_path_mask)); $$->next = $2; $$->kind = PM_ASTERISK; }
| { $$ = NULL; }
;
@@ -647,6 +796,7 @@ constant:
constructor:
'(' term ',' term ')' { $$ = f_generate_dpair($2, $4); }
| '(' ec_kind ',' term ',' term ')' { $$ = f_generate_ec($2, $4, $6); }
+ | '(' term ',' term ',' term ')' { $$ = f_generate_lc($2, $4, $6); }
;
@@ -725,6 +875,7 @@ term:
| term '>' term { $$ = f_new_inst(); $$->code = '<'; $$->a1.p = $3; $$->a2.p = $1; }
| term GEQ term { $$ = f_new_inst(); $$->code = P('<','='); $$->a1.p = $3; $$->a2.p = $1; }
| term '~' term { $$ = f_new_inst(); $$->code = '~'; $$->a1.p = $1; $$->a2.p = $3; }
+ | term NMA term { $$ = f_new_inst(); $$->code = P('!','~'); $$->a1.p = $1; $$->a2.p = $3; }
| '!' term { $$ = f_new_inst(); $$->code = '!'; $$->a1.p = $2; }
| DEFINED '(' term ')' { $$ = f_new_inst(); $$->code = P('d','e'); $$->a1.p = $3; }
@@ -758,14 +909,17 @@ term:
| '+' EMPTY '+' { $$ = f_new_inst(); $$->code = 'E'; $$->aux = T_PATH; }
| '-' EMPTY '-' { $$ = f_new_inst(); $$->code = 'E'; $$->aux = T_CLIST; }
| '-' '-' EMPTY '-' '-' { $$ = f_new_inst(); $$->code = 'E'; $$->aux = T_ECLIST; }
- | PREPEND '(' term ',' term ')' { $$ = f_new_inst(); $$->code = P('A','p'); $$->a1.p = $3; $$->a2.p = $5; }
- | ADD '(' term ',' term ')' { $$ = f_new_inst(); $$->code = P('C','a'); $$->a1.p = $3; $$->a2.p = $5; $$->aux = 'a'; }
+ | '-' '-' '-' EMPTY '-' '-' '-' { $$ = f_new_inst(); $$->code = 'E'; $$->aux = T_LCLIST; }
+ | PREPEND '(' term ',' term ')' { $$ = f_new_inst(); $$->code = P('A','p'); $$->a1.p = $3; $$->a2.p = $5; }
+ | ADD '(' term ',' term ')' { $$ = f_new_inst(); $$->code = P('C','a'); $$->a1.p = $3; $$->a2.p = $5; $$->aux = 'a'; }
| DELETE '(' term ',' term ')' { $$ = f_new_inst(); $$->code = P('C','a'); $$->a1.p = $3; $$->a2.p = $5; $$->aux = 'd'; }
| FILTER '(' term ',' term ')' { $$ = f_new_inst(); $$->code = P('C','a'); $$->a1.p = $3; $$->a2.p = $5; $$->aux = 'f'; }
| ROA_CHECK '(' rtable ')' { $$ = f_generate_roa_check($3, NULL, NULL); }
| ROA_CHECK '(' rtable ',' term ',' term ')' { $$ = f_generate_roa_check($3, $5, $7); }
+ | FORMAT '(' term ')' { $$ = f_new_inst(); $$->code = P('f','m'); $$->a1.p = $3; }
+
/* | term '.' LEN { $$->code = P('P','l'); } */
/* function_call is inlined here */
@@ -814,7 +968,7 @@ print_list: /* EMPTY */ { $$ = NULL; }
}
;
-var_listn: term {
+var_listn: term {
$$ = f_new_inst();
$$->code = 's';
$$->a1.p = NULL;
@@ -882,7 +1036,7 @@ cmd:
$$ = f_new_inst();
$$->code = P('P','S');
$$->a1.p = $3;
- }
+ }
| UNSET '(' rtadot dynamic_attr ')' ';' {
$$ = $4;
$$->aux = EAF_TYPE_UNDEF | EAF_TEMP;
@@ -898,12 +1052,18 @@ cmd:
$$->a2.p = build_tree( $4 );
}
-
| rtadot dynamic_attr '.' EMPTY ';' { $$ = f_generate_empty($2); }
| rtadot dynamic_attr '.' PREPEND '(' term ')' ';' { $$ = f_generate_complex( P('A','p'), 'x', $2, $6 ); }
| rtadot dynamic_attr '.' ADD '(' term ')' ';' { $$ = f_generate_complex( P('C','a'), 'a', $2, $6 ); }
| rtadot dynamic_attr '.' DELETE '(' term ')' ';' { $$ = f_generate_complex( P('C','a'), 'd', $2, $6 ); }
| rtadot dynamic_attr '.' FILTER '(' term ')' ';' { $$ = f_generate_complex( P('C','a'), 'f', $2, $6 ); }
+ | BT_ASSERT '(' get_cf_position term get_cf_position ')' ';' { $$ = assert_done($4, $3 + 1, $5 - 1); }
;
+get_cf_position:
+{
+ $$ = cf_text;
+};
+
+
CF_END
diff --git a/filter/filter.c b/filter/filter.c
index ebdd02f2..4ec04554 100644
--- a/filter/filter.c
+++ b/filter/filter.c
@@ -52,6 +52,8 @@
#define CMP_ERROR 999
+void (*bt_assert_hook)(int result, struct f_inst *assert);
+
static struct adata *
adata_empty(struct linpool *pool, int l)
{
@@ -81,6 +83,10 @@ pm_format(struct f_path_mask *p, buffer *buf)
buffer_puts(buf, "* ");
break;
+ case PM_ASN_RANGE:
+ buffer_print(buf, "%u..%u ", p->val, p->val2);
+ break;
+
case PM_ASN_EXPR:
buffer_print(buf, "%u ", f_eval_asn((struct f_inst *) p->val));
break;
@@ -95,6 +101,18 @@ pm_format(struct f_path_mask *p, buffer *buf)
static inline int val_is_ip4(const struct f_val v)
{ return (v.type == T_IP) && ipa_is_ip4(v.val.ip); }
+static inline int
+lcomm_cmp(lcomm v1, lcomm v2)
+{
+ if (v1.asn != v2.asn)
+ return (v1.asn > v2.asn) ? 1 : -1;
+ if (v1.ldp1 != v2.ldp1)
+ return (v1.ldp1 > v2.ldp1) ? 1 : -1;
+ if (v1.ldp2 != v2.ldp2)
+ return (v1.ldp2 > v2.ldp2) ? 1 : -1;
+ return 0;
+}
+
/**
* val_compare - compare two values
* @v1: first value
@@ -134,6 +152,8 @@ val_compare(struct f_val v1, struct f_val v2)
return uint_cmp(v1.val.i, v2.val.i);
case T_EC:
return u64_cmp(v1.val.ec, v2.val.ec);
+ case T_LC:
+ return lcomm_cmp(v1.val.lc, v2.val.lc);
case T_IP:
return ipa_compare(v1.val.ip, v2.val.ip);
case T_NET:
@@ -146,18 +166,29 @@ val_compare(struct f_val v1, struct f_val v2)
}
static int
-pm_path_same(struct f_path_mask *m1, struct f_path_mask *m2)
+pm_same(struct f_path_mask *m1, struct f_path_mask *m2)
{
while (m1 && m2)
{
- if ((m1->kind != m2->kind) || (m1->val != m2->val))
+ if (m1->kind != m2->kind)
return 0;
+ if (m1->kind == PM_ASN_EXPR)
+ {
+ if (!i_same((struct f_inst *) m1->val, (struct f_inst *) m2->val))
+ return 0;
+ }
+ else
+ {
+ if ((m1->val != m2->val) || (m1->val2 != m2->val2))
+ return 0;
+ }
+
m1 = m1->next;
m2 = m2->next;
}
- return !m1 && !m2;
+ return !m1 && !m2;
}
/**
@@ -182,10 +213,11 @@ val_same(struct f_val v1, struct f_val v2)
switch (v1.type) {
case T_PATH_MASK:
- return pm_path_same(v1.val.path_mask, v2.val.path_mask);
+ return pm_same(v1.val.path_mask, v2.val.path_mask);
case T_PATH:
case T_CLIST:
case T_ECLIST:
+ case T_LCLIST:
return adata_same(v1.val.ad, v2.val.ad);
case T_SET:
return same_tree(v1.val.t, v2.val.t);
@@ -226,6 +258,10 @@ static inline int
eclist_set_type(struct f_tree *set)
{ return set->from.type == T_EC; }
+static inline int
+lclist_set_type(struct f_tree *set)
+{ return set->from.type == T_LC; }
+
static int
clist_match_set(struct adata *clist, struct f_tree *set)
{
@@ -271,6 +307,30 @@ eclist_match_set(struct adata *list, struct f_tree *set)
return 0;
}
+static int
+lclist_match_set(struct adata *list, struct f_tree *set)
+{
+ if (!list)
+ return 0;
+
+ if (!lclist_set_type(set))
+ return CMP_ERROR;
+
+ struct f_val v;
+ u32 *l = int_set_get_data(list);
+ int len = int_set_get_size(list);
+ int i;
+
+ v.type = T_LC;
+ for (i = 0; i < len; i += 3) {
+ v.val.lc = lc_get(l, i);
+ if (find_tree(set, v))
+ return 1;
+ }
+
+ return 0;
+}
+
static struct adata *
clist_filter(struct linpool *pool, struct adata *list, struct f_val set, int pos)
{
@@ -297,7 +357,7 @@ clist_filter(struct linpool *pool, struct adata *list, struct f_val set, int pos
*k++ = v.val.i;
}
- int nl = (k - tmp) * 4;
+ uint nl = (k - tmp) * sizeof(u32);
if (nl == list->length)
return list;
@@ -331,7 +391,39 @@ eclist_filter(struct linpool *pool, struct adata *list, struct f_val set, int po
}
}
- int nl = (k - tmp) * 4;
+ uint nl = (k - tmp) * sizeof(u32);
+ if (nl == list->length)
+ return list;
+
+ struct adata *res = adata_empty(pool, nl);
+ memcpy(res->data, tmp, nl);
+ return res;
+}
+
+static struct adata *
+lclist_filter(struct linpool *pool, struct adata *list, struct f_val set, int pos)
+{
+ if (!list)
+ return NULL;
+
+ int tree = (set.type == T_SET); /* 1 -> set is T_SET, 0 -> set is T_CLIST */
+ struct f_val v;
+
+ int len = int_set_get_size(list);
+ u32 *l = int_set_get_data(list);
+ u32 tmp[len];
+ u32 *k = tmp;
+ int i;
+
+ v.type = T_LC;
+ for (i = 0; i < len; i += 3) {
+ v.val.lc = lc_get(l, i);
+ /* pos && member(val, set) || !pos && !member(val, set), member() depends on tree */
+ if ((tree ? !!find_tree(set.val.t, v) : lc_set_contains(set.val.ad, v.val.lc)) == pos)
+ k = lc_copy(k, l+i);
+ }
+
+ uint nl = (k - tmp) * sizeof(u32);
if (nl == list->length)
return list;
@@ -366,6 +458,9 @@ val_in_range(struct f_val v1, struct f_val v2)
if ((v1.type == T_EC) && (v2.type == T_ECLIST))
return ec_set_contains(v2.val.ad, v1.val.ec);
+ if ((v1.type == T_LC) && (v2.type == T_LCLIST))
+ return lc_set_contains(v2.val.ad, v1.val.lc);
+
if ((v1.type == T_STRING) && (v2.type == T_STRING))
return patmatch(v2.val.s, v1.val.s);
@@ -392,6 +487,9 @@ val_in_range(struct f_val v1, struct f_val v2)
if (v1.type == T_ECLIST)
return eclist_match_set(v1.val.ad, v2.val.t);
+ if (v1.type == T_LCLIST)
+ return lclist_match_set(v1.val.ad, v2.val.t);
+
if (v1.type == T_PATH)
return as_path_match_set(v1.val.ad, v2.val.t);
@@ -416,12 +514,14 @@ val_format(struct f_val v, buffer *buf)
case T_PAIR: buffer_print(buf, "(%u,%u)", v.val.i >> 16, v.val.i & 0xffff); return;
case T_QUAD: buffer_print(buf, "%R", v.val.i); return;
case T_EC: ec_format(buf2, v.val.ec); buffer_print(buf, "%s", buf2); return;
+ case T_LC: lc_format(buf2, v.val.lc); buffer_print(buf, "%s", buf2); return;
case T_PREFIX_SET: trie_format(v.val.ti, buf); return;
case T_SET: tree_format(v.val.t, buf); return;
case T_ENUM: buffer_print(buf, "(enum %x)%u", v.type, v.val.i); return;
case T_PATH: as_path_format(v.val.ad, buf2, 1000); buffer_print(buf, "(path %s)", buf2); return;
case T_CLIST: int_set_format(v.val.ad, 1, -1, buf2, 1000); buffer_print(buf, "(clist %s)", buf2); return;
case T_ECLIST: ec_set_format(v.val.ad, -1, buf2, 1000); buffer_print(buf, "(eclist %s)", buf2); return;
+ case T_LCLIST: lc_set_format(v.val.ad, -1, buf2, 1000); buffer_print(buf, "(lclist %s)", buf2); return;
case T_PATH_MASK: pm_format(v.val.path_mask, buf); return;
default: buffer_print(buf, "[unknown type %x]", v.type); return;
}
@@ -463,10 +563,18 @@ f_rta_cow(void)
(*f_rte)->attrs = rta_do_cow((*f_rte)->attrs, f_pool);
}
+static char *
+val_format_str(struct f_val v) {
+ buffer b;
+ LOG_BUFFER_INIT(b);
+ val_format(v, &b);
+ return lp_strdup(f_pool, b.start);
+}
+
static struct tbf rl_runtime_err = TBF_DEFAULT_LOG_LIMITS;
-#define runtime(x) do { \
- log_rl(&rl_runtime_err, L_ERR "filters, line %d: %s", what->lineno, x); \
+#define runtime(fmt, ...) do { \
+ log_rl(&rl_runtime_err, L_ERR "filters, line %d: " fmt, what->lineno, ##__VA_ARGS__); \
res.type = T_RETURN; \
res.val.i = F_ERROR; \
return res; \
@@ -613,6 +721,7 @@ interpret(struct f_inst *what)
runtime("Can't operate with value of non-integer type in EC constructor");
val = v2.val.i;
+ /* XXXX */
res.type = T_EC;
if (what->aux == EC_GENERIC) {
@@ -634,6 +743,24 @@ interpret(struct f_inst *what)
break;
}
+ case P('m','l'):
+ {
+ TWOARGS;
+
+ /* Third argument hack */
+ struct f_val v3 = interpret(INST3(what).p);
+ if (v3.type & T_RETURN)
+ return v3;
+
+ if ((v1.type != T_INT) || (v2.type != T_INT) || (v3.type != T_INT))
+ runtime( "Can't operate with value of non-integer type in LC constructor" );
+
+ res.type = T_LC;
+ res.val.lc = (lcomm) { v1.val.i, v2.val.i, v3.val.i };
+
+ break;
+ }
+
/* Relational operators */
#define COMPARE(x) \
@@ -673,6 +800,16 @@ interpret(struct f_inst *what)
runtime( "~ applied on unknown type pair" );
res.val.i = !!res.val.i;
break;
+
+ case P('!','~'):
+ TWOARGS;
+ res.type = T_BOOL;
+ res.val.i = val_in_range(v1, v2);
+ if (res.val.i == CMP_ERROR)
+ runtime( "!~ applied on unknown type pair" );
+ res.val.i = !res.val.i;
+ break;
+
case P('d','e'):
ONEARG;
res.type = T_BOOL;
@@ -858,6 +995,13 @@ interpret(struct f_inst *what)
break;
}
+ /* The same special case for lc_set */
+ if ((what->aux & EAF_TYPE_MASK) == EAF_TYPE_LC_SET) {
+ res.type = T_LCLIST;
+ res.val.ad = adata_empty(f_pool, 0);
+ break;
+ }
+
/* Undefined value */
res.type = T_VOID;
break;
@@ -897,6 +1041,10 @@ interpret(struct f_inst *what)
res.type = T_ECLIST;
res.val.ad = e->u.ptr;
break;
+ case EAF_TYPE_LC_SET:
+ res.type = T_LCLIST;
+ res.val.ad = e->u.ptr;
+ break;
case EAF_TYPE_UNDEF:
res.type = T_VOID;
break;
@@ -917,7 +1065,7 @@ interpret(struct f_inst *what)
l->count = 1;
l->attrs[0].id = code;
l->attrs[0].flags = 0;
- l->attrs[0].type = what->aux | EAF_ORIGINATED;
+ l->attrs[0].type = what->aux | EAF_ORIGINATED | EAF_FRESH;
switch (what->aux & EAF_TYPE_MASK) {
case EAF_TYPE_INT:
@@ -985,6 +1133,11 @@ interpret(struct f_inst *what)
runtime( "Setting eclist attribute to non-eclist value" );
l->attrs[0].u.ptr = v1.val.ad;
break;
+ case EAF_TYPE_LC_SET:
+ if (v1.type != T_LCLIST)
+ runtime( "Setting lclist attribute to non-lclist value" );
+ l->attrs[0].u.ptr = v1.val.ad;
+ break;
case EAF_TYPE_UNDEF:
if (v1.type != T_VOID)
runtime( "Setting void attribute to non-void value" );
@@ -1026,6 +1179,7 @@ interpret(struct f_inst *what)
case T_PATH: res.val.i = as_path_getlen(v1.val.ad); break;
case T_CLIST: res.val.i = int_set_get_size(v1.val.ad); break;
case T_ECLIST: res.val.i = ec_set_get_size(v1.val.ad); break;
+ case T_LCLIST: res.val.i = lc_set_get_size(v1.val.ad); break;
default: runtime( "Prefix, path, clist or eclist expected" );
}
break;
@@ -1235,7 +1389,7 @@ interpret(struct f_inst *what)
else if (v2.type == T_ECLIST)
arg_set = 2;
else if (v2.type != T_EC)
- runtime("Can't add/delete non-pair");
+ runtime("Can't add/delete non-ec");
res.type = T_ECLIST;
switch (what->aux)
@@ -1266,8 +1420,50 @@ interpret(struct f_inst *what)
bug("unknown Ca operation");
}
}
+ else if (v1.type == T_LCLIST)
+ {
+ /* Large community list */
+ int arg_set = 0;
+
+ /* v2.val is either LC or LC-set */
+ if ((v2.type == T_SET) && lclist_set_type(v2.val.t))
+ arg_set = 1;
+ else if (v2.type == T_LCLIST)
+ arg_set = 2;
+ else if (v2.type != T_LC)
+ runtime("Can't add/delete non-lc");
+
+ res.type = T_LCLIST;
+ switch (what->aux)
+ {
+ case 'a':
+ if (arg_set == 1)
+ runtime("Can't add set");
+ else if (!arg_set)
+ res.val.ad = lc_set_add(f_pool, v1.val.ad, v2.val.lc);
+ else
+ res.val.ad = lc_set_union(f_pool, v1.val.ad, v2.val.ad);
+ break;
+
+ case 'd':
+ if (!arg_set)
+ res.val.ad = lc_set_del(f_pool, v1.val.ad, v2.val.lc);
+ else
+ res.val.ad = lclist_filter(f_pool, v1.val.ad, v2, 0);
+ break;
+
+ case 'f':
+ if (!arg_set)
+ runtime("Can't filter lc");
+ res.val.ad = lclist_filter(f_pool, v1.val.ad, v2, 1);
+ break;
+
+ default:
+ bug("unknown Ca operation");
+ }
+ }
else
- runtime("Can't add/delete to non-(e)clist");
+ runtime("Can't add/delete to non-[e|l]clist");
break;
@@ -1312,6 +1508,24 @@ interpret(struct f_inst *what)
break;
+ case P('f','m'): /* Format */
+ ONEARG;
+
+ res.type = T_STRING;
+ res.val.s = val_format_str(v1);
+ break;
+
+ case P('a','s'): /* Birdtest Assert */
+ ONEARG;
+
+ if (v1.type != T_BOOL)
+ runtime("Should be boolean value");
+
+ res.type = v1.type;
+ res.val = v1.val;
+
+ CALL(bt_assert_hook, res.val.i, what);
+ break;
default:
bug( "Unknown instruction %d (%c)", what->code, what->code & 0xff);
@@ -1368,6 +1582,12 @@ i_same(struct f_inst *f1, struct f_inst *f2)
case '~': TWOARGS; break;
case P('d','e'): ONEARG; break;
+ case P('m','l'):
+ TWOARGS;
+ if (!i_same(INST3(f1).p, INST3(f2).p))
+ return 0;
+ break;
+
case 's':
ARG(v2, a2.p);
{
@@ -1438,7 +1658,8 @@ i_same(struct f_inst *f1, struct f_inst *f2)
case P('A','p'): TWOARGS; break;
case P('C','a'): TWOARGS; break;
case P('a','f'):
- case P('a','l'): ONEARG; break;
+ case P('a','l'):
+ case P('a','L'): ONEARG; break;
#if 0
case P('R','C'):
TWOARGS;
diff --git a/filter/filter.h b/filter/filter.h
index af490121..a4808731 100644
--- a/filter/filter.h
+++ b/filter/filter.h
@@ -16,16 +16,16 @@
struct f_inst { /* Instruction */
struct f_inst *next; /* Structure is 16 bytes, anyway */
- u16 code;
- u16 aux;
+ u16 code; /* Instruction code, see the interpret() function and P() macro */
+ u16 aux; /* Extension to instruction code, T_*, EA_*, EAF_* */
union {
int i;
void *p;
- } a1;
+ } a1; /* The first argument */
union {
int i;
void *p;
- } a2;
+ } a2; /* The second argument */
int lineno;
};
@@ -38,16 +38,28 @@ struct f_inst_roa_check {
struct rtable_config *rtc;
};
+struct f_inst3 {
+ struct f_inst i;
+ union {
+ int i;
+ void *p;
+ } a3;
+};
+
+#define INST3(x) (((struct f_inst3 *) x)->a3)
+
+
struct f_prefix {
net_addr net;
u8 lo, hi;
};
struct f_val {
- int type;
+ int type; /* T_* */
union {
uint i;
u64 ec;
+ lcomm lc;
ip_addr ip;
const net_addr *net;
char *s;
@@ -146,8 +158,10 @@ void val_format(struct f_val v, buffer *buf);
#define T_PATH_MASK 0x23 /* mask for BGP path */
#define T_PATH 0x24 /* BGP path */
#define T_CLIST 0x25 /* Community list */
-#define T_ECLIST 0x26 /* Extended community list */
-#define T_EC 0x27 /* Extended community value, u64 */
+#define T_EC 0x26 /* Extended community value, u64 */
+#define T_ECLIST 0x27 /* Extended community list */
+#define T_LC 0x28 /* Large community value, lcomm */
+#define T_LCLIST 0x29 /* Large community list */
#define T_RETURN 0x40
#define T_SET 0x80
@@ -160,10 +174,10 @@ void val_format(struct f_val v, buffer *buf);
#define SA_PROTO 4
#define SA_SOURCE 5
#define SA_SCOPE 6
-#define SA_CAST 7
-#define SA_DEST 8
-#define SA_IFNAME 9
-#define SA_IFINDEX 10
+#define SA_CAST 7
+#define SA_DEST 8
+#define SA_IFNAME 9
+#define SA_IFINDEX 10
struct f_tree {
@@ -175,7 +189,7 @@ struct f_tree {
struct f_trie_node
{
ip_addr addr, mask, accept;
- int plen;
+ uint plen;
struct f_trie_node *c[2];
};
@@ -191,4 +205,15 @@ struct f_trie
#define FF_FORCE_TMPATTR 1 /* Force all attributes to be temporary */
+/* Bird Tests */
+struct f_bt_test_suite {
+ node n; /* Node in config->tests */
+ struct f_inst *fn; /* Root of function */
+ const char *fn_name; /* Name of test */
+ const char *dsc; /* Description */
+};
+
+/* Hook for call bt_assert() function in configuration */
+extern void (*bt_assert_hook)(int result, struct f_inst *assert);
+
#endif
diff --git a/filter/filter_test.c b/filter/filter_test.c
new file mode 100644
index 00000000..82efae0b
--- /dev/null
+++ b/filter/filter_test.c
@@ -0,0 +1,87 @@
+/*
+ * Filters: Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <string.h>
+#include <stdlib.h>
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "filter/filter.h"
+#include "conf/conf.h"
+
+#define BT_CONFIG_FILE "filter/test.conf"
+
+
+static struct config *
+parse_config_file(const void *filename_void)
+{
+ bt_bird_init();
+
+ size_t fn_size = strlen((const char *) filename_void) + 1;
+ char *filename = alloca(fn_size);
+ strncpy(filename, filename_void, fn_size);
+
+ struct config *c = bt_config_file_parse(filename);
+ bt_bird_cleanup();
+
+ return c;
+}
+
+static int
+run_function(const void *parsed_fn_def)
+{
+ /* XXX: const -> non-const */
+ struct f_inst *f = (struct f_inst *) parsed_fn_def;
+
+ linpool *tmp = lp_new(&root_pool, 4096);
+ struct f_val res = f_eval(f, tmp);
+ rfree(tmp);
+
+ if (res.type == T_RETURN && res.val.i >= F_REJECT)
+ return 0;
+
+ return 1;
+}
+
+static void
+bt_assert_filter(int result, struct f_inst *assert)
+{
+ int bt_suit_case_result = 1;
+ if (!result)
+ {
+ bt_result = 0;
+ bt_suite_result = 0;
+ bt_suit_case_result = 0;
+ }
+
+ bt_log_suite_case_result(bt_suit_case_result, "Assertion at line %d (%s)", assert->lineno, (char *) assert->a2.p);
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ struct config *c = parse_config_file(BT_CONFIG_FILE);
+
+ if (c)
+ {
+ bt_assert_hook = bt_assert_filter;
+
+ struct f_bt_test_suite *t;
+ WALK_LIST(t, c->tests)
+ bt_test_suite_base(run_function, t->fn_name, t->fn, BT_FORKING, BT_TIMEOUT, "%s", t->dsc);
+ }
+
+ return bt_exit_value();
+}
diff --git a/filter/test.conf b/filter/test.conf
index 8c820d4d..18aeaae1 100644
--- a/filter/test.conf
+++ b/filter/test.conf
@@ -1,170 +1,607 @@
-
/*
- * This is an example configuration file.
+ * This is unit testing configuration file for testing filters
+ *
* FIXME: add all examples from docs here.
*/
-# Yet another comment
-
router id 62.168.0.1;
-define xyzzy = (120+10);
-define '1a-a1' = (20+10);
-define one = 1;
-define ten = 10;
+/* We have to setup any protocol */
+protocol static { ipv4; }
-define p23 = (2, 3);
-define ip1222 = 1.2.2.2;
-define net10 = 10.0.0.0/8;
-define netdoc = 2001:db8::/32;
+/*
+ * Common definitions and functions
+ * --------------------------------
+ */
+
+define one = 1;
+define ten = 10;
+
function onef(int a)
{
return 1;
}
+
+
+/*
+ * Testing boolean expressions
+ * ---------------------------
+ */
+
+function t_bool()
+bool b;
+{
+ b = true;
+ bt_assert(b);
+ bt_assert(!!b);
+
+ bt_assert(format(true) = "TRUE");
+ bt_assert(format(false) = "FALSE");
+
+ if ( b = true ) then
+ bt_assert(b);
+ else
+ bt_assert(false);
+
+ bt_assert(true && true);
+ bt_assert(true || false);
+ bt_assert(! false && ! false && true);
+ bt_assert(1 < 2 && 1 != 3);
+ bt_assert(true && true && ! false);
+ bt_assert(true || 1+"a");
+ bt_assert(!(false && 1+"a"));
+ bt_assert(!(true && false));
+}
+
+bt_test_suite(t_bool, "Testing boolean expressions");
+
+
+
+
+/*
+ * Testing integers
+ * ----------------
+ */
+
+define four = 4;
+define xyzzy = (120+10);
+define '1a-a1' = (xyzzy-100);
+
+function t_int()
+int i;
+{
+ bt_assert(xyzzy = 130);
+ bt_assert('1a-a1' = 30);
+
+ i = four;
+ i = 12*100 + 60/2 + i;
+ i = (i + 0);
+ bt_assert(i = 1234);
+
+ bt_assert(format(i) = "1234");
+
+ i = 4200000000;
+ bt_assert(i = 4200000000);
+ bt_assert(i > 4100000000);
+ bt_assert(!(i > 4250000000));
+
+ bt_assert(1 = 1);
+ bt_assert(!(1 != 1));
+
+ bt_assert(1 != 2);
+ bt_assert(1 <= 2);
+
+ bt_assert(1 != "a");
+ bt_assert(1 != (0,1));
+
+ bt_assert(!(i = 4));
+ bt_assert(1 <= 1);
+ bt_assert(!(1234 < 1234));
+}
+
+bt_test_suite(t_int, "Testing integers");
+
+
+
+
+/*
+ * Testing sets of integers
+ * ------------------------
+ */
+
+define is1 = [ one, (2+1), (6-one), 8, 11, 15, 17, 19];
+define is2 = [(17+2), 17, 15, 11, 8, 5, 3, 2];
+define is3 = [5, 17, 2, 11, 8, 15, 3, 19];
+
+function t_int_set()
+int set is;
+{
+ bt_assert(1 ~ [1,2,3]);
+ bt_assert(5 ~ [1..20]);
+ bt_assert(2 ~ [ 1, 2, 3 ]);
+ bt_assert(5 ~ [ 4 .. 7 ]);
+ bt_assert(1 !~ [ 2, 3, 4 ]);
+
+ is = [ 2, 3, 4, 7..11 ];
+ bt_assert(10 ~ is);
+ bt_assert(5 !~ is);
+
+ bt_assert(1 ~ is1);
+ bt_assert(3 ~ is1);
+ bt_assert(5 ~ is1);
+ bt_assert((one+2) ~ is1);
+ bt_assert(2 ~ is2);
+ bt_assert(2 ~ is3);
+ bt_assert(4 !~ is1);
+ bt_assert(4 !~ is2);
+ bt_assert(4 !~ is3);
+ bt_assert(10 !~ is1);
+ bt_assert(10 !~ is2);
+ bt_assert(10 !~ is3);
+ bt_assert(15 ~ is1);
+ bt_assert(15 ~ is2);
+ bt_assert(15 ~ is3);
+ bt_assert(18 !~ is1);
+ bt_assert(18 !~ is2);
+ bt_assert(18 !~ is3);
+ bt_assert(19 ~ is1);
+ bt_assert(19 ~ is2);
+ bt_assert(19 ~ is3);
+ bt_assert(20 !~ is1);
+ bt_assert(20 !~ is2);
+ bt_assert(20 !~ is3);
+
+ bt_assert([1,2] != [1,3]);
+ bt_assert([1,4..10,20] = [1,4..10,20]);
+
+ bt_assert(format([ 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 5 ]) = "[1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5]");
+}
+
+bt_test_suite(t_int_set, "Testing sets of integers");
+
+
+
+
+/*
+ * Testing string matching
+ * -----------------------
+ */
+
+function t_string()
+string st;
+{
+ st = "Hello";
+ bt_assert(format(st) = "Hello");
+ bt_assert(st ~ "Hell*");
+ bt_assert(st ~ "?ello");
+ bt_assert(st ~ "Hello");
+ bt_assert(st ~ "Hell?");
+ bt_assert(st !~ "ell*");
+}
+
+bt_test_suite(t_string, "Testing string matching");
+
+
+
+
+/*
+ * Testing pairs
+ * -------------
+ */
+
function 'mkpair-a'(int a)
{
return (1, a);
}
-function mkpath(int a; int b)
+function t_pair()
+pair pp;
{
- return [= a b 3 2 1 =];
+ pp = (1, 2);
+ bt_assert(format(pp) = "(1,2)");
+ bt_assert((1,2) = pp);
+ bt_assert((1,1+1) = pp);
+ bt_assert('mkpair-a'(2) = pp);
+ bt_assert((1,2) = (1,1+1));
+ bt_assert(((1,2) < (2,2)));
+ bt_assert(!((1,1) > (1,1)));
}
-function callme(int arg1; int arg2)
-int local1;
-int local2;
-int i;
+bt_test_suite(t_pair, "Testing pairs");
+
+
+
+
+/*
+ * Testing sets of pairs
+ * ---------------------
+ */
+
+function t_pair_set()
+pair pp;
+pair set ps;
{
- printn "Function callme called arguments ", arg1, " and ", arg2, ": " ;
- i = arg2;
+ pp = (1, 2);
+ ps = [(1,(one+one)), (3,4)..(4,8), (5,*), (6,3..6)];
+ bt_assert(format(ps) = "[(1,2), (3,4)..(4,8), (5,0)..(5,65535), (6,3)..(6,6)]");
+ bt_assert(pp ~ ps);
+ bt_assert((3,5) ~ ps);
+ bt_assert((4,1) ~ ps);
+ bt_assert((5,4) ~ ps);
+ bt_assert((5,65535) ~ ps);
+ bt_assert((6,4) ~ ps);
+ bt_assert((3, 10000) ~ ps);
+ bt_assert((3,3) !~ ps);
+ bt_assert((4,9) !~ ps);
+ bt_assert((4,65535) !~ ps);
+ bt_assert((6,2) !~ ps);
+ bt_assert((6,6+one) !~ ps);
+ bt_assert(((one+6),2) !~ ps);
+ bt_assert((1,1) !~ ps);
- case arg1 {
- 11, 1, 111: printn "jedna, "; printn "jedna";
- (one+onef(2)): printn "dva, "; printn "jeste jednou dva";
- (2+one) .. 5: if arg2 < 3 then printn "tri az pet";
- else: printn "neco jineho";
- }
- print;
+ ps = [(20..150, 200..300), (50100..50200, 1000..50000), (*, 5+5)];
+ bt_assert((100,200) ~ ps);
+ bt_assert((150,300) ~ ps);
+ bt_assert((50180,1200) ~ ps);
+ bt_assert((50110,49000) ~ ps);
+ bt_assert((0,10) ~ ps);
+ bt_assert((64000,10) ~ ps);
+ bt_assert((20,199) !~ ps);
+ bt_assert((151,250) !~ ps);
+ bt_assert((50050,2000) !~ ps);
+ bt_assert((50150,50050) !~ ps);
+ bt_assert((10,9) !~ ps);
+ bt_assert((65535,11) !~ ps);
}
-function fifteen()
+bt_test_suite(t_pair_set, "Testing sets of pairs");
+
+
+
+
+/*
+ * Testing quads
+ * -------------
+ */
+
+function t_quad()
+quad qq;
{
- print "fifteen called";
- return 15;
+ qq = 1.2.3.4;
+ bt_assert(format(qq) = "1.2.3.4");
+ bt_assert(qq = 1.2.3.4);
+ bt_assert(qq != 4.3.2.1);
}
-roa4 table r4;
-roa6 table r6;
+bt_test_suite(t_quad, "Testing quads");
-protocol static
+
+
+
+/*
+ * Testing sets of quads
+ * ---------------------
+ */
+
+function t_quad_set()
+quad qq;
{
- roa4 { table r4; };
- route 10.110.0.0/16 max 16 as 1000 blackhole;
- route 10.120.0.0/16 max 24 as 1000 blackhole ;
- route 10.130.0.0/16 max 24 as 2000 blackhole;
- route 10.130.128.0/18 max 24 as 3000 blackhole;
+ qq = 1.2.3.4;
+ bt_assert(qq ~ [1.2.3.4, 5.6.7.8]);
+ bt_assert(qq !~ [1.2.1.1, 1.2.3.5]);
}
-protocol static
+bt_test_suite(t_quad_set, "Testing sets of quads");
+
+
+
+
+/*
+ * Testing ip address
+ * ------------------
+ */
+
+define onetwo = 1.2.3.4;
+
+function t_ip()
+ip p;
{
- roa6 { table r6; };
- route 2001:0db8:85a3:8a2e::/64 max 96 as 1000 blackhole;
+ p = 127.1.2.3;
+ bt_assert(p.mask(8) = 127.0.0.0);
+ bt_assert(1.2.3.4 = 1.2.3.4);
+ bt_assert(1.2.3.4 = onetwo);
+ bt_assert(format(p) = "127.1.2.3");
+
+ p = ::fffe:6:c0c:936d:88c7:35d3;
+ bt_assert(format(p) = "::fffe:6:c0c:936d:88c7:35d3");
+
+ p = 1234:5678::;
+ bt_assert(p.mask(24) = 1234:5600::);
}
-function test_roa_check()
+bt_test_suite(t_ip, "Testing ip address");
+
+
+
+
+/*
+ * Testing sets of ip address
+ * --------------------------
+ */
+
+define ip1222 = 1.2.2.2;
+
+function t_ip_set()
+ip set ips;
{
- # cannot be tested in __startup(), sorry
- print "Should be true: ", roa_check(r4, 10.10.0.0/16, 1000) = ROA_UNKNOWN,
- " ", roa_check(r4, 10.0.0.0/8, 1000) = ROA_UNKNOWN,
- " ", roa_check(r4, 10.110.0.0/16, 1000) = ROA_VALID,
- " ", roa_check(r4, 10.110.0.0/16, 2000) = ROA_INVALID,
- " ", roa_check(r4, 10.110.32.0/20, 1000) = ROA_INVALID,
- " ", roa_check(r4, 10.120.32.0/20, 1000) = ROA_VALID;
- print "Should be true: ", roa_check(r4, 10.120.32.0/20, 2000) = ROA_INVALID,
- " ", roa_check(r4, 10.120.32.32/28, 1000) = ROA_INVALID,
- " ", roa_check(r4, 10.130.130.0/24, 1000) = ROA_INVALID,
- " ", roa_check(r4, 10.130.130.0/24, 2000) = ROA_VALID,
- " ", roa_check(r4, 10.130.30.0/24, 3000) = ROA_INVALID,
- " ", roa_check(r4, 10.130.130.0/24, 3000) = ROA_VALID;
- print "Should be true: ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_VALID,
- " ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID,
- " ", roa_check(r6, 2001:0db8:85a3:8a2e::/64, 1000) = ROA_VALID,
- " ", roa_check(r6, 2001:0db8:85a3::/48, 1000) = ROA_UNKNOWN;
+ ips = [ 1.1.1.0 .. 1.1.1.255, ip1222];
+ bt_assert(format(ips) = "[1.1.1.0..1.1.1.255, 1.2.2.2]");
+ bt_assert(1.1.1.0 ~ ips);
+ bt_assert(1.1.1.100 ~ ips);
+ bt_assert(1.2.2.2 ~ ips);
+ bt_assert(1.1.0.255 !~ ips);
+ bt_assert(1.1.2.0 !~ ips);
+ bt_assert(1.2.2.3 !~ ips);
+ bt_assert(192.168.1.1 !~ ips);
+
+ bt_assert(1.2.3.4 !~ [ 1.2.3.3, 1.2.3.5 ]);
+ bt_assert(1.2.3.4 ~ [ 1.2.3.3..1.2.3.5 ]);
+}
- print "Should be true: ", roa_check(r4, 10.10.0.0/16, 1000) = ROA_UNKNOWN,
- " ", roa_check(r4, 10.0.0.0/8, 1000) = ROA_UNKNOWN,
- " ", roa_check(r4, 10.110.0.0/16, 1000) = ROA_VALID,
- " ", roa_check(r4, 10.110.0.0/16, 2000) = ROA_INVALID,
- " ", roa_check(r4, 10.110.32.0/20, 1000) = ROA_INVALID,
- " ", roa_check(r4, 10.120.32.0/20, 1000) = ROA_VALID;
+bt_test_suite(t_ip_set, "Testing sets of ip address");
- print "Should be true: ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_VALID,
- " ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID,
- " ", roa_check(r6, 2001:0db8:85a3:8a2e::/64, 1000) = ROA_VALID,
- " ", roa_check(r6, 2001:0db8:85a3::/48, 1000) = ROA_UNKNOWN;
- print "Should be true: ", roa_check(r4, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID ||
- roa_check(r6, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID;
- print "Should be false: ", roa_check(r4, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_INVALID ||
- roa_check(r6, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_INVALID,
- " ", roa_check(r4, 2001:0db8:85a3::/48, 1000) = ROA_INVALID ||
- roa_check(r6, 2001:0db8:85a3::/48, 1000) = ROA_INVALID;
- print "Should be true: ", 10.130.130.0/24 ~ 0.0.0.0/0,
- " ", 2001:0db8:85a3:8a2e::/64 ~ ::/0;
- print "Should be false: ", 10.130.130.0/24 ~ ::/0,
- " ", 2001:0db8:85a3:8a2e::/64 ~ 0.0.0.0/0;
+/*
+ * Testing enums
+ * -------------
+ */
+
+function t_enum()
+{
+ bt_assert(format(RTS_DUMMY) = "(enum 30)0");
+ bt_assert(format(RTS_STATIC) = "(enum 30)1");
+ bt_assert(RTS_STATIC ~ [RTS_STATIC, RTS_DEVICE]);
+ bt_assert(RTS_BGP !~ [RTS_STATIC, RTS_DEVICE]);
}
-function roa_operators_test()
-prefix pfx;
+bt_test_suite(t_enum, "Testing enums");
+
+
+
+
+/*
+ * Testing prefixes
+ * ----------------
+ */
+
+define netdoc = 2001:db8::/32;
+
+function t_prefix()
+prefix px;
{
- print "Testing ROA prefix operators '.maxlen' and '.asn':";
+ px = 1.2.0.0/18;
+ bt_assert(format(px) = "1.2.0.0/18");
+ bt_assert(192.168.0.0/16 ~ 192.168.0.0/16);
+ bt_assert(192.168.0.0/17 ~ 192.168.0.0/16);
+ bt_assert(192.168.254.0/24 ~ 192.168.0.0/16);
+ bt_assert(netdoc ~ 2001::/16);
+ bt_assert(192.168.0.0/15 !~ 192.168.0.0/16);
+ bt_assert(192.160.0.0/17 !~ 192.168.0.0/16);
+ bt_assert(px !~ netdoc);
+
+ bt_assert(1.2.3.4 ~ 1.0.0.0/8);
+ bt_assert(1.0.0.0/8 ~ 1.0.0.0/8);
+}
- pfx = 12.13.0.0/16 max 24 as 1234;
- print pfx;
- print "Should be true: ", pfx.len = 16, " ", pfx.maxlen = 24, " ", pfx.asn = 1234;
+bt_test_suite(t_prefix, "Testing prefixes");
- pfx = 1000::/8 max 32 as 1234;
- print pfx;
- print "Should be true: ", pfx.len = 8, " ", pfx.maxlen = 32, " ", pfx.asn = 1234;
+
+
+
+/*
+ * Testing prefix sets
+ * -------------------
+ */
+
+define net10 = 10.0.0.0/8;
+define pxs2 = [ 10.0.0.0/16{8,12}, 20.0.0.0/16{24,28} ];
+
+function test_pxset(prefix set pxs)
+{
+ bt_assert(net10 ~ pxs);
+ bt_assert(10.0.0.0/10 ~ pxs);
+ bt_assert(10.0.0.0/12 ~ pxs);
+ bt_assert(20.0.0.0/24 ~ pxs);
+ bt_assert(20.0.40.0/24 ~ pxs);
+ bt_assert(20.0.0.0/26 ~ pxs);
+ bt_assert(20.0.100.0/26 ~ pxs);
+ bt_assert(20.0.0.0/28 ~ pxs);
+ bt_assert(20.0.255.0/28 ~ pxs);
+
+ bt_assert(10.0.0.0/7 !~ pxs);
+ bt_assert(10.0.0.0/13 !~ pxs);
+ bt_assert(10.0.0.0/16 !~ pxs);
+ bt_assert(20.0.0.0/16 !~ pxs);
+ bt_assert(20.0.0.0/23 !~ pxs);
+ bt_assert(20.0.0.0/29 !~ pxs);
+ bt_assert(11.0.0.0/10 !~ pxs);
+ bt_assert(20.1.0.0/26 !~ pxs);
+
+ bt_assert(1.0.0.0/8 ~ [ 1.0.0.0/8+ ]);
+ bt_assert(1.0.0.0/9 !~ [ 1.0.0.0/8- ]);
+ bt_assert(1.2.0.0/17 !~ [ 1.0.0.0/8{ 15 , 16 } ]);
+
+ bt_assert([ 10.0.0.0/8{ 15 , 17 } ] = [ 10.0.0.0/8{ 15 , 17 } ]);
+}
+
+function t_prefix_set()
+prefix set pxs;
+{
+ pxs = [ 1.2.0.0/16, 1.4.0.0/16+];
+ bt_assert(format(pxs) = "[1.2.0.0/112{::0.1.0.0}, 1.4.0.0/112{::0.1.255.255}]");
+ bt_assert(1.2.0.0/16 ~ pxs);
+ bt_assert(1.4.0.0/16 ~ pxs);
+ bt_assert(1.4.0.0/18 ~ pxs);
+ bt_assert(1.4.0.0/32 ~ pxs);
+ bt_assert(1.1.0.0/16 !~ pxs);
+ bt_assert(1.3.0.0/16 !~ pxs);
+ bt_assert(1.2.0.0/15 !~ pxs);
+ bt_assert(1.2.0.0/17 !~ pxs);
+ bt_assert(1.2.0.0/32 !~ pxs);
+ bt_assert(1.4.0.0/15 !~ pxs);
+
+ test_pxset(pxs2);
+ test_pxset([ 10.0.0.0/16{8,12}, 20.0.0.0/16{24,28} ]);
+
+ bt_assert(1.2.0.0/16 ~ [ 1.0.0.0/8{ 15 , 17 } ]);
+ bt_assert([ 10.0.0.0/8{ 15 , 17 } ] != [ 11.0.0.0/8{ 15 , 17 } ]);
+}
+
+bt_test_suite(t_prefix_set, "Testing prefix sets");
+
+
+
+
+/*
+ * Testing Prefix IPv6
+ * -------------------
+ */
+
+function t_prefix6()
+prefix px;
+{
+ px = 1020::/18;
+ bt_assert(format(px) = "1020::/18");
+ bt_assert(1020:3040:5060:: ~ 1020:3040:5000::/40);
+ bt_assert(1020:3040::/32 ~ 1020:3040::/32);
+ bt_assert(1020:3040::/33 ~ 1020:3040::/32);
+ bt_assert(1020:3040:5060::/48 ~ 1020:3040::/32);
+ bt_assert(1020:3040::/31 !~ 1020:3040::/32);
+ bt_assert(1020:3041::/33 !~ 1020:3040::/32);
+}
+
+bt_test_suite(t_prefix6, "Testing prefix IPv6");
+
+
+
+
+/*
+ * Testing prefix IPv6 sets
+ * ------------------------
+ */
+
+function t_prefix6_set()
+prefix set pxs;
+{
+ bt_assert(1180::/16 ~ [ 1100::/8{15, 17} ]);
+ bt_assert(12::34 = 12::34);
+ bt_assert(12::34 ~ [ 12::33..12::35 ]);
+ bt_assert(1020::34 ~ 1000::/8);
+ bt_assert(1000::/8 ~ 1000::/8);
+ bt_assert(1000::/8 ~ [ 1000::/8+ ]);
+ bt_assert(12::34 !~ [ 12::33, 12::35 ]);
+ bt_assert(1000::/9 !~ [ 1000::/8- ]);
+ bt_assert(1000::/17 !~ [ 1000::/8{15, 16} ]);
+
+ pxs = [ 1102::/16, 1104::/16+];
+ bt_assert(1102::/16 ~ pxs);
+ bt_assert(1104::/16 ~ pxs);
+ bt_assert(1104::/18 ~ pxs);
+ bt_assert(1104::/32 ~ pxs);
+ bt_assert(1101::/16 !~ pxs);
+ bt_assert(1103::/16 !~ pxs);
+ bt_assert(1102::/15 !~ pxs);
+ bt_assert(1102::/17 !~ pxs);
+ bt_assert(1102::/32 !~ pxs);
+ bt_assert(1104::/15 !~ pxs);
+
+ pxs = ([ 1000::/16{8,12}, 2000::/16{24,28} ]);
+ bt_assert(format(pxs) = "[1000::/12{1f0::}, 2000::/16{0:1f0::}]");
+ bt_assert(1000::/8 ~ pxs);
+ bt_assert(1000::/10 ~ pxs);
+ bt_assert(1000::/12 ~ pxs);
+ bt_assert(2000::/24 ~ pxs);
+ bt_assert(2000:4000::/24 ~ pxs);
+ bt_assert(2000::/26 ~ pxs);
+ bt_assert(2000:8000::/26 ~ pxs);
+ bt_assert(2000::/28 ~ pxs);
+ bt_assert(2000:FFF0::/28 ~ pxs);
+ bt_assert(1000::/7 !~ pxs);
+ bt_assert(1000::/13 !~ pxs);
+ bt_assert(1000::/16 !~ pxs);
+ bt_assert(2000::/16 !~ pxs);
+ bt_assert(2000::/23 !~ pxs);
+ bt_assert(2000::/29 !~ pxs);
+ bt_assert(1100::/10 !~ pxs);
+ bt_assert(2010::/26 !~ pxs);
}
-function path_test()
+bt_test_suite(t_prefix6_set, "Testing prefix IPv6 sets");
+
+
+
+
+/*
+ * Testing Paths
+ * -------------
+ */
+
+function mkpath(int a; int b)
+{
+ return [= a b 3 2 1 =];
+}
+
+function t_path()
bgpmask pm1;
bgpmask pm2;
bgppath p2;
-clist l;
-clist l2;
-eclist el;
-eclist el2;
{
pm1 = / 4 3 2 1 /;
pm2 = [= 4 3 2 1 =];
- print "Testing path masks: ", pm1, " ", pm2;
+
+ bt_assert(pm1 = pm2);
+ bt_assert(format(pm2) = "[= 4 3 2 1 =]");
+
+ bt_assert(+empty+ = +empty+);
+ bt_assert(10 !~ +empty+);
+
p2 = prepend( + empty +, 1 );
p2 = prepend( p2, 2 );
p2 = prepend( p2, 3 );
p2 = prepend( p2, 4 );
- print "Testing paths: ", p2;
- print "Should be true: ", p2 ~ pm1, " ", p2 ~ pm2, " ", 3 ~ p2, " ", p2 ~ [2, 10..20], " ", p2 ~ [4, 10..20];
- print "4 = ", p2.len;
- p2 = prepend( p2, 5 );
- print "Should be false: ", p2 ~ pm1, " ", p2 ~ pm2, " ", 10 ~ p2, " ", p2 ~ [8, ten..(2*ten)];
- print "Should be true: ", p2 ~ / ? 4 3 2 1 /, " ", p2, " ", / ? 4 3 2 1 /;
- print "Should be true: ", p2 ~ [= * 4 3 * 1 =], " ", p2, " ", [= * 4 3 * 1 =];
- print "Should be true: ", p2 ~ [= (3+2) (2*2) 3 2 1 =], " ", p2 ~ mkpath(5, 4);
- print "Should be true: ", p2.len = 5, " ", p2.first = 5, " ", p2.last = 1;
- print "5 = ", p2.len;
- print "Delete 3: ", delete(p2, 3);
- print "Filter 1-3: ", filter(p2, [1..3]);
+
+ bt_assert(format(p2) = "(path 4 3 2 1)");
+ bt_assert(p2.len = 4);
+ bt_assert(p2 ~ pm1);
+ bt_assert(p2 ~ pm2);
+ bt_assert(3 ~ p2);
+ bt_assert(p2 ~ [2, 10..20]);
+ bt_assert(p2 ~ [4, 10..20]);
+
+ p2 = prepend(p2, 5);
+ bt_assert(p2 !~ pm1);
+ bt_assert(p2 !~ pm2);
+ bt_assert(10 !~ p2);
+ bt_assert(p2 !~ [8, ten..(2*ten)]);
+ bt_assert(p2 ~ / ? 4 3 2 1 /);
+ bt_assert(p2 ~ [= * 4 3 * 1 =]);
+ bt_assert(p2 ~ [= (3+2) (2*2) 3 2 1 =]);
+ bt_assert(p2 ~ mkpath(5, 4));
+
+ bt_assert(p2.len = 5);
+ bt_assert(p2.first = 5);
+ bt_assert(p2.last = 1);
+
+ bt_assert(p2.len = 5);
+ bt_assert(delete(p2, 3) = prepend(prepend(prepend(prepend(+empty+, 1), 2), 4), 5));
+ bt_assert(filter(p2, [1..3]) = prepend(prepend(prepend(+empty+, 1), 2), 3));
pm1 = [= 1 2 * 3 4 5 =];
p2 = prepend( + empty +, 5 );
@@ -173,63 +610,176 @@ eclist el2;
p2 = prepend( p2, 3 );
p2 = prepend( p2, 2 );
p2 = prepend( p2, 1 );
- print "Should be true: ", p2 ~ pm1, " ", p2, " ", pm1;
- print "Delete 3: ", delete(p2, 3);
- print "Delete 4-5: ", delete(p2, [4..5]);
+ bt_assert(p2 ~ pm1);
+ bt_assert(delete(p2, 3) = prepend(prepend(prepend(prepend(+empty+, 5), 4), 2), 1));
+ bt_assert(delete(p2, [4..5]) = prepend(prepend(prepend(prepend(+empty+, 3), 3), 2), 1));
+}
+
+bt_test_suite(t_path, "Testing paths");
+
+
+
+
+/*
+ * Testing Community List
+ * ----------------------
+ */
+
+define p23 = (2, 3);
+
+function t_clist()
+clist l;
+clist l2;
+clist r;
+{
l = - empty -;
- print "Should be false in this special case: ", l ~ [(*,*)];
+ bt_assert(l !~ [(*,*)]);
+ bt_assert((l ~ [(*,*)]) != (l !~ [(*,*)]));
+
+ bt_assert(-empty- = -empty-);
+
l = add( l, (one,2) );
- print "Should be always true: ", l ~ [(*,*)];
+ bt_assert(l ~ [(*,*)]);
l = add( l, (2,one+2) );
- print "Community list (1,2) (2,3) ", l;
- print "Should be true: ", (2,3) ~ l, " ", l ~ [(1,*)], " ", l ~ [p23]," ", l ~ [(2,2..3)], " ", l ~ [(1,1..2)], " ", l ~ [(1,1)..(1,2)];
- l = add( l, (2,5) );
- l = add( l, (5,one) );
- l = add( l, (6,one) );
- l = add( l, (one,one) );
- l = delete( l, [(5,1),(6,one),(one,1)] );
- l = delete( l, [(5,one),(6,one)] );
- l = filter( l, [(1,*)] );
- print "Community list (1,2) ", l;
- print "Should be false: ", (2,3) ~ l, " ", l ~ [(2,*)], " ", l ~ [(one,3..6)];
- print "Should be always true: ", l ~ [(*,*)];
- l = add( l, (3,one) );
- l = add( l, (one+one+one,one+one) );
- l = add( l, (3,3) );
- l = add( l, (3,4) );
- l = add( l, (3,5) );
- l2 = filter( l, [(3,*)] );
- l = delete( l, [(3,2..4)] );
- print "Community list (1,2) (3,1) (3,5) ", l, " len: ", l.len;
- l = add( l, (3,2) );
- l = add( l, (4,5) );
- print "Community list (1,2) (3,1) (3,2) (3,5) (4,5) ", l, " len: ", l.len;
- print "Should be true: ", l ~ [(*,2)], " ", l ~ [(*,5)], " ", l ~ [(*, one)];
- print "Should be false: ", l ~ [(*,3)], " ", l ~ [(*,(one+6))], " ", l ~ [(*, (one+one+one))];
- l = delete( l, [(*,(one+onef(3)))] );
- l = delete( l, [(*,(4+one))] );
- print "Community list (3,1) ", l;
- l = delete( l, [(*,(onef(5)))] );
- print "Community list empty ", l;
- l2 = add( l2, (3,6) );
- l = filter( l2, [(3,1..4)] );
- l2 = filter( l2, [(3,3..6)] );
- print "clist A (1..4): ", l;
- print "clist B (3..6): ", l2;
- print "clist A union B: ", add( l2, l );
- print "clist A isect B: ", filter( l, l2 );
- print "clist A \ B: ", delete( l, l2 );
+ bt_assert(format(l) = "(clist (1,2) (2,3))");
+
+ bt_assert((2,3) ~ l);
+ bt_assert(l ~ [(1,*)]);
+ bt_assert(l ~ [p23]);
+ bt_assert(l ~ [(2,2..3)]);
+ bt_assert(l ~ [(1,1..2)]);
+ bt_assert(l ~ [(1,1)..(1,2)]);
+
+ l = add(l, (2,5));
+ l = add(l, (5,one));
+ l = add(l, (6,one));
+ l = add(l, (one,one));
+ l = delete(l, [(5,1),(6,one),(one,1)]);
+ l = delete(l, [(5,one),(6,one)]);
+ l = filter(l, [(1,*)]);
+ bt_assert(l = add(-empty-, (1,2)));
+
+ bt_assert((2,3) !~ l);
+ bt_assert(l !~ [(2,*)]);
+ bt_assert(l !~ [(one,3..6)]);
+ bt_assert(l ~ [(*,*)]);
+
+ l = add(l, (3,one));
+ l = add(l, (one+one+one,one+one));
+ l = add(l, (3,3));
+ l = add(l, (3,4));
+ l = add(l, (3,5));
+ l2 = filter(l, [(3,*)]);
+ l = delete(l, [(3,2..4)]);
+ bt_assert(l = add(add(add(-empty-, (1,2)), (3,1)), (3,5)));
+ bt_assert(l.len = 3);
+
+ l = add(l, (3,2));
+ l = add(l, (4,5));
+ bt_assert(l = add(add(add(add(add(-empty-, (1,2)), (3,1)), (3,5)), (3,2)), (4,5)));
+
+ bt_assert(l.len = 5);
+ bt_assert(l ~ [(*,2)]);
+ bt_assert(l ~ [(*,5)]);
+ bt_assert(l ~ [(*, one)]);
+ bt_assert(l !~ [(*,3)]);
+ bt_assert(l !~ [(*,(one+6))]);
+ bt_assert(l !~ [(*, (one+one+one))]);
+
+ l = delete(l, [(*,(one+onef(3)))]);
+ l = delete(l, [(*,(4+one))]);
+ bt_assert(l = add(-empty-, (3,1)));
+
+ l = delete(l, [(*,(onef(5)))]);
+ bt_assert(l = -empty-);
+
+ l2 = add(l2, (3,6));
+ l = filter(l2, [(3,1..4)]);
+ l2 = filter(l2, [(3,3..6)]);
+
+ # clist A (10,20,30)
+ bt_assert(l = add(add(add(add(-empty-, (3,1)), (3,2)), (3,3)), (3,4)));
+ bt_assert(format(l) = "(clist (3,1) (3,2) (3,3) (3,4))");
+
+ # clist B (30,40,50)
+ bt_assert(l2 = add(add(add(add(-empty-, (3,3)), (3,4)), (3,5)), (3,6)));
+ bt_assert(format(l2) = "(clist (3,3) (3,4) (3,5) (3,6))");
+
+ # clist A union B
+ r = add(l, l2);
+ bt_assert(r = add(add(add(add(add(add(-empty-, (3,1)), (3,2)), (3,3)), (3,4)), (3,5)), (3,6)));
+ bt_assert(format(r) = "(clist (3,1) (3,2) (3,3) (3,4) (3,5) (3,6))");
+
+ # clist A isect B
+ r = filter(l, l2);
+ bt_assert(r = add(add(-empty-, (3,3)), (3,4)));
+ bt_assert(format(r) = "(clist (3,3) (3,4))");
+
+ # clist A \ B
+ r = delete(l, l2);
+ bt_assert(r = add(add(-empty-, (3,1)), (3,2)));
+ bt_assert(format(r) = "(clist (3,1) (3,2))");
+
+ # clist in c set
+ r = filter(l, [(3,1), (*,2)]);
+ bt_assert(r = add(add(-empty-, (3,1)), (3,2)));
+ bt_assert(format(r) = "(clist (3,1) (3,2))");
+}
+
+bt_test_suite(t_clist, "Testing lists of communities");
+
+
+
+/*
+ * Testing Extended Communities
+ * ----------------------------
+ */
+
+function t_ec()
+ec cc;
+{
+ cc = (rt, 12345, 200000);
+ bt_assert(format(cc) = "(rt, 12345, 200000)");
+
+ bt_assert(cc = (rt, 12345, 200000));
+ bt_assert(cc < (rt, 12345, 200010));
+ bt_assert(cc != (rt, 12346, 200000));
+ bt_assert(cc != (ro, 12345, 200000));
+ bt_assert(!(cc > (rt, 12345, 200010)));
+
+ bt_assert(format((ro, 100000, 20000)) = "(ro, 100000, 20000)");
+}
+
+bt_test_suite(t_ec, "Testing extended communities");
+
+
+
+
+/*
+ * Testing Extended Community List
+ * -------------------------------
+ */
+
+function t_eclist()
+eclist el;
+eclist el2;
+eclist r;
+{
el = -- empty --;
el = add(el, (rt, 10, 20));
el = add(el, (ro, 10.20.30.40, 100));
el = add(el, (ro, 11.21.31.41.mask(16), 200));
- print "EC list (rt, 10, 20) (ro, 10.20.30.40, 100) (ro, 11.21.0.0, 200):";
- print el;
- print "EC len: ", el.len;
+
+ bt_assert(--empty-- = --empty--);
+ bt_assert(((rt, 10, 20)) !~ --empty--);
+
+ bt_assert(format(el) = "(eclist (rt, 10, 20) (ro, 10.20.30.40, 100) (ro, 11.21.0.0, 200))");
+ bt_assert(el.len = 3);
el = delete(el, (rt, 10, 20));
el = delete(el, (rt, 10, 30));
+ bt_assert(el = add(add(--empty--, (ro, 10.20.30.40, 100)), (ro, 11.21.0.0, 200)));
el = add(el, (unknown 2, ten, 1));
el = add(el, (unknown 5, ten, 1));
el = add(el, (rt, ten, one+one));
@@ -238,251 +788,431 @@ eclist el2;
el = add(el, (rt, 10, 5));
el = add(el, (generic, 0x2000a, 3*ten));
el = delete(el, [(rt, 10, 2..ten)]);
- print "EC list (ro, 10.20.30.40, 100) (ro, 11.21.0.0, 200) (rt, 10, 1) (unknown 0x5, 10, 1) (rt, 10, 30):";
- print el;
+ bt_assert(el = add(add(add(add(add(--empty--, (ro, 10.20.30.40, 100)), (ro, 11.21.0.0, 200)), (rt, 10, 1)), (unknown 5, 10, 1)), (rt, 10, 30)));
+
el = filter(el, [(rt, 10, *)]);
- print "EC list (rt, 10, 1) (rt, 10, 30): ", el;
- print "Testing EC list, true: ", (rt, 10, 1) ~ el, " ", el ~ [(rt, 10, ten..40)];
- print "Testing EC list, false: ", (rt, 10, 20) ~ el, " ", (ro, 10.20.30.40, 100) ~ el, " ", el ~ [(rt, 10, 35..40)], " ", el ~ [(ro, 10, *)];
+ bt_assert(el = add(add(--empty--, (rt, 10, 1)), (rt, 10, 30)));
+ bt_assert((rt, 10, 1) ~ el);
+ bt_assert(el ~ [(rt, 10, ten..40)]);
+ bt_assert((rt, 10, 20) !~ el);
+ bt_assert((ro, 10.20.30.40, 100) !~ el);
+ bt_assert(el !~ [(rt, 10, 35..40)]);
+ bt_assert(el !~ [(ro, 10, *)]);
+
el = add(el, (rt, 10, 40));
el2 = filter(el, [(rt, 10, 20..40)] );
el2 = add(el2, (rt, 10, 50));
- print "eclist A (1,30,40): ", el;
- print "eclist B (30,40,50): ", el2;
- print "eclist A union B: ", add( el2, el );
- print "eclist A isect B: ", filter( el, el2 );
- print "eclist A \ B: ", delete( el, el2 );
+
+ # eclist A (1,30,40)
+ bt_assert(el = add(add(add(--empty--, (rt, 10, 1)), (rt, 10, 30)), (rt, 10, 40)));
+ bt_assert(format(el) = "(eclist (rt, 10, 1) (rt, 10, 30) (rt, 10, 40))");
+
+ # eclist B (30,40,50)
+ bt_assert(el2 = add(add(add(--empty--, (rt, 10, 30)), (rt, 10, 40)), (rt, 10, 50)));
+ bt_assert(format(el2) = "(eclist (rt, 10, 30) (rt, 10, 40) (rt, 10, 50))");
+
+ # eclist A union B
+ r = add(el2, el);
+ bt_assert(r = add(add(add(add(--empty--, (rt, 10, 30)), (rt, 10, 40)), (rt, 10, 50)), (rt, 10, 1)));
+ bt_assert(format(r) = "(eclist (rt, 10, 30) (rt, 10, 40) (rt, 10, 50) (rt, 10, 1))");
+
+ # eclist A isect B
+ r = filter(el, el2);
+ bt_assert(r = add(add(--empty--, (rt, 10, 30)), (rt, 10, 40)));
+ bt_assert(format(r) = "(eclist (rt, 10, 30) (rt, 10, 40))");
+
+ # eclist A \ B
+ r = delete(el, el2);
+ bt_assert(r = add(--empty--, (rt, 10, 1)));
+ bt_assert(format(r) = "(eclist (rt, 10, 1))");
+
+ # eclist in ec set
+ r = filter(el, [(rt, 10, 1), (rt, 10, 25..30), (ro, 10, 40)]);
+ bt_assert(r = add(add(--empty--, (rt, 10, 1)), (rt, 10, 30)));
+ bt_assert(format(r) = "(eclist (rt, 10, 1) (rt, 10, 30))");
}
-function bla()
+bt_test_suite(t_eclist, "Testing lists of extended communities");
+
+
+
+
+/*
+ * Testing sets of Extended Communities
+ * ------------------------------------
+ */
+
+define ecs2 = [(rt, ten, (one+onef(0))*10), (ro, 100000, 100..200), (rt, 12345, *)];
+
+function t_ec_set()
+ec set ecs;
{
- print "fifteen called";
- return 15;
+ ecs = [(rt, ten, (one+onef(0))*10), (ro, 100000, 100..200), (rt, 12345, *)];
+ bt_assert(format(ecs) = "[(rt, 10, 20), (rt, 12345, 0)..(rt, 12345, 4294967295), (ro, 100000, 100)..(ro, 100000, 200)]");
+ bt_assert(format(ecs2) = "[(rt, 10, 20), (rt, 12345, 0)..(rt, 12345, 4294967295), (ro, 100000, 100)..(ro, 100000, 200)]");
+
+ bt_assert((rt, 10, 20) ~ ecs);
+ bt_assert((ro, 100000, 100) ~ ecs);
+ bt_assert((ro, 100000, 128) ~ ecs);
+ bt_assert((ro, 100000, 200) ~ ecs);
+ bt_assert((rt, 12345, 0) ~ ecs);
+ bt_assert((rt, 12345, 200000) ~ ecs);
+ bt_assert((rt, 12345, 4000000) ~ ecs);
+ bt_assert((ro, 10, 20) !~ ecs);
+ bt_assert((rt, 10, 21) !~ ecs);
+ bt_assert((ro, 100000, 99) !~ ecs);
+ bt_assert((ro, 12345, 10) !~ ecs);
+ bt_assert((rt, 12346, 0) !~ ecs);
+ bt_assert((ro, 0.1.134.160, 150) !~ ecs);
}
-define four=4;
-define onetwo=1.2.3.4;
+bt_test_suite(t_ec_set, "Testing sets of extended communities");
-function __test1()
+
+
+
+/*
+ * Testing Large Communities
+ * -------------------------
+ */
+
+function mktrip(int a)
{
- if source ~ [ RTS_BGP, RTS_STATIC ] then {
-# ospf_metric1 = 65535;
-# ospf_metric2 = 1000;
- ospf_tag = 0x12345678;
- accept;
- } reject;
+ return (a, 2*a, 3*a);
}
-function __test2()
+function t_lclist()
+lclist ll;
+lclist ll2;
+lclist r;
{
- if source ~ [ RTS_BGP, RTS_STATIC ] then {
-# ospf_metric1 = 65535;
-# ospf_metric2 = 1000;
- ospf_tag = 0x12345678;
- accept;
- } reject;
+ bt_assert(---empty--- = ---empty---);
+ bt_assert((10, 20, 30) !~ ---empty---);
+
+ ll = --- empty ---;
+ ll = add(ll, (ten, 20, 30));
+ ll = add(ll, (1000, 2000, 3000));
+ ll = add(ll, mktrip(100000));
+ bt_assert(format(ll) = "(lclist (10, 20, 30) (1000, 2000, 3000) (100000, 200000, 300000))");
+ bt_assert(ll.len = 3);
+ bt_assert(ll = add(add(add(---empty---, (10, 20, 30)), (1000, 2000, 3000)), (100000, 200000, 300000)));
+
+ bt_assert(mktrip(1000) ~ ll);
+ bt_assert(mktrip(100) !~ ll);
+
+ ll = --- empty ---;
+ ll = add(ll, (10, 10, 10));
+ ll = add(ll, (20, 20, 20));
+ ll = add(ll, (30, 30, 30));
+
+ ll2 = --- empty ---;
+ ll2 = add(ll2, (20, 20, 20));
+ ll2 = add(ll2, (30, 30, 30));
+ ll2 = add(ll2, (40, 40, 40));
+
+ # lclist A (10, 20, 30)
+ bt_assert(format(ll) = "(lclist (10, 10, 10) (20, 20, 20) (30, 30, 30))");
+
+ # lclist B (20, 30, 40)
+ bt_assert(format(ll2) = "(lclist (20, 20, 20) (30, 30, 30) (40, 40, 40))");
+
+ # lclist A union B
+ r = add(ll, ll2);
+ bt_assert(r = add(add(add(add(---empty---, (10,10,10)), (20,20,20)), (30,30,30)), (40,40,40)));
+ bt_assert(format(r) = "(lclist (10, 10, 10) (20, 20, 20) (30, 30, 30) (40, 40, 40))");
+
+ # lclist A isect B
+ r = filter(ll, ll2);
+ bt_assert(r = add(add(---empty---, (20, 20, 20)), (30, 30, 30)));
+ bt_assert(format(r) = "(lclist (20, 20, 20) (30, 30, 30))");
+
+ # lclist A \ B
+ r = delete(ll, ll2);
+ bt_assert(r = add(---empty---, (10, 10, 10)));
+ bt_assert(format(r) = "(lclist (10, 10, 10))");
+
+ # lclist in lc set
+ r = filter(ll, [(5..15, *, *), (20, 15..25, *)]);
+ bt_assert(r = add(add(---empty---, (10, 10, 10)), (20, 20, 20)));
+ bt_assert(format(r) = "(lclist (10, 10, 10) (20, 20, 20))");
}
-function test_pxset(prefix set pxs)
+bt_test_suite(t_lclist, "Testing lists of large communities");
+
+
+
+
+/*
+ * Testing sets of Large Communities
+ * ---------------------------------
+ */
+
+function t_lclist_set()
+lclist ll;
+lc set lls;
{
- print pxs;
- print " must be true: ", net10 ~ pxs, ",", 10.0.0.0/10 ~ pxs, ",", 10.0.0.0/12 ~ pxs, ",",
- 20.0.0.0/24 ~ pxs, ",", 20.0.40.0/24 ~ pxs, ",", 20.0.0.0/26 ~ pxs, ",",
- 20.0.100.0/26 ~ pxs, ",", 20.0.0.0/28 ~ pxs, ",", 20.0.255.0/28 ~ pxs;
- print " must be false: ", 10.0.0.0/7 ~ pxs, ",", 10.0.0.0/13 ~ pxs, ",", 10.0.0.0/16 ~ pxs, ",",
- 20.0.0.0/16 ~ pxs, ",", 20.0.0.0/23 ~ pxs, ",", 20.0.0.0/29 ~ pxs, ",",
- 11.0.0.0/10 ~ pxs, ",", 20.1.0.0/26 ~ pxs;
+ ll = --- empty ---;
+ ll = add(ll, (10, 20, 30));
+ ll = add(ll, (1000, 2000, 3000));
+ ll = add(ll, mktrip(100000));
+
+ bt_assert(ll ~ [(5,10,15), (10,20,30)]);
+ bt_assert(ll ~ [(10,15..25,*)]);
+ bt_assert(ll ~ [(ten, *, *)]);
+
+ bt_assert(ll !~ [(5,10,15), (10,21,30)]);
+ bt_assert(ll !~ [(10,21..25,*)]);
+ bt_assert(ll !~ [(11, *, *)]);
+
+ lls = [(10, 10, 10), (20, 20, 15..25), (30, 30, *), (40, 35..45, *), (50, *, *), (55..65, *, *)];
+ bt_assert(format(lls) = "[(10, 10, 10), (20, 20, 15)..(20, 20, 25), (30, 30, 0)..(30, 30, 4294967295), (40, 35, 0)..(40, 45, 4294967295), (50, 0, 0)..(50, 4294967295, 4294967295), (55, 0, 0)..(65, 4294967295, 4294967295)]");
+ bt_assert((10, 10, 10) ~ lls);
+ bt_assert((20, 20, 25) ~ lls);
+ bt_assert((20, 20, 26) !~ lls);
+ bt_assert((30, 30, 0) ~ lls);
+ bt_assert((40, 35, 40) ~ lls);
+ bt_assert((40, 34, 40) !~ lls);
+ bt_assert((50, 0, 0) ~ lls);
+ bt_assert((60, 60, 60) ~ lls);
+ bt_assert((70, 60, 60) !~ lls);
}
+bt_test_suite(t_lclist_set, "Testing sets of large communities");
+
+
+
+
+/*
+ * Testing defined() function
+ * --------------------------
+ */
+
function test_undef(int a)
int b;
{
- if a = 3
- then b = 4;
- print "Defined: ", a, " ", b, " ", defined(b);
+ if a = 3 then {
+ b = 4;
+ bt_assert(defined(b));
+ }
+ else {
+ bt_assert(!defined(b));
+ }
}
-define is1 = [ one, (2+1), (6-one), 8, 11, 15, 17, 19];
-define is2 = [(17+2), 17, 15, 11, 8, 5, 3, 2];
-define is3 = [5, 17, 2, 11, 8, 15, 3, 19];
+function t_define()
+int i;
+{
+ test_undef(2);
+ test_undef(3);
+ test_undef(2);
-define pxs2 = [ 10.0.0.0/16{8,12}, 20.0.0.0/16{24,28} ];
+ bt_assert(defined(1));
+ bt_assert(defined(1.2.3.4));
+}
-define ecs2 = [(rt, ten, (one+onef(0))*10), (ro, 100000, 100..200), (rt, 12345, *)];
+bt_test_suite(t_define, "Testing defined() function");
-function __startup()
-int i;
-bool b;
-prefix px;
-ip p;
-pair pp;
-quad qq;
-ec cc;
-int set is;
-pair set ps;
-ec set ecs;
-ip set ips;
-prefix set pxs;
-string st;
-{
- print "1a-a1 = 30: ", '1a-a1';
- print "Testing filter language:";
- i = four;
- i = 12*100 + 60/2 + i;
- i = ( i + 0 );
- print " arithmetics: 1234 = ", i;
- printn " if statements ";
- print "what happens here?";
- printn ".";
- if (i = 4) then { print "*** FAIL: if 0"; quitbird; } else printn ".";
-# if !(i = 3) then { print "*** FAIL: if 0"; quitbird; } else printn ".";
- if 1234 = i then printn "."; else { print "*** FAIL: if 1 else"; }
-# if 1 <= 1 then printn "."; else { print "*** FAIL: test 3"; }
- if 1234 < 1234 then { print "*** FAIL: test 4"; quitbird; } else print "ok";
- is = [ 2, 3, 4, 7..11 ];
- print "must be true: ", 1 = 1, " ", 1 != (0,1), " ", 1 != "a", " ", +empty+ = +empty+, " ", -empty- = -empty-, " ", --empty-- = --empty-- ,
- " ", [1,4..10,20] = [1,4..10,20] , " ", [ 10.0.0.0/8{ 15 , 17 } ] = [ 10.0.0.0/8{ 15 , 17 } ];
- print "must be false: ", 1 != 1, " ", 1 = (0,1), " ", 1 = "a", " ", +empty+ = -empty-, " ", -empty- = --empty--, " ", --empty-- = +empty+ ,
- " ", [1,2] = [1,3], " ", [ 10.0.0.0/8{ 15 , 17 } ] = [ 11.0.0.0/8{ 15 , 17 } ];
- print " must be true: ", 1.2.0.0/16 ~ [ 1.0.0.0/8{ 15 , 17 } ];
- print " data types; must be true: ", 1.2.3.4 = 1.2.3.4, ",", 1 ~ [1,2,3], ",", 5 ~ [1..20], ",", 10 ~ is, ",", 2 ~ [ 1, 2, 3 ], ",", 5 ~ [ 4 .. 7 ], ",", 1.2.3.4 ~ [ 1.2.3.3..1.2.3.5 ], ",", 1.2.3.4 ~ 1.0.0.0/8, ",", 1.0.0.0/8 ~ 1.0.0.0/8, ",", 1.0.0.0/8 ~ [ 1.0.0.0/8+ ];
- print " must be true: ", true && true, ",", true || false, ",", ! false && ! false && true, ",", 1 < 2 && 1 != 3, ",", true && true && ! false, ",", true || 1+"a", ",", !(false && 1+"a");
+/*
+ * Testing calling functions
+ * -------------------------
+ */
- print " must be true: ", defined(1), ",", defined(1.2.3.4), ",", 1 != 2, ",", 1 <= 2;
- print " data types: must be false: ", 1 ~ [ 2, 3, 4 ], ",", 5 ~ is, ",", 1.2.3.4 ~ [ 1.2.3.3, 1.2.3.5 ], ",", (1,2) > (2,2), ",", (1,1) > (1,1), ",", 1.0.0.0/9 ~ [ 1.0.0.0/8- ], ",", 1.2.0.0/17 ~ [ 1.0.0.0/8{ 15 , 16 } ], ",", true && false;
+function callme(int arg1; int arg2)
+int i;
+{
+ case arg1 {
+ 1, 42: return 42;
+ else: return arg1 * arg2;
+ }
+ return 0;
+}
- print " must be true: ", 1 ~ is1, " ", 3 ~ is1, " ", 5 ~ is1;
- print " must be true: ", (one+2) ~ is1, " ", 2 ~ is2, " ", 2 ~ is3;
- print " must be false: ", 4 ~ is1, " ", 4 ~ is2, " ", 4 ~ is3;
- print " must be false: ", 10 ~ is1, " ", 10 ~ is2, " ", 10 ~ is3;
- print " must be true: ", 15 ~ is1, " ", 15 ~ is2, " ", 15 ~ is3;
- print " must be false: ", 18 ~ is1, " ", 18 ~ is2, " ", 18 ~ is3;
- print " must be true: ", 19 ~ is1, " ", 19 ~ is2, " ", 19 ~ is3;
- print " must be false: ", 20 ~ is1, " ", 20 ~ is2, " ", 20 ~ is3;
+function fifteen()
+{
+ return 15;
+}
- px = 1.2.0.0/18;
- print "Testing prefixes: 1.2.0.0/18 = ", px;
- print " must be true: ", 192.168.0.0/16 ~ 192.168.0.0/16, " ", 192.168.0.0/17 ~ 192.168.0.0/16, " ", 192.168.254.0/24 ~ 192.168.0.0/16, " ", netdoc ~ 2001::/16;
- print " must be false: ", 192.168.0.0/15 ~ 192.168.0.0/16, " ", 192.160.0.0/17 ~ 192.168.0.0/16, " ", px ~ netdoc;
+function t_call_function()
+{
+ bt_assert(fifteen() = 15);
- p = 127.1.2.3;
- print "Testing mask : 127.0.0.0 = ", p.mask(8);
+ bt_assert(callme(1, 2) = 42);
+ bt_assert(callme(42, 2) = 42);
- pp = (1, 2);
- print "Testing pairs: (1,2) = ", (1,2), " = ", pp, " = ", (1,1+1), " = ", 'mkpair-a'(2);
- print " must be true: ", (1,2) = (1,1+1);
- print "Testing enums: ", RTS_DUMMY, " ", RTS_STATIC, " ",
- ", true: ", RTS_STATIC ~ [RTS_STATIC, RTS_DEVICE],
- ", false: ", RTS_BGP ~ [RTS_STATIC, RTS_DEVICE];
+ bt_assert(callme(2, 2) = 4);
+ bt_assert(callme(3, 2) = 6);
+ bt_assert(callme(4, 4) = 16);
+ bt_assert(callme(7, 2) = 14);
+}
- ps = [(1,(one+one)), (3,4)..(4,8), (5,*), (6,3..6)];
- print "Pair set: ", ps;
- print "Testing pair set, true: ", pp ~ ps, " ", (3,5) ~ ps, " ", (4,1) ~ ps, " ", (5,4) ~ ps, " ", (5,65535) ~ ps, " ", (6,4) ~ ps, " ", (3, 10000) ~ ps;
- print "Testing pair set, false: ", (3,3) ~ ps, " ", (4,9) ~ ps, " ", (4,65535) ~ ps, " ", (6,2) ~ ps, " ", (6,6+one) ~ ps, " ", ((one+6),2) ~ ps, " ", (1,1) ~ ps;
+bt_test_suite(t_call_function, "Testing calling functions");
- ps = [(20..150, 200..300), (50100..50200, 1000..50000), (*, 5+5)];
- print "Pair set: .. too long ..";
- print "Testing pair set, true: ", (100,200) ~ ps, " ", (150,300) ~ ps, " ", (50180,1200) ~ ps, " ", (50110,49000) ~ ps, " ", (0,10) ~ ps, " ", (64000,10) ~ ps;
- print "Testing pair set, false: ", (20,199) ~ ps, " ", (151,250) ~ ps, " ", (50050,2000) ~ ps, " ", (50150,50050) ~ ps, " ", (10,9) ~ ps, " ", (65535,11) ~ ps ;
- qq = 1.2.3.4;
- print "Testinq quad: 1.2.3.4 = ", qq,
- ", true: ", qq = 1.2.3.4, " ", qq ~ [1.2.3.4, 5.6.7.8],
- ", false: ", qq = 4.3.2.1, " ", qq ~ [1.2.1.1, 1.2.3.5];
- cc = (rt, 12345, 200000);
- print "Testing EC: (rt, 12345, 200000) = ", cc;
- print "Testing EC: (ro, 100000, 20000) = ", (ro, 100000, 20000);
- print "Testing EC: (rt, 10.20.30.40, 20000) = ", (rt, 10.20.30.40, 20000);
- print " true: ", cc = (rt, 12345, 200000), " ", cc < (rt, 12345, 200010),
- ", false: ", cc = (rt, 12346, 200000), " ", cc = (ro, 12345, 200000), " ", cc > (rt, 12345, 200010);
- ecs = [(rt, ten, (one+onef(0))*10), (ro, 100000, 100..200), (rt, 12345, *)];
- print "EC set: ", ecs;
- print "EC set: ", ecs2;
- print "Testing EC set, true: ", (rt, 10, 20) ~ ecs, " ", (ro, 100000, 100) ~ ecs, " ", (ro, 100000, 200) ~ ecs,
- " ", (rt, 12345, 0) ~ ecs, " ", cc ~ ecs, " ", (rt, 12345, 4000000) ~ ecs;
- print "Testing EC set, false: ", (ro, 10, 20) ~ ecs, " ", (rt, 10, 21) ~ ecs, " ", (ro, 100000, 99) ~ ecs,
- " ", (ro, 12345, 10) ~ ecs, " ", (rt, 12346, 0) ~ ecs, " ", (ro, 0.1.134.160, 150) ~ ecs;
+/*
+ * Test including another config file
+ * ----------------------------------
+ */
- st = "Hello";
- print "Testing string: ", st, " true: ", st ~ "Hell*", " false: ", st ~ "ell*";
-
- b = true;
- print "Testing bool: ", b, ", ", !b;
+function t_include()
+int i;
+{
+ i = 1;
+ include "test.conf.inc";
+ bt_assert(i = 42);
+}
- if ( b = true ) then print "Testing bool comparison b = true: ", b;
- else { print "*** FAIL: TRUE test failed" ; quitbird; }
-
- ips = [ 1.1.1.0 .. 1.1.1.255, ip1222];
- print "Testing IP sets: ";
- print ips;
- print " must be true: ", 1.1.1.0 ~ ips, ",", 1.1.1.100 ~ ips, ",", 1.2.2.2 ~ ips;
- print " must be false: ", 1.1.0.255 ~ ips, ",", 1.1.2.0 ~ ips, ",", 1.2.2.3 ~ ips, ",", 192.168.1.1 ~ ips;
+bt_test_suite(t_include, "Testing including another config file");
- pxs = [ 1.2.0.0/16, 1.4.0.0/16+];
- print "Testing prefix sets: ";
- print pxs;
- print " must be true: ", 1.2.0.0/16 ~ pxs, ",", 1.4.0.0/16 ~ pxs, ",", 1.4.0.0/18 ~ pxs, ",", 1.4.0.0/32 ~ pxs;
- print " must be false: ", 1.1.0.0/16 ~ pxs, ",", 1.3.0.0/16 ~ pxs, ",", 1.2.0.0/15 ~ pxs, ",", 1.2.0.0/17 ~ pxs, ",",
- 1.2.0.0/32 ~ pxs, ",", 1.4.0.0/15 ~ pxs;
- test_pxset(pxs2);
- test_pxset([ 10.0.0.0/16{8,12}, 20.0.0.0/16{24,28} ]);
- print "What will this do? ", [ 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 5 ];
- roa_operators_test();
- print "Testing functions...";
- callme ( 1, 2 );
- callme ( 2, 2 );
- callme ( 2, 2 );
- callme ( 3, 2 );
- callme ( 4, 4 );
- callme ( 7, 2 );
+/*
+ * Test if-else statement
+ * ----------------------
+ */
- i = fifteen();
- print "Testing function calls: 15 = ", i;
+function t_if_else()
+int i;
+{
+ if true then
+ bt_assert(true);
+
+ if false then
+ bt_assert(false);
+ else if true then
+ bt_assert(true);
+ else
+ bt_assert(false);
+}
- path_test();
+bt_test_suite(t_if_else, "Testing if-else statement");
- print "1.2.3.4 = ", onetwo;
- i = 4200000000;
- print "4200000000 = ", i, " true: ", i = 4200000000, " ", i > 4100000000, " false: ", i > 4250000000;
- test_undef(2);
- test_undef(3);
- test_undef(2);
- print "Testing include";
- include "test.conf.inc";
+/*
+ * Unused functions -- testing only parsing
+ * ----------------------------------------
+ */
+
+function __test1()
+{
+ if source ~ [ RTS_BGP, RTS_STATIC ] then {
+# ospf_metric1 = 65535;
+# ospf_metric2 = 1000;
+ ospf_tag = 0x12345678;
+ accept;
+ }
+ reject;
+}
- print "done";
- print "Well, now call from birdc `eval test_roa_check()', please.";
- return 1;
-# quitbird;
-# print "*** FAIL: this is unreachable";
+function __test2()
+{
+ if source ~ [ RTS_BGP, RTS_STATIC ] then {
+# ospf_metric1 = 65535;
+# ospf_metric2 = 1000;
+ ospf_tag = 0x12345678;
+ accept;
+ }
+ reject;
}
-filter testf
-int j;
-{
+filter testf
+int j;
+{
print "Heya, filtering route to ", net.ip, " prefixlen ", net.len, " source ", source;
print "This route was from ", from;
j = 7;
j = 17;
if rip_metric > 15 then {
- reject "RIP Metric is more than infinity";
+ reject "RIP Metric is more than infinity";
}
rip_metric = 14;
unset(rip_metric);
-
+
accept "ok I take that";
}
-eval __startup();
+roa4 table r4;
+roa6 table r6;
+
+protocol static
+{
+ roa4 { table r4; };
+ route 10.110.0.0/16 max 16 as 1000 blackhole;
+ route 10.120.0.0/16 max 24 as 1000 blackhole ;
+ route 10.130.0.0/16 max 24 as 2000 blackhole;
+ route 10.130.128.0/18 max 24 as 3000 blackhole;
+}
+
+protocol static
+{
+ roa6 { table r6; };
+ route 2001:0db8:85a3:8a2e::/64 max 96 as 1000 blackhole;
+}
+
+function test_roa_check()
+{
+ # cannot be tested in __startup(), sorry
+ print "Should be true: ", roa_check(r4, 10.10.0.0/16, 1000) = ROA_UNKNOWN,
+ " ", roa_check(r4, 10.0.0.0/8, 1000) = ROA_UNKNOWN,
+ " ", roa_check(r4, 10.110.0.0/16, 1000) = ROA_VALID,
+ " ", roa_check(r4, 10.110.0.0/16, 2000) = ROA_INVALID,
+ " ", roa_check(r4, 10.110.32.0/20, 1000) = ROA_INVALID,
+ " ", roa_check(r4, 10.120.32.0/20, 1000) = ROA_VALID;
+ print "Should be true: ", roa_check(r4, 10.120.32.0/20, 2000) = ROA_INVALID,
+ " ", roa_check(r4, 10.120.32.32/28, 1000) = ROA_INVALID,
+ " ", roa_check(r4, 10.130.130.0/24, 1000) = ROA_INVALID,
+ " ", roa_check(r4, 10.130.130.0/24, 2000) = ROA_VALID,
+ " ", roa_check(r4, 10.130.30.0/24, 3000) = ROA_INVALID,
+ " ", roa_check(r4, 10.130.130.0/24, 3000) = ROA_VALID;
+ print "Should be true: ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_VALID,
+ " ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID,
+ " ", roa_check(r6, 2001:0db8:85a3:8a2e::/64, 1000) = ROA_VALID,
+ " ", roa_check(r6, 2001:0db8:85a3::/48, 1000) = ROA_UNKNOWN;
+
+ print "Should be true: ", roa_check(r4, 10.10.0.0/16, 1000) = ROA_UNKNOWN,
+ " ", roa_check(r4, 10.0.0.0/8, 1000) = ROA_UNKNOWN,
+ " ", roa_check(r4, 10.110.0.0/16, 1000) = ROA_VALID,
+ " ", roa_check(r4, 10.110.0.0/16, 2000) = ROA_INVALID,
+ " ", roa_check(r4, 10.110.32.0/20, 1000) = ROA_INVALID,
+ " ", roa_check(r4, 10.120.32.0/20, 1000) = ROA_VALID;
+
+ print "Should be true: ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_VALID,
+ " ", roa_check(r6, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID,
+ " ", roa_check(r6, 2001:0db8:85a3:8a2e::/64, 1000) = ROA_VALID,
+ " ", roa_check(r6, 2001:0db8:85a3::/48, 1000) = ROA_UNKNOWN;
+
+ print "Should be true: ", roa_check(r4, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID ||
+ roa_check(r6, 2001:0db8:85a3:8a2e:1234::/97, 1000) = ROA_INVALID;
+
+ print "Should be false: ", roa_check(r4, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_INVALID ||
+ roa_check(r6, 2001:0db8:85a3:8a2e:1234::/80, 1000) = ROA_INVALID,
+ " ", roa_check(r4, 2001:0db8:85a3::/48, 1000) = ROA_INVALID ||
+ roa_check(r6, 2001:0db8:85a3::/48, 1000) = ROA_INVALID;
+
+ print "Should be true: ", 10.130.130.0/24 ~ 0.0.0.0/0,
+ " ", 2001:0db8:85a3:8a2e::/64 ~ ::/0;
+ print "Should be false: ", 10.130.130.0/24 ~ ::/0,
+ " ", 2001:0db8:85a3:8a2e::/64 ~ 0.0.0.0/0;
+}
+
+function roa_operators_test()
+prefix pfx;
+{
+ print "Testing ROA prefix operators '.maxlen' and '.asn':";
+
+ pfx = 12.13.0.0/16 max 24 as 1234;
+ print pfx;
+ print "Should be true: ", pfx.len = 16, " ", pfx.maxlen = 24, " ", pfx.asn = 1234;
+
+ pfx = 1000::/8 max 32 as 1234;
+ print pfx;
+ print "Should be true: ", pfx.len = 8, " ", pfx.maxlen = 32, " ", pfx.asn = 1234;
+}
diff --git a/filter/test.conf.inc b/filter/test.conf.inc
index 109a49c5..8ede2d18 100644
--- a/filter/test.conf.inc
+++ b/filter/test.conf.inc
@@ -1,5 +1,3 @@
-print "Entering include";
-print "Should be 2: ", 1+1;
-print "Leaving include";
-
+bt_assert(1+1 = 2);
+i = 42;
diff --git a/filter/test.conf2 b/filter/test.conf2
index 60bdd965..2a5d896b 100644
--- a/filter/test.conf2
+++ b/filter/test.conf2
@@ -18,6 +18,7 @@ protocol direct {
protocol kernel {
disabled;
+ ipv4; # Must be specified at least one channel
# learn; # Learn all routes from the kernel
# scan time 10; # Scan kernel tables every 10 seconds
}
@@ -25,51 +26,58 @@ protocol kernel {
protocol static {
# disabled;
- import filter { print "ahoj";
- print source;
- if source = RTS_STATIC then {
- print "It is from static";
- }
- print from;
- from = 1.2.3.4;
- print from;
- print scope;
- scope = SCOPE_HOST;
- print scope;
- if !(scope ~ [ SCOPE_HOST, SCOPE_SITE ]) then {
- print "Failed in test";
- quitbird;
- }
-
- preference = 15;
- print preference;
- preference = 29;
- print preference;
- rip_metric = 1;
- print rip_metric;
- rip_metric = rip_metric + 5;
- print rip_metric;
- bgp_community = - empty - ;
- print "nazdar";
- bgp_community = add(bgp_community, (1,2));
- print "cau";
- bgp_community = add(bgp_community, (2,3));
- bgp_community.add((4,5));
- print "community = ", bgp_community;
- bgp_community.delete((2,3));
- print "community = ", bgp_community;
- bgp_community.empty;
- print "community = ", bgp_community;
- print "done";
- };
+ ipv4 {
+ export all;
+
+ import filter {
+ print "ahoj";
+ print source;
+ if source = RTS_STATIC then {
+ print "It is from static";
+ }
+ print from;
+ from = 1.2.3.4;
+ print from;
+ print scope;
+ scope = SCOPE_HOST;
+ print scope;
+ if !(scope ~ [ SCOPE_HOST, SCOPE_SITE ]) then {
+ print "Failed in test";
+ quitbird;
+ }
+ preference = 15;
+ print preference;
+ preference = 29;
+ print preference;
+ rip_metric = 1;
+ print rip_metric;
+ rip_metric = rip_metric + 5;
+ print rip_metric;
+
+#
+# TODO: uncomment this part after finishing BGP integration version
+#
+# bgp_community = -empty-;
+# print "hi";
+# bgp_community = add(bgp_community, (1,2));
+# print "hello";
+# bgp_community = add(bgp_community, (2,3));
+# bgp_community.add((4,5));
+# print "community = ", bgp_community;
+# bgp_community.delete((2,3));
+# print "community = ", bgp_community;
+# bgp_community.empty;
+# print "community = ", bgp_community;
+# print "done";
+ };
+ };
route 0.0.0.0/0 via 195.113.31.113;
route 62.168.0.0/25 reject;
route 1.2.3.4/32 via 195.113.31.124;
-# route 10.0.0.0/8 reject;
-# route 10.1.1.0:255.255.255.0 via 62.168.0.3;
-# route 10.1.2.0:255.255.255.0 via 62.168.0.3;
-# route 10.1.3.0:255.255.255.0 via 62.168.0.4;
-# route 10.2.0.0/24 via "arc0";
- export all;
+ route 10.0.0.0/8 reject;
+ route 10.1.1.0:255.255.255.0 via 62.168.0.3;
+ route 10.1.2.0:255.255.255.0 via 62.168.0.3;
+ route 10.1.3.0:255.255.255.0 via 62.168.0.4;
+ route 10.2.0.0/24 via "arc0";
}
diff --git a/filter/test6.conf b/filter/test6.conf
deleted file mode 100644
index f25ffc47..00000000
--- a/filter/test6.conf
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * This is an example configuration file.
- * FIXME: add all examples from docs here.
- */
-
-# Yet another comment
-
-router id 62.168.0.1;
-
-define xyzzy = (120+10);
-
-function callme(int arg1; int arg2)
-int local1;
-int local2;
-int i;
-{
- printn "Function callme called arguments ", arg1, " and ", arg2, ":" ;
- i = arg2;
-
- case arg1 {
- 2: print "dva"; print "jeste jednou dva";
- 3 .. 5: print "tri az pet";
- else: print "neco jineho";
- }
-}
-
-function fifteen()
-{
- print "fifteen called";
- return 15;
-}
-
-function paths()
-bgpmask pm1;
-bgpmask pm2;
-bgppath p2;
-clist l;
-{
- pm1 = / 4 3 2 1 /;
- pm2 = [= 4 3 2 1 =];
- print "Testing path masks: ", pm1, " ", pm2;
- p2 = prepend( + empty +, 1 );
- p2 = prepend( p2, 2 );
- p2 = prepend( p2, 3 );
- p2 = prepend( p2, 4 );
- print "Testing paths: ", p2;
- print "Should be true: ", p2 ~ pm1, " ", p2 ~ pm2;
- print "4 = ", p2.len;
- p2 = prepend( p2, 5 );
- print "Should be false: ", p2 ~ pm1, " ", p2 ~ pm2;
- print "Should be true: ", p2 ~ / ? 4 3 2 1 /, " ", p2, " ", / ? 4 3 2 1 /;
- print "Should be true: ", p2 ~ [= * 4 3 * 1 =], " ", p2, " ", [= * 4 3 * 1 =];
- print "5 = ", p2.len;
-
- pm1 = [= 1 2 * 3 4 5 =];
- p2 = prepend( + empty +, 5 );
- p2 = prepend( p2, 4 );
- p2 = prepend( p2, 3 );
- p2 = prepend( p2, 3 );
- p2 = prepend( p2, 2 );
- p2 = prepend( p2, 1 );
- print "Should be true: ", p2 ~ pm1, " ", p2, " ", pm1;
-
- l = - empty -;
- l = add( l, (1,2) );
- l = add( l, (2,3) );
- print "Community list (1,2) (2,3) ", l;
- print "Should be true: ", (2,3) ~ l;
- l = delete( l, (2,3) );
- print "Community list (1,2) ", l;
- print "Should be false: ", (2,3) ~ l;
-}
-
-function bla()
-{
- print "fifteen called";
- return 15;
-}
-
-define four=4;
-
-function test_pxset(prefix set pxs)
-{
- print " must be true: ", 1000::/8 ~ pxs, ",", 1000::/10 ~ pxs, ",", 1000::/12 ~ pxs, ",",
- 2000::/24 ~ pxs, ",", 2000:4000::/24 ~ pxs, ",", 2000::/26 ~ pxs, ",",
- 2000:8000::/26 ~ pxs, ",", 2000::/28 ~ pxs, ",", 2000:FFF0::/28 ~ pxs;
- print " must be false: ", 1000::/7 ~ pxs, ",", 1000::/13 ~ pxs, ",", 1000::/16 ~ pxs, ",",
- 2000::/16 ~ pxs, ",", 2000::/23 ~ pxs, ",", 2000::/29 ~ pxs, ",",
- 1100::/10 ~ pxs, ",", 2010::/26 ~ pxs;
-}
-
-function __startup()
-int i;
-bool b;
-prefix px;
-ip p;
-pair pp;
-int set is;
-prefix set pxs;
-string s;
-{
- print "Testing filter language:";
- i = four;
- i = 12*100 + 60/2 + i;
- i = ( i + 0 );
- print " arithmetics: 1234 = ", i;
- printn " if statements ";
- print "what happens here?";
- printn ".";
- if (i = 4) then { print "*** FAIL: if 0"; quitbird; } else printn ".";
-# if !(i = 3) then { print "*** FAIL: if 0"; quitbird; } else printn ".";
- if 1234 = i then printn "."; else { print "*** FAIL: if 1 else"; }
-# if 1 <= 1 then printn "."; else { print "*** FAIL: test 3"; }
- if 1234 < 1234 then { print "*** FAIL: test 4"; quitbird; } else print "ok";
- is = [ 2, 3, 4, 7..11 ];
- print " must be true: ", 1180::/16 ~ [ 1100::/8{ 15 , 17 } ];
- print " data types; must be true: ", 12::34 = 12::34, ",", 1 ~ [1,2,3], ",", 5 ~ [1..20], ",", 10 ~ is, ",", 2 ~ [ 1, 2, 3 ], ",", 5 ~ [ 4 .. 7 ], ",", 12::34 ~ [ 12::33..12::35 ], ",", 1020::34 ~ 1000::/8, ",", 1000::/8 ~ 1000::/8, ",", 1000::/8 ~ [ 1000::/8+ ];
- print " must be true: ", true && true, ",", true || false;
-
-# print " must be true: ", defined(1), ",", defined(1.2.3.4), ",", 1 != 2, ",", 1 <= 2;
- print " data types: must be false: ", 1 ~ [ 2, 3, 4 ], ",", 5 ~ is, ",", 12::34 ~ [ 12::33, 12::35 ], ",", (1,2) > (2,2), ",", (1,1) > (1,1), ",", 1000::/9 ~ [ 1000::/8- ], ",", 1000::/17 ~ [ 1000::/8{ 15 , 16 } ], ",", true && false;
-
- px = 1020::/18;
- print "Testing prefixes: 1020::/18 = ", px;
- p = 1234:5678::;
- print "Testing mask : 1200:: = ", p.mask(8);
-
- pp = (1, 2);
- print "Testing pairs: (1,2) = ", (1,2), " = ", pp;
- print "Testing enums: ", RTS_DUMMY, " ", RTS_STATIC;
-
- s = "Hello";
- print "Testing string: ", s, " true: ", s ~ "Hell*", " false: ", s ~ "ell*";
-
- b = true;
- print "Testing bool: ", b, ", ", !b;
-
- pxs = [ 1102::/16, 1104::/16+];
- print "Testing prefix sets: ";
- print pxs;
- print " must be true: ", 1102::/16 ~ pxs, ",", 1104::/16 ~ pxs, ",", 1104::/18 ~ pxs, ",", 1104::/32 ~ pxs;
- print " must be false: ", 1101::/16 ~ pxs, ",", 1103::/16 ~ pxs, ",", 1102::/15 ~ pxs, ",", 1102::/17 ~ pxs, ",",
- 1102::/32 ~ pxs, ",", 1104::/15 ~ pxs;
-
- test_pxset([ 1000::/16{8,12}, 2000::/16{24,28} ]);
- print "What will this do? ", [ 1, 2, 1, 1, 1, 3, 4, 1, 1, 1, 5 ];
-
- print "Testing functions...";
-# callme ( 1, 2 );
- callme ( 2, 2 );
- callme ( 2, 2 );
- callme ( 3, 2 );
- callme ( 4, 2 );
- callme ( 7, 2 );
-
- i = fifteen();
- print "Testing function calls: 15 = ", i;
-
- paths();
-
- print "done";
- quitbird;
-# print "*** FAIL: this is unreachable";
-}
-
-filter testf
-int j;
-{
- print "Heya, filtering route to ", net.ip, " prefixlen ", net.len, " source ", source;
- print "This route was from ", from;
- j = 7;
- j = 17;
- if rip_metric > 15 then {
- reject "RIP Metric is more than infinity";
- }
- rip_metric = 14;
- unset(rip_metric);
-
- accept "ok I take that";
-}
-
-eval __startup(); \ No newline at end of file
diff --git a/filter/tree.c b/filter/tree.c
index ee9f448a..f8379fa8 100644
--- a/filter/tree.c
+++ b/filter/tree.c
@@ -63,7 +63,7 @@ tree_compare(const void *p1, const void *p2)
* build_tree
* @from: degenerated tree (linked by @tree->left) to be transformed into form suitable for find_tree()
*
- * Transforms denerated tree into balanced tree.
+ * Transforms degenerated tree into balanced tree.
*/
struct f_tree *
build_tree(struct f_tree *from)
@@ -82,7 +82,7 @@ build_tree(struct f_tree *from)
if (len <= 1024)
buf = alloca(len * sizeof(struct f_tree *));
else
- buf = malloc(len * sizeof(struct f_tree *));
+ buf = xmalloc(len * sizeof(struct f_tree *));
/* Convert a degenerated tree into an sorted array */
i = 0;
@@ -94,7 +94,7 @@ build_tree(struct f_tree *from)
root = build_tree_rec(buf, 0, len);
if (len > 1024)
- free(buf);
+ xfree(buf);
return root;
}
@@ -162,12 +162,15 @@ void
tree_format(struct f_tree *t, buffer *buf)
{
buffer_puts(buf, "[");
-
- tree_node_format(t, buf);
- /* Undo last separator */
+ tree_node_format(t, buf);
+
+ if (buf->pos == buf->end)
+ return;
+
+ /* Undo last separator */
if (buf->pos[-1] != '[')
buf->pos -= 2;
-
+
buffer_puts(buf, "]");
}
diff --git a/filter/tree_test.c b/filter/tree_test.c
new file mode 100644
index 00000000..e224a559
--- /dev/null
+++ b/filter/tree_test.c
@@ -0,0 +1,304 @@
+/*
+ * Filters: Utility Functions Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "filter/filter.h"
+#include "conf/conf.h"
+
+#define MAX_TREE_HEIGHT 13
+
+static void
+start_conf_env(void)
+{
+ bt_bird_init();
+
+ pool *p = rp_new(&root_pool, "helper_pool");
+ linpool *l = lp_new(p, 4080);
+ cfg_mem = l;
+}
+
+static struct f_tree *
+new_tree(uint id)
+{
+ struct f_tree *tree = f_new_tree();
+ tree->from.type = tree->to.type = T_INT;
+ tree->from.val.i = tree->to.val.i = id;
+
+ return tree;
+}
+
+/*
+ * Show subtree in infix notation
+ */
+static void
+show_subtree(struct f_tree *node)
+{
+ if (!node)
+ return;
+
+ show_subtree(node->left);
+
+ if (node->from.val.i == node->to.val.i)
+ bt_debug("%u ", node->from.val.i);
+ else
+ bt_debug("%u..%u ", node->from.val.i, node->to.val.i);
+
+ show_subtree(node->right);
+}
+
+static void
+show_tree2(struct f_tree *root_node, const char *tree_name)
+{
+ bt_debug("%s: \n", tree_name);
+ bt_debug("[ ");
+ show_subtree(root_node);
+ bt_debug("]\n\n");
+}
+
+#define show_tree(tree) show_tree2(tree, #tree);
+
+static uint
+get_nodes_count_full_bin_tree(uint height)
+{
+ return (bt_naive_pow(2, height+1) - 1);
+}
+
+static struct f_tree *
+get_balanced_full_subtree(uint height, uint idx)
+{
+ struct f_tree *node = new_tree(idx);
+ if (height > 0)
+ {
+ uint nodes_in_subtree = get_nodes_count_full_bin_tree(--height);
+ node->left = get_balanced_full_subtree(height, idx - nodes_in_subtree/2 - 1);
+ node->right = get_balanced_full_subtree(height, idx + nodes_in_subtree/2 + 1);
+ }
+ return node;
+}
+
+static struct f_tree *
+get_balanced_full_tree(uint height)
+{
+ return get_balanced_full_subtree(height, get_nodes_count_full_bin_tree(height)/2);
+}
+
+static struct f_tree *
+get_degenerated_left_tree(uint nodes_count)
+{
+ struct f_tree *old = NULL;
+ struct f_tree *new = NULL;
+ uint i;
+
+ for (i = 0; i < nodes_count; i++)
+ {
+ old = new;
+ new = new_tree(nodes_count-1-i);
+ new->left = old;
+ }
+
+ return new;
+}
+
+static struct f_tree *
+get_random_degenerated_left_tree(uint nodes_count)
+{
+ struct f_tree *tree = get_degenerated_left_tree(nodes_count);
+
+ size_t avaible_indexes_size = nodes_count * sizeof(byte);
+ byte *avaible_indexes = malloc(avaible_indexes_size);
+ memset(avaible_indexes, 0, avaible_indexes_size);
+
+ struct f_tree *n;
+ for (n = tree; n; n = n->left)
+ {
+ uint selected_idx;
+ do
+ {
+ selected_idx = bt_random() % nodes_count;
+ } while(avaible_indexes[selected_idx] != 0);
+
+ avaible_indexes[selected_idx] = 1;
+ n->from.type = n->to.type = T_INT;
+ n->from.val.i = n->to.val.i = selected_idx;
+ }
+
+ free(avaible_indexes);
+ return tree;
+}
+
+static struct f_tree *
+get_balanced_tree_with_ranged_values(uint nodes_count)
+{
+ struct f_tree *tree = get_degenerated_left_tree(nodes_count);
+
+ uint idx = 0;
+ struct f_tree *n;
+ for (n = tree; n; n = n->left)
+ {
+ n->from.type = n->to.type = T_INT;
+ n->from.val.i = idx;
+ idx += (uint)bt_random() / nodes_count; /* (... / nodes_count) preventing overflow an uint idx */
+ n->to.val.i = idx++;
+ }
+
+ return build_tree(tree);
+}
+
+
+static int
+t_balancing(void)
+{
+ start_conf_env();
+
+ uint height;
+ for (height = 1; height < MAX_TREE_HEIGHT; height++)
+ {
+ uint nodes_count = get_nodes_count_full_bin_tree(height);
+
+ struct f_tree *simple_degenerated_tree = get_degenerated_left_tree(nodes_count);
+ show_tree(simple_degenerated_tree);
+
+ struct f_tree *expected_balanced_tree = get_balanced_full_tree(height);
+ show_tree(expected_balanced_tree);
+
+ struct f_tree *balanced_tree_from_simple = build_tree(simple_degenerated_tree);
+ show_tree(balanced_tree_from_simple);
+
+ bt_assert(same_tree(balanced_tree_from_simple, expected_balanced_tree));
+ }
+
+ return 1;
+}
+
+
+static int
+t_balancing_random(void)
+{
+ start_conf_env();
+
+ uint height;
+ for (height = 1; height < MAX_TREE_HEIGHT; height++)
+ {
+ uint nodes_count = get_nodes_count_full_bin_tree(height);
+
+ struct f_tree *expected_balanced_tree = get_balanced_full_tree(height);
+
+ uint i;
+ for(i = 0; i < 10; i++)
+ {
+ struct f_tree *random_degenerated_tree = get_random_degenerated_left_tree(nodes_count);
+ show_tree(random_degenerated_tree);
+
+ struct f_tree *balanced_tree_from_random = build_tree(random_degenerated_tree);
+
+ show_tree(expected_balanced_tree);
+ show_tree(balanced_tree_from_random);
+
+ bt_assert(same_tree(balanced_tree_from_random, expected_balanced_tree));
+ }
+ }
+
+ return 1;
+}
+
+static int
+t_find(void)
+{
+ start_conf_env();
+
+ uint height;
+ for (height = 1; height < MAX_TREE_HEIGHT; height++)
+ {
+ uint nodes_count = get_nodes_count_full_bin_tree(height);
+
+ struct f_tree *tree = get_balanced_full_tree(height);
+ show_tree(tree);
+
+ struct f_val looking_up_value = {
+ .type = T_INT
+ };
+ for(looking_up_value.val.i = 0; looking_up_value.val.i < nodes_count; looking_up_value.val.i++)
+ {
+ struct f_tree *found_tree = find_tree(tree, looking_up_value);
+ bt_assert((val_compare(looking_up_value, found_tree->from) == 0) && (val_compare(looking_up_value, found_tree->to) == 0));
+ }
+ }
+
+ return 1;
+}
+
+static uint
+get_max_value_in_unbalanced_tree(struct f_tree *node, uint max)
+{
+ if (!node)
+ return max;
+
+ if (node->to.val.i > max)
+ max = node->to.val.i;
+
+ uint max_left = get_max_value_in_unbalanced_tree(node->left, max);
+ if (max_left > max)
+ max = max_left;
+
+ uint max_right = get_max_value_in_unbalanced_tree(node->right, max);
+ if (max_right > max)
+ max = max_right;
+
+ return max;
+}
+
+static int
+t_find_ranges(void)
+{
+ start_conf_env();
+
+ uint height;
+ for (height = 1; height < MAX_TREE_HEIGHT; height++)
+ {
+ uint nodes_count = get_nodes_count_full_bin_tree(height);
+
+ struct f_tree *tree = get_balanced_tree_with_ranged_values(nodes_count);
+ uint max_value = get_max_value_in_unbalanced_tree(tree, 0);
+
+ show_tree(tree);
+
+ bt_debug("max_value: %u \n", max_value);
+
+ struct f_val needle = {
+ .type = T_INT
+ };
+ uint *i = &needle.val.i;
+
+ for(*i = 0; *i <= max_value; *i += (uint)bt_random()/nodes_count)
+ {
+ struct f_tree *found_tree = find_tree(tree, needle);
+ bt_debug("searching: %u \n", *i);
+ bt_assert(
+ (val_compare(needle, found_tree->from) == 0) || (val_compare(needle, found_tree->to) == 0) ||
+ ((val_compare(needle, found_tree->from) == 1) && (val_compare(needle, found_tree->to) == -1))
+ );
+ }
+ }
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_balancing, "Balancing strong unbalanced trees");
+ bt_test_suite(t_balancing_random, "Balancing random unbalanced trees");
+ bt_test_suite(t_find, "Finding values in trees");
+ bt_test_suite(t_find_ranges, "Finding values in trees with random ranged values");
+
+ return bt_exit_value();
+}
diff --git a/filter/trie.c b/filter/trie.c
index dad87339..adcfcdf3 100644
--- a/filter/trie.c
+++ b/filter/trie.c
@@ -220,7 +220,7 @@ trie_add_prefix(struct f_trie *t, const net_addr *net, uint l, uint h)
}
static int
-trie_match_prefix(struct f_trie *t, ip_addr px, int plen)
+trie_match_prefix(struct f_trie *t, ip_addr px, uint plen)
{
ip_addr pmask = ipa_mkmask(plen);
ip_addr paddr = ipa_and(px, pmask);
@@ -266,7 +266,8 @@ trie_match_prefix(struct f_trie *t, ip_addr px, int plen)
int
trie_match_net(struct f_trie *t, const net_addr *n)
{
- int add = 0;
+ uint add = 0;
+
switch (n->type) {
case NET_IP4:
case NET_VPN4:
@@ -333,9 +334,12 @@ trie_format(struct f_trie *t, buffer *buf)
buffer_puts(buf, "[");
if (t->zero)
- buffer_print(buf, "%I/%d", IPA_NONE, 0);
+ buffer_print(buf, "%I/%d, ", IPA_NONE, 0);
trie_node_format(t->root, buf);
+ if (buf->pos == buf->end)
+ return;
+
/* Undo last separator */
if (buf->pos[-1] != '[')
buf->pos -= 2;
diff --git a/filter/trie_test.c b/filter/trie_test.c
new file mode 100644
index 00000000..7529a5c5
--- /dev/null
+++ b/filter/trie_test.c
@@ -0,0 +1,185 @@
+/*
+ * Filters: Utility Functions Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "filter/filter.h"
+#include "conf/conf.h"
+
+#define TESTS_NUM 10
+#define PREFIXES_NUM 10
+#define PREFIX_TESTS_NUM 10000
+
+#define BIG_BUFFER_SIZE 10000
+
+/* Wrapping structure for storing f_prefixes structures in list */
+struct f_prefix_node {
+ node n;
+ struct f_prefix prefix;
+};
+
+static u32
+xrandom(u32 max)
+{
+ return (bt_random() % max);
+}
+
+static int
+is_prefix_included(list *prefixes, struct f_prefix *needle)
+{
+ struct f_prefix_node *n;
+ WALK_LIST(n, *prefixes)
+ {
+ ip6_addr cmask = ip6_mkmask(MIN(n->prefix.net.pxlen, needle->net.pxlen));
+
+ ip6_addr ip = net6_prefix(&n->prefix.net);
+ ip6_addr needle_ip = net6_prefix(&needle->net);
+
+ if ((ipa_compare(ipa_and(ip, cmask), ipa_and(needle_ip, cmask)) == 0) &&
+ (n->prefix.lo <= needle->net.pxlen) && (needle->net.pxlen <= n->prefix.hi))
+ {
+ bt_debug("FOUND\t" PRIip6 "/%d %d-%d\n", ARGip6(net6_prefix(&n->prefix.net)), n->prefix.net.pxlen, n->prefix.lo, n->prefix.hi);
+ return 1; /* OK */
+ }
+ }
+ return 0; /* FAIL */
+}
+
+static struct f_prefix
+get_random_ip6_prefix(void)
+{
+ struct f_prefix p;
+ u8 pxlen = xrandom(120)+8;
+ ip6_addr ip6 = ip6_build(bt_random(),bt_random(),bt_random(),bt_random());
+ net_addr_ip6 net6 = NET_ADDR_IP6(ip6, pxlen);
+
+ p.net = *((net_addr*) &net6);
+
+ if (bt_random() % 2)
+ {
+ p.lo = 0;
+ p.hi = p.net.pxlen;
+ }
+ else
+ {
+ p.lo = p.net.pxlen;
+ p.hi = net_max_prefix_length[p.net.type];
+ }
+
+ return p;
+}
+
+static void
+generate_random_ipv6_prefixes(list *prefixes)
+{
+ int i;
+ for (i = 0; i < PREFIXES_NUM; i++)
+ {
+ struct f_prefix f = get_random_ip6_prefix();
+
+ struct f_prefix_node *px = calloc(1, sizeof(struct f_prefix_node));
+ px->prefix = f;
+
+ bt_debug("ADD\t" PRIip6 "/%d %d-%d\n", ARGip6(net6_prefix(&px->prefix.net)), px->prefix.net.pxlen, px->prefix.lo, px->prefix.hi);
+ add_tail(prefixes, &px->n);
+ }
+}
+
+static int
+t_match_net(void)
+{
+ bt_bird_init();
+ bt_config_parse(BT_CONFIG_SIMPLE);
+
+ uint round;
+ for (round = 0; round < TESTS_NUM; round++)
+ {
+ list prefixes; /* of structs f_extended_prefix */
+ init_list(&prefixes);
+ struct f_trie *trie = f_new_trie(config->mem, sizeof(struct f_trie_node));
+
+ generate_random_ipv6_prefixes(&prefixes);
+ struct f_prefix_node *n;
+ WALK_LIST(n, prefixes)
+ {
+ trie_add_prefix(trie, &n->prefix.net, n->prefix.lo, n->prefix.hi);
+ }
+
+ int i;
+ for (i = 0; i < PREFIX_TESTS_NUM; i++)
+ {
+ struct f_prefix f = get_random_ip6_prefix();
+ bt_debug("TEST\t" PRIip6 "/%d\n", ARGip6(net6_prefix(&f.net)), f.net.pxlen);
+
+ int should_be = is_prefix_included(&prefixes, &f);
+ int is_there = trie_match_net(trie, &f.net);
+ bt_assert_msg(should_be == is_there, "Prefix " PRIip6 "/%d %s", ARGip6(net6_prefix(&f.net)), f.net.pxlen, (should_be ? "should be found in trie" : "should not be found in trie"));
+ }
+
+ struct f_prefix_node *nxt;
+ WALK_LIST_DELSAFE(n, nxt, prefixes)
+ {
+ free(n);
+ }
+ }
+
+ bt_bird_cleanup();
+ return 1;
+}
+
+static int
+t_trie_same(void)
+{
+ bt_bird_init();
+ bt_config_parse(BT_CONFIG_SIMPLE);
+
+ int round;
+ for (round = 0; round < TESTS_NUM*4; round++)
+ {
+ struct f_trie * trie1 = f_new_trie(config->mem, sizeof(struct f_trie_node));
+ struct f_trie * trie2 = f_new_trie(config->mem, sizeof(struct f_trie_node));
+
+ list prefixes; /* a list of f_extended_prefix structures */
+ init_list(&prefixes);
+ int i;
+ for (i = 0; i < 100; i++)
+ generate_random_ipv6_prefixes(&prefixes);
+
+ struct f_prefix_node *n;
+ WALK_LIST(n, prefixes)
+ {
+ trie_add_prefix(trie1, &n->prefix.net, n->prefix.lo, n->prefix.hi);
+ }
+ WALK_LIST_BACKWARDS(n, prefixes)
+ {
+ trie_add_prefix(trie2, &n->prefix.net, n->prefix.lo, n->prefix.hi);
+ }
+
+ bt_assert(trie_same(trie1, trie2));
+
+ struct f_prefix_node *nxt;
+ WALK_LIST_DELSAFE(n, nxt, prefixes)
+ {
+ free(n);
+ }
+ }
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_match_net, "Testing random prefix matching");
+ bt_test_suite(t_trie_same, "A trie filled forward should be same with a trie filled backward.");
+
+ return bt_exit_value();
+}
diff --git a/lib/Doc b/lib/Doc
index 8af1c669..632bf1f6 100644
--- a/lib/Doc
+++ b/lib/Doc
@@ -2,6 +2,7 @@ H Library functions
S ip.c
S lists.c
S checksum.c bitops.c patmatch.c printf.c xmalloc.c tbf.c
+S mac.c
D resource.sgml
S resource.c
S mempool.c
diff --git a/lib/Makefile b/lib/Makefile
index a9aae66f..a7da9802 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -2,6 +2,10 @@ src := bitops.c checksum.c ip.c lists.c md5.c net.c patmatch.c printf.c sha1.c s
obj := $(src-o-files)
$(all-client)
-src := bitops.c checksum.c event.c idm.c ip.c lists.c md5.c mempool.c net.c patmatch.c printf.c resource.c sha1.c sha256.c sha512.c slab.c slists.c tbf.c xmalloc.c
+src := bitops.c checksum.c event.c idm.c ip.c lists.c mac.c md5.c mempool.c net.c patmatch.c printf.c resource.c sha1.c sha256.c sha512.c slab.c slists.c tbf.c xmalloc.c
obj := $(src-o-files)
$(all-daemon)
+
+tests_src := heap_test.c buffer_test.c event_test.c bitops_test.c patmatch_test.c fletcher16_test.c slist_test.c checksum_test.c lists_test.c mac_test.c ip_test.c hash_test.c printf_test.c
+tests_targets := $(tests_targets) $(tests-target-files)
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/lib/birdlib.h b/lib/birdlib.h
index 188e59b2..bb19df54 100644
--- a/lib/birdlib.h
+++ b/lib/birdlib.h
@@ -35,6 +35,7 @@
#define DELTA(a,b) (((a)>=(b))?(a)-(b):(b)-(a))
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a)))
#define CALL(fn, args...) ({ if (fn) fn(args); })
+#define ADVANCE(w, r, l) ({ r -= l; w += l; })
static inline int uint_cmp(uint i1, uint i2)
{ return (int)(i1 > i2) - (int)(i1 < i2); }
@@ -56,14 +57,12 @@ static inline int u64_cmp(u64 i1, u64 i2)
#define NULL ((void *) 0)
#endif
-
/* Macros for gcc attributes */
#define NORET __attribute__((noreturn))
#define UNUSED __attribute__((unused))
#define PACKED __attribute__((packed))
-
/* Microsecond time */
typedef s64 btime;
@@ -151,7 +150,7 @@ void bug(const char *msg, ...) NORET;
#define L_FATAL "\010" /* Fatal errors */
#define L_BUG "\011" /* BIRD bugs */
-void debug(const char *msg, ...); /* Printf to debug output */
+void debug(const char *msg, ...); /* Printf to debug output */
/* Debugging */
diff --git a/lib/bitops.h b/lib/bitops.h
index 9f954374..af648c26 100644
--- a/lib/bitops.h
+++ b/lib/bitops.h
@@ -9,6 +9,8 @@
#ifndef _BIRD_BITOPTS_H_
#define _BIRD_BITOPTS_H_
+#include "sysdep/config.h"
+
/*
* Bit mask operations:
*
diff --git a/lib/bitops_test.c b/lib/bitops_test.c
new file mode 100644
index 00000000..f816b9d1
--- /dev/null
+++ b/lib/bitops_test.c
@@ -0,0 +1,123 @@
+/*
+ * BIRD Library -- Generic Bit Operations Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h" /* naive_pow() */
+
+#include "lib/bitops.h"
+
+#define MAX_NUM 1000
+#define CHECK_BIT(var,pos) ((var) & (u32)(1<<(pos)))
+
+static int
+t_mkmask(void)
+{
+ int i;
+ u32 compute, expect;
+
+ bt_assert(u32_mkmask(0) == 0x00000000);
+ for (i = 1; i <= 32; i++)
+ {
+ compute = u32_mkmask(i);
+ expect = (u32) (0xffffffff << (32-i));
+ bt_assert_msg(compute == expect, "u32_mkmask(%d) = 0x%08X, expected 0x%08X", i, compute, expect);
+ }
+
+ return 1;
+}
+
+static int
+u32_masklen_expected(u32 mask)
+{
+ int j, expect = 0;
+
+ int valid = 0;
+ for (j = 0; j <= 32; j++)
+ if (mask == (j ? (0xffffffff << (32-j)) : 0)) /* Shifting 32-bit value by 32 bits is undefined behavior */
+ valid = 1;
+
+ if (!valid && mask != 0)
+ expect = 255;
+ else
+ for (j = 0; j <= 31; j++)
+ if (CHECK_BIT(mask, (31-j)))
+ expect = j+1;
+ else
+ break;
+ return expect;
+}
+
+static void
+check_mask(u32 mask)
+{
+ int expected, masklen;
+
+ expected = u32_masklen_expected(mask);
+ masklen = u32_masklen(mask);
+ int ok = (expected == masklen);
+ bt_debug("u32_masklen(Ox%08x) = %d, expected %d %s\n", mask, masklen, expected, ok ? "OK" : "FAIL!");
+ bt_assert(ok);
+}
+
+static int
+t_masklen(void)
+{
+ u32 i;
+
+ check_mask(0x82828282);
+ check_mask(0x00000000);
+
+ for (i = 0; i <= 32; i++)
+ check_mask(((u32) (i ? (0xffffffff << (32-i)) : 0)) & 0xffffffff); /* Shifting 32-bit value by 32 bits is undefined behavior */
+
+ for (i = 0; i <= MAX_NUM; i++)
+ check_mask(bt_random());
+
+ return 1;
+}
+
+static void
+check_log2(u32 n)
+{
+ u32 log = u32_log2(n);
+ u32 low = bt_naive_pow(2, log);
+ u32 high = bt_naive_pow(2, log+1);
+
+ bt_assert_msg(n >= low && n < high,
+ "u32_log2(%u) = %u, %u should be in the range <%u, %u)",
+ n, log, n, low, high);
+}
+
+static int
+t_log2(void)
+{
+ u32 i;
+
+ for (i = 0; i < 31; i++)
+ bt_assert(u32_log2(bt_naive_pow(2, i+1)) == i+1);
+
+ for (i = 1; i < MAX_NUM; i++)
+ check_log2(i);
+
+ for (i = 1; i < MAX_NUM; i++)
+ check_log2(((u32) bt_random()) % 0x0fffffff);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_mkmask, "u32_mkmask()");
+ bt_test_suite(t_masklen, "u32_masklen()");
+ bt_test_suite(t_log2, "u32_log2()");
+
+ return bt_exit_value();
+}
diff --git a/lib/buffer.h b/lib/buffer.h
index cf073e88..2a53f211 100644
--- a/lib/buffer.h
+++ b/lib/buffer.h
@@ -1,3 +1,17 @@
+/*
+ * BIRD Library -- Generic Buffer Structure
+ *
+ * (c) 2013 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2013 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#ifndef _BIRD_BUFFER_H_
+#define _BIRD_BUFFER_H_
+
+#include "lib/resource.h"
+#include "sysdep/config.h"
#define BUFFER(type) struct { type *data; uint used, size; }
@@ -32,4 +46,4 @@
#define BUFFER_FLUSH(v) ({ (v).used = 0; })
-
+#endif /* _BIRD_BUFFER_H_ */
diff --git a/lib/buffer_test.c b/lib/buffer_test.c
new file mode 100644
index 00000000..55179e82
--- /dev/null
+++ b/lib/buffer_test.c
@@ -0,0 +1,147 @@
+/*
+ * BIRD Library -- Buffer Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include <stdlib.h>
+
+#include "test/birdtest.h"
+
+#include "lib/buffer.h"
+
+#define MAX_NUM 33
+
+typedef BUFFER(int) buffer_int;
+static int expected[MAX_NUM];
+static buffer_int buf;
+static struct pool *buffer_pool;
+
+static void
+show_buf(buffer_int *b)
+{
+ uint i;
+ bt_debug(".used = %d, .size = %d\n", b->used, b->size);
+
+ for (i = 0; i < b->used; i++)
+ bt_debug(" .data[%3u] = %-16d expected %-16d %s\n", i, b->data[i], expected[i], (b->data[i] == expected[i] ? "OK" : "FAIL!"));
+}
+
+static void
+fill_expected_array(void)
+{
+ int i;
+
+ for (i = 0; i < MAX_NUM; i++)
+ expected[i] = bt_random();
+}
+
+static void
+init_buffer(void)
+{
+ resource_init();
+ buffer_pool = &root_pool;
+ BUFFER_INIT(buf, buffer_pool, MAX_NUM);
+}
+
+static int
+is_buffer_as_expected(buffer_int *b)
+{
+ show_buf(b);
+
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ bt_assert(b->data[i] == expected[i]);
+ return 1;
+}
+
+static int
+t_buffer_push(void)
+{
+ int i;
+
+ init_buffer();
+ fill_expected_array();
+
+ for (i = 0; i < MAX_NUM; i++)
+ BUFFER_PUSH(buf) = expected[i];
+ is_buffer_as_expected(&buf);
+
+ return 1;
+}
+
+static int
+t_buffer_pop(void)
+{
+ int i;
+
+ init_buffer();
+ fill_expected_array();
+
+ /* POP a half of elements */
+ for (i = 0; i < MAX_NUM; i++)
+ BUFFER_PUSH(buf) = expected[i];
+ for (i = MAX_NUM-1; i >= MAX_NUM/2; i--)
+ BUFFER_POP(buf);
+ for (i = MAX_NUM/2; i < MAX_NUM; i++)
+ BUFFER_PUSH(buf) = expected[i] = bt_random();
+ is_buffer_as_expected(&buf);
+
+ /* POP all of elements */
+ for (i = MAX_NUM-1; i >= 0; i--)
+ BUFFER_POP(buf);
+ bt_assert(buf.used == 0);
+ for (i = 0; i < MAX_NUM; i++)
+ BUFFER_PUSH(buf) = expected[i];
+ is_buffer_as_expected(&buf);
+
+ return 1;
+}
+
+static int
+t_buffer_resize(void)
+{
+ int i;
+
+ init_buffer();
+ BUFFER_INIT(buf, buffer_pool, 0);
+ fill_expected_array();
+
+ for (i = 0; i < MAX_NUM; i++)
+ BUFFER_PUSH(buf) = expected[i];
+ is_buffer_as_expected(&buf);
+ bt_assert(buf.size >= MAX_NUM);
+
+ return 1;
+}
+
+static int
+t_buffer_flush(void)
+{
+ int i;
+
+ init_buffer();
+ fill_expected_array();
+ for (i = 0; i < MAX_NUM; i++)
+ BUFFER_PUSH(buf) = expected[i];
+
+ BUFFER_FLUSH(buf);
+ bt_assert(buf.used == 0);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_buffer_push, "Pushing new elements");
+ bt_test_suite(t_buffer_pop, "Fill whole buffer (PUSH), a half of elements POP and PUSH new elements");
+ bt_test_suite(t_buffer_resize, "Init a small buffer and try overfill");
+ bt_test_suite(t_buffer_flush, "Fill and flush all elements");
+
+ return bt_exit_value();
+}
diff --git a/lib/checksum_test.c b/lib/checksum_test.c
new file mode 100644
index 00000000..7e5658eb
--- /dev/null
+++ b/lib/checksum_test.c
@@ -0,0 +1,94 @@
+/*
+ * BIRD Library -- IP One-Complement Checksum Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include <stdio.h>
+
+#include "test/birdtest.h"
+
+#include "lib/checksum.h"
+
+#define MAX_NUM 10000
+
+static u16
+ipsum_calculate_expected(u32 *a)
+{
+ int i;
+ u32 sum = 0;
+
+ for(i = 0; i < MAX_NUM; i++)
+ {
+ sum += a[i] & 0xffff;
+ bt_debug("low) \t0x%08X \n", sum);
+
+ sum += a[i] >> 16;
+ bt_debug("high) \t0x%08X \n", sum);
+
+ u16 carry = sum >> 16;
+ sum = (sum & 0xffff) + carry;
+ bt_debug("carry) \t0x%08X \n\n", sum);
+ }
+ bt_debug("sum) \t0x%08X \n", sum);
+
+ sum = sum ^ 0xffff;
+ bt_debug("~sum) \t0x%08X \n", sum);
+
+ return sum;
+}
+
+static int
+t_calculate(void)
+{
+ u32 a[MAX_NUM];
+ int i;
+
+ for (i = 0; i < MAX_NUM; i++)
+ a[i] = bt_random();
+
+ u16 sum_calculated = ipsum_calculate(a, sizeof(a), NULL);
+ u16 sum_calculated_2 = ipsum_calculate(&a[0], sizeof(u32)*(MAX_NUM/2), &a[MAX_NUM/2], sizeof(u32)*(MAX_NUM - MAX_NUM/2), NULL);
+ bt_assert(sum_calculated == sum_calculated_2);
+
+ u16 sum_expected = ipsum_calculate_expected(a);
+
+ bt_debug("sum_calculated: %08X \n", sum_calculated);
+ bt_debug("sum_expected: %08X \n", sum_expected);
+
+ bt_assert(sum_calculated == sum_expected);
+
+ return 1;
+}
+
+static int
+t_verify(void)
+{
+ u32 a[MAX_NUM+1];
+ int i;
+
+ for (i = 0; i < MAX_NUM; i++)
+ a[i] = bt_random();
+
+ u16 sum = ipsum_calculate_expected(a);
+
+ a[MAX_NUM] = sum;
+
+ bt_assert(ipsum_verify(a, sizeof(a), NULL));
+
+ return 1;
+}
+
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_calculate, "Checksum of pseudo-random data");
+ bt_test_suite(t_verify, "Verification of pseudo-random data.");
+
+ return bt_exit_value();
+}
diff --git a/lib/event_test.c b/lib/event_test.c
new file mode 100644
index 00000000..92172389
--- /dev/null
+++ b/lib/event_test.c
@@ -0,0 +1,88 @@
+/*
+ * BIRD Library -- Event Processing Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+
+#include "test/birdtest.h"
+
+#include "lib/net.h"
+#include "lib/event.h"
+#include "conf/conf.h"
+#include "nest/locks.h"
+#include "sysdep/unix/unix.h"
+#include "nest/iface.h"
+#include "nest/route.h"
+
+#define MAX_NUM 4
+
+int event_check_points[MAX_NUM];
+
+#define event_hook_body(num) \
+ do { \
+ bt_debug("Event Hook " #num "\n"); \
+ event_check_points[num] = 1; \
+ bt_assert_msg(event_check_points[num-1], "Events should be run in right order"); \
+ } while (0)
+
+static void event_hook_1(void *data UNUSED) { event_hook_body(1); }
+static void event_hook_2(void *data UNUSED) { event_hook_body(2); }
+static void event_hook_3(void *data UNUSED) { event_hook_body(3); }
+
+#define schedule_event(num) \
+ do { \
+ struct event *event_##num = ev_new(&root_pool); \
+ event_##num->hook = event_hook_##num; \
+ ev_schedule(event_##num); \
+ } while (0)
+
+static void
+init_event_check_points(void)
+{
+ int i;
+ event_check_points[0] = 1;
+ for (i = 1; i < MAX_NUM; i++)
+ event_check_points[i] = 0;
+}
+
+static int
+t_ev_run_list(void)
+{
+ int i;
+
+ resource_init();
+ olock_init();
+ io_init();
+ rt_init();
+ if_init();
+// roa_init();
+ config_init();
+ config = config_alloc("");
+
+ init_event_check_points();
+
+ schedule_event(1);
+ schedule_event(2);
+ schedule_event(3);
+
+ ev_run_list(&global_event_list);
+
+ for (i = 1; i < MAX_NUM; i++)
+ bt_assert(event_check_points[i]);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_ev_run_list, "Schedule and run 3 events in right order.");
+
+ return bt_exit_value();
+}
+
diff --git a/lib/fletcher16_test.c b/lib/fletcher16_test.c
new file mode 100644
index 00000000..1020e6ec
--- /dev/null
+++ b/lib/fletcher16_test.c
@@ -0,0 +1,169 @@
+/*
+ * BIRD Library -- Fletcher-16 Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "lib/fletcher16.h"
+
+static u16
+straightforward_fletcher16_compute(const char *data)
+{
+ int count = strlen(data);
+
+ u16 sum1 = 0;
+ u16 sum2 = 0;
+ int index;
+
+ for (index = 0; index < count; ++index)
+ {
+ sum1 = (sum1 + data[index]) % 255;
+ sum2 = (sum2 + sum1) % 255;
+ }
+
+ return (sum2 << 8) | sum1;
+}
+
+static u16
+straightforward_fletcher16_checksum(const char *data)
+{
+ u16 csum;
+ u8 c0,c1,f0,f1;
+
+ csum = straightforward_fletcher16_compute(data);
+ f0 = csum & 0xff;
+ f1 = (csum >> 8) & 0xff;
+ c0 = 0xff - ((f0 + f1) % 0xff);
+ c1 = 0xff - ((f0 + c0) % 0xff);
+
+ return (c1 << 8) | c0;
+}
+
+static int
+test_fletcher16(void *out_, const void *in_, const void *expected_out_)
+{
+ u16 *out = out_;
+ const char *in = in_;
+ const u16 *expected_out = expected_out_;
+
+ struct fletcher16_context ctxt;
+
+ fletcher16_init(&ctxt);
+ fletcher16_update(&ctxt, in, strlen(in));
+ put_u16(out, fletcher16_compute(&ctxt));
+
+ return *out == *expected_out;
+}
+
+static int
+test_fletcher16_checksum(void *out_, const void *in_, const void *expected_out_)
+{
+ u16 *out = out_;
+ const char *in = in_;
+ const u16 *expected_out = expected_out_;
+
+ struct fletcher16_context ctxt;
+ int len = strlen(in);
+
+ fletcher16_init(&ctxt);
+ fletcher16_update(&ctxt, in, len);
+ put_u16(out, fletcher16_final(&ctxt, len, len));
+
+ return *out == *expected_out;
+}
+
+static int
+t_fletcher16_compute(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "\001\002",
+ .out = & (const u16) { 0x0403 },
+ },
+ {
+ .in = "",
+ .out = & ((const u16) { straightforward_fletcher16_compute("") }),
+ },
+ {
+ .in = "a",
+ .out = & ((const u16) { straightforward_fletcher16_compute("a") }),
+ },
+ {
+ .in = "abcd",
+ .out = & ((const u16) { straightforward_fletcher16_compute("abcd") }),
+ },
+ {
+ .in = "message digest",
+ .out = & ((const u16) { straightforward_fletcher16_compute("message digest") }),
+ },
+ {
+ .in = "abcdefghijklmnopqrstuvwxyz",
+ .out = & ((const u16) { straightforward_fletcher16_compute("abcdefghijklmnopqrstuvwxyz") }),
+ },
+ {
+ .in = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ .out = & ((const u16) { straightforward_fletcher16_compute("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") }),
+ },
+ {
+ .in = "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ .out = & ((const u16) { straightforward_fletcher16_compute("12345678901234567890123456789012345678901234567890123456789012345678901234567890") }),
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_fletcher16, bt_fmt_str, bt_fmt_unsigned);
+}
+
+static int
+t_fletcher16_checksum(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "\001\002",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("\001\002") }),
+ },
+ {
+ .in = "",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("") }),
+ },
+ {
+ .in = "a",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("a") }),
+ },
+ {
+ .in = "abcd",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("abcd") }),
+ },
+ {
+ .in = "message digest",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("message digest") }),
+ },
+ {
+ .in = "abcdefghijklmnopqrstuvwxyz",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("abcdefghijklmnopqrstuvwxyz") }),
+ },
+ {
+ .in = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") }),
+ },
+ {
+ .in = "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ .out = & ((const u16) { straightforward_fletcher16_checksum("12345678901234567890123456789012345678901234567890123456789012345678901234567890") }),
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_fletcher16_checksum, bt_fmt_str, bt_fmt_unsigned);
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_fletcher16_compute, "Fletcher-16 Compute Tests");
+ bt_test_suite(t_fletcher16_checksum, "Fletcher-16 Checksum Tests");
+
+ return bt_exit_value();
+}
diff --git a/lib/hash.h b/lib/hash.h
index c2fd8bca..b37d8fa5 100644
--- a/lib/hash.h
+++ b/lib/hash.h
@@ -1,8 +1,18 @@
-
+/*
+ * BIRD Library -- Generic Hash Table
+ *
+ * (c) 2013 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2013 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#ifndef _BIRD_HASH_H_
+#define _BIRD_HASH_H_
#define HASH(type) struct { type **data; uint count, order; }
#define HASH_TYPE(v) typeof(** (v).data)
-#define HASH_SIZE(v) (1 << (v).order)
+#define HASH_SIZE(v) (1U << (v).order)
#define HASH_EQ(v,id,k1,k2...) (id##_EQ(k1, k2))
#define HASH_FN(v,id,key...) ((u32) (id##_FN(key)) >> (32 - (v).order))
@@ -116,12 +126,12 @@
#define HASH_MAY_RESIZE_DOWN_(v,pool,rehash_fn,args) \
({ \
- int _o = (v).order; \
- while (((v).count < ((1 << _o) REHASH_LO_MARK(args))) && \
+ uint _o = (v).order; \
+ while (((v).count < ((1U << _o) REHASH_LO_MARK(args))) && \
(_o > (REHASH_LO_BOUND(args)))) \
_o -= (REHASH_LO_STEP(args)); \
if (_o < (v).order) \
- rehash_fn(&(v), pool, _o - (int) (v).order); \
+ rehash_fn(&(v), pool, _o - (v).order); \
})
@@ -178,6 +188,7 @@
#define HASH_WALK_FILTER_END } while (0)
+
static inline void
mem_hash_init(u64 *h)
{
@@ -185,14 +196,15 @@ mem_hash_init(u64 *h)
}
static inline void
-mem_hash_mix(u64 *h, void *p, int s)
+mem_hash_mix(u64 *h, void *p, uint s)
{
const u64 multiplier = 0xb38bc09a61202731ULL;
const char *pp = p;
uint i;
+
for (i=0; i<s/4; i++)
*h = *h * multiplier + ((const u32 *)pp)[i];
-
+
for (i=s & ~0x3; i<s; i++)
*h = *h * multiplier + pp[i];
}
@@ -204,7 +216,7 @@ mem_hash_value(u64 *h)
}
static inline uint
-mem_hash(void *p, int s)
+mem_hash(void *p, uint s)
{
static u64 h;
mem_hash_init(&h);
@@ -212,3 +224,4 @@ mem_hash(void *p, int s)
return mem_hash_value(&h);
}
+#endif
diff --git a/lib/hash_test.c b/lib/hash_test.c
new file mode 100644
index 00000000..59beb7c0
--- /dev/null
+++ b/lib/hash_test.c
@@ -0,0 +1,305 @@
+/*
+ * BIRD Library -- Hash Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#undef LOCAL_DEBUG
+
+#include "test/birdtest.h"
+
+#include "lib/hash.h"
+
+struct test_node {
+ struct test_node *next; /* Hash chain */
+ u32 key;
+};
+
+#define TEST_KEY(n) n->key
+#define TEST_NEXT(n) n->next
+#define TEST_EQ(n1,n2) n1 == n2
+#define TEST_FN(n) (n) ^ u32_hash((n))
+#define TEST_ORDER 13
+#define TEST_PARAMS /TEST_ORDER, *2, 2, 2, TEST_ORDER, 20
+#define TEST_REHASH test_rehash
+
+HASH_DEFINE_REHASH_FN(TEST, struct test_node);
+
+HASH(struct test_node) hash;
+struct pool *my_pool;
+
+#define MAX_NUM (1 << TEST_ORDER)
+
+struct test_node nodes[MAX_NUM];
+
+static void
+print_rate_of_fulfilment(void)
+{
+ int i;
+ int num_stacked_items = 0;
+
+ for (i = 0; i < MAX_NUM; i++)
+ if (!hash.data[i])
+ num_stacked_items++;
+
+ double percent_stacked_items = ((double)num_stacked_items/(double)MAX_NUM)*100.;
+ bt_debug("%d (%.2f %%) chained of %d hashes \n", num_stacked_items, percent_stacked_items, MAX_NUM);
+}
+
+#ifdef LOCAL_DEBUG
+static void
+dump_nodes(void)
+{
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ bt_debug("nodes[%3d] is at address %14p has .key %3d, .next %14p \n", i, &nodes[i], nodes[i].key, nodes[i].next);
+}
+#endif
+
+static void
+init_hash_(uint order)
+{
+ resource_init();
+ my_pool = rp_new(&root_pool, "Test pool");
+
+ HASH_INIT(hash, my_pool, order);
+
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ nodes[i].key = i;
+ nodes[i].next = NULL;
+ }
+
+ bt_debug("MAX_NUM %d \n", MAX_NUM);
+}
+
+static void
+init_hash(void)
+{
+ init_hash_(TEST_ORDER);
+}
+
+static void
+validate_filled_hash(void)
+{
+ int i;
+ struct test_node *node;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ node = HASH_FIND(hash, TEST, nodes[i].key);
+ bt_assert_msg(node->key == nodes[i].key, "Hash should be filled, to find (%p) the node[%d] (%p) with .key = %u, .next %p", node, i, &nodes[i], nodes[i].key, nodes[i].next);
+ }
+
+ print_rate_of_fulfilment();
+}
+
+static void
+validate_empty_hash(void)
+{
+ int i;
+ struct test_node *node;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ node = HASH_FIND(hash, TEST, nodes[i].key);
+ bt_assert_msg(node == NULL, "Hash should be empty, to find (%p) the node[%d] (%p) with .key %u, .next %p", node, i, &nodes[i], nodes[i].key, nodes[i].next);
+ }
+}
+
+static void
+fill_hash(void)
+{
+ int i;
+ struct test_node *node;
+
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ nodes[i].key = i;
+ node = &nodes[i];
+ HASH_INSERT(hash, TEST, node);
+ }
+}
+
+static int
+t_insert_find(void)
+{
+ init_hash();
+ fill_hash();
+ validate_filled_hash();
+
+ return 1;
+}
+
+static int
+t_insert_find_random(void)
+{
+ init_hash();
+
+ int i;
+ struct test_node *node;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ nodes[i].key = bt_random();
+ node = &nodes[i];
+ HASH_INSERT(hash, TEST, node);
+ }
+
+ validate_filled_hash();
+
+ return 1;
+}
+
+static int
+t_insert2_find(void)
+{
+ init_hash_(1);
+
+ int i;
+ struct test_node *node;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ nodes[i].key = i;
+ node = &nodes[i];
+ HASH_INSERT2(hash, TEST, my_pool, node);
+ }
+ bt_assert_msg(hash.order != 1, "The hash should auto-resize from order 2^1. The order of the hash is 2^%u.", hash.order);
+
+ validate_filled_hash();
+
+ return 1;
+}
+
+static int
+t_walk(void)
+{
+ init_hash();
+ fill_hash();
+
+ uint i;
+ uint check[MAX_NUM];
+ for (i = 0; i < MAX_NUM; i++)
+ check[i] = 0;
+
+ HASH_WALK(hash, next, n)
+ {
+ check[n->key]++;
+ }
+ HASH_WALK_END;
+
+ for (i = 0; i < MAX_NUM; i++)
+ bt_assert(check[i] == 1);
+
+ return 1;
+}
+
+static int
+t_walk_delsafe_delete(void)
+{
+ init_hash();
+ fill_hash();
+
+ HASH_WALK_DELSAFE(hash, next, n)
+ {
+ HASH_DELETE(hash, TEST, n->key);
+ }
+ HASH_WALK_DELSAFE_END;
+
+ validate_empty_hash();
+
+ return 1;
+}
+
+static int
+t_walk_delsafe_remove(void)
+{
+ init_hash();
+ fill_hash();
+
+ HASH_WALK_DELSAFE(hash, next, n)
+ {
+ HASH_REMOVE(hash, TEST, n);
+ }
+ HASH_WALK_DELSAFE_END;
+
+ validate_empty_hash();
+
+ return 1;
+}
+
+static int
+t_walk_delsafe_delete2(void)
+{
+ init_hash();
+ fill_hash();
+
+ HASH_WALK_DELSAFE(hash, next, n)
+ {
+ HASH_DELETE2(hash, TEST, my_pool, n->key);
+ }
+ HASH_WALK_DELSAFE_END;
+
+ validate_empty_hash();
+
+ return 1;
+}
+
+static int
+t_walk_delsafe_remove2(void)
+{
+ init_hash();
+ fill_hash();
+
+ HASH_WALK_DELSAFE(hash, next, n)
+ {
+ HASH_REMOVE2(hash, TEST, my_pool, n);
+ }
+ HASH_WALK_DELSAFE_END;
+
+ validate_empty_hash();
+
+ return 1;
+}
+
+static int
+t_walk_filter(void)
+{
+ init_hash();
+ fill_hash();
+
+ uint i;
+ uint check[MAX_NUM];
+ for (i = 0; i < MAX_NUM; i++)
+ check[i] = 0;
+
+ HASH_WALK_FILTER(hash, next, n, m)
+ {
+ bt_assert(n == *m);
+ check[n->key]++;
+ }
+ HASH_WALK_FILTER_END;
+
+ for (i = 0; i < MAX_NUM; i++)
+ bt_assert(check[i] == 1);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_insert_find, "HASH_INSERT and HASH_FIND");
+ bt_test_suite(t_insert_find_random, "HASH_INSERT pseudo-random keys and HASH_FIND");
+ bt_test_suite(t_insert2_find, "HASH_INSERT2 and HASH_FIND. HASH_INSERT2 is HASH_INSERT and a smart auto-resize function");
+ bt_test_suite(t_walk, "HASH_WALK");
+ bt_test_suite(t_walk_delsafe_delete, "HASH_WALK_DELSAFE and HASH_DELETE");
+ bt_test_suite(t_walk_delsafe_delete2, "HASH_WALK_DELSAFE and HASH_DELETE2. HASH_DELETE2 is HASH_DELETE and smart auto-resize function");
+ bt_test_suite(t_walk_delsafe_remove, "HASH_WALK_DELSAFE and HASH_REMOVE");
+ bt_test_suite(t_walk_delsafe_remove2, "HASH_WALK_DELSAFE and HASH_REMOVE2. HASH_REMOVE2 is HASH_REMOVE and smart auto-resize function");
+ bt_test_suite(t_walk_filter, "HASH_WALK_FILTER");
+
+ return bt_exit_value();
+}
diff --git a/lib/heap_test.c b/lib/heap_test.c
new file mode 100644
index 00000000..c04a0450
--- /dev/null
+++ b/lib/heap_test.c
@@ -0,0 +1,186 @@
+/*
+ * BIRD Library -- Universal Heap Macros Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "sysdep/config.h"
+#include "lib/heap.h"
+
+#define MAX_NUM 1000
+#define SPECIAL_KEY -3213
+
+#define MY_CMP(x, y) ((x) < (y))
+
+#define MY_HEAP_SWAP(heap,a,b,t) \
+ do { \
+ bt_debug("swap(%u %u) ", a, b); \
+ HEAP_SWAP(heap,a,b,t); \
+ } while(0)
+
+static int heap[MAX_NUM+1];
+static uint num;
+
+/*
+ * A valid heap must follow these rules:
+ * - `num >= 0`
+ * - `heap[i] >= heap[i / 2]` for each `i` in `[2, num]`
+ */
+static int
+is_heap_valid(int heap[], uint num)
+{
+ uint i;
+
+ if (num > MAX_NUM)
+ return 0;
+
+ for (i = 2; i <= num; i++)
+ if (heap[i] < heap[i / 2])
+ return 0;
+
+ return 1;
+}
+
+static void
+show_heap(void)
+{
+ uint i;
+ bt_debug("\n");
+ bt_debug("numbers %u; ", num);
+ for (i = 0; i <= num; i++)
+ bt_debug("%d ", heap[i]);
+ bt_debug(is_heap_valid(heap, num) ? "OK" : "NON-VALID HEAP!");
+ bt_debug("\n");
+}
+
+static void
+init_heap(void)
+{
+ uint i;
+ num = 0;
+ heap[0] = SPECIAL_KEY; /* heap[0] should be unused */
+ for (i = 1; i <= MAX_NUM; i++)
+ heap[i] = 0;
+}
+
+static int
+t_heap_insert(void)
+{
+ uint i;
+
+ init_heap();
+
+ for (i = MAX_NUM; i >= 1; i--)
+ {
+ bt_debug("ins %u at pos %u ", i, MAX_NUM - i);
+ heap[MAX_NUM - i + 1] = i;
+ HEAP_INSERT(heap, ++num, int, MY_CMP, MY_HEAP_SWAP);
+ show_heap();
+ bt_assert(is_heap_valid(heap, num));
+ }
+
+ return 1;
+}
+
+static int
+t_heap_increase_decrease(void)
+{
+ uint i;
+
+ t_heap_insert();
+
+ for (i = 1; i <= MAX_NUM; i++)
+ {
+ if ((int)i > heap[i])
+ {
+ bt_debug("inc %u ", i);
+ heap[i] = i;
+ HEAP_INCREASE(heap, num, int, MY_CMP, MY_HEAP_SWAP, i);
+ }
+ else if ((int)i < heap[i])
+ {
+ bt_debug("dec %u ", i);
+ heap[i] = i;
+ HEAP_INCREASE(heap, num, int, MY_CMP, MY_HEAP_SWAP, i);
+ }
+ show_heap();
+ bt_assert(is_heap_valid(heap, num));
+ }
+
+ return 1;
+}
+
+static int
+t_heap_delete(void)
+{
+ uint i;
+
+ t_heap_insert();
+
+ for (i = 1; i <= num; i++)
+ {
+ bt_debug("del at pos %u ", i);
+ HEAP_DELETE(heap, num, int, MY_CMP, MY_HEAP_SWAP, i);
+ show_heap();
+ bt_assert(is_heap_valid(heap, num));
+ }
+
+ return 1;
+}
+
+static int
+t_heap_0(void)
+{
+ init_heap();
+ t_heap_insert();
+ t_heap_increase_decrease();
+ t_heap_delete();
+
+ return heap[0] == SPECIAL_KEY;
+}
+
+static int
+t_heap_insert_random(void)
+{
+ int i, j;
+ int expected[MAX_NUM+1];
+
+ init_heap();
+
+ for (i = 1; i <= MAX_NUM; i++)
+ {
+ heap[i] = expected[i] = bt_random();
+ HEAP_INSERT(heap, ++num, int, MY_CMP, MY_HEAP_SWAP);
+ show_heap();
+ bt_assert(is_heap_valid(heap, num));
+ }
+
+ for (i = 1; i <= MAX_NUM; i++)
+ for (j = 1; j <= MAX_NUM; j++)
+ if(expected[i] == heap[j])
+ break;
+ else if (j == MAX_NUM)
+ {
+ show_heap();
+ bt_abort_msg("Did not find a number %d in heap.", expected[i]);
+ }
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_heap_insert, "Inserting a descending sequence of numbers (the worst case)");
+ bt_test_suite(t_heap_insert_random, "Inserting pseudo-random numbers");
+ bt_test_suite(t_heap_increase_decrease, "Increasing/Decreasing");
+ bt_test_suite(t_heap_delete, "Deleting");
+ bt_test_suite(t_heap_0, "Is a heap[0] really unused?");
+
+ return bt_exit_value();
+}
diff --git a/lib/idm.c b/lib/idm.c
index 16d0e855..66e311c6 100644
--- a/lib/idm.c
+++ b/lib/idm.c
@@ -53,7 +53,7 @@ idm_alloc(struct idm *m)
ASSERT(0);
- found:
+found:
ASSERT(i < 0x8000000);
m->pos = i;
diff --git a/lib/ip.c b/lib/ip.c
index 5e039c12..9497248c 100644
--- a/lib/ip.c
+++ b/lib/ip.c
@@ -306,7 +306,7 @@ ip6_pton(const char *a, ip6_addr *o)
if (*a == ':' && a[1])
a++;
- else if (*a == '.' && (i == 6 || i < 6 && hfil >= 0))
+ else if (*a == '.' && (i == 6 || (i < 6 && hfil >= 0)))
{ /* Embedded IPv4 address */
ip4_addr x;
if (!ip4_pton(start, &x))
diff --git a/lib/ip.h b/lib/ip.h
index 6541ce1e..86750675 100644
--- a/lib/ip.h
+++ b/lib/ip.h
@@ -91,6 +91,7 @@ typedef ip6_addr ip_addr;
#define ipa_to_u32(x) ip4_to_u32(ipa_to_ip4(x))
#define ipa_is_ip4(a) ip6_is_v4mapped(a)
+#define ipa_is_ip6(a) (! ip6_is_v4mapped(a))
#define IPA_NONE4 ipa_from_ip4(IP4_NONE)
#define IPA_NONE6 ipa_from_ip6(IP6_NONE)
diff --git a/lib/ip_test.c b/lib/ip_test.c
new file mode 100644
index 00000000..fd70c957
--- /dev/null
+++ b/lib/ip_test.c
@@ -0,0 +1,161 @@
+/*
+ * BIRD Library -- IP address functions Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+
+#include "lib/ip.h"
+
+#define IP4_MAX_LEN 16
+
+static int
+test_ipa_pton(void *out_, const void *in_, const void *expected_out_)
+{
+ ip_addr *out = out_;
+ const char *in = in_;
+ const ip_addr *expected_out = expected_out_;
+
+ if (ipa_is_ip4(*expected_out))
+ {
+ ip4_addr ip4;
+ bt_assert(ip4_pton(in, &ip4));
+ *out = ipa_from_ip4(ip4);
+ }
+ else
+ {
+ bt_assert(ip6_pton(in, out));
+ /* ip_addr == ip6_addr */
+ }
+
+ return ipa_equal(*out, *expected_out);
+}
+
+static int
+t_ip4_pton(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "192.168.1.128",
+ .out = & ipa_build4(192, 168, 1, 128),
+ },
+ {
+ .in = "255.255.255.255",
+ .out = & ipa_build4(255, 255, 255, 255),
+ },
+ {
+ .in = "0.0.0.0",
+ .out = & ipa_build4(0, 0, 0, 0),
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_ipa_pton, bt_fmt_str, bt_fmt_ipa);
+}
+
+static int
+t_ip6_pton(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "2001:0db8:0000:0000:0000:0000:1428:57ab",
+ .out = & ipa_build6(0x20010DB8, 0x00000000, 0x00000000, 0x142857AB),
+ },
+ {
+ .in = "2001:0db8:0000:0000:0000::1428:57ab",
+ .out = & ipa_build6(0x20010DB8, 0x00000000, 0x00000000, 0x142857AB),
+ },
+ {
+ .in = "2001:0db8::1428:57ab",
+ .out = & ipa_build6(0x20010DB8, 0x00000000, 0x00000000, 0x142857AB),
+ },
+ {
+ .in = "2001:db8::1428:57ab",
+ .out = & ipa_build6(0x20010DB8, 0x00000000, 0x00000000, 0x142857AB),
+ },
+ {
+ .in = "::1",
+ .out = & ipa_build6(0x00000000, 0x00000000, 0x00000000, 0x00000001),
+ },
+ {
+ .in = "::",
+ .out = & ipa_build6(0x00000000, 0x00000000, 0x00000000, 0x00000000),
+ },
+ {
+ .in = "2605:2700:0:3::4713:93e3",
+ .out = & ipa_build6(0x26052700, 0x00000003, 0x00000000, 0x471393E3),
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_ipa_pton, bt_fmt_str, bt_fmt_ipa);
+}
+
+static int
+test_ipa_ntop(void *out_, const void *in_, const void *expected_out_)
+{
+ char *out = out_;
+ const ip_addr *in = in_;
+ const char *expected_out = expected_out_;
+
+ if (ipa_is_ip4(*in))
+ ip4_ntop(ipa_to_ip4(*in), out);
+ else
+ ip6_ntop(ipa_to_ip6(*in), out);
+
+ int result = strncmp(out, expected_out, ipa_is_ip4(*in) ? IP4_MAX_TEXT_LENGTH : IP6_MAX_TEXT_LENGTH) == 0;
+ return result;
+}
+
+static int
+t_ip4_ntop(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & ipa_build4(192, 168, 1, 128),
+ .out = "192.168.1.128",
+ },
+ {
+ .in = & ipa_build4(255, 255, 255, 255),
+ .out = "255.255.255.255",
+ },
+ {
+ .in = & ipa_build4(0, 0, 0, 1),
+ .out = "0.0.0.1",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_ipa_ntop, bt_fmt_ipa, bt_fmt_str);
+}
+
+static int
+t_ip6_ntop(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & ipa_build6(0x20010DB8, 0x00000000, 0x00000000, 0x142857AB),
+ .out = "2001:db8::1428:57ab",
+ },
+ {
+ .in = & ipa_build6(0x26052700, 0x00000003, 0x00000000, 0x471393E3),
+ .out = "2605:2700:0:3::4713:93e3",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_ipa_ntop, bt_fmt_ipa, bt_fmt_str);
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_ip4_pton, "Converting IPv4 string to ip4_addr struct");
+ bt_test_suite(t_ip6_pton, "Converting IPv6 string to ip6_addr struct");
+ bt_test_suite(t_ip4_ntop, "Converting ip4_addr struct to IPv4 string");
+ bt_test_suite(t_ip6_ntop, "Converting ip6_addr struct to IPv6 string");
+
+ return bt_exit_value();
+}
+
diff --git a/lib/lists.c b/lib/lists.c
index 12ef3cc6..4a48d3b7 100644
--- a/lib/lists.c
+++ b/lib/lists.c
@@ -158,3 +158,15 @@ add_tail_list(list *to, list *l)
q->next = &to->tail_node;
to->tail = q;
}
+
+LIST_INLINE uint
+list_length(list *l)
+{
+ uint len = 0;
+ node *n;
+
+ WALK_LIST(n, *l)
+ len++;
+
+ return len;
+}
diff --git a/lib/lists.h b/lib/lists.h
index 46b33446..066eafbb 100644
--- a/lib/lists.h
+++ b/lib/lists.h
@@ -80,6 +80,7 @@ void rem_node(node *);
void add_tail_list(list *, list *);
void init_list(list *);
void insert_node(node *, node *);
+uint list_length(list *);
#endif
#endif
diff --git a/lib/lists_test.c b/lib/lists_test.c
new file mode 100644
index 00000000..f26a88e2
--- /dev/null
+++ b/lib/lists_test.c
@@ -0,0 +1,287 @@
+/*
+ * BIRD Library -- Linked Lists Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "lib/lists.h"
+
+#define MAX_NUM 1000
+
+static node nodes[MAX_NUM];
+static list l;
+
+static void
+show_list(void)
+{
+ bt_debug("\n");
+ bt_debug("list.null is at %p and point to %p\n", &l.null, l.null);
+ bt_debug("list.head is at %p and point to %p\n", &l.head, l.head);
+ bt_debug("list.tail is at %p and point to %p\n", &l.tail, l.tail);
+
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ bt_debug("n[%3i] is at %p\n", i, &nodes[i]);
+ bt_debug(" prev is at %p and point to %p\n", &(nodes[i].prev), nodes[i].prev);
+ bt_debug(" next is at %p and point to %p\n", &(nodes[i].next), nodes[i].next);
+ }
+}
+
+static int
+is_filled_list_well_linked(void)
+{
+ int i;
+ bt_assert(l.head == &nodes[0]);
+ bt_assert(l.tail == &nodes[MAX_NUM-1]);
+ bt_assert((void *) nodes[0].prev == (void *) &l.head);
+ bt_assert((void *) nodes[MAX_NUM-1].next == (void *) &l.null);
+
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ if (i < (MAX_NUM-1))
+ bt_assert(nodes[i].next == &nodes[i+1]);
+
+ if (i > 0)
+ bt_assert(nodes[i].prev == &nodes[i-1]);
+ }
+
+ return 1;
+}
+
+static int
+is_empty_list_well_unlinked(void)
+{
+ int i;
+
+ bt_assert(l.head == NODE &l.null);
+ bt_assert(l.tail == NODE &l.head);
+ bt_assert(EMPTY_LIST(l));
+
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ bt_assert(nodes[i].next == NULL);
+ bt_assert(nodes[i].prev == NULL);
+ }
+
+ return 1;
+}
+
+static void
+init_list__(list *l, struct node nodes[])
+{
+ init_list(l);
+
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ nodes[i].next = NULL;
+ nodes[i].prev = NULL;
+ }
+}
+
+static void
+init_list_(void)
+{
+ init_list__(&l, (node *) nodes);
+}
+
+static int
+t_add_tail(void)
+{
+ int i;
+
+ init_list_();
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ add_tail(&l, &nodes[i]);
+ bt_debug(".");
+ bt_assert(l.tail == &nodes[i]);
+ bt_assert(l.head == &nodes[0]);
+ bt_assert((void *) nodes[i].next == (void *) &l.null);
+ if (i > 0)
+ {
+ bt_assert(nodes[i-1].next == &nodes[i]);
+ bt_assert(nodes[i].prev == &nodes[i-1]);
+ }
+ }
+ show_list();
+ bt_assert(is_filled_list_well_linked());
+
+ return 1;
+}
+
+static int
+t_add_head(void)
+{
+ int i;
+
+ init_list_();
+ for (i = MAX_NUM-1; i >= 0; i--)
+ {
+ add_head(&l, &nodes[i]);
+ bt_debug(".");
+ bt_assert(l.head == &nodes[i]);
+ bt_assert(l.tail == &nodes[MAX_NUM-1]);
+ if (i < MAX_NUM-1)
+ {
+ bt_assert(nodes[i+1].prev == &nodes[i]);
+ bt_assert(nodes[i].next == &nodes[i+1]);
+ }
+ }
+ show_list();
+ bt_assert(is_filled_list_well_linked());
+
+ return 1;
+}
+
+static void
+insert_node_(node *n, node *after)
+{
+ insert_node(n, after);
+ bt_debug(".");
+}
+
+static int
+t_insert_node(void)
+{
+ int i;
+
+ init_list_();
+
+ // add first node
+ insert_node_(&nodes[0], NODE &l.head);
+
+ // add odd nodes
+ for (i = 2; i < MAX_NUM; i+=2)
+ insert_node_(&nodes[i], &nodes[i-2]);
+
+ // add even nodes
+ for (i = 1; i < MAX_NUM; i+=2)
+ insert_node_(&nodes[i], &nodes[i-1]);
+
+ bt_debug("\n");
+ bt_assert(is_filled_list_well_linked());
+
+ return 1;
+}
+
+static void
+fill_list2(list *l, node nodes[])
+{
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ add_tail(l, &nodes[i]);
+}
+
+static void
+fill_list(void)
+{
+ fill_list2(&l, (node *) nodes);
+}
+
+static int
+t_remove_node(void)
+{
+ int i;
+
+ init_list_();
+
+ /* Fill & Remove & Check */
+ fill_list();
+ for (i = 0; i < MAX_NUM; i++)
+ rem_node(&nodes[i]);
+ bt_assert(is_empty_list_well_unlinked());
+
+ /* Fill & Remove the half of nodes & Check & Remove the rest nodes & Check */
+ fill_list();
+ for (i = 0; i < MAX_NUM; i+=2)
+ rem_node(&nodes[i]);
+
+ int tail_node_index = (MAX_NUM % 2) ? MAX_NUM - 2 : MAX_NUM - 1;
+ bt_assert(l.head == &nodes[1]);
+ bt_assert(l.tail == &nodes[tail_node_index]);
+ bt_assert(nodes[tail_node_index].next == NODE &l.null);
+
+ for (i = 1; i < MAX_NUM; i+=2)
+ {
+ if (i > 1)
+ bt_assert(nodes[i].prev == &nodes[i-2]);
+ if (i < tail_node_index)
+ bt_assert(nodes[i].next == &nodes[i+2]);
+ }
+
+ for (i = 1; i < MAX_NUM; i+=2)
+ rem_node(&nodes[i]);
+ bt_assert(is_empty_list_well_unlinked());
+
+ return 1;
+}
+
+static int
+t_replace_node(void)
+{
+ node head, inside, tail;
+
+ init_list_();
+ fill_list();
+
+ replace_node(&nodes[0], &head);
+ bt_assert(l.head == &head);
+ bt_assert(head.prev == NODE &l.head);
+ bt_assert(head.next == &nodes[1]);
+ bt_assert(nodes[1].prev == &head);
+
+ replace_node(&nodes[MAX_NUM/2], &inside);
+ bt_assert(nodes[MAX_NUM/2-1].next == &inside);
+ bt_assert(nodes[MAX_NUM/2+1].prev == &inside);
+ bt_assert(inside.prev == &nodes[MAX_NUM/2-1]);
+ bt_assert(inside.next == &nodes[MAX_NUM/2+1]);
+
+ replace_node(&nodes[MAX_NUM-1], &tail);
+ bt_assert(l.tail == &tail);
+ bt_assert(tail.prev == &nodes[MAX_NUM-2]);
+ bt_assert(tail.next == NODE &l.null);
+ bt_assert(nodes[MAX_NUM-2].next == &tail);
+
+ return 1;
+}
+
+static int
+t_add_tail_list(void)
+{
+ node nodes2[MAX_NUM];
+ list l2;
+
+ init_list__(&l, (node *) nodes);
+ fill_list2(&l, (node *) nodes);
+
+ init_list__(&l2, (node *) nodes2);
+ fill_list2(&l2, (node *) nodes2);
+
+ add_tail_list(&l, &l2);
+
+ bt_assert(nodes[MAX_NUM-1].next == &nodes2[0]);
+ bt_assert(nodes2[0].prev == &nodes[MAX_NUM-1]);
+ bt_assert(l.tail == &nodes2[MAX_NUM-1]);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_add_tail, "Adding nodes to tail of list");
+ bt_test_suite(t_add_head, "Adding nodes to head of list");
+ bt_test_suite(t_insert_node, "Inserting nodes to list");
+ bt_test_suite(t_remove_node, "Removing nodes from list");
+ bt_test_suite(t_replace_node, "Replacing nodes in list");
+ bt_test_suite(t_add_tail_list, "At the tail of a list adding the another list");
+
+ return bt_exit_value();
+}
diff --git a/lib/mac.c b/lib/mac.c
new file mode 100644
index 00000000..977d6559
--- /dev/null
+++ b/lib/mac.c
@@ -0,0 +1,289 @@
+/*
+ * BIRD Library -- Message Authentication Codes
+ *
+ * (c) 2016 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2016 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+/**
+ * DOC: Message authentication codes
+ *
+ * MAC algorithms are simple cryptographic tools for message authentication.
+ * They use shared a secret key a and message text to generate authentication
+ * code, which is then passed with the message to the other side, where the code
+ * is verified. There are multiple families of MAC algorithms based on different
+ * cryptographic primitives, BIRD implements two MAC families which use hash
+ * functions.
+ *
+ * The first family is simply a cryptographic hash camouflaged as MAC algorithm.
+ * Originally supposed to be (m|k)-hash (message is concatenated with key, and
+ * that is hashed), but later it turned out that a raw hash is more practical.
+ * This is used for cryptographic authentication in OSPFv2, RIP and BFD.
+ *
+ * The second family is the standard HMAC (RFC 2104), using inner and outer hash
+ * to process key and message. HMAC (with SHA) is used in advanced OSPF and RIP
+ * authentication (RFC 5709, RFC 4822).
+ */
+
+#include "lib/mac.h"
+#include "lib/md5.h"
+#include "lib/sha1.h"
+#include "lib/sha256.h"
+#include "lib/sha512.h"
+
+
+/*
+ * Internal hash calls
+ */
+
+static inline void
+hash_init(struct mac_context *mctx, struct hash_context *hctx)
+{ mctx->type->hash_init(hctx); }
+
+static inline void
+hash_update(struct mac_context *mctx, struct hash_context *hctx, const byte *buf, uint len)
+{ mctx->type->hash_update(hctx, buf, len); }
+
+static inline byte *
+hash_final(struct mac_context *mctx, struct hash_context *hctx)
+{ return mctx->type->hash_final(hctx); }
+
+static inline void
+hash_buffer(struct mac_context *mctx, byte *outbuf, const byte *buffer, uint length)
+{
+ struct hash_context hctx;
+
+ hash_init(mctx, &hctx);
+ hash_update(mctx, &hctx, buffer, length);
+ memcpy(outbuf, hash_final(mctx, &hctx), mctx->type->hash_size);
+}
+
+
+/*
+ * (not-really-MAC) Hash
+ */
+
+static void
+nrmh_init(struct mac_context *ctx, const byte *key UNUSED, uint keylen UNUSED)
+{
+ struct nrmh_context *ct = (void *) ctx;
+ hash_init(ctx, &ct->ictx);
+}
+
+static void
+nrmh_update(struct mac_context *ctx, const byte *data, uint datalen)
+{
+ struct nrmh_context *ct = (void *) ctx;
+ hash_update(ctx, &ct->ictx, data, datalen);
+}
+
+static byte *
+nrmh_final(struct mac_context *ctx)
+{
+ struct nrmh_context *ct = (void *) ctx;
+ return hash_final(ctx, &ct->ictx);
+}
+
+
+/*
+ * HMAC
+ */
+
+static void
+hmac_init(struct mac_context *ctx, const byte *key, uint keylen)
+{
+ struct hmac_context *ct = (void *) ctx;
+ uint block_size = ctx->type->block_size;
+ uint hash_size = ctx->type->hash_size;
+
+ byte *keybuf = alloca(block_size);
+ byte *buf = alloca(block_size);
+ uint i;
+
+ /* Hash the key if necessary */
+ if (keylen <= block_size)
+ {
+ memcpy(keybuf, key, keylen);
+ memset(keybuf + keylen, 0, block_size - keylen);
+ }
+ else
+ {
+ hash_buffer(ctx, keybuf, key, keylen);
+ memset(keybuf + hash_size, 0, block_size - hash_size);
+ }
+
+ /* Initialize the inner digest */
+ hash_init(ctx, &ct->ictx);
+ for (i = 0; i < block_size; i++)
+ buf[i] = keybuf[i] ^ 0x36;
+ hash_update(ctx, &ct->ictx, buf, block_size);
+
+ /* Initialize the outer digest */
+ hash_init(ctx, &ct->octx);
+ for (i = 0; i < block_size; i++)
+ buf[i] = keybuf[i] ^ 0x5c;
+ hash_update(ctx, &ct->octx, buf, block_size);
+}
+
+static void
+hmac_update(struct mac_context *ctx, const byte *data, uint datalen)
+{
+ struct hmac_context *ct = (void *) ctx;
+
+ /* Just update the inner digest */
+ hash_update(ctx, &ct->ictx, data, datalen);
+}
+
+static byte *
+hmac_final(struct mac_context *ctx)
+{
+ struct hmac_context *ct = (void *) ctx;
+
+ /* Finish the inner digest */
+ byte *isha = hash_final(ctx, &ct->ictx);
+
+ /* Finish the outer digest */
+ hash_update(ctx, &ct->octx, isha, ctx->type->hash_size);
+ return hash_final(ctx, &ct->octx);
+}
+
+
+/*
+ * Common code
+ */
+
+#define HASH_DESC(name, px, PX) \
+ { name, PX##_SIZE, sizeof(struct nrmh_context), nrmh_init, nrmh_update, nrmh_final, \
+ PX##_SIZE, PX##_BLOCK_SIZE, px##_init, px##_update, px##_final }
+
+#define HMAC_DESC(name, px, PX) \
+ { name, PX##_SIZE, sizeof(struct hmac_context), hmac_init, hmac_update, hmac_final, \
+ PX##_SIZE, PX##_BLOCK_SIZE, px##_init, px##_update, px##_final }
+
+const struct mac_desc mac_table[ALG_MAX] = {
+ [ALG_MD5] = HASH_DESC("Keyed MD5", md5, MD5),
+ [ALG_SHA1] = HASH_DESC("Keyed SHA-1", sha1, SHA1),
+ [ALG_SHA224] = HASH_DESC("Keyed SHA-224", sha224, SHA224),
+ [ALG_SHA256] = HASH_DESC("Keyed SHA-256", sha256, SHA256),
+ [ALG_SHA384] = HASH_DESC("Keyed SHA-384", sha384, SHA384),
+ [ALG_SHA512] = HASH_DESC("Keyed SHA-512", sha512, SHA512),
+ [ALG_HMAC_MD5] = HMAC_DESC("HMAC-MD5", md5, MD5),
+ [ALG_HMAC_SHA1] = HMAC_DESC("HMAC-SHA-1", sha1, SHA1),
+ [ALG_HMAC_SHA224] = HMAC_DESC("HMAC-SHA-224", sha224, SHA224),
+ [ALG_HMAC_SHA256] = HMAC_DESC("HMAC-SHA-256", sha256, SHA256),
+ [ALG_HMAC_SHA384] = HMAC_DESC("HMAC-SHA-384", sha384, SHA384),
+ [ALG_HMAC_SHA512] = HMAC_DESC("HMAC-SHA-512", sha512, SHA512),
+};
+
+
+/**
+ * mac_init - initialize MAC algorithm
+ * @ctx: context to initialize
+ * @id: MAC algorithm ID
+ * @key: MAC key
+ * @keylen: MAC key length
+ *
+ * Initialize MAC context @ctx for algorithm @id (e.g., %ALG_HMAC_SHA1), with
+ * key @key of length @keylen. After that, message data could be added using
+ * mac_update() function.
+ */
+void
+mac_init(struct mac_context *ctx, uint id, const byte *key, uint keylen)
+{
+ ctx->type = &mac_table[id];
+ ctx->type->init(ctx, key, keylen);
+}
+
+#if 0
+/**
+ * mac_update - add more data to MAC algorithm
+ * @ctx: MAC context
+ * @data: data to add
+ * @datalen: length of data
+ *
+ * Push another @datalen bytes of data pointed to by @data into the MAC
+ * algorithm currently in @ctx. Can be called multiple times for the same MAC
+ * context. It has the same effect as concatenating all the data together and
+ * passing them at once.
+ */
+void mac_update(struct mac_context *ctx, const byte *data, uint datalen)
+{ DUMMY; }
+
+/**
+ * mac_final - finalize MAC algorithm
+ * @ctx: MAC context
+ *
+ * Finish MAC computation and return a pointer to the result. No more
+ * @mac_update() calls could be done, but the context may be reinitialized
+ * later.
+ *
+ * Note that the returned pointer points into data in the @ctx context. If it
+ * ceases to exist, the pointer becomes invalid.
+ */
+byte *mac_final(struct mac_context *ctx)
+{ DUMMY; }
+
+/**
+ * mac_cleanup - cleanup MAC context
+ * @ctx: MAC context
+ *
+ * Cleanup MAC context after computation (by filling with zeros). Not strictly
+ * necessary, just to erase sensitive data from stack. This also invalidates the
+ * pointer returned by @mac_final().
+ */
+void mac_cleanup(struct mac_context *ctx)
+{ DUMMY; }
+
+#endif
+
+/**
+ * mac_fill - compute and fill MAC
+ * @id: MAC algorithm ID
+ * @key: secret key
+ * @keylen: key length
+ * @data: message data
+ * @datalen: message length
+ * @mac: place to fill MAC
+ *
+ * Compute MAC for specified key @key and message @data using algorithm @id and
+ * copy it to buffer @mac. mac_fill() is a shortcut function doing all usual
+ * steps for transmitted messages.
+ */
+void
+mac_fill(uint id, const byte *key, uint keylen, const byte *data, uint datalen, byte *mac)
+{
+ struct mac_context ctx;
+
+ mac_init(&ctx, id, key, keylen);
+ mac_update(&ctx, data, datalen);
+ memcpy(mac, mac_final(&ctx), mac_get_length(&ctx));
+ mac_cleanup(&ctx);
+}
+
+/**
+ * mac_verify - compute and verify MAC
+ * @id: MAC algorithm ID
+ * @key: secret key
+ * @keylen: key length
+ * @data: message data
+ * @datalen: message length
+ * @mac: received MAC
+ *
+ * Compute MAC for specified key @key and message @data using algorithm @id and
+ * compare it with received @mac, return whether they are the same. mac_verify()
+ * is a shortcut function doing all usual steps for received messages.
+ */
+int
+mac_verify(uint id, const byte *key, uint keylen, const byte *data, uint datalen, const byte *mac)
+{
+ struct mac_context ctx;
+
+ mac_init(&ctx, id, key, keylen);
+ mac_update(&ctx, data, datalen);
+ int res = !memcmp(mac, mac_final(&ctx), mac_get_length(&ctx));
+ mac_cleanup(&ctx);
+
+ return res;
+}
diff --git a/lib/mac.h b/lib/mac.h
new file mode 100644
index 00000000..b6f3af52
--- /dev/null
+++ b/lib/mac.h
@@ -0,0 +1,121 @@
+/*
+ * BIRD Library -- Message Authentication Codes
+ *
+ * (c) 2016 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2016 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#ifndef _BIRD_MAC_H_
+#define _BIRD_MAC_H_
+
+#include "nest/bird.h"
+#include "lib/sha512.h"
+
+
+#define ALG_UNDEFINED 0
+#define ALG_MD5 0x01
+#define ALG_SHA1 0x02
+#define ALG_SHA224 0x03
+#define ALG_SHA256 0x04
+#define ALG_SHA384 0x05
+#define ALG_SHA512 0x06
+#define ALG_HMAC 0x10
+#define ALG_HMAC_MD5 0x11
+#define ALG_HMAC_SHA1 0x12
+#define ALG_HMAC_SHA224 0x13
+#define ALG_HMAC_SHA256 0x14
+#define ALG_HMAC_SHA384 0x15
+#define ALG_HMAC_SHA512 0x16
+#define ALG_MAX 0x17
+
+/* These are maximums for HASH/MAC lengths and required context space */
+#define MAX_HASH_SIZE SHA512_SIZE
+#define HASH_STORAGE sizeof(struct sha512_context)
+#define MAC_STORAGE sizeof(struct hmac_context)
+
+/* This value is used by several IETF protocols for padding */
+#define HMAC_MAGIC htonl(0x878FE1F3)
+
+/* Generic context used by hash functions */
+struct hash_context
+{
+ u8 data[HASH_STORAGE];
+ u64 align[0];
+};
+
+/* Context for embedded hash (not-really-MAC hash) */
+struct nrmh_context {
+ const struct mac_desc *type;
+ struct hash_context ictx;
+};
+
+/* Context for hash based HMAC */
+struct hmac_context {
+ const struct mac_desc *type;
+ struct hash_context ictx;
+ struct hash_context octx;
+};
+
+/* Generic context used by MAC functions */
+struct mac_context
+{
+ const struct mac_desc *type;
+ u8 data[MAC_STORAGE - sizeof(void *)];
+ u64 align[0];
+};
+
+/* Union to satisfy C aliasing rules */
+union mac_context_union {
+ struct mac_context mac;
+ struct nrmh_context nrmh;
+ struct hmac_context hmac;
+};
+
+
+struct mac_desc {
+ const char *name; /* Name of MAC algorithm */
+ uint mac_length; /* Length of authentication code */
+ uint ctx_length; /* Length of algorithm context */
+ void (*init)(struct mac_context *ctx, const byte *key, uint keylen);
+ void (*update)(struct mac_context *ctx, const byte *data, uint datalen);
+ byte *(*final)(struct mac_context *ctx);
+
+ uint hash_size; /* Hash length, for hash-based MACs */
+ uint block_size; /* Hash block size, for hash-based MACs */
+ void (*hash_init)(struct hash_context *ctx);
+ void (*hash_update)(struct hash_context *ctx, const byte *data, uint datalen);
+ byte *(*hash_final)(struct hash_context *ctx);
+};
+
+extern const struct mac_desc mac_table[ALG_MAX];
+
+static inline const char *mac_type_name(uint id)
+{ return mac_table[id].name; }
+
+static inline uint mac_type_length(uint id)
+{ return mac_table[id].mac_length; }
+
+static inline const char *mac_get_name(struct mac_context *ctx)
+{ return ctx->type->name; }
+
+static inline uint mac_get_length(struct mac_context *ctx)
+{ return ctx->type->mac_length; }
+
+void mac_init(struct mac_context *ctx, uint id, const byte *key, uint keylen);
+
+static inline void mac_update(struct mac_context *ctx, const byte *data, uint datalen)
+{ ctx->type->update(ctx, data, datalen); }
+
+static inline byte *mac_final(struct mac_context *ctx)
+{ return ctx->type->final(ctx); }
+
+static inline void mac_cleanup(struct mac_context *ctx)
+{ memset(ctx, 0, ctx->type->ctx_length); }
+
+void mac_fill(uint id, const byte *key, uint keylen, const byte *data, uint datalen, byte *mac);
+int mac_verify(uint id, const byte *key, uint keylen, const byte *data, uint datalen, const byte *mac);
+
+
+#endif /* _BIRD_MAC_H_ */
diff --git a/lib/mac_test.c b/lib/mac_test.c
new file mode 100644
index 00000000..806fe3e4
--- /dev/null
+++ b/lib/mac_test.c
@@ -0,0 +1,1159 @@
+/*
+ * BIRD Library -- SHA and HMAC-SHA functions tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "lib/mac.h"
+
+
+#define define_test_hash_fn(name,id) \
+static int \
+test_##name(void *out_, const void *in_, const void *expected_out_) \
+{ \
+ char *out = out_; \
+ const char *in = in_; \
+ const char *expected_out = expected_out_; \
+ \
+ struct mac_context ctx; \
+ mac_init(&ctx, id, NULL, 0); \
+ mac_update(&ctx, in, strlen(in)); \
+ byte *out_bin = mac_final(&ctx); \
+ \
+ uint len = mac_type_length(id); \
+ bt_bytes_to_hex(out, out_bin, len); \
+ \
+ return strncmp(out, expected_out, 2*len+1) == 0; \
+}
+
+define_test_hash_fn(md5, ALG_MD5)
+define_test_hash_fn(sha1, ALG_SHA1)
+define_test_hash_fn(sha224, ALG_SHA224)
+define_test_hash_fn(sha256, ALG_SHA256)
+define_test_hash_fn(sha384, ALG_SHA384)
+define_test_hash_fn(sha512, ALG_SHA512)
+
+
+static int
+t_md5(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "",
+ .out = "d41d8cd98f00b204e9800998ecf8427e",
+ },
+ {
+ .in = "a",
+ .out = "0cc175b9c0f1b6a831c399e269772661",
+ },
+ {
+ .in = "abc",
+ .out = "900150983cd24fb0d6963f7d28e17f72",
+ },
+ {
+ .in = "message digest",
+ .out = "f96b697d7cb7938d525a2f31aaf161d0",
+ },
+ {
+ .in = "abcdefghijklmnopqrstuvwxyz",
+ .out = "c3fcd3d76192e4007dfb496cca67e13b",
+ },
+ {
+ .in = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ .out = "d174ab98d277d9f5a5611c2c9f419d9f",
+ },
+ {
+ .in = "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ .out = "57edf4a22be3c955ac49da2e2107b67a",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_md5, bt_fmt_str, bt_fmt_str);
+}
+
+
+/*
+ * Testing SHAxxx functions
+ */
+
+
+static int
+t_sha1(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "",
+ .out = "da39a3ee5e6b4b0d3255bfef95601890afd80709",
+ },
+ {
+ .in = "a",
+ .out = "86f7e437faa5a7fce15d1ddcb9eaeaea377667b8",
+ },
+ {
+ .in = "abc",
+ .out = "a9993e364706816aba3e25717850c26c9cd0d89d",
+ },
+ {
+ .in = "message digest",
+ .out = "c12252ceda8be8994d5fa0290a47231c1d16aae3",
+ },
+ {
+ .in = "abcdefghijklmnopqrstuvwxyz",
+ .out = "32d10c7b8cf96570ca04ce37f2a19d84240d3a89",
+ },
+ {
+ .in = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
+ .out = "761c457bf73b14d27e9e9265c46f4b4dda11f940",
+ },
+ {
+ .in = "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
+ .out = "50abf5706a150990a08b2c5ea40fa0e585554732",
+ },
+ {
+ .in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ .out = "6a64fcc1fb970f7339ce886601775d2efea5cd4b",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha1, bt_fmt_str, bt_fmt_str);
+}
+
+static int
+t_sha224(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "",
+ .out = "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f",
+ },
+ {
+ .in = "a",
+ .out = "abd37534c7d9a2efb9465de931cd7055ffdb8879563ae98078d6d6d5",
+ },
+ {
+ .in = "abc",
+ .out = "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7",
+ },
+ {
+ .in = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ .out = "75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525",
+ },
+ {
+ .in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ .out = "cca7dd1a332a17775d8b0429bdb45055c2d4368ebaab0c7cf385586e",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha224, bt_fmt_str, bt_fmt_str);
+}
+
+static int
+t_sha256(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "",
+ .out = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ },
+ {
+ .in = "a",
+ .out = "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb",
+ },
+ {
+ .in = "abc",
+ .out = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
+ },
+ {
+ .in = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ .out = "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
+ },
+ {
+ .in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ .out = "bf18b43b61652b5d73f41ebf3d72e5e43aebf5076f497dde31ea3de9de4998ef",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha256, bt_fmt_str, bt_fmt_str);
+}
+
+static int
+t_sha384(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "",
+ .out = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b",
+ },
+ {
+ .in = "a",
+ .out = "54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31",
+ },
+ {
+ .in = "abc",
+ .out = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7",
+ },
+ {
+ .in = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ .out = "3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b",
+ },
+ {
+ .in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ .out = "6452928a62ca915a60f2d16ea22cc832d8ecb35443d78a3ff6986e7def9174a1dc16ce2ff65d3ed1666db98357f3c05e",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha384, bt_fmt_str, bt_fmt_str);
+}
+
+static int
+t_sha512(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = "",
+ .out = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e",
+ },
+ {
+ .in = "a",
+ .out = "1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75",
+ },
+ {
+ .in = "abc",
+ .out = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
+ },
+ {
+ .in = "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
+ .out = "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445",
+ },
+ {
+ .in = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ .out = "415509a1c345371acb3e27a88b3835e3b6dfebcbbab5134850596f4db64d7bb22ac42c3cd179446a80c92b8be955460eb536eac01389a7e1fdf09d1dca83922f",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha512, bt_fmt_str, bt_fmt_str);
+}
+
+
+/*
+ * Testing SHAxxx HMAC functions
+ */
+
+#define HMAC_BUFFER_SIZE 160
+struct hmac_data_in {
+ byte key[HMAC_BUFFER_SIZE];
+ uint key_len;
+ byte data[HMAC_BUFFER_SIZE];
+ uint data_len;
+};
+
+static void
+hmac_in_fmt(char *buf, size_t size, const void *data_)
+{
+ uint i;
+ const struct hmac_data_in *data = data_;
+
+ snprintf(buf, size, "data: '");
+ for (i = 0; i < data->data_len; i++)
+ snprintf(buf+strlen(buf), size-strlen(buf), bt_is_char(data->data[i]) ? "%c" : " 0x%02x", data->data[i]);
+
+ snprintf(buf+strlen(buf), size-strlen(buf), "', key: '");
+ for (i = 0; i < data->key_len; i++)
+ snprintf(buf+strlen(buf), size-strlen(buf), bt_is_char(data->key[i]) ? "%c" : " 0x%02x", data->key[i]);
+ snprintf(buf+strlen(buf), size-strlen(buf), "'");
+}
+
+#define define_test_hmac_fn(name,id) \
+static int \
+test_##name##_hmac(void *out_, const void *in_, const void *expected_out_) \
+{ \
+ char *out = out_; \
+ const struct hmac_data_in *in = in_; \
+ const char *expected_out = expected_out_; \
+ \
+ struct mac_context ctx; \
+ mac_init(&ctx, id, in->key, in->key_len); \
+ mac_update(&ctx, in->data, in->data_len); \
+ byte *out_bin = mac_final(&ctx); \
+ \
+ uint len = mac_type_length(id); \
+ bt_bytes_to_hex(out, out_bin, len); \
+ \
+ return strncmp(out, expected_out, 2*len+1) == 0; \
+}
+
+define_test_hmac_fn(md5, ALG_HMAC_MD5)
+define_test_hmac_fn(sha1, ALG_HMAC_SHA1)
+define_test_hmac_fn(sha224, ALG_HMAC_SHA224)
+define_test_hmac_fn(sha256, ALG_HMAC_SHA256)
+define_test_hmac_fn(sha384, ALG_HMAC_SHA384)
+define_test_hmac_fn(sha512, ALG_HMAC_SHA512)
+
+
+static int
+t_md5_hmac(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ },
+ .key_len = 16,
+ .data = "Hi There",
+ .data_len = 8,
+ },
+ .out = "9294727a3638bb1c13f48ef8158bfc9d",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = "Jefe",
+ .key_len = 4,
+ .data = "what do ya want for nothing?",
+ .data_len = 28,
+ },
+ .out = "750c783e6ab0b503eaa86e310a5db738",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 16,
+ .data = {
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ },
+ .data_len = 50,
+ },
+ .out = "56be34521d144c88dbb8c733f0e8b3f6",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
+ 0x15, 0x16, 0x17, 0x18, 0x19,
+ },
+ .key_len = 25,
+ .data = {
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ },
+ .data_len = 50,
+ },
+ .out = "697eaf0aca3a3aea3a75164746ffaa79",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ },
+ .key_len = 16,
+ .data = "Test With Truncation",
+ .data_len = 20,
+ },
+ .out = "56461ef2342edc00f9bab995690efd4c",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 80,
+ .data = "Test Using Larger Than Block-Size Key - Hash Key First",
+ .data_len = 54,
+ },
+ .out = "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 80,
+ .data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data",
+ .data_len = 73,
+ },
+ .out = "6f630fad67cda0ee1fb1f562db3aa53e",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_md5_hmac, hmac_in_fmt, bt_fmt_str);
+}
+
+static int
+t_sha1_hmac(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ },
+ .key_len = 20,
+ .data = "Hi There",
+ .data_len = 8,
+ },
+ .out = "b617318655057264e28bc0b6fb378c8ef146be00",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = "Jefe",
+ .key_len = 4,
+ .data = "what do ya want for nothing?",
+ .data_len = 28,
+ },
+ .out = "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 20,
+ .data = {
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ },
+ .data_len = 50,
+ },
+ .out = "125d7342b9ac11cd91a39af48aa17b4f63f175d3",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
+ 0x15, 0x16, 0x17, 0x18, 0x19,
+ },
+ .key_len = 25,
+ .data = {
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ },
+ .data_len = 50,
+ },
+ .out = "4c9007f4026250c6bc8414f9bf50c86c2d7235da",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ },
+ .key_len = 20,
+ .data = "Test With Truncation",
+ .data_len = 20,
+ },
+ .out = "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 80,
+ .data = "Test Using Larger Than Block-Size Key - Hash Key First",
+ .data_len = 54,
+ },
+ .out = "aa4ae5e15272d00e95705637ce8a3b55ed402112",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 80,
+ .data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data",
+ .data_len = 73,
+ },
+ .out = "e8e99d0f45237d786d6bbaa7965c7808bbff1a91",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
+ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
+ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
+ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
+ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
+ 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61,
+ 0x61, 0x61, 0x61, 0x61,
+ },
+ .key_len = 64,
+ .data = "Test Using key 64 bytes sized",
+ .data_len = 29,
+ },
+ .out = "a55d4fb80962a6b3d2e720705314bee417d68cf6",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha1_hmac, hmac_in_fmt, bt_fmt_str);
+}
+
+static int
+t_sha224_hmac(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ },
+ .key_len = 20,
+ .data = "Hi There",
+ .data_len = 8,
+ },
+ .out = "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = "Jefe",
+ .key_len = 4,
+ .data = "what do ya want for nothing?",
+ .data_len = 28,
+ },
+ .out = "a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 20,
+ .data = {
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ },
+ .data_len = 50,
+ },
+ .out = "7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
+ 0x15, 0x16, 0x17, 0x18, 0x19,
+ },
+ .key_len = 25,
+ .data = {
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ },
+ .data_len = 50,
+ },
+ .out = "6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ },
+ .key_len = 20,
+ .data = "Test With Truncation",
+ .data_len = 20,
+ },
+ .out = "0e2aea68a90c8d37c988bcdb9fca6fa8099cd857c7ec4a1815cac54c",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "Test Using Larger Than Block-Size Key - Hash Key First",
+ .data_len = 54,
+ },
+ .out = "95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.",
+ .data_len = 152,
+ },
+ .out = "3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha224_hmac, hmac_in_fmt, bt_fmt_str);
+}
+
+static int
+t_sha256_hmac(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ },
+ .key_len = 20,
+ .data = "Hi There",
+ .data_len = 8,
+ },
+ .out = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = "Jefe",
+ .key_len = 4,
+ .data = "what do ya want for nothing?",
+ .data_len = 28,
+ },
+ .out = "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 20,
+ .data = {
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ },
+ .data_len = 50,
+ },
+ .out = "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
+ 0x15, 0x16, 0x17, 0x18, 0x19,
+ },
+ .key_len = 25,
+ .data = {
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ },
+ .data_len = 50,
+ },
+ .out = "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ },
+ .key_len = 20,
+ .data = "Test With Truncation",
+ .data_len = 20,
+ },
+ .out = "a3b6167473100ee06e0c796c2955552bfa6f7c0a6a8aef8b93f860aab0cd20c5",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "Test Using Larger Than Block-Size Key - Hash Key First",
+ .data_len = 54,
+ },
+ .out = "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.",
+ .data_len = 152,
+ },
+ .out = "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha256_hmac, hmac_in_fmt, bt_fmt_str);
+}
+
+static int
+t_sha384_hmac(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ },
+ .key_len = 20,
+ .data = "Hi There",
+ .data_len = 8,
+ },
+ .out = "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = "Jefe",
+ .key_len = 4,
+ .data = "what do ya want for nothing?",
+ .data_len = 28,
+ },
+ .out = "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 20,
+ .data = {
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ },
+ .data_len = 50,
+ },
+ .out = "88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc13814b94e3ab6e101a34f27",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
+ 0x15, 0x16, 0x17, 0x18, 0x19,
+ },
+ .key_len = 25,
+ .data = {
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ },
+ .data_len = 50,
+ },
+ .out = "3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c4a7d679ccf8a386c674cffb",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ },
+ .key_len = 20,
+ .data = "Test With Truncation",
+ .data_len = 20,
+ },
+ .out = "3abf34c3503b2a23a46efc619baef897f4c8e42c934ce55ccbae9740fcbc1af4ca62269e2a37cd88ba926341efe4aeea",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "Test Using Larger Than Block-Size Key - Hash Key First",
+ .data_len = 54,
+ },
+ .out = "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.",
+ .data_len = 152,
+ },
+ .out = "6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e799176d3860e6110c46523e",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha384_hmac, hmac_in_fmt, bt_fmt_str);
+}
+
+static int
+t_sha512_hmac(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
+ },
+ .key_len = 20,
+ .data = "Hi There",
+ .data_len = 8,
+ },
+ .out = "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = "Jefe",
+ .key_len = 4,
+ .data = "what do ya want for nothing?",
+ .data_len = 28,
+ },
+ .out = "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ },
+ .key_len = 20,
+ .data = {
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd,
+ },
+ .data_len = 50,
+ },
+ .out = "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
+ 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
+ 0x15, 0x16, 0x17, 0x18, 0x19,
+ },
+ .key_len = 25,
+ .data = {
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd,
+ },
+ .data_len = 50,
+ },
+ .out = "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,
+ },
+ .key_len = 20,
+ .data = "Test With Truncation",
+ .data_len = 20,
+ },
+ .out = "415fad6271580a531d4179bc891d87a650188707922a4fbb36663a1eb16da008711c5b50ddd0fc235084eb9d3364a1454fb2ef67cd1d29fe6773068ea266e96b",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "Test Using Larger Than Block-Size Key - Hash Key First",
+ .data_len = 54,
+ },
+ .out = "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598",
+ },
+ {
+ .in = & (struct hmac_data_in) {
+ .key = {
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
+ 0xaa,
+ },
+ .key_len = 131,
+ .data = "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.",
+ .data_len = 152,
+ },
+ .out = "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58",
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_sha512_hmac, hmac_in_fmt, bt_fmt_str);
+}
+
+
+/*
+ * Testing SHAxxx concating independence
+ */
+
+#include "lib/sha256.h"
+#include "lib/sha512.h"
+
+static int
+t_sha256_concating(void)
+{
+ char hash_a[SHA256_HEX_SIZE];
+ char hash_b[SHA256_HEX_SIZE];
+
+ char *str_a = "a" "bb" "ccc" "dddd" "eeeee" "ffffff";
+ char *str_b1 = "a" ;
+ char *str_b2 = "bb" ;
+ char *str_b3 = "ccc" ;
+ char *str_b4 = "dddd" ;
+ char *str_b5 = "eeeee" ;
+ char *str_b6 = "ffffff";
+
+ struct hash_context ctx_a;
+ sha256_init(&ctx_a);
+ sha256_update(&ctx_a, str_a, strlen(str_a));
+ byte *hash_a_ = sha256_final(&ctx_a);
+ bt_bytes_to_hex(hash_a, hash_a_, SHA256_SIZE);
+
+ struct hash_context ctx_b;
+ sha256_init(&ctx_b);
+ sha256_update(&ctx_b, str_b1, strlen(str_b1));
+ sha256_update(&ctx_b, str_b2, strlen(str_b2));
+ sha256_update(&ctx_b, str_b3, strlen(str_b3));
+ sha256_update(&ctx_b, str_b4, strlen(str_b4));
+ sha256_update(&ctx_b, str_b5, strlen(str_b5));
+ sha256_update(&ctx_b, str_b6, strlen(str_b6));
+ byte *hash_b_ = sha256_final(&ctx_b);
+ bt_bytes_to_hex(hash_b, hash_b_, SHA256_SIZE);
+
+ int are_hash_a_b_equal = (strncmp(hash_a, hash_b, sizeof(hash_a)) == 0);
+ bt_assert_msg(are_hash_a_b_equal, "Hashes A: %s, B: %s should be same", hash_a, hash_b);
+
+ return 1;
+}
+
+
+static int
+t_sha512_concating(void)
+{
+ char hash_a[SHA512_HEX_SIZE];
+ char hash_b[SHA512_HEX_SIZE];
+
+ char *str_a = "a" "bb" "ccc" "dddd" "eeeee" "ffffff";
+ char *str_b1 = "a" ;
+ char *str_b2 = "bb" ;
+ char *str_b3 = "ccc" ;
+ char *str_b4 = "dddd" ;
+ char *str_b5 = "eeeee" ;
+ char *str_b6 = "ffffff";
+
+ struct hash_context ctx_a;
+ sha512_init(&ctx_a);
+ sha512_update(&ctx_a, str_a, strlen(str_a));
+ byte *hash_a_ = sha512_final(&ctx_a);
+ bt_bytes_to_hex(hash_a, hash_a_, SHA512_SIZE);
+
+ struct hash_context ctx_b;
+ sha512_init(&ctx_b);
+ sha512_update(&ctx_b, str_b1, strlen(str_b1));
+ sha512_update(&ctx_b, str_b2, strlen(str_b2));
+ sha512_update(&ctx_b, str_b3, strlen(str_b3));
+ sha512_update(&ctx_b, str_b4, strlen(str_b4));
+ sha512_update(&ctx_b, str_b5, strlen(str_b5));
+ sha512_update(&ctx_b, str_b6, strlen(str_b6));
+ byte *hash_b_ = sha512_final(&ctx_b);
+ bt_bytes_to_hex(hash_b, hash_b_, SHA512_SIZE);
+
+ int are_hash_a_b_equal = (strncmp(hash_a, hash_b, sizeof(hash_a)) == 0);
+ bt_assert_msg(are_hash_a_b_equal, "Hashes A: %s, B: %s should be same", hash_a, hash_b);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_md5, "Testing MD5 by RFC 1321");
+ bt_test_suite(t_sha1, "Testing SHA-1");
+ bt_test_suite(t_sha224, "Testing SHA-224");
+ bt_test_suite(t_sha256, "Testing SHA-256");
+ bt_test_suite(t_sha384, "Testing SHA-384");
+ bt_test_suite(t_sha512, "Testing SHA-512");
+
+ bt_test_suite(t_md5_hmac, "Testing HMAC-MD5 by RFC 2202");
+ bt_test_suite(t_sha1_hmac, "Testing HMAC-SHA-1 by RFC 2202");
+ bt_test_suite(t_sha224_hmac, "Testing HMAC-SHA-224 by RFC 4231");
+ bt_test_suite(t_sha256_hmac, "Testing HMAC-SHA-256 by RFC 4231");
+ bt_test_suite(t_sha384_hmac, "Testing HMAC-SHA-384 by RFC 4231");
+ bt_test_suite(t_sha512_hmac, "Testing HMAC-SHA-512 by RFC 4231");
+
+ bt_test_suite(t_sha256_concating, "Testing concatenation input string to hash using sha256_update");
+ bt_test_suite(t_sha512_concating, "Testing concatenation input string to hash using sha512_update");
+
+ return bt_exit_value();
+}
diff --git a/lib/md5.c b/lib/md5.c
index 8efa62d6..df49de5d 100644
--- a/lib/md5.c
+++ b/lib/md5.c
@@ -39,8 +39,10 @@ static void md5_transform(u32 buf[4], u32 const in[16]);
* initialization constants.
*/
void
-md5_init(struct md5_context *ctx)
+md5_init(struct hash_context *CTX)
{
+ struct md5_context *ctx = (void *) CTX;
+
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
@@ -55,8 +57,9 @@ md5_init(struct md5_context *ctx)
* of bytes.
*/
void
-md5_update(struct md5_context *ctx, const byte *buf, uint len)
+md5_update(struct hash_context *CTX, const byte *buf, uint len)
{
+ struct md5_context *ctx = (void *) CTX;
u32 t;
/* Update bitcount */
@@ -105,8 +108,9 @@ md5_update(struct md5_context *ctx, const byte *buf, uint len)
* 1 0* (64-bit count of bits processed, MSB-first)
*/
byte *
-md5_final(struct md5_context *ctx)
+md5_final(struct hash_context *CTX)
{
+ struct md5_context *ctx = (void *) CTX;
uint count;
byte *p;
@@ -149,13 +153,6 @@ md5_final(struct md5_context *ctx)
return (byte*) ctx->buf;
}
-/* I am a hard paranoid */
-void
-md5_erase_ctx(struct md5_context *ctx)
-{
- memset((char *) ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
-}
-
/* The four core functions - F1 is optimized somewhat */
/* #define F1(x, y, z) (x & y | ~x & z) */
@@ -256,67 +253,3 @@ md5_transform(u32 buf[4], u32 const in[16])
buf[2] += c;
buf[3] += d;
}
-
-
-/*
- * MD5-HMAC
- */
-
-static void
-md5_hash_buffer(byte *outbuf, const byte *buffer, size_t length)
-{
- struct md5_context hd_tmp;
-
- md5_init(&hd_tmp);
- md5_update(&hd_tmp, buffer, length);
- memcpy(outbuf, md5_final(&hd_tmp), MD5_SIZE);
-}
-
-void
-md5_hmac_init(struct md5_hmac_context *ctx, const byte *key, size_t keylen)
-{
- byte keybuf[MD5_BLOCK_SIZE], buf[MD5_BLOCK_SIZE];
-
- /* Hash the key if necessary */
- if (keylen <= MD5_BLOCK_SIZE)
- {
- memcpy(keybuf, key, keylen);
- bzero(keybuf + keylen, MD5_BLOCK_SIZE - keylen);
- }
- else
- {
- md5_hash_buffer(keybuf, key, keylen);
- bzero(keybuf + MD5_SIZE, MD5_BLOCK_SIZE - MD5_SIZE);
- }
-
- /* Initialize the inner digest */
- md5_init(&ctx->ictx);
- int i;
- for (i = 0; i < MD5_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x36;
- md5_update(&ctx->ictx, buf, MD5_BLOCK_SIZE);
-
- /* Initialize the outer digest */
- md5_init(&ctx->octx);
- for (i = 0; i < MD5_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x5c;
- md5_update(&ctx->octx, buf, MD5_BLOCK_SIZE);
-}
-
-void
-md5_hmac_update(struct md5_hmac_context *ctx, const byte *buf, size_t buflen)
-{
- /* Just update the inner digest */
- md5_update(&ctx->ictx, buf, buflen);
-}
-
-byte *
-md5_hmac_final(struct md5_hmac_context *ctx)
-{
- /* Finish the inner digest */
- byte *isha = md5_final(&ctx->ictx);
-
- /* Finish the outer digest */
- md5_update(&ctx->octx, isha, MD5_SIZE);
- return md5_final(&ctx->octx);
-}
diff --git a/lib/md5.h b/lib/md5.h
index 034d764c..4e001851 100644
--- a/lib/md5.h
+++ b/lib/md5.h
@@ -19,29 +19,18 @@
#define MD5_BLOCK_SIZE 64
+struct hash_context;
+
struct md5_context {
u32 buf[4];
u32 bits[2];
byte in[64];
};
-void md5_init(struct md5_context *ctx);
-void md5_update(struct md5_context *ctx, const byte *buf, uint len);
-byte *md5_final(struct md5_context *ctx);
-
-
-/*
- * HMAC-MD5
- */
-
-struct md5_hmac_context {
- struct md5_context ictx;
- struct md5_context octx;
-};
-void md5_hmac_init(struct md5_hmac_context *ctx, const byte *key, size_t keylen);
-void md5_hmac_update(struct md5_hmac_context *ctx, const byte *buf, size_t buflen);
-byte *md5_hmac_final(struct md5_hmac_context *ctx);
+void md5_init(struct hash_context *ctx);
+void md5_update(struct hash_context *ctx, const byte *buf, uint len);
+byte *md5_final(struct hash_context *ctx);
#endif /* _BIRD_MD5_H_ */
diff --git a/lib/net.c b/lib/net.c
index 55eec4b5..53991b4c 100644
--- a/lib/net.c
+++ b/lib/net.c
@@ -109,6 +109,24 @@ net_compare(const net_addr *a, const net_addr *b)
return 0;
}
+#define NET_HASH(a,t) net_hash_##t((const net_addr_##t *) a)
+
+u32
+net_hash(const net_addr *n)
+{
+ switch (n->type)
+ {
+ case NET_IP4: return NET_HASH(n, ip4);
+ case NET_IP6: return NET_HASH(n, ip6);
+ case NET_VPN4: return NET_HASH(n, vpn4);
+ case NET_VPN6: return NET_HASH(n, vpn6);
+ case NET_ROA4: return NET_HASH(n, roa4);
+ case NET_ROA6: return NET_HASH(n, roa6);
+ default: bug("invalid type");
+ }
+}
+
+
int
net_validate(const net_addr *N)
{
diff --git a/lib/net.h b/lib/net.h
index 3deedb1f..e8310894 100644
--- a/lib/net.h
+++ b/lib/net.h
@@ -324,6 +324,8 @@ static inline u32 net_hash_roa4(const net_addr_roa4 *n)
static inline u32 net_hash_roa6(const net_addr_roa6 *n)
{ return ip6_hash(n->prefix) ^ ((u32) n->pxlen << 26); }
+u32 net_hash(const net_addr *a);
+
static inline int net_validate_ip4(const net_addr_ip4 *n)
{
diff --git a/lib/patmatch_test.c b/lib/patmatch_test.c
new file mode 100644
index 00000000..d65f316f
--- /dev/null
+++ b/lib/patmatch_test.c
@@ -0,0 +1,149 @@
+/*
+ * BIRD Library -- Pattern Matching Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+
+#include "nest/bird.h"
+#include "lib/string.h"
+
+#define MATCH (int) { 1 }
+#define NOMATCH (int) { 0 }
+
+struct match_pair {
+ byte *pattern;
+ byte *data;
+};
+
+static int
+test_matching(void *out_, const void *in_, const void *expected_out_)
+{
+ int *out = out_;
+ const struct match_pair *in = in_;
+ const int *expected_out = expected_out_;
+
+ *out = patmatch(in->pattern, in->data);
+
+ return *out == *expected_out;
+}
+
+static void
+fmt_match_pair(char *buf, size_t size, const void *data)
+{
+ const struct match_pair *mp = data;
+ snprintf(buf, size, "pattern: '%s', subject: '%s'", mp->pattern, mp->data);
+}
+
+static void
+fmt_match_result(char *buf, size_t size, const void *data)
+{
+ const int *result = data;
+ snprintf(buf, size, *result ? "match" : "no-match");
+}
+
+static int
+t_matching(void)
+{
+ struct bt_pair test_vectors[] = {
+ {
+ .in = & (struct match_pair) {
+ .pattern = "",
+ .data = "",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "*",
+ .data = "",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "\\*",
+ .data = "*",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "\\*",
+ .data = "a",
+ },
+ .out = & NOMATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "?",
+ .data = "",
+ },
+ .out = & NOMATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "abcdefghijklmnopqrstuvwxyz",
+ .data = "abcdefghijklmnopqrstuvwxyz",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "??????????????????????????",
+ .data = "abcdefghijklmnopqrstuvwxyz",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "*abcdefghijklmnopqrstuvwxyz*",
+ .data = "abcdefghijklmnopqrstuvwxyz",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "ab?defg*jklmnop*stu*wxy*z",
+ .data = "abcdefghijklmnopqrstuvwxyz",
+ },
+ .out = & MATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "abcdefghijklmnopqrstuvwxyz",
+ .data = "abcdefghijklmnopqrtuvwxyz",
+ },
+ .out = & NOMATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "abcdefghijklmnopqr?uvwxyz",
+ .data = "abcdefghijklmnopqrstuvwxyz",
+ },
+ .out = & NOMATCH,
+ },
+ {
+ .in = & (struct match_pair) {
+ .pattern = "aa*aaaaa?aaaaaaaaaaaaaaaaaaa",
+ .data = "aaaaaaaaaaaaaaaaaaaaaaaaaa",
+ },
+ .out = & NOMATCH,
+ },
+ };
+
+ return bt_assert_batch(test_vectors, test_matching, fmt_match_pair, fmt_match_result);
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_matching, "Pattern matching");
+
+ return bt_exit_value();
+}
diff --git a/lib/printf.c b/lib/printf.c
index 844f5969..1632b5f3 100644
--- a/lib/printf.c
+++ b/lib/printf.c
@@ -169,7 +169,7 @@ int bvsnprintf(char *buf, int size, const char *fmt, va_list args)
case ' ': flags |= SPACE; goto repeat;
case '#': flags |= SPECIAL; goto repeat;
case '0': flags |= ZEROPAD; goto repeat;
- }
+ }
/* get field width */
field_width = -1;
diff --git a/lib/printf_test.c b/lib/printf_test.c
new file mode 100644
index 00000000..3981d3da
--- /dev/null
+++ b/lib/printf_test.c
@@ -0,0 +1,70 @@
+/*
+ * BIRD Library -- String Functions Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+
+#include "lib/string.h"
+
+#define BSPRINTF(nw, res, buf, fmt, ...) \
+ do { \
+ int n = bsprintf(buf, fmt, ##__VA_ARGS__); \
+ bt_assert_msg(n == nw, "fmt=\"%s\" returns n=%d, want %d", fmt, n, nw); \
+ bt_assert_msg(buf[n] == 0, "fmt=\"%s\" buf[%d] should be \'\\0\', found 0x%02x", fmt, n, buf[n]); \
+ bt_assert_msg(memcmp(buf, res, nw) == 0, "fmt=\"%s\" writes \"%*s\", want \"%*s\"", fmt, (n < nw ? n : nw), buf, nw, res); \
+ } while (0)
+
+static int
+t_simple(void)
+{
+ char buf[256];
+ memset(buf, 0xa5, 256);
+
+ BSPRINTF(0, "", buf, "", NULL);
+ BSPRINTF(1, "%", buf, "%%", NULL);
+ BSPRINTF(2, "%%", buf, "%%%%", NULL);
+
+ BSPRINTF(1, "\x00", buf, "%c", 0);
+ BSPRINTF(1, "@", buf, "@", 64);
+ BSPRINTF(1, "\xff", buf, "%c", 0xff);
+
+ errno = 5;
+ BSPRINTF(18, "Input/output error", buf, "%m");
+ errno = 0;
+
+ BSPRINTF(18, "Input/output error", buf, "%M", 5);
+
+ BSPRINTF(11, "TeSt%StRiNg", buf, "%s", "TeSt%StRiNg");
+
+ if (sizeof(void *) == 4)
+ BSPRINTF(8, "1a15600d", buf, "%p", (void *) 0x1a15600d);
+ else
+ BSPRINTF(16, "00000fee1a15600d", buf, "%p", (void *) 0xfee1a15600d);
+
+ long ln = 0;
+ BSPRINTF(10, "TeStStRiNg", buf, "TeStS%lntRiNg", &ln);
+ bt_assert_msg(ln == 5, "fmt=\"TeStS%%lntRiNg\", &ln makes ln=%ld, want 5", ln);
+
+ BSPRINTF(2, "%d", buf, "%%d", 1);
+ BSPRINTF(1, "1", buf, "%d", 1);
+ BSPRINTF(2, "+1", buf, "%+d", 1);
+ BSPRINTF(2, " 1", buf, "% d", 1);
+ BSPRINTF(2, "-1", buf, "%d", -1);
+ BSPRINTF(11, "-2147483648", buf, "%d", -2147483648);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_simple, "printf without varargs");
+
+ return bt_exit_value();
+}
diff --git a/lib/sha1.c b/lib/sha1.c
index 73b4b280..d6298b89 100644
--- a/lib/sha1.c
+++ b/lib/sha1.c
@@ -1,5 +1,5 @@
/*
- * BIRD Library -- SHA-1 Hash Function (FIPS 180-1, RFC 3174) and HMAC-SHA-1
+ * BIRD Library -- SHA-1 Hash Function (FIPS 180-1, RFC 3174)
*
* (c) 2015 CZ.NIC z.s.p.o.
*
@@ -17,8 +17,10 @@
void
-sha1_init(struct sha1_context *ctx)
+sha1_init(struct hash_context *CTX)
{
+ struct sha1_context *ctx = (void *) CTX;
+
ctx->h0 = 0x67452301;
ctx->h1 = 0xefcdab89;
ctx->h2 = 0x98badcfe;
@@ -167,8 +169,10 @@ sha1_transform(struct sha1_context *ctx, const byte *data)
* Update the message digest with the contents of BUF with length LEN.
*/
void
-sha1_update(struct sha1_context *ctx, const byte *buf, uint len)
+sha1_update(struct hash_context *CTX, const byte *buf, uint len)
{
+ struct sha1_context *ctx = (void *) CTX;
+
if (ctx->count)
{
/* Fill rest of internal buffer */
@@ -209,11 +213,12 @@ sha1_update(struct sha1_context *ctx, const byte *buf, uint len)
* Returns: 20 bytes representing the digest.
*/
byte *
-sha1_final(struct sha1_context *ctx)
+sha1_final(struct hash_context *CTX)
{
+ struct sha1_context *ctx = (void *) CTX;
u32 t, msb, lsb;
- sha1_update(ctx, NULL, 0); /* flush */
+ sha1_update(CTX, NULL, 0); /* flush */
t = ctx->nblocks;
/* multiply by 64 to make a byte count */
@@ -242,7 +247,7 @@ sha1_final(struct sha1_context *ctx)
ctx->buf[ctx->count++] = 0x80; /* pad character */
while (ctx->count < 64)
ctx->buf[ctx->count++] = 0;
- sha1_update(ctx, NULL, 0); /* flush */
+ sha1_update(CTX, NULL, 0); /* flush */
memset(ctx->buf, 0, 56); /* fill next block with zeroes */
}
@@ -268,81 +273,3 @@ sha1_final(struct sha1_context *ctx)
return ctx->buf;
}
-
-
-/*
- * SHA1-HMAC
- */
-
-/*
- * Shortcut function which puts the hash value of the supplied buffer
- * into outbuf which must have a size of 20 bytes.
- */
-void
-sha1_hash_buffer(byte *outbuf, const byte *buffer, uint length)
-{
- struct sha1_context ctx;
-
- sha1_init(&ctx);
- sha1_update(&ctx, buffer, length);
- memcpy(outbuf, sha1_final(&ctx), SHA1_SIZE);
-}
-
-void
-sha1_hmac_init(struct sha1_hmac_context *ctx, const byte *key, uint keylen)
-{
- byte keybuf[SHA1_BLOCK_SIZE], buf[SHA1_BLOCK_SIZE];
-
- /* Hash the key if necessary */
- if (keylen <= SHA1_BLOCK_SIZE)
- {
- memcpy(keybuf, key, keylen);
- memset(keybuf + keylen, 0, SHA1_BLOCK_SIZE - keylen);
- }
- else
- {
- sha1_hash_buffer(keybuf, key, keylen);
- memset(keybuf + SHA1_SIZE, 0, SHA1_BLOCK_SIZE - SHA1_SIZE);
- }
-
- /* Initialize the inner digest */
- sha1_init(&ctx->ictx);
- int i;
- for (i = 0; i < SHA1_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x36;
- sha1_update(&ctx->ictx, buf, SHA1_BLOCK_SIZE);
-
- /* Initialize the outer digest */
- sha1_init(&ctx->octx);
- for (i = 0; i < SHA1_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x5c;
- sha1_update(&ctx->octx, buf, SHA1_BLOCK_SIZE);
-}
-
-void
-sha1_hmac_update(struct sha1_hmac_context *ctx, const byte *data, uint datalen)
-{
- /* Just update the inner digest */
- sha1_update(&ctx->ictx, data, datalen);
-}
-
-byte *
-sha1_hmac_final(struct sha1_hmac_context *ctx)
-{
- /* Finish the inner digest */
- byte *isha = sha1_final(&ctx->ictx);
-
- /* Finish the outer digest */
- sha1_update(&ctx->octx, isha, SHA1_SIZE);
- return sha1_final(&ctx->octx);
-}
-
-void
-sha1_hmac(byte *outbuf, const byte *key, uint keylen, const byte *data, uint datalen)
-{
- struct sha1_hmac_context ctx;
-
- sha1_hmac_init(&ctx, key, keylen);
- sha1_hmac_update(&ctx, data, datalen);
- memcpy(outbuf, sha1_hmac_final(&ctx), SHA1_SIZE);
-}
diff --git a/lib/sha1.h b/lib/sha1.h
index c019bb49..8666a651 100644
--- a/lib/sha1.h
+++ b/lib/sha1.h
@@ -1,5 +1,5 @@
/*
- * BIRD Library -- SHA-1 Hash Function (FIPS 180-1, RFC 3174) and HMAC-SHA-1
+ * BIRD Library -- SHA-1 Hash Function (FIPS 180-1, RFC 3174)
*
* (c) 2015 CZ.NIC z.s.p.o.
*
@@ -27,6 +27,8 @@
* Internal SHA1 state.
* You should use it just as an opaque handle only.
*/
+struct hash_context;
+
struct sha1_context {
u32 h0, h1, h2, h3, h4;
byte buf[SHA1_BLOCK_SIZE];
@@ -34,15 +36,14 @@ struct sha1_context {
uint count;
};
-
-void sha1_init(struct sha1_context *ctx); /* Initialize new algorithm run in the @ctx context. **/
+void sha1_init(struct hash_context *ctx); /* Initialize new algorithm run in the @ctx context. **/
/*
* Push another @len bytes of data pointed to by @buf onto the SHA1 hash
* currently in @ctx. You can call this any times you want on the same hash (and
* you do not need to reinitialize it by @sha1_init()). It has the same effect
* as concatenating all the data together and passing them at once.
*/
-void sha1_update(struct sha1_context *ctx, const byte *buf, uint len);
+void sha1_update(struct hash_context *ctx, const byte *buf, uint len);
/*
* No more @sha1_update() calls will be done. This terminates the hash and
* returns a pointer to it.
@@ -50,7 +51,7 @@ void sha1_update(struct sha1_context *ctx, const byte *buf, uint len);
* Note that the pointer points into data in the @ctx context. If it ceases to
* exist, the pointer becomes invalid.
*/
-byte *sha1_final(struct sha1_context *ctx);
+byte *sha1_final(struct hash_context *ctx);
/*
* A convenience one-shot function for SHA1 hash. It is equivalent to this
@@ -63,24 +64,5 @@ byte *sha1_final(struct sha1_context *ctx);
*/
void sha1_hash_buffer(byte *outbuf, const byte *buffer, uint length);
-/*
- * SHA1 HMAC message authentication. If you provide @key and @data, the result
- * will be stored in @outbuf.
- */
-void sha1_hmac(byte *outbuf, const byte *key, uint keylen, const byte *data, uint datalen);
-
-/*
- * The HMAC also exists in a stream version in a way analogous to the plain
- * SHA1. Pass this as a context.
- */
-struct sha1_hmac_context {
- struct sha1_context ictx;
- struct sha1_context octx;
-};
-
-void sha1_hmac_init(struct sha1_hmac_context *ctx, const byte *key, uint keylen); /* Initialize HMAC with context @ctx and the given key. See sha1_init(). */
-void sha1_hmac_update(struct sha1_hmac_context *ctx, const byte *data, uint datalen); /* Hash another @datalen bytes of data. See sha1_update(). */
-byte *sha1_hmac_final(struct sha1_hmac_context *ctx); /* Terminate the HMAC and return a pointer to the allocated hash. See sha1_final(). */
-
#endif /* _BIRD_SHA1_H_ */
diff --git a/lib/sha256.c b/lib/sha256.c
index 440245d5..11ff2b05 100644
--- a/lib/sha256.c
+++ b/lib/sha256.c
@@ -1,6 +1,5 @@
/*
- * BIRD Library -- SHA-256 and SHA-224 Hash Functions,
- * HMAC-SHA-256 and HMAC-SHA-224 Functions
+ * BIRD Library -- SHA-256 and SHA-224 Hash Functions
*
* (c) 2015 CZ.NIC z.s.p.o.
*
@@ -17,8 +16,10 @@
// #define SHA256_UNROLLED
void
-sha256_init(struct sha256_context *ctx)
+sha256_init(struct hash_context *CTX)
{
+ struct sha256_context *ctx = (void *) CTX;
+
ctx->h0 = 0x6a09e667;
ctx->h1 = 0xbb67ae85;
ctx->h2 = 0x3c6ef372;
@@ -33,8 +34,10 @@ sha256_init(struct sha256_context *ctx)
}
void
-sha224_init(struct sha224_context *ctx)
+sha224_init(struct hash_context *CTX)
{
+ struct sha224_context *ctx = (void *) CTX;
+
ctx->h0 = 0xc1059ed8;
ctx->h1 = 0x367cd507;
ctx->h2 = 0x3070dd17;
@@ -219,8 +222,10 @@ sha256_transform(struct sha256_context *ctx, const byte *data)
not have any meaning but writing after finalize is sometimes
helpful to mitigate timing attacks. */
void
-sha256_update(struct sha256_context *ctx, const byte *buf, size_t len)
+sha256_update(struct hash_context *CTX, const byte *buf, uint len)
{
+ struct sha256_context *ctx = (void *) CTX;
+
if (ctx->count)
{
/* Fill rest of internal buffer */
@@ -261,11 +266,12 @@ sha256_update(struct sha256_context *ctx, const byte *buf, size_t len)
* Returns: 32 bytes with the message the digest. 28 bytes for SHA-224.
*/
byte *
-sha256_final(struct sha256_context *ctx)
+sha256_final(struct hash_context *CTX)
{
+ struct sha256_context *ctx = (void *) CTX;
u32 t, th, msb, lsb;
- sha256_update(ctx, NULL, 0); /* flush */
+ sha256_update(CTX, NULL, 0); /* flush */
t = ctx->nblocks;
th = 0;
@@ -296,7 +302,7 @@ sha256_final(struct sha256_context *ctx)
ctx->buf[ctx->count++] = 0x80; /* pad character */
while (ctx->count < 64)
ctx->buf[ctx->count++] = 0;
- sha256_update(ctx, NULL, 0); /* flush */;
+ sha256_update(CTX, NULL, 0); /* flush */;
memset(ctx->buf, 0, 56 ); /* fill next block with zeroes */
}
@@ -319,131 +325,3 @@ sha256_final(struct sha256_context *ctx)
return ctx->buf;
}
-
-
-/*
- * SHA256-HMAC
- */
-
-static void
-sha256_hash_buffer(byte *outbuf, const byte *buffer, size_t length)
-{
- struct sha256_context ctx;
-
- sha256_init(&ctx);
- sha256_update(&ctx, buffer, length);
- memcpy(outbuf, sha256_final(&ctx), SHA256_SIZE);
-}
-
-void
-sha256_hmac_init(struct sha256_hmac_context *ctx, const byte *key, size_t keylen)
-{
- byte keybuf[SHA256_BLOCK_SIZE], buf[SHA256_BLOCK_SIZE];
-
- /* Hash the key if necessary */
- if (keylen <= SHA256_BLOCK_SIZE)
- {
- memcpy(keybuf, key, keylen);
- memset(keybuf + keylen, 0, SHA256_BLOCK_SIZE - keylen);
- }
- else
- {
- sha256_hash_buffer(keybuf, key, keylen);
- memset(keybuf + SHA256_SIZE, 0, SHA256_BLOCK_SIZE - SHA256_SIZE);
- }
-
- /* Initialize the inner digest */
- sha256_init(&ctx->ictx);
- int i;
- for (i = 0; i < SHA256_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x36;
- sha256_update(&ctx->ictx, buf, SHA256_BLOCK_SIZE);
-
- /* Initialize the outer digest */
- sha256_init(&ctx->octx);
- for (i = 0; i < SHA256_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x5c;
- sha256_update(&ctx->octx, buf, SHA256_BLOCK_SIZE);
-}
-
-void
-sha256_hmac_update(struct sha256_hmac_context *ctx, const byte *buf, size_t buflen)
-{
- /* Just update the inner digest */
- sha256_update(&ctx->ictx, buf, buflen);
-}
-
-byte *
-sha256_hmac_final(struct sha256_hmac_context *ctx)
-{
- /* Finish the inner digest */
- byte *isha = sha256_final(&ctx->ictx);
-
- /* Finish the outer digest */
- sha256_update(&ctx->octx, isha, SHA256_SIZE);
- return sha256_final(&ctx->octx);
-}
-
-
-/*
- * SHA224-HMAC
- */
-
-static void
-sha224_hash_buffer(byte *outbuf, const byte *buffer, size_t length)
-{
- struct sha224_context ctx;
-
- sha224_init(&ctx);
- sha224_update(&ctx, buffer, length);
- memcpy(outbuf, sha224_final(&ctx), SHA224_SIZE);
-}
-
-void
-sha224_hmac_init(struct sha224_hmac_context *ctx, const byte *key, size_t keylen)
-{
- byte keybuf[SHA224_BLOCK_SIZE], buf[SHA224_BLOCK_SIZE];
-
- /* Hash the key if necessary */
- if (keylen <= SHA224_BLOCK_SIZE)
- {
- memcpy(keybuf, key, keylen);
- memset(keybuf + keylen, 0, SHA224_BLOCK_SIZE - keylen);
- }
- else
- {
- sha224_hash_buffer(keybuf, key, keylen);
- memset(keybuf + SHA224_SIZE, 0, SHA224_BLOCK_SIZE - SHA224_SIZE);
- }
-
- /* Initialize the inner digest */
- sha224_init(&ctx->ictx);
- int i;
- for (i = 0; i < SHA224_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x36;
- sha224_update(&ctx->ictx, buf, SHA224_BLOCK_SIZE);
-
- /* Initialize the outer digest */
- sha224_init(&ctx->octx);
- for (i = 0; i < SHA224_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x5c;
- sha224_update(&ctx->octx, buf, SHA224_BLOCK_SIZE);
-}
-
-void
-sha224_hmac_update(struct sha224_hmac_context *ctx, const byte *buf, size_t buflen)
-{
- /* Just update the inner digest */
- sha256_update(&ctx->ictx, buf, buflen);
-}
-
-byte *
-sha224_hmac_final(struct sha224_hmac_context *ctx)
-{
- /* Finish the inner digest */
- byte *isha = sha224_final(&ctx->ictx);
-
- /* Finish the outer digest */
- sha224_update(&ctx->octx, isha, SHA224_SIZE);
- return sha224_final(&ctx->octx);
-}
diff --git a/lib/sha256.h b/lib/sha256.h
index 381200a9..88a948eb 100644
--- a/lib/sha256.h
+++ b/lib/sha256.h
@@ -1,6 +1,5 @@
/*
- * BIRD Library -- SHA-256 and SHA-224 Hash Functions,
- * HMAC-SHA-256 and HMAC-SHA-224 Functions
+ * BIRD Library -- SHA-256 and SHA-224 Hash Functions
*
* (c) 2015 CZ.NIC z.s.p.o.
*
@@ -25,6 +24,8 @@
#define SHA256_BLOCK_SIZE 64
+struct hash_context;
+
struct sha256_context {
u32 h0, h1, h2, h3, h4, h5, h6, h7;
byte buf[SHA256_BLOCK_SIZE];
@@ -35,39 +36,14 @@ struct sha256_context {
#define sha224_context sha256_context
-void sha256_init(struct sha256_context *ctx);
-void sha224_init(struct sha224_context *ctx);
-
-void sha256_update(struct sha256_context *ctx, const byte *buf, size_t len);
-static inline void sha224_update(struct sha224_context *ctx, const byte *buf, size_t len)
-{ sha256_update(ctx, buf, len); }
-
-byte *sha256_final(struct sha256_context *ctx);
-static inline byte *sha224_final(struct sha224_context *ctx)
-{ return sha256_final(ctx); }
-
-
-/*
- * HMAC-SHA256, HMAC-SHA224
- */
-
-struct sha256_hmac_context
-{
- struct sha256_context ictx;
- struct sha256_context octx;
-};
-
-#define sha224_hmac_context sha256_hmac_context
-
-
-void sha256_hmac_init(struct sha256_hmac_context *ctx, const byte *key, size_t keylen);
-void sha224_hmac_init(struct sha224_hmac_context *ctx, const byte *key, size_t keylen);
+void sha256_init(struct hash_context *ctx);
+void sha224_init(struct hash_context *ctx);
-void sha256_hmac_update(struct sha256_hmac_context *ctx, const byte *buf, size_t buflen);
-void sha224_hmac_update(struct sha224_hmac_context *ctx, const byte *buf, size_t buflen);
+void sha256_update(struct hash_context *ctx, const byte *buf, uint len);
+#define sha224_update sha256_update
-byte *sha256_hmac_final(struct sha256_hmac_context *ctx);
-byte *sha224_hmac_final(struct sha224_hmac_context *ctx);
+byte *sha256_final(struct hash_context *ctx);
+#define sha224_final sha256_final
#endif /* _BIRD_SHA256_H_ */
diff --git a/lib/sha512.c b/lib/sha512.c
index 37e660f7..576ae1e8 100644
--- a/lib/sha512.c
+++ b/lib/sha512.c
@@ -1,6 +1,5 @@
/*
- * BIRD Library -- SHA-512 and SHA-384 Hash Functions,
- * HMAC-SHA-512 and HMAC-SHA-384 Functions
+ * BIRD Library -- SHA-512 and SHA-384 Hash Functions
*
* (c) 2015 CZ.NIC z.s.p.o.
*
@@ -17,8 +16,10 @@
// #define SHA512_UNROLLED
void
-sha512_init(struct sha512_context *ctx)
+sha512_init(struct hash_context *CTX)
{
+ struct sha512_context *ctx = (void *) CTX;
+
ctx->h0 = U64(0x6a09e667f3bcc908);
ctx->h1 = U64(0xbb67ae8584caa73b);
ctx->h2 = U64(0x3c6ef372fe94f82b);
@@ -33,8 +34,10 @@ sha512_init(struct sha512_context *ctx)
}
void
-sha384_init(struct sha384_context *ctx)
+sha384_init(struct hash_context *CTX)
{
+ struct sha384_context *ctx = (void *) CTX;
+
ctx->h0 = U64(0xcbbb9d5dc1059ed8);
ctx->h1 = U64(0x629a292a367cd507);
ctx->h2 = U64(0x9159015a3070dd17);
@@ -389,8 +392,10 @@ sha512_transform(struct sha512_context *ctx, const byte *data)
}
void
-sha512_update(struct sha512_context *ctx, const byte *buf, size_t len)
+sha512_update(struct hash_context *CTX, const byte *buf, uint len)
{
+ struct sha512_context *ctx = (void *) CTX;
+
if (ctx->count)
{
/* Fill rest of internal buffer */
@@ -432,11 +437,12 @@ sha512_update(struct sha512_context *ctx, const byte *buf, size_t len)
* first 48 of those bytes.
*/
byte *
-sha512_final(struct sha512_context *ctx)
+sha512_final(struct hash_context *CTX)
{
+ struct sha512_context *ctx = (void *) CTX;
u64 t, th, msb, lsb;
- sha512_update(ctx, NULL, 0); /* flush */
+ sha512_update(CTX, NULL, 0); /* flush */
t = ctx->nblocks;
th = 0;
@@ -467,7 +473,7 @@ sha512_final(struct sha512_context *ctx)
ctx->buf[ctx->count++] = 0x80; /* pad character */
while(ctx->count < 128)
ctx->buf[ctx->count++] = 0;
- sha512_update(ctx, NULL, 0); /* flush */
+ sha512_update(CTX, NULL, 0); /* flush */
memset(ctx->buf, 0, 112); /* fill next block with zeroes */
}
@@ -490,131 +496,3 @@ sha512_final(struct sha512_context *ctx)
return ctx->buf;
}
-
-
-/*
- * SHA512-HMAC
- */
-
-static void
-sha512_hash_buffer(byte *outbuf, const byte *buffer, size_t length)
-{
- struct sha512_context ctx;
-
- sha512_init(&ctx);
- sha512_update(&ctx, buffer, length);
- memcpy(outbuf, sha512_final(&ctx), SHA512_SIZE);
-}
-
-void
-sha512_hmac_init(struct sha512_hmac_context *ctx, const byte *key, size_t keylen)
-{
- byte keybuf[SHA512_BLOCK_SIZE], buf[SHA512_BLOCK_SIZE];
-
- /* Hash the key if necessary */
- if (keylen <= SHA512_BLOCK_SIZE)
- {
- memcpy(keybuf, key, keylen);
- memset(keybuf + keylen, 0, SHA512_BLOCK_SIZE - keylen);
- }
- else
- {
- sha512_hash_buffer(keybuf, key, keylen);
- memset(keybuf + SHA512_SIZE, 0, SHA512_BLOCK_SIZE - SHA512_SIZE);
- }
-
- /* Initialize the inner digest */
- sha512_init(&ctx->ictx);
- int i;
- for (i = 0; i < SHA512_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x36;
- sha512_update(&ctx->ictx, buf, SHA512_BLOCK_SIZE);
-
- /* Initialize the outer digest */
- sha512_init(&ctx->octx);
- for (i = 0; i < SHA512_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x5c;
- sha512_update(&ctx->octx, buf, SHA512_BLOCK_SIZE);
-}
-
-void
-sha512_hmac_update(struct sha512_hmac_context *ctx, const byte *buf, size_t buflen)
-{
- /* Just update the inner digest */
- sha512_update(&ctx->ictx, buf, buflen);
-}
-
-byte *
-sha512_hmac_final(struct sha512_hmac_context *ctx)
-{
- /* Finish the inner digest */
- byte *isha = sha512_final(&ctx->ictx);
-
- /* Finish the outer digest */
- sha512_update(&ctx->octx, isha, SHA512_SIZE);
- return sha512_final(&ctx->octx);
-}
-
-
-/*
- * SHA384-HMAC
- */
-
-static void
-sha384_hash_buffer(byte *outbuf, const byte *buffer, size_t length)
-{
- struct sha384_context ctx;
-
- sha384_init(&ctx);
- sha384_update(&ctx, buffer, length);
- memcpy(outbuf, sha384_final(&ctx), SHA384_SIZE);
-}
-
-void
-sha384_hmac_init(struct sha384_hmac_context *ctx, const byte *key, size_t keylen)
-{
- byte keybuf[SHA384_BLOCK_SIZE], buf[SHA384_BLOCK_SIZE];
-
- /* Hash the key if necessary */
- if (keylen <= SHA384_BLOCK_SIZE)
- {
- memcpy(keybuf, key, keylen);
- memset(keybuf + keylen, 0, SHA384_BLOCK_SIZE - keylen);
- }
- else
- {
- sha384_hash_buffer(keybuf, key, keylen);
- memset(keybuf + SHA384_SIZE, 0, SHA384_BLOCK_SIZE - SHA384_SIZE);
- }
-
- /* Initialize the inner digest */
- sha384_init(&ctx->ictx);
- int i;
- for (i = 0; i < SHA384_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x36;
- sha384_update(&ctx->ictx, buf, SHA384_BLOCK_SIZE);
-
- /* Initialize the outer digest */
- sha384_init(&ctx->octx);
- for (i = 0; i < SHA384_BLOCK_SIZE; i++)
- buf[i] = keybuf[i] ^ 0x5c;
- sha384_update(&ctx->octx, buf, SHA384_BLOCK_SIZE);
-}
-
-void
-sha384_hmac_update(struct sha384_hmac_context *ctx, const byte *buf, size_t buflen)
-{
- /* Just update the inner digest */
- sha384_update(&ctx->ictx, buf, buflen);
-}
-
-byte *
-sha384_hmac_final(struct sha384_hmac_context *ctx)
-{
- /* Finish the inner digest */
- byte *isha = sha384_final(&ctx->ictx);
-
- /* Finish the outer digest */
- sha384_update(&ctx->octx, isha, SHA384_SIZE);
- return sha384_final(&ctx->octx);
-}
diff --git a/lib/sha512.h b/lib/sha512.h
index 1614a3ac..02220c93 100644
--- a/lib/sha512.h
+++ b/lib/sha512.h
@@ -1,6 +1,5 @@
/*
- * BIRD Library -- SHA-512 and SHA-384 Hash Functions,
- * HMAC-SHA-512 and HMAC-SHA-384 Functions
+ * BIRD Library -- SHA-512 and SHA-384 Hash Functions
*
* (c) 2015 CZ.NIC z.s.p.o.
*
@@ -25,8 +24,10 @@
#define SHA512_BLOCK_SIZE 128
+struct hash_context;
+
struct sha512_context {
- u64 h0, h1, h2, h3, h4, h5, h6, h7;
+ u64 h0, h1, h2, h3, h4, h5, h6, h7;
byte buf[SHA512_BLOCK_SIZE];
uint nblocks;
uint count;
@@ -35,39 +36,14 @@ struct sha512_context {
#define sha384_context sha512_context
-void sha512_init(struct sha512_context *ctx);
-void sha384_init(struct sha384_context *ctx);
-
-void sha512_update(struct sha512_context *ctx, const byte *buf, size_t len);
-static inline void sha384_update(struct sha384_context *ctx, const byte *buf, size_t len)
-{ sha512_update(ctx, buf, len); }
-
-byte *sha512_final(struct sha512_context *ctx);
-static inline byte *sha384_final(struct sha384_context *ctx)
-{ return sha512_final(ctx); }
-
-
-/*
- * HMAC-SHA512, HMAC-SHA384
- */
-
-struct sha512_hmac_context
-{
- struct sha512_context ictx;
- struct sha512_context octx;
-};
-
-#define sha384_hmac_context sha512_hmac_context
-
-
-void sha512_hmac_init(struct sha512_hmac_context *ctx, const byte *key, size_t keylen);
-void sha384_hmac_init(struct sha384_hmac_context *ctx, const byte *key, size_t keylen);
+void sha512_init(struct hash_context *ctx);
+void sha384_init(struct hash_context *ctx);
-void sha512_hmac_update(struct sha512_hmac_context *ctx, const byte *buf, size_t buflen);
-void sha384_hmac_update(struct sha384_hmac_context *ctx, const byte *buf, size_t buflen);
+void sha512_update(struct hash_context *ctx, const byte *buf, uint len);
+#define sha384_update sha512_update
-byte *sha512_hmac_final(struct sha512_hmac_context *ctx);
-byte *sha384_hmac_final(struct sha384_hmac_context *ctx);
+byte *sha512_final(struct hash_context *ctx);
+#define sha384_final sha512_final
#endif /* _BIRD_SHA512_H_ */
diff --git a/lib/slist_test.c b/lib/slist_test.c
new file mode 100644
index 00000000..069e361c
--- /dev/null
+++ b/lib/slist_test.c
@@ -0,0 +1,384 @@
+/*
+ * BIRD Library -- Safe Linked Lists Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+
+#include "lib/slists.h"
+
+#define MAX_NUM 1000
+
+static snode nodes[MAX_NUM];
+static slist lst;
+
+static void
+show_list(void)
+{
+ bt_debug("\n");
+ bt_debug("list.null is at %p and point to %p \n", &lst.null, lst.null);
+ bt_debug("list.head is at %p and point to %p \n", &lst.head, lst.head);
+ bt_debug("list.tail is at %p and point to %p \n", &lst.tail, lst.tail);
+ bt_debug("list.tail_readers is at %p and point to %p \n", &lst.tail_readers, lst.tail_readers);
+
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ bt_debug("n[%3i] is at %p, .prev (%p) points to %p, .next (%p) points to %p, .readers (%p) points to %p \n",
+ i, &nodes[i], &(nodes[i].prev), nodes[i].prev, &(nodes[i].next), nodes[i].next, &(nodes[i].readers), nodes[i].readers);
+}
+
+static int
+is_filled_list_well_linked(void)
+{
+ int i;
+ bt_assert(lst.head == &nodes[0]);
+ bt_assert(lst.tail == &nodes[MAX_NUM-1]);
+ bt_assert((void *) nodes[0].prev == (void *) &lst.head);
+ bt_assert((void *) nodes[MAX_NUM-1].next == (void *) &lst.null);
+
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ if (i < (MAX_NUM-1))
+ bt_assert(nodes[i].next == &nodes[i+1]);
+
+ if (i > 0)
+ bt_assert(nodes[i].prev == &nodes[i-1]);
+ }
+
+ return 1;
+}
+
+static int
+is_empty_list_well_unlinked(void)
+{
+ bt_assert(lst.head == SNODE &lst.null);
+ bt_assert(lst.tail == SNODE &lst.head);
+
+ bt_assert(EMPTY_SLIST(lst));
+
+ return 1;
+}
+
+static void
+init_list__(slist *l, struct snode nodes[])
+{
+ s_init_list(l);
+
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ nodes[i].next = NULL;
+ nodes[i].prev = NULL;
+ }
+}
+
+static void
+init_list_(void)
+{
+ init_list__(&lst, nodes);
+}
+
+static int
+t_add_tail(void)
+{
+ int i;
+
+ init_list_();
+ for (i = 0; i < MAX_NUM; i++)
+ {
+ s_add_tail(&lst, &nodes[i]);
+ bt_debug(".");
+ bt_assert(lst.tail == &nodes[i]);
+ bt_assert(lst.head == &nodes[0]);
+ bt_assert((void *) nodes[i].next == (void *) &lst.null);
+ if (i > 0)
+ {
+ bt_assert(nodes[i-1].next == &nodes[i]);
+ bt_assert(nodes[i].prev == &nodes[i-1]);
+ }
+ }
+
+ bt_assert(is_filled_list_well_linked());
+
+ return 1;
+}
+
+static int
+t_add_head(void)
+{
+ int i;
+
+ init_list_();
+ for (i = MAX_NUM-1; i >= 0; i--)
+ {
+ s_add_head(&lst, &nodes[i]);
+ bt_debug(".");
+ bt_assert(lst.head == &nodes[i]);
+ bt_assert(lst.tail == &nodes[MAX_NUM-1]);
+ if (i < MAX_NUM-1)
+ {
+ bt_assert(nodes[i+1].prev == &nodes[i]);
+ bt_assert(nodes[i].next == &nodes[i+1]);
+ }
+ }
+
+ bt_assert(is_filled_list_well_linked());
+
+ return 1;
+}
+
+static void
+insert_node_(snode *n, snode *after)
+{
+ s_insert_node(n, after);
+ bt_debug(".");
+}
+
+static int
+t_insert_node(void)
+{
+ int i;
+
+ init_list_();
+
+ // add first node
+ insert_node_(&nodes[0], SNODE &lst.head);
+
+ // add odd nodes
+ for (i = 2; i < MAX_NUM; i+=2)
+ insert_node_(&nodes[i], &nodes[i-2]);
+
+ // add even nodes
+ for (i = 1; i < MAX_NUM; i+=2)
+ insert_node_(&nodes[i], &nodes[i-1]);
+
+ bt_debug("\n");
+ bt_assert(is_filled_list_well_linked());
+
+ return 1;
+}
+
+static void
+fill_list2(slist *l, snode nodes[])
+{
+ int i;
+ for (i = 0; i < MAX_NUM; i++)
+ s_add_tail(l, &nodes[i]);
+}
+
+static void
+fill_list(void)
+{
+ fill_list2(&lst, SNODE nodes);
+}
+
+
+static int
+t_remove_node(void)
+{
+ int i;
+
+ init_list_();
+
+ /* Fill & Remove & Check */
+ fill_list();
+ for (i = 0; i < MAX_NUM; i++)
+ s_rem_node(&nodes[i]);
+ bt_assert(is_empty_list_well_unlinked());
+
+ /* Fill & Remove the half of nodes & Check & Remove the rest nodes & Check */
+ fill_list();
+ for (i = 0; i < MAX_NUM; i+=2)
+ s_rem_node(&nodes[i]);
+
+ int tail_node_index = (MAX_NUM % 2) ? MAX_NUM - 2 : MAX_NUM - 1;
+ bt_assert(lst.head == &nodes[1]);
+ bt_assert(lst.tail == &nodes[tail_node_index]);
+ bt_assert(nodes[tail_node_index].next == SNODE &lst.null);
+
+ for (i = 1; i < MAX_NUM; i+=2)
+ {
+ if (i > 1)
+ bt_assert(nodes[i].prev == &nodes[i-2]);
+ if (i < tail_node_index)
+ bt_assert(nodes[i].next == &nodes[i+2]);
+ }
+
+ for (i = 1; i < MAX_NUM; i+=2)
+ s_rem_node(&nodes[i]);
+ bt_assert(is_empty_list_well_unlinked());
+
+ return 1;
+}
+
+static int
+t_add_tail_list(void)
+{
+ snode nodes2[MAX_NUM];
+ slist l2;
+
+ init_list__(&lst, SNODE &nodes);
+ fill_list2(&lst, SNODE &nodes);
+
+ init_list__(&l2, SNODE &nodes2);
+ fill_list2(&l2, SNODE &nodes2);
+
+ s_add_tail_list(&lst, &l2);
+
+ bt_assert(nodes[MAX_NUM-1].next == &nodes2[0]);
+ bt_assert(nodes2[0].prev == &nodes[MAX_NUM-1]);
+ bt_assert(lst.tail == &nodes2[MAX_NUM-1]);
+
+ return 1;
+}
+
+void
+dump(const char *str, slist *a)
+{
+ snode *x;
+
+ bt_debug("%s \n", str);
+ for (x = SHEAD(*a); x; x = x->next)
+ {
+ siterator *i, *j;
+ bt_debug("%p", x);
+ j = (siterator *) x;
+ for (i = x->readers; i; i = i->next)
+ {
+ if (i->prev != j)
+ bt_debug(" ???");
+ j = i;
+ bt_debug(" [%p:%p]", i, i->node);
+ }
+ bt_debug("\n");
+ }
+ bt_debug("---\n");
+}
+
+static int
+t_iterator_walk(void)
+{
+ snode *node;
+ siterator iter;
+
+ init_list_();
+ fill_list();
+
+ int k;
+ int i = 0;
+
+ show_list();
+
+ s_init(&iter, &lst);
+ WALK_SLIST(node, lst)
+ {
+ s_get(&iter);
+ s_put(&iter, node);
+ bt_debug("node->readers: %p, iter: %p, nodes[%d].readers: %p, node: %p, nodes[i]: %p, node->next: %p \n",
+ node->readers, &iter, i, nodes[i].readers, node, &(nodes[i]), node->next);
+ bt_assert(node->readers == &iter);
+ bt_assert(node->readers == nodes[i].readers);
+ bt_assert(node == &(nodes[i]));
+ for (k = 0; k < MAX_NUM; k++)
+ if (k != i)
+ bt_assert(nodes[k].readers == NULL);
+
+ dump("",&lst);
+ i++;
+ }
+
+ return 1;
+}
+
+static int
+t_original(void)
+{
+ slist a, b;
+ snode *x, *y;
+ siterator i, j;
+
+ s_init_list(&a);
+ s_init_list(&b);
+ x = xmalloc(sizeof(*x));
+ s_add_tail(&a, x);
+ x = xmalloc(sizeof(*x));
+ s_add_tail(&a, x);
+ x = xmalloc(sizeof(*x));
+ s_add_tail(&a, x);
+ dump("1", &a);
+
+ s_init(&i, &a);
+ s_init(&j, &a);
+ dump("2", &a);
+
+ x = s_get(&i);
+ bt_debug("Got %p\n", x);
+ dump("3", &a);
+
+ s_put(&i, x->next);
+ dump("4", &a);
+
+ y = s_get(&j);
+ while (y)
+ {
+ s_put(&j, y);
+ dump("5*", &a);
+ y = s_get(&j)->next;
+ }
+
+ dump("5 done", &a);
+
+ s_rem_node(a.head->next);
+ dump("6 (deletion)", &a);
+
+ s_put(&i, s_get(&i)->next);
+ dump("6 (relink)", &a);
+
+ x = xmalloc(sizeof(*x));
+ s_add_tail(&b, x);
+ dump("7 (second list)", &b);
+
+ s_add_tail_list(&b, &a);
+ dump("8 (after merge)", &b);
+
+ return 1;
+}
+
+static int
+t_safe_del_walk(void)
+{
+ init_list_();
+ fill_list();
+
+ show_list();
+
+ snode *node, *node_next;
+ WALK_SLIST_DELSAFE(node,node_next, lst)
+ {
+ bt_debug("Will remove node %p \n", node);
+ s_rem_node(SNODE node);
+ }
+ bt_assert(is_empty_list_well_unlinked());
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_add_tail, "Adding nodes to tail of list");
+ bt_test_suite(t_add_head, "Adding nodes to head of list");
+ bt_test_suite(t_insert_node, "Inserting nodes to list");
+ bt_test_suite(t_remove_node, "Removing nodes from list");
+ bt_test_suite(t_add_tail_list, "At the tail of a list adding the another list");
+ bt_test_suite(t_iterator_walk, "Iterator walk");
+ bt_test_suite(t_safe_del_walk, "WALK_SLIST_DELSAFE and s_rem_node all nodes");
+ bt_test_suite(t_original, "The original BIRD test suit for SLIST");
+
+ return bt_exit_value();
+}
diff --git a/lib/slists.c b/lib/slists.c
index 6e0df39e..00f3c84f 100644
--- a/lib/slists.c
+++ b/lib/slists.c
@@ -150,85 +150,3 @@ s_add_tail_list(slist *to, slist *l)
to->tail = q;
s_merge((snode *) &l->null, (snode *) &to->null);
}
-
-#ifdef TEST
-
-#include "lib/resource.h"
-#include <stdio.h>
-
-void dump(char *c, slist *a)
-{
- snode *x;
-
- puts(c);
- for(x=SHEAD(*a); x; x=x->next)
- {
- siterator *i, *j;
- printf("%p", x);
- j = (siterator *) x;
- for(i=x->readers; i; i=i->next)
- {
- if (i->prev != j)
- printf(" ???");
- j = i;
- printf(" [%p:%p]", i, i->node);
- }
- putchar('\n');
- }
- puts("---");
-}
-
-int main(void)
-{
- slist a, b;
- snode *x, *y;
- siterator i, j;
-
- s_init_list(&a);
- s_init_list(&b);
- x = xmalloc(sizeof(*x));
- s_add_tail(&a, x);
- x = xmalloc(sizeof(*x));
- s_add_tail(&a, x);
- x = xmalloc(sizeof(*x));
- s_add_tail(&a, x);
- dump("1", &a);
-
- s_init(&i, &a);
- s_init(&j, &a);
- dump("2", &a);
-
- x = s_get(&i);
- printf("Got %p\n", x);
- dump("3", &a);
-
- s_put(&i, x->next);
- dump("4", &a);
-
- y = s_get(&j);
- while (y)
- {
- s_put(&j, y);
- dump("5*", &a);
- y = s_get(&j)->next;
- }
-
- dump("5 done", &a);
-
- s_rem_node(a.head->next);
- dump("6 (deletion)", &a);
-
- s_put(&i, s_get(&i)->next);
- dump("6 (relink)", &a);
-
- x = xmalloc(sizeof(*x));
- s_add_tail(&b, x);
- dump("7 (second list)", &b);
-
- s_add_tail_list(&b, &a);
- dump("8 (after merge)", &b);
-
- return 0;
-}
-
-#endif
diff --git a/lib/socket.h b/lib/socket.h
index 99bac6f8..d5281b83 100644
--- a/lib/socket.h
+++ b/lib/socket.h
@@ -54,7 +54,7 @@ typedef struct birdsock {
byte *rbuf, *rpos; /* NULL=allocate automatically */
uint fast_rx; /* RX has higher priority in event loop */
uint rbsize;
- int (*rx_hook)(struct birdsock *, int size); /* NULL=receiving turned off, returns 1 to clear rx buffer */
+ int (*rx_hook)(struct birdsock *, uint size); /* NULL=receiving turned off, returns 1 to clear rx buffer */
byte *tbuf, *tpos; /* NULL=allocate automatically */
byte *ttx; /* Internal */
diff --git a/lib/string.h b/lib/string.h
index 9af49b9e..0d34f9c5 100644
--- a/lib/string.h
+++ b/lib/string.h
@@ -13,6 +13,8 @@
#include <string.h>
#include <strings.h>
+#include "lib/resource.h"
+
int bsprintf(char *str, const char *fmt, ...);
int bvsprintf(char *str, const char *fmt, va_list args);
int bsnprintf(char *str, int size, const char *fmt, ...);
@@ -30,6 +32,34 @@ static inline char *xbasename(const char *str)
return s ? s+1 : (char *) str;
}
+static inline char *
+xstrdup(const char *c)
+{
+ size_t l = strlen(c) + 1;
+ char *z = xmalloc(l);
+ memcpy(z, c, l);
+ return z;
+}
+
+static inline char *
+lp_strdup(linpool *lp, const char *c)
+{
+ size_t l = strlen(c) + 1;
+ char *z = lp_allocu(lp, l);
+ memcpy(z, c, l);
+ return z;
+}
+
+static inline void
+memset32(void *D, u32 val, uint n)
+{
+ u32 *dst = D;
+ uint i;
+
+ for (i = 0; i < n; i++)
+ dst[i] = val;
+}
+
#define ROUTER_ID_64_LENGTH 23
#endif
diff --git a/lib/unaligned.h b/lib/unaligned.h
index ad5811ab..4e841f3a 100644
--- a/lib/unaligned.h
+++ b/lib/unaligned.h
@@ -69,4 +69,22 @@ put_u64(void *p, u64 x)
memcpy(p+4, &xl, 4);
}
+static inline void
+get_u32s(const void *p, u32 *x, int n)
+{
+ int i;
+ memcpy(x, p, 4*n);
+ for (i = 0; i < n; i++)
+ x[i] = ntohl(x[i]);
+}
+
+static inline void
+put_u32s(void *p, const u32 *x, int n)
+{
+ int i;
+ for (i = 0; i < n; i++)
+ put_u32((byte *) p + 4*i, x[i]);
+}
+
+
#endif
diff --git a/misc/bird.spec b/misc/bird.spec
index 857f03e5..ebc0c942 100644
--- a/misc/bird.spec
+++ b/misc/bird.spec
@@ -1,6 +1,6 @@
Summary: BIRD Internet Routing Daemon
Name: bird
-Version: 1.6.0
+Version: 1.6.2
Release: 1
Copyright: GPL
Group: Networking/Daemons
diff --git a/nest/Makefile b/nest/Makefile
index 6f0f9a08..d673cee5 100644
--- a/nest/Makefile
+++ b/nest/Makefile
@@ -2,3 +2,7 @@ src := a-path.c a-set.c cli.c cmds.c iface.c locks.c neighbor.c password.c proto
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_src := a-set_test.c a-path_test.c
+tests_targets := $(tests_targets) $(tests-target-files)
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/nest/a-path.c b/nest/a-path.c
index 32e2d27e..6ced703d 100644
--- a/nest/a-path.c
+++ b/nest/a-path.c
@@ -20,114 +20,315 @@
#define put_as put_u32
#define get_as get_u32
-#define BS 4
+#define BS 4 /* Default block size of ASN (autonomous system number) */
-struct adata *
-as_path_prepend(struct linpool *pool, struct adata *olda, u32 as)
+#define BAD(DSC, VAL) ({ err_dsc = DSC; err_val = VAL; goto bad; })
+
+int
+as_path_valid(byte *data, uint len, int bs, char *err, uint elen)
+{
+ byte *pos = data;
+ char *err_dsc = NULL;
+ uint err_val = 0;
+
+ while (len)
+ {
+ if (len < 2)
+ BAD("segment framing error", 0);
+
+ /* Process one AS path segment */
+ uint type = pos[0];
+ uint slen = 2 + bs * pos[1];
+
+ if (len < slen)
+ BAD("segment framing error", len);
+
+ /* XXXX handle CONFED segments */
+ if ((type != AS_PATH_SET) && (type != AS_PATH_SEQUENCE))
+ BAD("unknown segment", type);
+
+ if (pos[1] == 0)
+ BAD("zero-length segment", type);
+
+ pos += slen;
+ len -= slen;
+ }
+
+ return 1;
+
+bad:
+ if (err)
+ if (bsnprintf(err, elen, "%s (%u) at %d", err_dsc, err_val, (int) (pos - data)) < 0)
+ err[0] = 0;
+
+ return 0;
+}
+
+int
+as_path_16to32(byte *dst, byte *src, uint len)
{
- struct adata *newa;
+ byte *dst0 = dst;
+ byte *end = src + len;
+ uint i, n;
- if (olda->length && olda->data[0] == AS_PATH_SEQUENCE && olda->data[1] < 255)
- /* Starting with sequence => just prepend the AS number */
+ while (src < end)
+ {
+ n = src[1];
+ *dst++ = *src++;
+ *dst++ = *src++;
+
+ for (i = 0; i < n; i++)
{
- int nl = olda->length + BS;
- newa = lp_alloc(pool, sizeof(struct adata) + nl);
- newa->length = nl;
- newa->data[0] = AS_PATH_SEQUENCE;
- newa->data[1] = olda->data[1] + 1;
- memcpy(newa->data + BS + 2, olda->data + 2, olda->length - 2);
+ put_u32(dst, get_u16(src));
+ src += 2;
+ dst += 4;
}
- else /* Create new path segment */
+ }
+
+ return dst - dst0;
+}
+
+int
+as_path_32to16(byte *dst, byte *src, uint len)
+{
+ byte *dst0 = dst;
+ byte *end = src + len;
+ uint i, n;
+
+ while (src < end)
+ {
+ n = src[1];
+ *dst++ = *src++;
+ *dst++ = *src++;
+
+ for (i = 0; i < n; i++)
{
- int nl = olda->length + BS + 2;
- newa = lp_alloc(pool, sizeof(struct adata) + nl);
- newa->length = nl;
- newa->data[0] = AS_PATH_SEQUENCE;
- newa->data[1] = 1;
- memcpy(newa->data + BS + 2, olda->data, olda->length);
+ put_u16(dst, get_u32(src));
+ src += 4;
+ dst += 2;
}
- put_as(newa->data + 2, as);
- return newa;
+ }
+
+ return dst - dst0;
}
int
-as_path_convert_to_old(struct adata *path, byte *dst, int *new_used)
+as_path_contains_as4(const struct adata *path)
{
- byte *src = path->data;
- byte *src_end = src + path->length;
- byte *dst_start = dst;
- u32 as;
- int i, n;
- *new_used = 0;
+ const byte *pos = path->data;
+ const byte *end = pos + path->length;
+ uint i, n;
+
+ while (pos < end)
+ {
+ n = pos[1];
+ pos += 2;
- while (src < src_end)
+ for (i = 0; i < n; i++)
{
- n = src[1];
- *dst++ = *src++;
- *dst++ = *src++;
+ if (get_as(pos) > 0xFFFF)
+ return 1;
- for(i=0; i<n; i++)
- {
- as = get_u32(src);
- if (as > 0xFFFF)
- {
- as = AS_TRANS;
- *new_used = 1;
- }
- put_u16(dst, as);
- src += 4;
- dst += 2;
- }
+ pos += BS;
}
+ }
- return dst - dst_start;
+ return 0;
}
int
-as_path_convert_to_new(struct adata *path, byte *dst, int req_as)
+as_path_contains_confed(const struct adata *path)
+{
+ const byte *pos = path->data;
+ const byte *end = pos + path->length;
+
+ while (pos < end)
+ {
+ uint type = pos[0];
+ uint slen = 2 + BS * pos[1];
+
+ if ((type == AS_PATH_CONFED_SEQUENCE) ||
+ (type == AS_PATH_CONFED_SET))
+ return 1;
+
+ pos += slen;
+ }
+
+ return 0;
+}
+
+static void
+as_path_strip_confed_(byte *dst, const byte *src, uint len)
+{
+ const byte *end = src + len;
+
+ while (src < end)
+ {
+ uint type = src[0];
+ uint slen = 2 + BS * src[1];
+
+ /* Copy regular segments */
+ if ((type == AS_PATH_SET) || (type == AS_PATH_SEQUENCE))
+ {
+ memcpy(dst, src, slen);
+ dst += slen;
+ }
+
+ src += slen;
+ }
+}
+
+struct adata *
+as_path_strip_confed(struct linpool *pool, const struct adata *op)
+{
+ struct adata *np = lp_alloc_adata(pool, op->length);
+ as_path_strip_confed_(np->data, op->data, op->length);
+ return np;
+}
+
+struct adata *
+as_path_prepend2(struct linpool *pool, const struct adata *op, int seq, u32 as, int strip)
+{
+ struct adata *np;
+ const byte *pos = op->data;
+ uint len = op->length;
+
+ if (len && (pos[0] == seq) && (pos[1] < 255))
+ {
+ /* Starting with matching segment => just prepend the AS number */
+ np = lp_alloc_adata(pool, len + BS);
+ np->data[0] = seq;
+ np->data[1] = pos[1] + 1;
+ put_as(np->data + 2, as);
+
+ uint dlen = BS * pos[1];
+ memcpy(np->data + 2 + BS, pos + 2, dlen);
+ ADVANCE(pos, len, 2 + dlen);
+ }
+ else
+ {
+ /* Create a new path segment */
+ np = lp_alloc_adata(pool, len + 2 + BS);
+ np->data[0] = seq;
+ np->data[1] = 1;
+ put_as(np->data + 2, as);
+ }
+
+ if (len)
+ {
+ byte *dst = np->data + 2 + BS * np->data[1];
+
+ if (strip)
+ as_path_strip_confed_(dst, pos, len);
+ else
+ memcpy(dst, pos, len);
+ }
+
+ return np;
+}
+
+
+struct adata *
+as_path_to_old(struct linpool *pool, const struct adata *path)
{
- byte *src = path->data;
- byte *src_end = src + path->length;
- byte *dst_start = dst;
+ struct adata *res = lp_alloc_adata(pool, path->length);
+ byte *pos = res->data;
+ byte *end = pos + res->length;
+ uint i, n;
u32 as;
- int i, t, n;
+ /* Copy the whole path */
+ memcpy(res->data, path->data, path->length);
+
+ /* Replace 32-bit AS numbers with AS_TRANS */
+ while (pos < end)
+ {
+ n = pos[1];
+ pos += 2;
- while ((src < src_end) && (req_as > 0))
+ for (i = 0; i < n; i++)
{
- t = *src++;
- n = *src++;
+ as = get_as(pos);
+ if (as > 0xFFFF)
+ put_as(pos, AS_TRANS);
- if (t == AS_PATH_SEQUENCE)
- {
- if (n > req_as)
- n = req_as;
+ pos += BS;
+ }
+ }
- req_as -= n;
- }
- else // t == AS_PATH_SET
- req_as--;
+ return res;
+}
- *dst++ = t;
- *dst++ = n;
+/*
+ * Cut the path to the length @num, measured to the usual path metric. Note that
+ * AS_CONFED_* segments have zero length and must be added if they are on edge.
+ * In contrast to other as_path_* functions, @path is modified in place.
+ */
+void
+as_path_cut(struct adata *path, uint num)
+{
+ byte *pos = path->data;
+ byte *end = pos + path->length;
- for(i=0; i<n; i++)
- {
- as = get_u16(src);
- put_u32(dst, as);
- src += 2;
- dst += 4;
- }
+ while (pos < end)
+ {
+ uint t = pos[0];
+ uint l = pos[1];
+ uint n = 0;
+
+ switch (t)
+ {
+ case AS_PATH_SET: n = 1; break;
+ case AS_PATH_SEQUENCE: n = l; break;
+ case AS_PATH_CONFED_SEQUENCE: n = 0; break;
+ case AS_PATH_CONFED_SET: n = 0; break;
+ default: bug("as_path_cut: Invalid path segment");
+ }
+
+ /* Cannot add whole segment, so try partial one and finish */
+ if (num < n)
+ {
+ if (num)
+ {
+ pos[1] = num;
+ pos += 2 + BS * num;
+ }
+
+ break;
}
- return dst - dst_start;
+ num -= n;
+ pos += 2 + BS * l;
+ }
+
+ path->length = pos - path->data;
+}
+
+/*
+ * Merge (concatenate) paths @p1 and @p2 and return the result.
+ * In contrast to other as_path_* functions, @p1 and @p2 may be reused.
+ */
+struct adata *
+as_path_merge(struct linpool *pool, struct adata *p1, struct adata *p2)
+{
+ if (p1->length == 0)
+ return p2;
+
+ if (p2->length == 0)
+ return p1;
+
+ struct adata *res = lp_alloc_adata(pool, p1->length + p2->length);
+ memcpy(res->data, p1->data, p1->length);
+ memcpy(res->data + p1->length, p2->data, p2->length);
+
+ return res;
}
void
-as_path_format(struct adata *path, byte *buf, uint size)
+as_path_format(const struct adata *path, byte *buf, uint size)
{
- byte *p = path->data;
- byte *e = p + path->length;
+ const byte *p = path->data;
+ const byte *e = p + path->length;
byte *end = buf + size - 16;
int sp = 1;
int l, isset;
@@ -167,38 +368,41 @@ as_path_format(struct adata *path, byte *buf, uint size)
}
int
-as_path_getlen(struct adata *path)
+as_path_getlen(const struct adata *path)
{
- return as_path_getlen_int(path, BS);
-}
+ const byte *pos = path->data;
+ const byte *end = pos + path->length;
+ uint res = 0;
-int
-as_path_getlen_int(struct adata *path, int bs)
-{
- int res = 0;
- u8 *p = path->data;
- u8 *q = p+path->length;
- int len;
+ while (pos < end)
+ {
+ uint t = pos[0];
+ uint l = pos[1];
+ uint n = 0;
- while (p<q)
+ switch (t)
{
- switch (*p++)
- {
- case AS_PATH_SET: len = *p++; res++; p += bs * len; break;
- case AS_PATH_SEQUENCE: len = *p++; res += len; p += bs * len; break;
- default: bug("as_path_getlen: Invalid path segment");
- }
+ case AS_PATH_SET: n = 1; break;
+ case AS_PATH_SEQUENCE: n = l; break;
+ case AS_PATH_CONFED_SEQUENCE: n = 0; break;
+ case AS_PATH_CONFED_SET: n = 0; break;
+ default: bug("as_path_getlen: Invalid path segment");
}
+
+ res += n;
+ pos += 2 + BS * l;
+ }
+
return res;
}
int
-as_path_get_last(struct adata *path, u32 *orig_as)
+as_path_get_last(const struct adata *path, u32 *orig_as)
{
int found = 0;
u32 res = 0;
- u8 *p = path->data;
- u8 *q = p+path->length;
+ const u8 *p = path->data;
+ const u8 *q = p+path->length;
int len;
while (p<q)
@@ -230,10 +434,10 @@ as_path_get_last(struct adata *path, u32 *orig_as)
}
u32
-as_path_get_last_nonaggregated(struct adata *path)
+as_path_get_last_nonaggregated(const struct adata *path)
{
- u8 *p = path->data;
- u8 *q = p+path->length;
+ const u8 *p = path->data;
+ const u8 *q = p+path->length;
u32 res = 0;
int len;
@@ -257,11 +461,10 @@ as_path_get_last_nonaggregated(struct adata *path)
return res;
}
-
int
-as_path_get_first(struct adata *path, u32 *last_as)
+as_path_get_first(const struct adata *path, u32 *last_as)
{
- u8 *p = path->data;
+ const u8 *p = path->data;
if ((path->length == 0) || (p[0] != AS_PATH_SEQUENCE) || (p[1] == 0))
return 0;
@@ -273,10 +476,10 @@ as_path_get_first(struct adata *path, u32 *last_as)
}
int
-as_path_contains(struct adata *path, u32 as, int min)
+as_path_contains(const struct adata *path, u32 as, int min)
{
- u8 *p = path->data;
- u8 *q = p+path->length;
+ const u8 *p = path->data;
+ const u8 *q = p+path->length;
int num = 0;
int i, n;
@@ -296,10 +499,10 @@ as_path_contains(struct adata *path, u32 as, int min)
}
int
-as_path_match_set(struct adata *path, struct f_tree *set)
+as_path_match_set(const struct adata *path, struct f_tree *set)
{
- u8 *p = path->data;
- u8 *q = p+path->length;
+ const u8 *p = path->data;
+ const u8 *q = p+path->length;
int i, n;
while (p<q)
@@ -325,8 +528,8 @@ as_path_filter(struct linpool *pool, struct adata *path, struct f_tree *set, u32
return NULL;
int len = path->length;
- u8 *p = path->data;
- u8 *q = path->data + len;
+ const u8 *p = path->data;
+ const u8 *q = path->data + len;
u8 *d, *d2;
int i, bt, sn, dn;
u8 buf[len];
@@ -370,7 +573,7 @@ as_path_filter(struct linpool *pool, struct adata *path, struct f_tree *set, u32
}
}
- int nl = d - buf;
+ uint nl = d - buf;
if (nl == path->length)
return path;
@@ -388,16 +591,16 @@ struct pm_pos
u8 mark;
union
{
- char *sp;
+ const char *sp;
u32 asn;
} val;
};
static int
-parse_path(struct adata *path, struct pm_pos *pos)
+parse_path(const struct adata *path, struct pm_pos *pos)
{
- u8 *p = path->data;
- u8 *q = p + path->length;
+ const u8 *p = path->data;
+ const u8 *q = p + path->length;
struct pm_pos *opos = pos;
int i, len;
@@ -429,24 +632,28 @@ parse_path(struct adata *path, struct pm_pos *pos)
default:
bug("as_path_match: Invalid path component");
}
-
+
return pos - opos;
}
-
static int
-pm_match(struct pm_pos *pos, u32 asn)
+pm_match(struct pm_pos *pos, u32 asn, u32 asn2)
{
+ u32 gas;
if (! pos->set)
- return pos->val.asn == asn;
+ return ((pos->val.asn >= asn) && (pos->val.asn <= asn2));
- u8 *p = pos->val.sp;
+ const u8 *p = pos->val.sp;
int len = *p++;
int i;
for (i = 0; i < len; i++)
- if (get_as(p + i * BS) == asn)
+ {
+ gas = get_as(p + i * BS);
+
+ if ((gas >= asn) && (gas <= asn2))
return 1;
+ }
return 0;
}
@@ -458,7 +665,7 @@ pm_mark(struct pm_pos *pos, int i, int plen, int *nl, int *nh)
if (pos[i].set)
pos[i].mark = 1;
-
+
for (j = i + 1; (j < plen) && pos[j].set && (! pos[j].mark); j++)
pos[j].mark = 1;
pos[j].mark = 1;
@@ -490,18 +697,18 @@ pm_mark(struct pm_pos *pos, int i, int plen, int *nl, int *nh)
* next part of mask, we advance each marked state.
* We start with marked first position, when we
* run out of marked positions, we reject. When
- * we process the whole mask, we accept iff final position
+ * we process the whole mask, we accept if final position
* (auxiliary position after last real position in AS path)
* is marked.
*/
-
int
-as_path_match(struct adata *path, struct f_path_mask *mask)
+as_path_match(const struct adata *path, struct f_path_mask *mask)
{
struct pm_pos pos[2048 + 1];
int plen = parse_path(path, pos);
int l, h, i, nh, nl;
u32 val = 0;
+ u32 val2 = 0;
/* l and h are bound of interval of positions where
are marked states */
@@ -525,12 +732,16 @@ as_path_match(struct adata *path, struct f_path_mask *mask)
h = plen;
break;
- case PM_ASN:
- val = mask->val;
+ case PM_ASN: /* Define single ASN as ASN..ASN - very narrow interval */
+ val2 = val = mask->val;
goto step;
case PM_ASN_EXPR:
- val = f_eval_asn((struct f_inst *) mask->val);
+ val2 = val = f_eval_asn((struct f_inst *) mask->val);
goto step;
+ case PM_ASN_RANGE:
+ val = mask->val;
+ val2 = mask->val2;
+ goto step;
case PM_QUESTION:
step:
nh = nl = -1;
@@ -538,7 +749,7 @@ as_path_match(struct adata *path, struct f_path_mask *mask)
if (pos[i].mark)
{
pos[i].mark = 0;
- if ((mask->kind == PM_QUESTION) || pm_match(pos + i, val))
+ if ((mask->kind == PM_QUESTION) || pm_match(pos + i, val, val2))
pm_mark(pos, i, plen, &nl, &nh);
}
diff --git a/nest/a-path_test.c b/nest/a-path_test.c
new file mode 100644
index 00000000..d2ca46a7
--- /dev/null
+++ b/nest/a-path_test.c
@@ -0,0 +1,214 @@
+/*
+ * BIRD -- Path Operations Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "nest/route.h"
+#include "nest/attrs.h"
+#include "lib/resource.h"
+
+#define TESTS_NUM 30
+#define AS_PATH_LENGTH 1000
+
+#if AS_PATH_LENGTH > AS_PATH_MAXLEN
+#warning "AS_PATH_LENGTH should be <= AS_PATH_MAXLEN"
+#endif
+
+static int
+t_as_path_match(void)
+{
+ resource_init();
+
+ int round;
+ for (round = 0; round < TESTS_NUM; round++)
+ {
+ struct adata empty_as_path = {};
+ struct adata *as_path = &empty_as_path;
+ u32 first_prepended, last_prepended;
+ first_prepended = last_prepended = 0;
+ struct linpool *lp = lp_new(&root_pool, 0);
+
+ struct f_path_mask mask[AS_PATH_LENGTH] = {};
+ int i;
+ for (i = 0; i < AS_PATH_LENGTH; i++)
+ {
+ u32 val = bt_random();
+ as_path = as_path_prepend(lp, as_path, val);
+ bt_debug("Prepending ASN: %10u \n", val);
+
+ if (i == 0)
+ first_prepended = val;
+ if (i == AS_PATH_LENGTH-1)
+ last_prepended = val;
+
+ mask[i].kind = PM_ASN;
+ mask[i].val = val;
+ if (i)
+ mask[i].next = &mask[i-1];
+ }
+
+ bt_assert_msg(as_path_match(as_path, &mask[AS_PATH_LENGTH-1]), "Mask should match with AS path");
+
+ u32 asn;
+
+ bt_assert(as_path_get_first(as_path, &asn));
+ bt_assert_msg(asn == last_prepended, "as_path_get_first() should return the last prepended ASN");
+
+ bt_assert(as_path_get_last(as_path, &asn));
+ bt_assert_msg(asn == first_prepended, "as_path_get_last() should return the first prepended ASN");
+
+ rfree(lp);
+ }
+
+ return 1;
+}
+
+static int
+t_path_format(void)
+{
+ resource_init();
+
+ struct adata empty_as_path = {};
+ struct adata *as_path = &empty_as_path;
+ struct linpool *lp = lp_new(&root_pool, 0);
+
+ uint i;
+ for (i = 4294967285; i <= 4294967294; i++)
+ {
+ as_path = as_path_prepend(lp, as_path, i);
+ bt_debug("Prepending ASN: %10u \n", i);
+ }
+
+#define BUFFER_SIZE 26
+ byte buf[BUFFER_SIZE] = {};
+ as_path_format(as_path, buf, BUFFER_SIZE);
+ bt_assert_msg(strcmp(buf, "4294967294 4294967293 ...") == 0, "Buffer(%zu): '%s'", strlen(buf), buf);
+
+#define SMALL_BUFFER_SIZE 25
+ byte buf2[SMALL_BUFFER_SIZE] = {};
+ as_path_format(as_path, buf2, SMALL_BUFFER_SIZE);
+ bt_assert_msg(strcmp(buf2, "4294967294 ...") == 0, "Small Buffer(%zu): '%s'", strlen(buf2), buf2);
+
+ rfree(lp);
+
+ return 1;
+}
+
+static int
+count_asn_in_array(const u32 *array, u32 asn)
+{
+ int counts_of_contains = 0;
+ int u;
+ for (u = 0; u < AS_PATH_LENGTH; u++)
+ if (array[u] == asn)
+ counts_of_contains++;
+ return counts_of_contains;
+}
+
+static int
+t_path_include(void)
+{
+ resource_init();
+
+ struct adata empty_as_path = {};
+ struct adata *as_path = &empty_as_path;
+ struct linpool *lp = lp_new(&root_pool, 0);
+
+ u32 as_nums[AS_PATH_LENGTH] = {};
+ int i;
+ for (i = 0; i < AS_PATH_LENGTH; i++)
+ {
+ u32 val = bt_random();
+ as_nums[i] = val;
+ as_path = as_path_prepend(lp, as_path, val);
+ }
+
+ for (i = 0; i < AS_PATH_LENGTH; i++)
+ {
+ int counts_of_contains = count_asn_in_array(as_nums, as_nums[i]);
+ bt_assert_msg(as_path_contains(as_path, as_nums[i], counts_of_contains), "AS Path should contains %d-times number %d", counts_of_contains, as_nums[i]);
+
+ bt_assert(as_path_filter(lp, as_path, NULL, as_nums[i], 0) != NULL);
+ bt_assert(as_path_filter(lp, as_path, NULL, as_nums[i], 1) != NULL);
+ }
+
+ for (i = 0; i < 10000; i++)
+ {
+ u32 test_val = bt_random();
+ int counts_of_contains = count_asn_in_array(as_nums, test_val);
+ int result = as_path_contains(as_path, test_val, (counts_of_contains == 0 ? 1 : counts_of_contains));
+
+ if (counts_of_contains)
+ bt_assert_msg(result, "As path should contain %d-times the number %u", counts_of_contains, test_val);
+ else
+ bt_assert_msg(result == 0, "As path should not contain the number %u", test_val);
+ }
+
+ rfree(lp);
+
+ return 1;
+}
+
+static int
+t_as_path_converting(void)
+{
+ resource_init();
+
+ struct adata empty_as_path = {};
+ struct adata *as_path = &empty_as_path;
+ struct linpool *lp = lp_new(&root_pool, 0);
+#define AS_PATH_LENGTH_FOR_CONVERTING_TEST 10
+
+ int i;
+ for (i = 0; i < AS_PATH_LENGTH_FOR_CONVERTING_TEST; i++)
+ as_path = as_path_prepend(lp, as_path, i);
+
+ bt_debug("data length: %u \n", as_path->length);
+
+ byte buffer[100] = {};
+ int used_size = as_path_convert_to_new(as_path, buffer, AS_PATH_LENGTH_FOR_CONVERTING_TEST-1);
+ bt_debug("as_path_convert_to_new: len %d \n%s\n", used_size, buffer);
+ for (i = 0; i < used_size; i++)
+ {
+ bt_debug("\\03%d", buffer[i]);
+ }
+ bt_debug("\n");
+ bt_assert(memcmp(buffer,
+ "\032\039\030\030\030\030\030\030\030\039\030\030\030\030\030\030\030\038\030\030\030\030\030\030"
+ "\030\037\030\030\030\030\030\030\030\036\030\030\030\030",
+ 38));
+
+ bzero(buffer, sizeof(buffer));
+ int new_used;
+ used_size = as_path_convert_to_old(as_path, buffer, &new_used);
+ bt_debug("as_path_convert_to_old: len %d, new_used: %d \n", used_size, new_used);
+ for (i = 0; i < used_size; i++)
+ {
+ bt_debug("\\03%d", buffer[i]);
+ }
+ bt_debug("\n");
+ bt_assert(memcmp(buffer,
+ "\032\0310\030\039\030\038\030\037\030\036\030\035\030\034\030\033\030\032\030\031\030\030",
+ 22));
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_as_path_match, "Testing AS path matching and some a-path utilities.");
+ bt_test_suite(t_path_format, "Testing formating as path into byte buffer");
+ bt_test_suite(t_path_include, "Testing including a AS number in AS path");
+ bt_test_suite(t_as_path_converting, "Testing as_path_convert_to_*() output constancy");
+
+ return bt_exit_value();
+}
diff --git a/nest/a-set.c b/nest/a-set.c
index a6116022..82bf8b0d 100644
--- a/nest/a-set.c
+++ b/nest/a-set.c
@@ -7,6 +7,8 @@
* Can be freely distributed and used under the terms of the GNU GPL.
*/
+#include <stdlib.h>
+
#include "nest/bird.h"
#include "nest/route.h"
#include "nest/attrs.h"
@@ -116,7 +118,7 @@ int
ec_set_format(struct adata *set, int from, byte *buf, uint size)
{
u32 *z = int_set_get_data(set);
- byte *end = buf + size - 24;
+ byte *end = buf + size - 64;
int from2 = MAX(from, 0);
int to = int_set_get_size(set);
int i;
@@ -142,6 +144,43 @@ ec_set_format(struct adata *set, int from, byte *buf, uint size)
}
int
+lc_format(byte *buf, lcomm lc)
+{
+ return bsprintf(buf, "(%u, %u, %u)", lc.asn, lc.ldp1, lc.ldp2);
+}
+
+int
+lc_set_format(struct adata *set, int from, byte *buf, uint bufsize)
+{
+ u32 *d = (u32 *) set->data;
+ byte *end = buf + bufsize - 64;
+ int from2 = MAX(from, 0);
+ int to = set->length / 4;
+ int i;
+
+ for (i = from2; i < to; i += 3)
+ {
+ if (buf > end)
+ {
+ if (from < 0)
+ strcpy(buf, "...");
+ else
+ buf[-1] = 0;
+ return i;
+ }
+
+ buf += bsprintf(buf, "(%u, %u, %u)", d[i], d[i+1], d[i+2]);
+ *buf++ = ' ';
+ }
+
+ if (i != from2)
+ buf--;
+
+ *buf = 0;
+ return 0;
+}
+
+int
int_set_contains(struct adata *list, u32 val)
{
if (!list)
@@ -177,6 +216,24 @@ ec_set_contains(struct adata *list, u64 val)
return 0;
}
+int
+lc_set_contains(struct adata *list, lcomm val)
+{
+ if (!list)
+ return 0;
+
+ u32 *l = int_set_get_data(list);
+ int len = int_set_get_size(list);
+ int i;
+
+ for (i = 0; i < len; i += 3)
+ if (lc_match(l, i, val))
+ return 1;
+
+ return 0;
+}
+
+
struct adata *
int_set_add(struct linpool *pool, struct adata *list, u32 val)
{
@@ -189,9 +246,13 @@ int_set_add(struct linpool *pool, struct adata *list, u32 val)
len = list ? list->length : 0;
res = lp_alloc(pool, sizeof(struct adata) + len + 4);
res->length = len + 4;
- * (u32 *) res->data = val;
+
if (list)
- memcpy((char *) res->data + 4, list->data, list->length);
+ memcpy(res->data, list->data, list->length);
+
+ u32 *c = (u32 *) (res->data + len);
+ *c = val;
+
return res;
}
@@ -208,13 +269,30 @@ ec_set_add(struct linpool *pool, struct adata *list, u64 val)
if (list)
memcpy(res->data, list->data, list->length);
- u32 *l = (u32 *) (res->data + res->length - 8);
+ u32 *l = (u32 *) (res->data + olen);
l[0] = ec_hi(val);
l[1] = ec_lo(val);
return res;
}
+struct adata *
+lc_set_add(struct linpool *pool, struct adata *list, lcomm val)
+{
+ if (lc_set_contains(list, val))
+ return list;
+
+ int olen = list ? list->length : 0;
+ struct adata *res = lp_alloc(pool, sizeof(struct adata) + olen + LCOMM_LENGTH);
+ res->length = olen + LCOMM_LENGTH;
+
+ if (list)
+ memcpy(res->data, list->data, list->length);
+
+ lc_put((u32 *) (res->data + olen), val);
+
+ return res;
+}
struct adata *
int_set_del(struct linpool *pool, struct adata *list, u32 val)
@@ -265,6 +343,27 @@ ec_set_del(struct linpool *pool, struct adata *list, u64 val)
return res;
}
+struct adata *
+lc_set_del(struct linpool *pool, struct adata *list, lcomm val)
+{
+ if (!lc_set_contains(list, val))
+ return list;
+
+ struct adata *res;
+ res = lp_alloc(pool, sizeof(struct adata) + list->length - LCOMM_LENGTH);
+ res->length = list->length - LCOMM_LENGTH;
+
+ u32 *l = int_set_get_data(list);
+ u32 *k = int_set_get_data(res);
+ int len = int_set_get_size(list);
+ int i;
+
+ for (i=0; i < len; i += 3)
+ if (! lc_match(l, i, val))
+ k = lc_copy(k, l+i);
+
+ return res;
+}
struct adata *
int_set_union(struct linpool *pool, struct adata *l1, struct adata *l2)
@@ -328,3 +427,115 @@ ec_set_union(struct linpool *pool, struct adata *l1, struct adata *l2)
memcpy(res->data + l1->length, tmp, len);
return res;
}
+
+struct adata *
+lc_set_union(struct linpool *pool, struct adata *l1, struct adata *l2)
+{
+ if (!l1)
+ return l2;
+ if (!l2)
+ return l1;
+
+ struct adata *res;
+ int len = int_set_get_size(l2);
+ u32 *l = int_set_get_data(l2);
+ u32 tmp[len];
+ u32 *k = tmp;
+ int i;
+
+ for (i = 0; i < len; i += 3)
+ if (!lc_set_contains(l1, lc_get(l, i)))
+ k = lc_copy(k, l+i);
+
+ if (k == tmp)
+ return l1;
+
+ len = (k - tmp) * 4;
+ res = lp_alloc(pool, sizeof(struct adata) + l1->length + len);
+ res->length = l1->length + len;
+ memcpy(res->data, l1->data, l1->length);
+ memcpy(res->data + l1->length, tmp, len);
+ return res;
+}
+
+
+struct adata *
+ec_set_del_nontrans(struct linpool *pool, struct adata *set)
+{
+ adata *res = lp_alloc_adata(pool, set->length);
+ u32 *src = int_set_get_data(set);
+ u32 *dst = int_set_get_data(res);
+ int len = int_set_get_size(set);
+ int i;
+
+ /* Remove non-transitive communities (EC_TBIT set) */
+ for (i = 0; i < len; i += 2)
+ {
+ if (src[i] & EC_TBIT)
+ continue;
+
+ *dst++ = src[i];
+ *dst++ = src[i+1];
+ }
+
+ res->length = ((byte *) dst) - res->data;
+
+ return res;
+}
+
+static int
+int_set_cmp(const void *X, const void *Y)
+{
+ const u32 *x = X, *y = Y;
+ return (*x < *y) ? -1 : (*x > *y) ? 1 : 0;
+}
+
+struct adata *
+int_set_sort(struct linpool *pool, struct adata *src)
+{
+ struct adata *dst = lp_alloc_adata(pool, src->length);
+ memcpy(dst->data, src->data, src->length);
+ qsort(dst->data, dst->length / 4, 4, int_set_cmp);
+ return dst;
+}
+
+
+static int
+ec_set_cmp(const void *X, const void *Y)
+{
+ u64 x = ec_get(X, 0);
+ u64 y = ec_get(Y, 0);
+ return (x < y) ? -1 : (x > y) ? 1 : 0;
+}
+
+struct adata *
+ec_set_sort(struct linpool *pool, struct adata *src)
+{
+ struct adata *dst = lp_alloc_adata(pool, src->length);
+ memcpy(dst->data, src->data, src->length);
+ qsort(dst->data, dst->length / 8, 8, ec_set_cmp);
+ return dst;
+}
+
+
+static int
+lc_set_cmp(const void *X, const void *Y)
+{
+ const u32 *x = X, *y = Y;
+ if (x[0] != y[0])
+ return (x[0] > y[0]) ? 1 : -1;
+ if (x[1] != y[1])
+ return (x[1] > y[1]) ? 1 : -1;
+ if (x[2] != y[2])
+ return (x[2] > y[2]) ? 1 : -1;
+ return 0;
+}
+
+struct adata *
+lc_set_sort(struct linpool *pool, struct adata *src)
+{
+ struct adata *dst = lp_alloc_adata(pool, src->length);
+ memcpy(dst->data, src->data, src->length);
+ qsort(dst->data, dst->length / LCOMM_LENGTH, LCOMM_LENGTH, lc_set_cmp);
+ return dst;
+}
diff --git a/nest/a-set_test.c b/nest/a-set_test.c
new file mode 100644
index 00000000..f4588d65
--- /dev/null
+++ b/nest/a-set_test.c
@@ -0,0 +1,260 @@
+/*
+ * BIRD -- Set/Community-list Operations Tests
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "lib/net.h"
+#include "nest/route.h"
+#include "nest/attrs.h"
+#include "lib/resource.h"
+
+#define SET_SIZE 10
+static struct adata *set_sequence; /* <0; SET_SIZE) */
+static struct adata *set_sequence_same; /* <0; SET_SIZE) */
+static struct adata *set_sequence_higher; /* <SET_SIZE; 2*SET_SIZE) */
+static struct adata *set_random;
+
+#define BUFFER_SIZE 1000
+static byte buf[BUFFER_SIZE] = {};
+
+#define SET_SIZE_FOR_FORMAT_OUTPUT 10
+
+struct linpool *lp;
+
+enum set_type
+{
+ SET_TYPE_INT,
+ SET_TYPE_EC
+};
+
+static void
+generate_set_sequence(enum set_type type)
+{
+ struct adata empty_as_path = {};
+ set_sequence = set_sequence_same = set_sequence_higher = set_random = &empty_as_path;
+ lp = lp_new(&root_pool, 0);
+
+ int i;
+ for (i = 0; i < SET_SIZE; i++)
+ {
+ if (type == SET_TYPE_INT)
+ {
+ set_sequence = int_set_add(lp, set_sequence, i);
+ set_sequence_same = int_set_add(lp, set_sequence_same, i);
+ set_sequence_higher = int_set_add(lp, set_sequence_higher, i + SET_SIZE);
+ set_random = int_set_add(lp, set_random, bt_random());
+ }
+ else if (type == SET_TYPE_EC)
+ {
+ set_sequence = ec_set_add(lp, set_sequence, i);
+ set_sequence_same = ec_set_add(lp, set_sequence_same, i);
+ set_sequence_higher = ec_set_add(lp, set_sequence_higher, i + SET_SIZE);
+ set_random = ec_set_add(lp, set_random, (bt_random() << 32 | bt_random()));
+ }
+ else
+ bt_abort_msg("This should be unreachable");
+ }
+}
+
+/*
+ * SET INT TESTS
+ */
+
+static int
+t_set_int_contains(void)
+{
+ int i;
+
+ resource_init();
+ generate_set_sequence(SET_TYPE_INT);
+
+ bt_assert(int_set_get_size(set_sequence) == SET_SIZE);
+
+ for (i = 0; i < SET_SIZE; i++)
+ bt_assert(int_set_contains(set_sequence, i));
+ bt_assert(int_set_contains(set_sequence, -1) == 0);
+ bt_assert(int_set_contains(set_sequence, SET_SIZE) == 0);
+
+ int *data = int_set_get_data(set_sequence);
+ for (i = 0; i < SET_SIZE; i++)
+ bt_assert_msg(data[i] == i, "(data[i] = %d) == i = %d)", data[i], i);
+
+ rfree(lp);
+ return 1;
+}
+
+static int
+t_set_int_union(void)
+{
+ resource_init();
+ generate_set_sequence(SET_TYPE_INT);
+
+ struct adata *set_union;
+ set_union = int_set_union(lp, set_sequence, set_sequence_same);
+ bt_assert(int_set_get_size(set_union) == SET_SIZE);
+ bt_assert(int_set_format(set_union, 0, 2, buf, BUFFER_SIZE) == 0);
+
+ set_union = int_set_union(lp, set_sequence, set_sequence_higher);
+ bt_assert_msg(int_set_get_size(set_union) == SET_SIZE*2, "int_set_get_size(set_union) %d, SET_SIZE*2 %d", int_set_get_size(set_union), SET_SIZE*2);
+ bt_assert(int_set_format(set_union, 0, 2, buf, BUFFER_SIZE) == 0);
+
+ rfree(lp);
+ return 1;
+}
+
+static int
+t_set_int_format(void)
+{
+ resource_init();
+ generate_set_sequence(SET_TYPE_INT);
+
+ set_sequence->length = 4 * SET_SIZE_FOR_FORMAT_OUTPUT; /* dirty */
+ bt_assert(int_set_format(set_sequence, 0, 0, buf, BUFFER_SIZE) == 0);
+ bt_assert(strcmp(buf, "0.0.0.0 0.0.0.1 0.0.0.2 0.0.0.3 0.0.0.4 0.0.0.5 0.0.0.6 0.0.0.7 0.0.0.8 0.0.0.9") == 0);
+
+ bzero(buf, BUFFER_SIZE);
+ bt_assert(int_set_format(set_sequence, 0, 2, buf, BUFFER_SIZE) == 0);
+ bt_assert(strcmp(buf, "0.0.0.2 0.0.0.3 0.0.0.4 0.0.0.5 0.0.0.6 0.0.0.7 0.0.0.8 0.0.0.9") == 0);
+
+ bzero(buf, BUFFER_SIZE);
+ bt_assert(int_set_format(set_sequence, 1, 0, buf, BUFFER_SIZE) == 0);
+ bt_assert(strcmp(buf, "(0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (0,6) (0,7) (0,8) (0,9)") == 0);
+
+ rfree(lp);
+ return 1;
+}
+
+static int
+t_set_int_delete(void)
+{
+ resource_init();
+ generate_set_sequence(SET_TYPE_INT);
+
+ struct adata *deleting_sequence = set_sequence;
+ u32 i;
+ for (i = 0; i < SET_SIZE; i++)
+ {
+ deleting_sequence = int_set_del(lp, deleting_sequence, i);
+ bt_assert_msg(int_set_get_size(deleting_sequence) == (int) (SET_SIZE-1-i),
+ "int_set_get_size(deleting_sequence) %d == SET_SIZE-1-i %d",
+ int_set_get_size(deleting_sequence),
+ SET_SIZE-1-i);
+ }
+
+ bt_assert(int_set_get_size(set_sequence) == SET_SIZE);
+
+ return 1;
+}
+
+/*
+ * SET EC TESTS
+ */
+
+static int
+t_set_ec_contains(void)
+{
+ u32 i;
+
+ resource_init();
+ generate_set_sequence(SET_TYPE_EC);
+
+ bt_assert(ec_set_get_size(set_sequence) == SET_SIZE);
+
+ for (i = 0; i < SET_SIZE; i++)
+ bt_assert(ec_set_contains(set_sequence, i));
+ bt_assert(ec_set_contains(set_sequence, -1) == 0);
+ bt_assert(ec_set_contains(set_sequence, SET_SIZE) == 0);
+
+// int *data = ec_set_get_data(set_sequence);
+// for (i = 0; i < SET_SIZE; i++)
+// bt_assert_msg(data[i] == (SET_SIZE-1-i), "(data[i] = %d) == ((SET_SIZE-1-i) = %d)", data[i], SET_SIZE-1-i);
+
+ rfree(lp);
+ return 1;
+}
+
+static int
+t_set_ec_union(void)
+{
+ resource_init();
+ generate_set_sequence(SET_TYPE_EC);
+
+ struct adata *set_union;
+ set_union = ec_set_union(lp, set_sequence, set_sequence_same);
+ bt_assert(ec_set_get_size(set_union) == SET_SIZE);
+ bt_assert(ec_set_format(set_union, 0, buf, BUFFER_SIZE) == 0);
+
+ set_union = ec_set_union(lp, set_sequence, set_sequence_higher);
+ bt_assert_msg(ec_set_get_size(set_union) == SET_SIZE*2, "ec_set_get_size(set_union) %d, SET_SIZE*2 %d", ec_set_get_size(set_union), SET_SIZE*2);
+ bt_assert(ec_set_format(set_union, 0, buf, BUFFER_SIZE) == 0);
+
+ rfree(lp);
+ return 1;
+}
+
+static int
+t_set_ec_format(void)
+{
+ resource_init();
+
+ struct adata empty_as_path = {};
+ set_sequence = set_sequence_same = set_sequence_higher = set_random = &empty_as_path;
+ lp = lp_new(&root_pool, 0);
+
+ u64 i = 0;
+ set_sequence = ec_set_add(lp, set_sequence, i);
+ for (i = 1; i < SET_SIZE_FOR_FORMAT_OUTPUT; i++)
+ set_sequence = ec_set_add(lp, set_sequence, i + ((i%2) ? ((u64)EC_RO << 48) : ((u64)EC_RT << 48)));
+
+ bt_assert(ec_set_format(set_sequence, 0, buf, BUFFER_SIZE) == 0);
+ bt_assert_msg(strcmp(buf, "(unknown 0x0, 0, 0) (ro, 0, 1) (rt, 0, 2) (ro, 0, 3) (rt, 0, 4) (ro, 0, 5) (rt, 0, 6) (ro, 0, 7) (rt, 0, 8) (ro, 0, 9)") == 0,
+ "ec_set_format() returns '%s'", buf);
+
+ rfree(lp);
+ return 1;
+}
+
+static int
+t_set_ec_delete(void)
+{
+ resource_init();
+ generate_set_sequence(SET_TYPE_EC);
+
+ struct adata *deleting_sequence = set_sequence;
+ u32 i;
+ for (i = 0; i < SET_SIZE; i++)
+ {
+ deleting_sequence = ec_set_del(lp, deleting_sequence, i);
+ bt_assert_msg(ec_set_get_size(deleting_sequence) == (int) (SET_SIZE-1-i),
+ "ec_set_get_size(deleting_sequence) %d == SET_SIZE-1-i %d",
+ ec_set_get_size(deleting_sequence), SET_SIZE-1-i);
+ }
+
+ bt_assert(ec_set_get_size(set_sequence) == SET_SIZE);
+
+ return 1;
+}
+
+int
+main(int argc, char *argv[])
+{
+ bt_init(argc, argv);
+
+ bt_test_suite(t_set_int_contains, "Testing sets of integers: contains, get_data");
+ bt_test_suite(t_set_int_format, "Testing sets of integers: format");
+ bt_test_suite(t_set_int_union, "Testing sets of integers: union");
+ bt_test_suite(t_set_int_delete, "Testing sets of integers: delete");
+
+ bt_test_suite(t_set_ec_contains, "Testing sets of Extended Community values: contains, get_data");
+ bt_test_suite(t_set_ec_format, "Testing sets of Extended Community values: format");
+ bt_test_suite(t_set_ec_union, "Testing sets of Extended Community values: union");
+ bt_test_suite(t_set_ec_delete, "Testing sets of Extended Community values: delete");
+
+ return bt_exit_value();
+}
diff --git a/nest/attrs.h b/nest/attrs.h
index 0171c6a8..810ff583 100644
--- a/nest/attrs.h
+++ b/nest/attrs.h
@@ -10,6 +10,9 @@
#define _BIRD_ATTRS_H_
#include <stdint.h>
+#include "lib/unaligned.h"
+#include "nest/route.h"
+
/* a-path.c */
@@ -27,32 +30,79 @@
struct f_tree;
-struct adata *as_path_prepend(struct linpool *pool, struct adata *olda, u32 as);
-int as_path_convert_to_old(struct adata *path, byte *dst, int *new_used);
-int as_path_convert_to_new(struct adata *path, byte *dst, int req_as);
-void as_path_format(struct adata *path, byte *buf, uint size);
-int as_path_getlen(struct adata *path);
-int as_path_getlen_int(struct adata *path, int bs);
-int as_path_get_first(struct adata *path, u32 *orig_as);
-int as_path_get_last(struct adata *path, u32 *last_as);
-u32 as_path_get_last_nonaggregated(struct adata *path);
-int as_path_contains(struct adata *path, u32 as, int min);
-int as_path_match_set(struct adata *path, struct f_tree *set);
+int as_path_valid(byte *data, uint len, int bs, char *err, uint elen);
+int as_path_16to32(byte *dst, byte *src, uint len);
+int as_path_32to16(byte *dst, byte *src, uint len);
+int as_path_contains_as4(const struct adata *path);
+int as_path_contains_confed(const struct adata *path);
+struct adata *as_path_strip_confed(struct linpool *pool, const struct adata *op);
+struct adata *as_path_prepend2(struct linpool *pool, const struct adata *op, int seq, u32 as, int strip);
+struct adata *as_path_to_old(struct linpool *pool, const struct adata *path);
+void as_path_cut(struct adata *path, uint num);
+struct adata *as_path_merge(struct linpool *pool, struct adata *p1, struct adata *p2);
+void as_path_format(const struct adata *path, byte *buf, uint size);
+int as_path_getlen(const struct adata *path);
+int as_path_getlen_int(const struct adata *path, int bs);
+int as_path_get_first(const struct adata *path, u32 *orig_as);
+int as_path_get_last(const struct adata *path, u32 *last_as);
+u32 as_path_get_last_nonaggregated(const struct adata *path);
+int as_path_contains(const struct adata *path, u32 as, int min);
+int as_path_match_set(const struct adata *path, struct f_tree *set);
struct adata *as_path_filter(struct linpool *pool, struct adata *path, struct f_tree *set, u32 key, int pos);
+static inline struct adata *as_path_prepend(struct linpool *pool, const struct adata *path, u32 as)
+{ return as_path_prepend2(pool, path, AS_PATH_SEQUENCE, as, 0); }
+
#define PM_ASN 0
#define PM_QUESTION 1
#define PM_ASTERISK 2
#define PM_ASN_EXPR 3
+#define PM_ASN_RANGE 4
struct f_path_mask {
struct f_path_mask *next;
int kind;
uintptr_t val;
+ uintptr_t val2;
};
-int as_path_match(struct adata *path, struct f_path_mask *mask);
+int as_path_match(const struct adata *path, struct f_path_mask *mask);
+
+
+/* Counterparts to appropriate as_path_* functions */
+
+static inline int
+aggregator_16to32(byte *dst, byte *src)
+{
+ put_u32(dst, get_u16(src));
+ memcpy(dst+4, src+2, 4);
+ return 8;
+}
+
+static inline int
+aggregator_32to16(byte *dst, byte *src)
+{
+ put_u16(dst, get_u32(src));
+ memcpy(dst+2, src+4, 4);
+ return 6;
+}
+
+static inline int
+aggregator_contains_as4(struct adata *a)
+{
+ return get_u32(a->data) > 0xFFFF;
+}
+
+static inline struct adata *
+aggregator_to_old(struct linpool *pool, struct adata *a)
+{
+ struct adata *d = lp_alloc_adata(pool, 8);
+ put_u32(d->data, 0xFFFF);
+ memcpy(d->data + 4, a->data + 4, 4);
+ return d;
+}
+
/* a-set.c */
@@ -66,6 +116,7 @@ int as_path_match(struct adata *path, struct f_path_mask *mask);
/* Transitive bit (for first u32 half of EC) */
#define EC_TBIT 0x40000000
+#define ECOMM_LENGTH 8
static inline int int_set_get_size(struct adata *list)
{ return list->length / 4; }
@@ -73,6 +124,9 @@ static inline int int_set_get_size(struct adata *list)
static inline int ec_set_get_size(struct adata *list)
{ return list->length / 8; }
+static inline int lc_set_get_size(struct adata *list)
+{ return list->length / 12; }
+
static inline u32 *int_set_get_data(struct adata *list)
{ return (u32 *) list->data; }
@@ -96,17 +150,49 @@ static inline u64 ec_ip4(u64 kind, u64 key, u64 val)
static inline u64 ec_generic(u64 key, u64 val)
{ return (key << 32) | val; }
+/* Large community value */
+typedef struct lcomm {
+ u32 asn;
+ u32 ldp1;
+ u32 ldp2;
+} lcomm;
+
+#define LCOMM_LENGTH 12
+
+static inline lcomm lc_get(const u32 *l, int i)
+{ return (lcomm) { l[i], l[i+1], l[i+2] }; }
+
+static inline void lc_put(u32 *l, lcomm v)
+{ l[0] = v.asn; l[1] = v.ldp1; l[2] = v.ldp2; }
+
+static inline int lc_match(const u32 *l, int i, lcomm v)
+{ return (l[i] == v.asn && l[i+1] == v.ldp1 && l[i+2] == v.ldp2); }
+
+static inline u32 *lc_copy(u32 *dst, const u32 *src)
+{ memcpy(dst, src, LCOMM_LENGTH); return dst + 3; }
+
+
int int_set_format(struct adata *set, int way, int from, byte *buf, uint size);
int ec_format(byte *buf, u64 ec);
int ec_set_format(struct adata *set, int from, byte *buf, uint size);
+int lc_format(byte *buf, lcomm lc);
+int lc_set_format(struct adata *set, int from, byte *buf, uint size);
int int_set_contains(struct adata *list, u32 val);
int ec_set_contains(struct adata *list, u64 val);
+int lc_set_contains(struct adata *list, lcomm val);
struct adata *int_set_add(struct linpool *pool, struct adata *list, u32 val);
struct adata *ec_set_add(struct linpool *pool, struct adata *list, u64 val);
+struct adata *lc_set_add(struct linpool *pool, struct adata *list, lcomm val);
struct adata *int_set_del(struct linpool *pool, struct adata *list, u32 val);
struct adata *ec_set_del(struct linpool *pool, struct adata *list, u64 val);
+struct adata *lc_set_del(struct linpool *pool, struct adata *list, lcomm val);
struct adata *int_set_union(struct linpool *pool, struct adata *l1, struct adata *l2);
struct adata *ec_set_union(struct linpool *pool, struct adata *l1, struct adata *l2);
+struct adata *lc_set_union(struct linpool *pool, struct adata *l1, struct adata *l2);
+struct adata *ec_set_del_nontrans(struct linpool *pool, struct adata *set);
+struct adata *int_set_sort(struct linpool *pool, struct adata *src);
+struct adata *ec_set_sort(struct linpool *pool, struct adata *src);
+struct adata *lc_set_sort(struct linpool *pool, struct adata *src);
#endif
diff --git a/nest/bfd.h b/nest/bfd.h
index f1e95cb2..b0ebe31d 100644
--- a/nest/bfd.h
+++ b/nest/bfd.h
@@ -42,7 +42,7 @@ struct bfd_request {
struct bfd_request * bfd_request_session(pool *p, ip_addr addr, ip_addr local, struct iface *iface, void (*hook)(struct bfd_request *), void *data);
-static inline void cf_check_bfd(int use) { }
+static inline void cf_check_bfd(int use UNUSED) { }
#else
diff --git a/nest/cmds.c b/nest/cmds.c
index 82fdca66..f0a14425 100644
--- a/nest/cmds.c
+++ b/nest/cmds.c
@@ -80,7 +80,6 @@ print_size(char *dsc, size_t val)
extern pool *rt_table_pool;
extern pool *rta_pool;
-extern pool *proto_pool;
void
cmd_show_memory(void)
diff --git a/nest/config.Y b/nest/config.Y
index 2961dafb..776e5d16 100644
--- a/nest/config.Y
+++ b/nest/config.Y
@@ -13,6 +13,7 @@ CF_HDR
#include "nest/password.h"
#include "nest/cmds.h"
#include "lib/lists.h"
+#include "lib/mac.h"
CF_DEFINES
@@ -68,13 +69,14 @@ CF_KEYWORDS(INTERFACE, IMPORT, EXPORT, FILTER, NONE, TABLE, STATES, ROUTES, FILT
CF_KEYWORDS(IPV4, IPV6, VPN4, VPN6, ROA4, ROA6)
CF_KEYWORDS(RECEIVE, LIMIT, ACTION, WARN, BLOCK, RESTART, DISABLE, KEEP, FILTERED)
CF_KEYWORDS(PASSWORD, FROM, PASSIVE, TO, ID, EVENTS, PACKETS, PROTOCOLS, INTERFACES)
-CF_KEYWORDS(PRIMARY, STATS, COUNT, FOR, COMMANDS, PREEXPORT, NOEXPORT, GENERATE) /* ,ROA */
+CF_KEYWORDS(ALGORITHM, KEYED, HMAC, MD5, SHA1, SHA256, SHA384, SHA512)
+CF_KEYWORDS(PRIMARY, STATS, COUNT, FOR, COMMANDS, PREEXPORT, NOEXPORT, GENERATE)
CF_KEYWORDS(LISTEN, BGP, V6ONLY, DUAL, ADDRESS, PORT, PASSWORDS, DESCRIPTION, SORTED)
CF_KEYWORDS(RELOAD, IN, OUT, MRTDUMP, MESSAGES, RESTRICT, MEMORY, IGP_METRIC, CLASS, DSCP)
CF_KEYWORDS(GRACEFUL, RESTART, WAIT, MAX, FLUSH, AS)
CF_ENUM(T_ENUM_RTS, RTS_, DUMMY, STATIC, INHERIT, DEVICE, STATIC_DEVICE, REDIRECT,
- RIP, OSPF, OSPF_IA, OSPF_EXT1, OSPF_EXT2, BGP, PIPE)
+ RIP, OSPF, OSPF_IA, OSPF_EXT1, OSPF_EXT2, BGP, PIPE, BABEL)
CF_ENUM(T_ENUM_SCOPE, SCOPE_, HOST, LINK, SITE, ORGANIZATION, UNIVERSE, UNDEFINED)
CF_ENUM(T_ENUM_RTC, RTC_, UNICAST, BROADCAST, MULTICAST, ANYCAST)
CF_ENUM(T_ENUM_RTD, RTD_, ROUTER, DEVICE, BLACKHOLE, UNREACHABLE, PROHIBIT, MULTIPATH)
@@ -86,7 +88,7 @@ CF_ENUM(T_ENUM_ROA, ROA_, UNKNOWN, VALID, INVALID)
%type <s> optsym
%type <ra> r_args
%type <sd> sym_args
-%type <i> proto_start echo_mask echo_size debug_mask debug_list debug_flag mrtdump_mask mrtdump_list mrtdump_flag export_mode limit_action net_type table_sorted tos
+%type <i> proto_start echo_mask echo_size debug_mask debug_list debug_flag mrtdump_mask mrtdump_list mrtdump_flag export_mode limit_action net_type table_sorted tos password_algorithm
%type <ps> proto_patt proto_patt2
%type <cc> channel_start proto_channel
%type <cl> limit_spec
@@ -419,7 +421,7 @@ password_list:
| password_item
;
-password_items:
+password_items:
/* empty */
| password_item ';' password_items
;
@@ -438,11 +440,13 @@ password_item_begin:
}
this_p_item = cfg_alloc(sizeof (struct password_item));
this_p_item->password = $2;
+ this_p_item->length = strlen($2);
this_p_item->genfrom = 0;
this_p_item->gento = TIME_INFINITY;
this_p_item->accfrom = 0;
this_p_item->accto = TIME_INFINITY;
this_p_item->id = password_id++;
+ this_p_item->alg = ALG_UNDEFINED;
add_tail(this_p_list, &this_p_item->n);
}
;
@@ -453,10 +457,24 @@ password_item_params:
| GENERATE TO datetime ';' password_item_params { this_p_item->gento = $3; }
| ACCEPT FROM datetime ';' password_item_params { this_p_item->accfrom = $3; }
| ACCEPT TO datetime ';' password_item_params { this_p_item->accto = $3; }
+ | FROM datetime ';' password_item_params { this_p_item->genfrom = this_p_item->accfrom = $2; }
+ | TO datetime ';' password_item_params { this_p_item->gento = this_p_item->accto = $2; }
| ID expr ';' password_item_params { this_p_item->id = $2; if ($2 <= 0) cf_error("Password ID has to be greated than zero."); }
+ | ALGORITHM password_algorithm ';' password_item_params { this_p_item->alg = $2; }
;
-
+password_algorithm:
+ KEYED MD5 { $$ = ALG_MD5; }
+ | KEYED SHA1 { $$ = ALG_SHA1; }
+ | KEYED SHA256 { $$ = ALG_SHA256; }
+ | KEYED SHA384 { $$ = ALG_SHA384; }
+ | KEYED SHA512 { $$ = ALG_SHA512; }
+ | HMAC MD5 { $$ = ALG_HMAC_MD5; }
+ | HMAC SHA1 { $$ = ALG_HMAC_SHA1; }
+ | HMAC SHA256 { $$ = ALG_HMAC_SHA256; }
+ | HMAC SHA384 { $$ = ALG_HMAC_SHA384; }
+ | HMAC SHA512 { $$ = ALG_HMAC_SHA512; }
+ ;
/* Core commands */
CF_CLI_HELP(SHOW, ..., [[Show status information]])
@@ -605,7 +623,7 @@ CF_CLI(EVAL, term, <expr>, [[Evaluate an expression]])
{ cmd_eval($2); } ;
CF_CLI_HELP(ECHO, ..., [[Control echoing of log messages]])
-CF_CLI(ECHO, echo_mask echo_size, (all | off | { debug | trace | info | remote | warning | error | auth }) [<buffer-size>], [[Control echoing of log messages]]) {
+CF_CLI(ECHO, echo_mask echo_size, (all | off | { debug|trace|info|remote|warning|error|auth [, ...] }) [<buffer-size>], [[Control echoing of log messages]]) {
cli_set_log_echo(this_cli, $2, $3);
cli_msg(0, "");
} ;
@@ -638,11 +656,11 @@ CF_CLI(RELOAD OUT, proto_patt, <protocol> | \"<pattern>\" | all, [[Reload protoc
{ proto_apply_cmd($3, proto_cmd_reload, 1, CMD_RELOAD_OUT); } ;
CF_CLI_HELP(DEBUG, ..., [[Control protocol debugging via BIRD logs]])
-CF_CLI(DEBUG, proto_patt debug_mask, (<protocol> | <pattern> | all) (all | off | { states | routes | filters | interfaces | events | packets }), [[Control protocol debugging via BIRD logs]])
+CF_CLI(DEBUG, proto_patt debug_mask, (<protocol> | \"<pattern>\" | all) (all | off | { states|routes|filters|interfaces|events|packets [, ...] }), [[Control protocol debugging via BIRD logs]])
{ proto_apply_cmd($2, proto_cmd_debug, 1, $3); } ;
CF_CLI_HELP(MRTDUMP, ..., [[Control protocol debugging via MRTdump files]])
-CF_CLI(MRTDUMP, proto_patt mrtdump_mask, (<protocol> | <pattern> | all) (all | off | { states | messages }), [[Control protocol debugging via MRTdump format]])
+CF_CLI(MRTDUMP, proto_patt mrtdump_mask, (<protocol> | \"<pattern>\" | all) (all | off | { states|messages [, ...] }), [[Control protocol debugging via MRTdump format]])
{ proto_apply_cmd($2, proto_cmd_mrtdump, 1, $3); } ;
CF_CLI(RESTRICT,,,[[Restrict current CLI session to safe commands]])
diff --git a/nest/iface.h b/nest/iface.h
index c4f414ec..d960b859 100644
--- a/nest/iface.h
+++ b/nest/iface.h
@@ -10,6 +10,7 @@
#define _BIRD_IFACE_H_
#include "lib/lists.h"
+#include "lib/ip.h"
extern list iface_list;
diff --git a/nest/locks.c b/nest/locks.c
index ad2af493..84b8b0ae 100644
--- a/nest/locks.c
+++ b/nest/locks.c
@@ -100,7 +100,8 @@ static struct resclass olock_class = {
sizeof(struct object_lock),
olock_free,
olock_dump,
- NULL
+ NULL,
+ NULL,
};
/**
diff --git a/nest/password.c b/nest/password.c
index 91aaa418..e4813741 100644
--- a/nest/password.c
+++ b/nest/password.c
@@ -10,6 +10,7 @@
#include "nest/bird.h"
#include "nest/password.h"
#include "lib/string.h"
+#include "lib/mac.h"
struct password_item *last_password_item = NULL;
@@ -37,7 +38,7 @@ password_find(list *l, int first_fit)
}
struct password_item *
-password_find_by_id(list *l, int id)
+password_find_by_id(list *l, uint id)
{
struct password_item *pi;
@@ -66,3 +67,17 @@ password_find_by_value(list *l, char *pass, uint size)
return NULL;
}
+uint
+max_mac_length(list *l)
+{
+ struct password_item *pi;
+ uint val = 0;
+
+ if (!l)
+ return 0;
+
+ WALK_LIST(pi, *l)
+ val = MAX(val, mac_type_length(pi->alg));
+
+ return val;
+}
diff --git a/nest/password.h b/nest/password.h
index cbf80b99..78244985 100644
--- a/nest/password.h
+++ b/nest/password.h
@@ -9,19 +9,22 @@
#ifndef PASSWORD_H
#define PASSWORD_H
+
#include "sysdep/unix/timer.h"
struct password_item {
node n;
- char *password;
- int id;
+ char *password; /* Key data, null terminated */
+ uint length; /* Key length, without null */
+ uint id; /* Key ID */
+ uint alg; /* MAC algorithm */
bird_clock_t accfrom, accto, genfrom, gento;
};
extern struct password_item *last_password_item;
struct password_item *password_find(list *l, int first_fit);
-struct password_item *password_find_by_id(list *l, int id);
+struct password_item *password_find_by_id(list *l, uint id);
struct password_item *password_find_by_value(list *l, char *pass, uint size);
static inline int password_verify(struct password_item *p1, char *p2, uint size)
@@ -31,4 +34,6 @@ static inline int password_verify(struct password_item *p1, char *p2, uint size)
return !memcmp(buf, p2, size);
}
+uint max_mac_length(list *l);
+
#endif
diff --git a/nest/proto.c b/nest/proto.c
index 670ee00e..815d0652 100644
--- a/nest/proto.c
+++ b/nest/proto.c
@@ -39,7 +39,7 @@ static int graceful_restart_state;
static u32 graceful_restart_locks;
static char *p_states[] = { "DOWN", "START", "UP", "STOP" };
-static char *c_states[] UNUSED = { "DOWN", "START", "UP", "FLUSHING" };
+static char *c_states[] = { "DOWN", "START", "UP", "FLUSHING" };
extern struct protocol proto_unix_iface;
@@ -304,6 +304,8 @@ channel_do_down(struct channel *c)
memset(&c->stats, 0, sizeof(struct proto_stats));
+ CALL(c->channel->cleanup, c);
+
/* Schedule protocol shutddown */
if (proto_is_done(c->proto))
ev_schedule(c->proto->event);
@@ -514,7 +516,9 @@ channel_reconfigure(struct channel *c, struct channel_config *cf)
channel_verify_limits(c);
- CALL(c->channel->reconfigure, c, cf);
+ /* Execute channel-specific reconfigure hook */
+ if (c->channel->reconfigure && !c->channel->reconfigure(c, cf))
+ return 0;
/* If the channel is not open, it has no routes and we cannot reload it anyways */
if (c->channel_state != CS_UP)
@@ -797,7 +801,6 @@ proto_reconfigure(struct proto *p, struct proto_config *oc, struct proto_config
if ((nc->protocol != oc->protocol) ||
(nc->net_type != oc->net_type) ||
(nc->disabled != p->disabled))
-
return 0;
p->name = nc->name;
@@ -1578,6 +1581,7 @@ void
channel_show_info(struct channel *c)
{
cli_msg(-1006, " Channel %s", c->name);
+ cli_msg(-1006, " State: %s", c_states[c->channel_state]);
cli_msg(-1006, " Table: %s", c->table->name);
cli_msg(-1006, " Preference: %d", c->preference);
cli_msg(-1006, " Input filter: %s", filter_name(c->in_filter));
diff --git a/nest/protocol.h b/nest/protocol.h
index 6041f314..6efaaaf7 100644
--- a/nest/protocol.h
+++ b/nest/protocol.h
@@ -273,6 +273,7 @@ proto_get_router_id(struct proto_config *pc)
/* Moved from route.h to avoid dependency conflicts */
static inline void rte_update(struct proto *p, const net_addr *n, rte *new) { rte_update2(p->main_channel, n, new, p->main_source); }
+extern pool *proto_pool;
extern list proto_list;
/*
@@ -418,20 +419,22 @@ struct channel_class {
uint channel_size; /* Size of channel data structure */
uint config_size; /* Size of channel config data structure */
- struct channel * (*init)(struct channel *, struct channel_config *); /* Create new instance */
+ void (*init)(struct channel *, struct channel_config *); /* Create new instance */
int (*reconfigure)(struct channel *, struct channel_config *); /* Try to reconfigure instance, returns success */
int (*start)(struct channel *); /* Start the instance */
- int (*shutdown)(struct channel *); /* Stop the instance */
+ void (*shutdown)(struct channel *); /* Stop the instance */
+ void (*cleanup)(struct channel *); /* Channel finished flush */
void (*copy_config)(struct channel_config *, struct channel_config *); /* Copy config from given channel instance */
#if 0
+ XXXX;
void (*preconfig)(struct protocol *, struct config *); /* Just before configuring */
void (*postconfig)(struct proto_config *); /* After configuring each instance */
void (*dump)(struct proto *); /* Debugging dump */
void (*dump_attrs)(struct rte *); /* Dump protocol-dependent attributes */
- void (*cleanup)(struct proto *); /* Called after shutdown when protocol became hungry/down */
+
void (*get_status)(struct proto *, byte *buf); /* Get instance status (for `show protocols' command) */
void (*get_route_info)(struct rte *, byte *buf, struct ea_list *attrs); /* Get route information (for `show route' command) */
int (*get_attr)(struct eattr *, byte *buf, int buflen); /* ASCIIfy dynamic attribute (returns GA_*) */
@@ -440,6 +443,8 @@ struct channel_class {
#endif
};
+extern struct channel_class channel_bgp;
+
struct channel_config {
node n;
const char *name;
@@ -484,6 +489,7 @@ struct channel {
u8 merge_limit; /* Maximal number of nexthops for RA_MERGED */
u8 in_keep_filtered; /* Routes rejected in import filter are kept */
u8 disabled;
+ u8 stale; /* Used in reconfiguration */
u8 channel_state;
u8 export_state; /* Route export state (ES_*, see below) */
diff --git a/nest/route.h b/nest/route.h
index 74bbe4ab..d652ca15 100644
--- a/nest/route.h
+++ b/nest/route.h
@@ -12,7 +12,7 @@
#include "lib/lists.h"
#include "lib/resource.h"
#include "sysdep/unix/timer.h"
-//#include "nest/protocol.h"
+#include "lib/net.h"
struct ea_list;
struct protocol;
@@ -285,9 +285,8 @@ rte *rte_find(net *net, struct rte_src *src);
rte *rte_get_temp(struct rta *);
void rte_update2(struct channel *c, const net_addr *n, rte *new, struct rte_src *src);
/* rte_update() moved to protocol.h to avoid dependency conflicts */
-void rte_discard(rtable *tab, rte *old);
int rt_examine(rtable *t, net_addr *a, struct proto *p, struct filter *filter);
-rte *rt_export_merged(struct channel *c, net *net, rte **rt_free, struct ea_list **tmpa, int silent);
+rte *rt_export_merged(struct channel *c, net *net, rte **rt_free, struct ea_list **tmpa, linpool *pool, int silent);
void rt_refresh_begin(rtable *t, struct channel *c);
void rt_refresh_end(rtable *t, struct channel *c);
void rt_schedule_prune(rtable *t);
@@ -447,7 +446,7 @@ typedef struct eattr {
#define EA_ALLOW_UNDEF 0x10000 /* ea_find: allow EAF_TYPE_UNDEF */
#define EA_BIT(n) ((n) << 24) /* Used in bitfield accessors */
-#define EAF_TYPE_MASK 0x0f /* Mask with this to get type */
+#define EAF_TYPE_MASK 0x1f /* Mask with this to get type */
#define EAF_TYPE_INT 0x01 /* 32-bit unsigned integer number */
#define EAF_TYPE_OPAQUE 0x02 /* Opaque byte string (not filterable) */
#define EAF_TYPE_IP_ADDRESS 0x04 /* IP address */
@@ -456,16 +455,26 @@ typedef struct eattr {
#define EAF_TYPE_BITFIELD 0x09 /* 32-bit embedded bitfield */
#define EAF_TYPE_INT_SET 0x0a /* Set of u32's (e.g., a community list) */
#define EAF_TYPE_EC_SET 0x0e /* Set of pairs of u32's - ext. community list */
-#define EAF_TYPE_UNDEF 0x0f /* `force undefined' entry */
+#define EAF_TYPE_LC_SET 0x12 /* Set of triplets of u32's - large community list */
+#define EAF_TYPE_UNDEF 0x1f /* `force undefined' entry */
#define EAF_EMBEDDED 0x01 /* Data stored in eattr.u.data (part of type spec) */
#define EAF_VAR_LENGTH 0x02 /* Attribute length is variable (part of type spec) */
-#define EAF_ORIGINATED 0x40 /* The attribute has originated locally */
+#define EAF_ORIGINATED 0x20 /* The attribute has originated locally */
+#define EAF_FRESH 0x40 /* An uncached attribute (e.g. modified in export filter) */
#define EAF_TEMP 0x80 /* A temporary attribute (the one stored in the tmp attr list) */
-struct adata {
+typedef struct adata {
uint length; /* Length of data */
byte data[0];
-};
+} adata;
+
+static inline struct adata *
+lp_alloc_adata(struct linpool *pool, uint len)
+{
+ struct adata *ad = lp_alloc(pool, sizeof(struct adata) + len);
+ ad->length = len;
+ return ad;
+}
static inline int adata_same(struct adata *a, struct adata *b)
{ return (a->length == b->length && !memcmp(a->data, b->data, a->length)); }
@@ -511,6 +520,8 @@ int mpnh__same(struct mpnh *x, struct mpnh *y); /* Compare multipath nexthops */
static inline int mpnh_same(struct mpnh *x, struct mpnh *y)
{ return (x == y) || mpnh__same(x, y); }
struct mpnh *mpnh_merge(struct mpnh *x, struct mpnh *y, int rx, int ry, int max, linpool *lp);
+void mpnh_insert(struct mpnh **n, struct mpnh *y);
+int mpnh_is_sorted(struct mpnh *x);
void rta_init(void);
rta *rta_lookup(rta *); /* Get rta equivalent to this one, uc++ */
@@ -523,7 +534,7 @@ static inline rta * rta_cow(rta *r, linpool *lp) { return rta_is_cached(r) ? rta
void rta_dump(rta *);
void rta_dump_all(void);
void rta_show(struct cli *, rta *, ea_list *);
-void rta_set_recursive_next_hop(rtable *dep, rta *a, rtable *tab, ip_addr *gw, ip_addr *ll);
+void rta_set_recursive_next_hop(rtable *dep, rta *a, rtable *tab, ip_addr gw, ip_addr ll);
/*
* rta_set_recursive_next_hop() acquires hostentry from hostcache and fills
diff --git a/nest/rt-attr.c b/nest/rt-attr.c
index 167bfc44..94f25de8 100644
--- a/nest/rt-attr.c
+++ b/nest/rt-attr.c
@@ -250,6 +250,34 @@ mpnh_merge(struct mpnh *x, struct mpnh *y, int rx, int ry, int max, linpool *lp)
return root;
}
+void
+mpnh_insert(struct mpnh **n, struct mpnh *x)
+{
+ for (; *n; n = &((*n)->next))
+ {
+ int cmp = mpnh_compare_node(*n, x);
+
+ if (cmp < 0)
+ continue;
+ else if (cmp > 0)
+ break;
+ else
+ return;
+ }
+
+ x->next = *n;
+ *n = x;
+}
+
+int
+mpnh_is_sorted(struct mpnh *x)
+{
+ for (; x && x->next; x = x->next)
+ if (mpnh_compare_node(x, x->next) >= 0)
+ return 0;
+
+ return 1;
+}
static struct mpnh *
mpnh_copy(struct mpnh *o)
@@ -500,7 +528,7 @@ ea_do_prune(ea_list *e)
if ((s0->type & EAF_TYPE_MASK) != EAF_TYPE_UNDEF)
{
*d = *s0;
- d->type = (d->type & ~EAF_ORIGINATED) | (s[-1].type & EAF_ORIGINATED);
+ d->type = (d->type & ~(EAF_ORIGINATED|EAF_FRESH)) | (s[-1].type & EAF_ORIGINATED);
d++;
i++;
}
@@ -705,7 +733,7 @@ static inline void
opaque_format(struct adata *ad, byte *buf, uint size)
{
byte *bound = buf + size - 10;
- int i;
+ uint i;
for(i = 0; i < ad->length; i++)
{
@@ -748,6 +776,18 @@ ea_show_ec_set(struct cli *c, struct adata *ad, byte *pos, byte *buf, byte *end)
}
}
+static inline void
+ea_show_lc_set(struct cli *c, struct adata *ad, byte *pos, byte *buf, byte *end)
+{
+ int i = lc_set_format(ad, 0, pos, end - pos);
+ cli_printf(c, -1012, "\t%s", buf);
+ while (i)
+ {
+ i = lc_set_format(ad, i, buf, end - buf - 1);
+ cli_printf(c, -1012, "\t\t%s", buf);
+ }
+}
+
/**
* ea_show - print an &eattr to CLI
* @c: destination CLI
@@ -812,6 +852,9 @@ ea_show(struct cli *c, eattr *e)
case EAF_TYPE_EC_SET:
ea_show_ec_set(c, ad, pos, buf, end);
return;
+ case EAF_TYPE_LC_SET:
+ ea_show_lc_set(c, ad, pos, buf, end);
+ return;
case EAF_TYPE_UNDEF:
default:
bsprintf(pos, "<type %02x>", e->type);
@@ -1114,7 +1157,7 @@ rta_dump(rta *a)
static char *rts[] = { "RTS_DUMMY", "RTS_STATIC", "RTS_INHERIT", "RTS_DEVICE",
"RTS_STAT_DEV", "RTS_REDIR", "RTS_RIP",
"RTS_OSPF", "RTS_OSPF_IA", "RTS_OSPF_EXT1",
- "RTS_OSPF_EXT2", "RTS_BGP" };
+ "RTS_OSPF_EXT2", "RTS_BGP", "RTS_PIPE", "RTS_BABEL" };
static char *rtc[] = { "", " BC", " MC", " AC" };
static char *rtd[] = { "", " DEV", " HOLE", " UNREACH", " PROHIBIT" };
diff --git a/nest/rt-table.c b/nest/rt-table.c
index cb45898f..6bf6c2fe 100644
--- a/nest/rt-table.c
+++ b/nest/rt-table.c
@@ -50,7 +50,7 @@ static linpool *rte_update_pool;
static list routing_tables;
-static void rt_format_via(rte *e, byte *via);
+static byte *rt_format_via(rte *e);
static void rt_free_hostcache(rtable *tab);
static void rt_notify_hostcache(rtable *tab, net *net);
static void rt_update_hostcache(rtable *tab);
@@ -63,7 +63,7 @@ make_tmp_attrs(struct rte *rt, struct linpool *pool)
{
struct ea_list *(*mta)(struct rte *rt, struct linpool *pool);
mta = rt->attrs->src->proto->make_tmp_attrs;
- return mta ? mta(rt, rte_update_pool) : NULL;
+ return mta ? mta(rt, pool) : NULL;
}
@@ -346,10 +346,7 @@ rte_mergable(rte *pri, rte *sec)
static void
rte_trace(struct proto *p, rte *e, int dir, char *msg)
{
- byte via[IPA_MAX_TEXT_LENGTH+32];
-
- rt_format_via(e, via);
- log(L_TRACE "%s %c %s %N %s", p->name, dir, msg, e->net->n.addr, via);
+ log(L_TRACE "%s %c %s %N %s", p->name, dir, msg, e->net->n.addr, rt_format_via(e));
}
static inline void
@@ -367,7 +364,7 @@ rte_trace_out(uint flag, struct proto *p, rte *e, char *msg)
}
static rte *
-export_filter(struct channel *c, rte *rt0, rte **rt_free, ea_list **tmpa, int silent)
+export_filter_(struct channel *c, rte *rt0, rte **rt_free, ea_list **tmpa, linpool *pool, int silent)
{
struct proto *p = c->proto;
struct filter *filter = c->out_filter;
@@ -382,9 +379,9 @@ export_filter(struct channel *c, rte *rt0, rte **rt_free, ea_list **tmpa, int si
if (!tmpa)
tmpa = &tmpb;
- *tmpa = make_tmp_attrs(rt, rte_update_pool);
+ *tmpa = make_tmp_attrs(rt, pool);
- v = p->import_control ? p->import_control(p, &rt, tmpa, rte_update_pool) : 0;
+ v = p->import_control ? p->import_control(p, &rt, tmpa, pool) : 0;
if (v < 0)
{
if (silent)
@@ -403,7 +400,7 @@ export_filter(struct channel *c, rte *rt0, rte **rt_free, ea_list **tmpa, int si
}
v = filter && ((filter == FILTER_REJECT) ||
- (f_run(filter, &rt, tmpa, rte_update_pool, FF_FORCE_TMPATTR) > F_ACCEPT));
+ (f_run(filter, &rt, tmpa, pool, FF_FORCE_TMPATTR) > F_ACCEPT));
if (v)
{
if (silent)
@@ -426,6 +423,12 @@ export_filter(struct channel *c, rte *rt0, rte **rt_free, ea_list **tmpa, int si
return NULL;
}
+static inline rte *
+export_filter(struct channel *c, rte *rt0, rte **rt_free, ea_list **tmpa, int silent)
+{
+ return export_filter_(c, rt0, rt_free, tmpa, rte_update_pool, silent);
+}
+
static void
do_rt_notify(struct channel *c, net *net, rte *new, rte *old, ea_list *tmpa, int refeed)
{
@@ -706,15 +709,15 @@ rt_notify_accepted(struct channel *c, net *net, rte *new_changed, rte *old_chang
static struct mpnh *
-mpnh_merge_rta(struct mpnh *nhs, rta *a, int max)
+mpnh_merge_rta(struct mpnh *nhs, rta *a, linpool *pool, int max)
{
struct mpnh nh = { .gw = a->gw, .iface = a->iface };
struct mpnh *nh2 = (a->dest == RTD_MULTIPATH) ? a->nexthops : &nh;
- return mpnh_merge(nhs, nh2, 1, 0, max, rte_update_pool);
+ return mpnh_merge(nhs, nh2, 1, 0, max, pool);
}
rte *
-rt_export_merged(struct channel *c, net *net, rte **rt_free, ea_list **tmpa, int silent)
+rt_export_merged(struct channel *c, net *net, rte **rt_free, ea_list **tmpa, linpool *pool, int silent)
{
// struct proto *p = c->proto;
struct mpnh *nhs = NULL;
@@ -726,7 +729,7 @@ rt_export_merged(struct channel *c, net *net, rte **rt_free, ea_list **tmpa, int
if (!rte_is_valid(best0))
return NULL;
- best = export_filter(c, best0, rt_free, tmpa, silent);
+ best = export_filter_(c, best0, rt_free, tmpa, pool, silent);
if (!best || !rte_is_reachable(best))
return best;
@@ -736,13 +739,13 @@ rt_export_merged(struct channel *c, net *net, rte **rt_free, ea_list **tmpa, int
if (!rte_mergable(best0, rt0))
continue;
- rt = export_filter(c, rt0, &tmp, NULL, 1);
+ rt = export_filter_(c, rt0, &tmp, NULL, pool, 1);
if (!rt)
continue;
if (rte_is_reachable(rt))
- nhs = mpnh_merge_rta(nhs, rt->attrs, c->merge_limit);
+ nhs = mpnh_merge_rta(nhs, rt->attrs, pool, c->merge_limit);
if (tmp)
rte_free(tmp);
@@ -750,11 +753,11 @@ rt_export_merged(struct channel *c, net *net, rte **rt_free, ea_list **tmpa, int
if (nhs)
{
- nhs = mpnh_merge_rta(nhs, best->attrs, c->merge_limit);
+ nhs = mpnh_merge_rta(nhs, best->attrs, pool, c->merge_limit);
if (nhs->next)
{
- best = rte_cow_rta(best, rte_update_pool);
+ best = rte_cow_rta(best, pool);
best->attrs->dest = RTD_MULTIPATH;
best->attrs->nexthops = nhs;
}
@@ -805,7 +808,7 @@ rt_notify_merged(struct channel *c, net *net, rte *new_changed, rte *old_changed
/* Prepare new merged route */
if (new_best)
- new_best = rt_export_merged(c, net, &new_best_free, &tmpa, 0);
+ new_best = rt_export_merged(c, net, &new_best_free, &tmpa, rte_update_pool, 0);
/* Prepare old merged route (without proper merged next hops) */
/* There are some issues with running filter on old route - see rt_notify_basic() */
@@ -919,6 +922,13 @@ rte_validate(rte *e)
return 0;
}
+ if ((e->attrs->dest == RTD_MULTIPATH) && !mpnh_is_sorted(e->attrs->nexthops))
+ {
+ log(L_WARN "Ignoring unsorted multipath route %N received via %s",
+ n->n.addr, e->sender->proto->name);
+ return 0;
+ }
+
return 1;
}
@@ -1393,8 +1403,8 @@ rte_announce_i(rtable *tab, unsigned type, net *net, rte *new, rte *old,
rte_update_unlock();
}
-void
-rte_discard(rtable *t, rte *old) /* Non-filtered route deletion, used during garbage collection */
+static inline void
+rte_discard(rte *old) /* Non-filtered route deletion, used during garbage collection */
{
rte_update_lock();
rte_recalculate(old->sender, old->net, NULL, old->attrs->src);
@@ -1685,7 +1695,7 @@ again:
return;
}
- rte_discard(tab, e);
+ rte_discard(e);
limit--;
goto rescan;
@@ -1770,7 +1780,7 @@ rta_apply_hostentry(rta *a, struct hostentry *he)
}
static inline rte *
-rt_next_hop_update_rte(rtable *tab, rte *old)
+rt_next_hop_update_rte(rtable *tab UNUSED, rte *old)
{
rta a;
memcpy(&a, old->attrs, sizeof(rta));
@@ -1848,7 +1858,7 @@ rt_next_hop_update_net(rtable *tab, net *n)
/* FIXME: Better announcement of merged routes */
rte_announce_i(tab, RA_MERGED, n, new, old_best, new, old_best);
- if (free_old_best)
+ if (free_old_best)
rte_free_quick(old_best);
return count;
@@ -2156,11 +2166,11 @@ hc_remove(struct hostcache *hc, struct hostentry *he)
static void
hc_alloc_table(struct hostcache *hc, unsigned order)
{
- unsigned hsize = 1 << order;
+ uint hsize = 1 << order;
hc->hash_order = order;
hc->hash_shift = 32 - order;
- hc->hash_max = (order >= HC_HI_ORDER) ? ~0 : (hsize HC_HI_MARK);
- hc->hash_min = (order <= HC_LO_ORDER) ? 0 : (hsize HC_LO_MARK);
+ hc->hash_max = (order >= HC_HI_ORDER) ? ~0U : (hsize HC_HI_MARK);
+ hc->hash_min = (order <= HC_LO_ORDER) ? 0U : (hsize HC_LO_MARK);
hc->hash_table = mb_allocz(rt_table_pool, hsize * sizeof(struct hostentry *));
}
@@ -2168,10 +2178,10 @@ hc_alloc_table(struct hostcache *hc, unsigned order)
static void
hc_resize(struct hostcache *hc, unsigned new_order)
{
- unsigned old_size = 1 << hc->hash_order;
struct hostentry **old_table = hc->hash_table;
struct hostentry *he, *hen;
- int i;
+ uint old_size = 1 << hc->hash_order;
+ uint i;
hc_alloc_table(hc, new_order);
for (i = 0; i < old_size; i++)
@@ -2416,9 +2426,9 @@ rt_get_hostentry(rtable *tab, ip_addr a, ip_addr ll, rtable *dep)
}
void
-rta_set_recursive_next_hop(rtable *dep, rta *a, rtable *tab, ip_addr *gw, ip_addr *ll)
+rta_set_recursive_next_hop(rtable *dep, rta *a, rtable *tab, ip_addr gw, ip_addr ll)
{
- rta_apply_hostentry(a, rt_get_hostentry(tab, *gw, *ll, dep));
+ rta_apply_hostentry(a, rt_get_hostentry(tab, gw, ipa_zero(ll) ? gw : ll, dep));
}
@@ -2426,11 +2436,14 @@ rta_set_recursive_next_hop(rtable *dep, rta *a, rtable *tab, ip_addr *gw, ip_add
* CLI commands
*/
-static void
-rt_format_via(rte *e, byte *via)
+static byte *
+rt_format_via(rte *e)
{
rta *a = e->attrs;
+ /* Max text length w/o IP addr and interface name is 16 */
+ static byte via[IPA_MAX_TEXT_LENGTH+sizeof(a->iface->name)+16];
+
switch (a->dest)
{
case RTD_ROUTER: bsprintf(via, "via %I on %s", a->gw, a->iface->name); break;
@@ -2441,12 +2454,12 @@ rt_format_via(rte *e, byte *via)
case RTD_MULTIPATH: bsprintf(via, "multipath"); break;
default: bsprintf(via, "???");
}
+ return via;
}
static void
rt_show_rte(struct cli *c, byte *ia, rte *e, struct rt_show_data *d, ea_list *tmpa)
{
- byte via[IPA_MAX_TEXT_LENGTH+32];
byte from[IPA_MAX_TEXT_LENGTH+8];
byte tm[TM_DATETIME_BUFFER_SIZE], info[256];
rta *a = e->attrs;
@@ -2455,7 +2468,6 @@ rt_show_rte(struct cli *c, byte *ia, rte *e, struct rt_show_data *d, ea_list *tm
void (*get_route_info)(struct rte *, byte *buf, struct ea_list *attrs);
struct mpnh *nh;
- rt_format_via(e, via);
tm_format_datetime(tm, &config->tf_route, e->lastmod);
if (ipa_nonzero(a->from) && !ipa_equal(a->from, a->gw))
bsprintf(from, " from %I", a->from);
@@ -2476,7 +2488,7 @@ rt_show_rte(struct cli *c, byte *ia, rte *e, struct rt_show_data *d, ea_list *tm
get_route_info(e, info, tmpa);
else
bsprintf(info, " (%d)", e->pref);
- cli_printf(c, -1007, "%-18s %s [%s %s%s]%s%s", ia, via, a->src->proto->name,
+ cli_printf(c, -1007, "%-18s %s [%s %s%s]%s%s", ia, rt_format_via(e), a->src->proto->name,
tm, from, primary ? (sync_error ? " !" : " *") : "", info);
for (nh = a->nexthops; nh; nh = nh->next)
cli_printf(c, -1007, "\tvia %I on %s weight %d", nh->gw, nh->iface->name, nh->weight + 1);
@@ -2517,7 +2529,7 @@ rt_show_net(struct cli *c, net *n, struct rt_show_data *d)
if ((d->export_mode == RSEM_EXPORT) && (ec->ra_mode == RA_MERGED))
{
rte *rt_free;
- e = rt_export_merged(ec, n, &rt_free, &tmpa, 1);
+ e = rt_export_merged(ec, n, &rt_free, &tmpa, rte_update_pool, 1);
pass = 1;
if (!e)
diff --git a/proto/babel/babel.c b/proto/babel/babel.c
index 8e104d60..38be6909 100644
--- a/proto/babel/babel.c
+++ b/proto/babel/babel.c
@@ -565,6 +565,11 @@ babel_select_route(struct babel_entry *e)
babel_send_seqno_request(e);
babel_announce_rte(p, e);
+
+ /* Section 3.6 of the RFC forbids an infeasible from being selected. This
+ is cleared after announcing the route to the core to make sure an
+ unreachable route is propagated first. */
+ e->selected_in = NULL;
}
else
{
@@ -783,16 +788,21 @@ babel_send_update(struct babel_iface *ifa, bird_clock_t changed)
msg.update.prefix = e->n.prefix;
msg.update.router_id = r->router_id;
- /* Update feasibility distance */
- struct babel_source *s = babel_get_source(e, r->router_id);
- s->expires = now + BABEL_GARBAGE_INTERVAL;
- if ((msg.update.seqno > s->seqno) ||
- ((msg.update.seqno == s->seqno) && (msg.update.metric < s->metric)))
+ babel_enqueue(&msg, ifa);
+
+ /* Update feasibility distance for redistributed routes */
+ if (!OUR_ROUTE(r))
{
- s->seqno = msg.update.seqno;
- s->metric = msg.update.metric;
+ struct babel_source *s = babel_get_source(e, r->router_id);
+ s->expires = now + BABEL_GARBAGE_INTERVAL;
+
+ if ((msg.update.seqno > s->seqno) ||
+ ((msg.update.seqno == s->seqno) && (msg.update.metric < s->metric)))
+ {
+ s->seqno = msg.update.seqno;
+ s->metric = msg.update.metric;
+ }
}
- babel_enqueue(&msg, ifa);
}
FIB_WALK_END;
}
@@ -834,8 +844,8 @@ babel_send_retraction(struct babel_iface *ifa, ip_addr prefix, int plen)
struct babel_proto *p = ifa->proto;
union babel_msg msg = {};
- TRACE(D_PACKETS, "Sending retraction for %I/%d router-id %lR seqno %d",
- prefix, plen, p->router_id, p->update_seqno);
+ TRACE(D_PACKETS, "Sending retraction for %I/%d seqno %d",
+ prefix, plen, p->update_seqno);
msg.type = BABEL_TLV_UPDATE;
msg.update.plen = plen;
@@ -843,7 +853,23 @@ babel_send_retraction(struct babel_iface *ifa, ip_addr prefix, int plen)
msg.update.seqno = p->update_seqno;
msg.update.metric = BABEL_INFINITY;
msg.update.prefix = prefix;
- msg.update.router_id = p->router_id;
+
+ babel_enqueue(&msg, ifa);
+}
+
+static void
+babel_send_wildcard_retraction(struct babel_iface *ifa)
+{
+ struct babel_proto *p = ifa->proto;
+ union babel_msg msg = {};
+
+ TRACE(D_PACKETS, "Sending wildcard retraction on %s", ifa->ifname);
+
+ msg.type = BABEL_TLV_UPDATE;
+ msg.update.wildcard = 1;
+ msg.update.interval = ifa->cf->update_interval;
+ msg.update.seqno = p->update_seqno;
+ msg.update.metric = BABEL_INFINITY;
babel_enqueue(&msg, ifa);
}
@@ -1040,17 +1066,18 @@ babel_handle_update(union babel_msg *m, struct babel_iface *ifa)
struct babel_proto *p = ifa->proto;
struct babel_msg_update *msg = &m->update;
- struct babel_neighbor *n;
+ struct babel_neighbor *nbr;
struct babel_entry *e;
struct babel_source *s;
struct babel_route *r;
+ node *n;
int feasible;
TRACE(D_PACKETS, "Handling update for %I/%d with seqno %d metric %d",
msg->prefix, msg->plen, msg->seqno, msg->metric);
- n = babel_find_neighbor(ifa, msg->sender);
- if (!n)
+ nbr = babel_find_neighbor(ifa, msg->sender);
+ if (!nbr)
{
DBG("Babel: Haven't heard from neighbor %I; ignoring update.\n", msg->sender);
return;
@@ -1095,55 +1122,88 @@ babel_handle_update(union babel_msg *m, struct babel_iface *ifa)
* of the Interval value included in the update.
*/
+ /* Retraction */
if (msg->metric == BABEL_INFINITY)
- e = babel_find_entry(p, msg->prefix, msg->plen);
- else
- e = babel_get_entry(p, msg->prefix, msg->plen);
+ {
+ if (msg->wildcard)
+ {
+ /*
+ * Special case: This is a retraction of all prefixes announced by this
+ * neighbour (see second-to-last paragraph of section 4.4.9 in the RFC).
+ */
+ WALK_LIST(n, nbr->routes)
+ {
+ r = SKIP_BACK(struct babel_route, neigh_route, n);
+ r->metric = BABEL_INFINITY;
+ babel_select_route(r->e);
+ }
+ }
+ else
+ {
+ e = babel_find_entry(p, msg->prefix, msg->plen);
- if (!e)
+ if (!e)
+ return;
+
+ /* The route entry indexed by neighbour */
+ r = babel_find_route(e, nbr);
+
+ if (!r)
+ return;
+
+ r->metric = BABEL_INFINITY;
+ babel_select_route(e);
+ }
+
+ /* Done with retractions */
return;
+ }
+ e = babel_get_entry(p, msg->prefix, msg->plen);
+ r = babel_find_route(e, nbr); /* the route entry indexed by neighbour */
s = babel_find_source(e, msg->router_id); /* for feasibility */
- r = babel_find_route(e, n); /* the route entry indexed by neighbour */
feasible = babel_is_feasible(s, msg->seqno, msg->metric);
if (!r)
{
- if (!feasible || (msg->metric == BABEL_INFINITY))
+ if (!feasible)
return;
- r = babel_get_route(e, n);
+ r = babel_get_route(e, nbr);
r->advert_metric = msg->metric;
r->router_id = msg->router_id;
- r->metric = babel_compute_metric(n, msg->metric);
+ r->metric = babel_compute_metric(nbr, msg->metric);
r->next_hop = msg->next_hop;
r->seqno = msg->seqno;
}
else if (r == r->e->selected_in && !feasible)
{
- /* Route is installed and update is infeasible - we may lose the route, so
- send a unicast seqno request (section 3.8.2.2 second paragraph). */
+ /*
+ * Route is installed and update is infeasible - we may lose the route,
+ * so send a unicast seqno request (section 3.8.2.2 second paragraph).
+ */
babel_unicast_seqno_request(r);
- if (msg->router_id == r->router_id) return;
- r->metric = BABEL_INFINITY; /* retraction */
+ if (msg->router_id == r->router_id)
+ return;
+
+ /* Treat as retraction */
+ r->metric = BABEL_INFINITY;
}
else
{
/* Last paragraph above - update the entry */
r->advert_metric = msg->metric;
- r->metric = babel_compute_metric(n, msg->metric);
- r->router_id = msg->router_id;
+ r->metric = babel_compute_metric(nbr, msg->metric);
r->next_hop = msg->next_hop;
+
+ r->router_id = msg->router_id;
r->seqno = msg->seqno;
- if (msg->metric != BABEL_INFINITY)
- {
- r->expiry_interval = BABEL_ROUTE_EXPIRY_FACTOR(msg->interval);
- r->expires = now + r->expiry_interval;
- if (r->expiry_interval > BABEL_ROUTE_REFRESH_INTERVAL)
- r->refresh_time = now + r->expiry_interval - BABEL_ROUTE_REFRESH_INTERVAL;
- }
+ r->expiry_interval = BABEL_ROUTE_EXPIRY_FACTOR(msg->interval);
+ r->expires = now + r->expiry_interval;
+ if (r->expiry_interval > BABEL_ROUTE_REFRESH_INTERVAL)
+ r->refresh_time = now + r->expiry_interval - BABEL_ROUTE_REFRESH_INTERVAL;
/* If the route is not feasible at this point, it means it is from another
neighbour than the one currently selected; so send a unicast seqno
@@ -1313,6 +1373,7 @@ babel_iface_start(struct babel_iface *ifa)
ifa->up = 1;
babel_send_hello(ifa, 0);
+ babel_send_wildcard_retraction(ifa);
babel_send_wildcard_request(ifa);
babel_send_update(ifa, 0); /* Full update */
}
@@ -1529,6 +1590,9 @@ babel_reconfigure_iface(struct babel_proto *p, struct babel_iface *ifa, struct b
ifa->cf = new;
+ if (ifa->next_hello > (now + new->hello_interval))
+ ifa->next_hello = now + (random() % new->hello_interval) + 1;
+
if (ifa->next_regular > (now + new->update_interval))
ifa->next_regular = now + (random() % new->update_interval) + 1;
@@ -1659,7 +1723,7 @@ babel_dump(struct proto *P)
}
static void
-babel_get_route_info(rte *rte, byte *buf, ea_list *attrs)
+babel_get_route_info(rte *rte, byte *buf, ea_list *attrs UNUSED)
{
buf += bsprintf(buf, " (%d/%d) [%lR]", rte->pref, rte->u.babel.metric, rte->u.babel.router_id);
}
@@ -1901,7 +1965,7 @@ babel_store_tmp_attrs(struct rte *rt, struct ea_list *attrs)
*/
static void
babel_rt_notify(struct proto *P, struct rtable *table UNUSED, struct network *net,
- struct rte *new, struct rte *old, struct ea_list *attrs)
+ struct rte *new, struct rte *old UNUSED, struct ea_list *attrs UNUSED)
{
struct babel_proto *p = (void *) P;
struct babel_entry *e;
@@ -2022,6 +2086,30 @@ babel_start(struct proto *P)
return PS_UP;
}
+static inline void
+babel_iface_shutdown(struct babel_iface *ifa)
+{
+ if (ifa->sk)
+ {
+ babel_send_wildcard_retraction(ifa);
+ babel_send_queue(ifa);
+ }
+}
+
+static int
+babel_shutdown(struct proto *P)
+{
+ struct babel_proto *p = (void *) P;
+ struct babel_iface *ifa;
+
+ TRACE(D_EVENTS, "Shutdown requested");
+
+ WALK_LIST(ifa, p->interfaces)
+ babel_iface_shutdown(ifa);
+
+ return PS_DOWN;
+}
+
static int
babel_reconfigure(struct proto *P, struct proto_config *c)
{
@@ -2049,6 +2137,7 @@ struct protocol proto_babel = {
.init = babel_init,
.dump = babel_dump,
.start = babel_start,
+ .shutdown = babel_shutdown,
.reconfigure = babel_reconfigure,
.get_route_info = babel_get_route_info,
.get_attr = babel_get_attr
diff --git a/proto/babel/babel.h b/proto/babel/babel.h
index 04689976..e8b6c314 100644
--- a/proto/babel/babel.h
+++ b/proto/babel/babel.h
@@ -46,10 +46,12 @@
#define BABEL_INITIAL_HOP_COUNT 255
#define BABEL_MAX_SEND_INTERVAL 5
#define BABEL_TIME_UNITS 100 /* On-wire times are counted in centiseconds */
-
#define BABEL_SEQNO_REQUEST_EXPIRY 60
#define BABEL_GARBAGE_INTERVAL 300
+/* Max interval that will not overflow when carried as 16-bit centiseconds */
+#define BABEL_MAX_INTERVAL (0xFFFF/BABEL_TIME_UNITS)
+
#define BABEL_OVERHEAD (SIZE_OF_IP_HEADER+UDP_HEADER_LENGTH)
#define BABEL_MIN_MTU (512 + BABEL_OVERHEAD)
@@ -105,7 +107,7 @@ struct babel_iface_config {
u16 rxcost;
u8 type;
u8 check_link;
- int port;
+ uint port;
u16 hello_interval;
u16 ihu_interval;
u16 update_interval;
@@ -262,7 +264,7 @@ struct babel_msg_ihu {
struct babel_msg_update {
u8 type;
- u8 ae;
+ u8 wildcard;
u8 plen;
u16 interval;
u16 seqno;
diff --git a/proto/babel/config.Y b/proto/babel/config.Y
index e7ce6a93..b6170852 100644
--- a/proto/babel/config.Y
+++ b/proto/babel/config.Y
@@ -77,17 +77,18 @@ babel_iface_finish:
BABEL_IFACE->rxcost = BABEL_RXCOST_WIRED;
}
+ /* Make sure we do not overflow the 16-bit centisec fields */
if (!BABEL_IFACE->update_interval)
- BABEL_IFACE->update_interval = BABEL_IFACE->hello_interval*BABEL_UPDATE_INTERVAL_FACTOR;
- BABEL_IFACE->ihu_interval = BABEL_IFACE->hello_interval*BABEL_IHU_INTERVAL_FACTOR;
+ BABEL_IFACE->update_interval = MIN_(BABEL_IFACE->hello_interval*BABEL_UPDATE_INTERVAL_FACTOR, BABEL_MAX_INTERVAL);
+ BABEL_IFACE->ihu_interval = MIN_(BABEL_IFACE->hello_interval*BABEL_IHU_INTERVAL_FACTOR, BABEL_MAX_INTERVAL);
};
babel_iface_item:
| PORT expr { BABEL_IFACE->port = $2; if (($2<1) || ($2>65535)) cf_error("Invalid port number"); }
| RXCOST expr { BABEL_IFACE->rxcost = $2; if (($2<1) || ($2>65535)) cf_error("Invalid rxcost"); }
- | HELLO INTERVAL expr { BABEL_IFACE->hello_interval = $3; if (($3<1) || ($3>65535)) cf_error("Invalid hello interval"); }
- | UPDATE INTERVAL expr { BABEL_IFACE->update_interval = $3; if (($3<1) || ($3>65535)) cf_error("Invalid hello interval"); }
+ | HELLO INTERVAL expr { BABEL_IFACE->hello_interval = $3; if (($3<1) || ($3>BABEL_MAX_INTERVAL)) cf_error("Invalid hello interval"); }
+ | UPDATE INTERVAL expr { BABEL_IFACE->update_interval = $3; if (($3<1) || ($3>BABEL_MAX_INTERVAL)) cf_error("Invalid update interval"); }
| TYPE WIRED { BABEL_IFACE->type = BABEL_IFACE_TYPE_WIRED; }
| TYPE WIRELESS { BABEL_IFACE->type = BABEL_IFACE_TYPE_WIRELESS; }
| RX BUFFER expr { BABEL_IFACE->rx_buffer = $3; if (($3<256) || ($3>65535)) cf_error("RX buffer must be in range 256-65535"); }
diff --git a/proto/babel/packets.c b/proto/babel/packets.c
index be47aa75..08054832 100644
--- a/proto/babel/packets.c
+++ b/proto/babel/packets.c
@@ -146,6 +146,7 @@ struct babel_write_state {
#define TLV_HDR(tlv,t,l) ({ tlv->type = t; tlv->length = l - sizeof(struct babel_tlv); })
#define TLV_HDR0(tlv,t) TLV_HDR(tlv, t, tlv_data[t].min_length)
+#define BYTES(n) ((((uint) n) + 7) / 8)
static inline u16
get_time16(const void *p)
@@ -161,18 +162,18 @@ put_time16(void *p, u16 v)
}
static inline ip6_addr
-get_ip6_px(const void *p, int plen)
+get_ip6_px(const void *p, uint plen)
{
ip6_addr addr = IPA_NONE;
- memcpy(&addr, p, (plen + 7) / 8);
+ memcpy(&addr, p, BYTES(plen));
return ip6_ntoh(addr);
}
static inline void
-put_ip6_px(void *p, ip6_addr addr, int plen)
+put_ip6_px(void *p, ip6_addr addr, uint plen)
{
addr = ip6_hton(addr);
- memcpy(p, &addr, (plen + 7) / 8);
+ memcpy(p, &addr, BYTES(plen));
}
static inline ip6_addr
@@ -202,21 +203,21 @@ static int babel_read_update(struct babel_tlv *hdr, union babel_msg *msg, struct
static int babel_read_route_request(struct babel_tlv *hdr, union babel_msg *msg, struct babel_parse_state *state);
static int babel_read_seqno_request(struct babel_tlv *hdr, union babel_msg *msg, struct babel_parse_state *state);
-static int babel_write_ack(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, int max_len);
-static int babel_write_hello(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, int max_len);
-static int babel_write_ihu(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, int max_len);
-static int babel_write_update(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, int max_len);
-static int babel_write_route_request(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, int max_len);
-static int babel_write_seqno_request(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, int max_len);
+static uint babel_write_ack(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, uint max_len);
+static uint babel_write_hello(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, uint max_len);
+static uint babel_write_ihu(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, uint max_len);
+static uint babel_write_update(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, uint max_len);
+static uint babel_write_route_request(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, uint max_len);
+static uint babel_write_seqno_request(struct babel_tlv *hdr, union babel_msg *msg, struct babel_write_state *state, uint max_len);
struct babel_tlv_data {
u8 min_length;
int (*read_tlv)(struct babel_tlv *hdr, union babel_msg *m, struct babel_parse_state *state);
- int (*write_tlv)(struct babel_tlv *hdr, union babel_msg *m, struct babel_write_state *state, int max_len);
+ uint (*write_tlv)(struct babel_tlv *hdr, union babel_msg *m, struct babel_write_state *state, uint max_len);
void (*handle_tlv)(union babel_msg *m, struct babel_iface *ifa);
};
-const static struct babel_tlv_data tlv_data[BABEL_TLV_MAX] = {
+static const struct babel_tlv_data tlv_data[BABEL_TLV_MAX] = {
[BABEL_TLV_ACK_REQ] = {
sizeof(struct babel_tlv_ack_req),
babel_read_ack_req,
@@ -291,9 +292,9 @@ babel_read_ack_req(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_SUCCESS;
}
-static int
+static uint
babel_write_ack(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_write_state *state, int max_len)
+ struct babel_write_state *state UNUSED, uint max_len UNUSED)
{
struct babel_tlv_ack *tlv = (void *) hdr;
struct babel_msg_ack *msg = &m->ack;
@@ -319,9 +320,9 @@ babel_read_hello(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_SUCCESS;
}
-static int
+static uint
babel_write_hello(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_write_state *state, int max_len)
+ struct babel_write_state *state UNUSED, uint max_len UNUSED)
{
struct babel_tlv_hello *tlv = (void *) hdr;
struct babel_msg_hello *msg = &m->hello;
@@ -363,9 +364,9 @@ babel_read_ihu(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_SUCCESS;
}
-static int
+static uint
babel_write_ihu(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_write_state *state, int max_len)
+ struct babel_write_state *state UNUSED, uint max_len)
{
struct babel_tlv_ihu *tlv = (void *) hdr;
struct babel_msg_ihu *msg = &m->ihu;
@@ -401,9 +402,9 @@ babel_read_router_id(struct babel_tlv *hdr, union babel_msg *m UNUSED,
}
/* This is called directly from babel_write_update() */
-static int
+static uint
babel_write_router_id(struct babel_tlv *hdr, u64 router_id,
- struct babel_write_state *state, int max_len UNUSED)
+ struct babel_write_state *state, uint max_len UNUSED)
{
struct babel_tlv_router_id *tlv = (void *) hdr;
@@ -462,16 +463,15 @@ babel_read_update(struct babel_tlv *hdr, union babel_msg *m,
struct babel_msg_update *msg = &m->update;
msg->type = BABEL_TLV_UPDATE;
- msg->ae = tlv->ae;
msg->interval = get_time16(&tlv->interval);
msg->seqno = get_u16(&tlv->seqno);
msg->metric = get_u16(&tlv->metric);
/* Length of received prefix data without omitted part */
- int len = (tlv->plen + 7)/8 - (int) tlv->omitted;
+ int len = BYTES(tlv->plen) - (int) tlv->omitted;
u8 buf[16] = {};
- if ((len < 0) || (len > TLV_OPT_LENGTH(tlv)))
+ if ((len < 0) || ((uint) len > TLV_OPT_LENGTH(tlv)))
return PARSE_ERROR;
switch (tlv->ae)
@@ -480,7 +480,7 @@ babel_read_update(struct babel_tlv *hdr, union babel_msg *m,
if (tlv->plen > 0)
return PARSE_ERROR;
- msg->prefix = IPA_NONE;
+ msg->wildcard = 1;
break;
case BABEL_AE_IP4:
@@ -523,7 +523,8 @@ babel_read_update(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_IGNORE;
}
- if (!state->router_id_seen)
+ /* Update must have Router ID, unless it is retraction */
+ if (!state->router_id_seen && (msg->metric != BABEL_INFINITY))
{
DBG("Babel: No router ID seen before update\n");
return PARSE_ERROR;
@@ -536,45 +537,58 @@ babel_read_update(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_SUCCESS;
}
-static int
+static uint
babel_write_update(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_write_state *state, int max_len)
+ struct babel_write_state *state, uint max_len)
{
struct babel_tlv_update *tlv = (void *) hdr;
struct babel_msg_update *msg = &m->update;
- int len0 = 0;
+ uint len0 = 0;
/*
* When needed, we write Router-ID TLV before Update TLV and return size of
* both of them. There is enough space for the Router-ID TLV, because
* sizeof(struct babel_tlv_router_id) == sizeof(struct babel_tlv_update).
+ *
+ * Router ID is not used for retractions, so do not us it in such case.
*/
- if (!state->router_id_seen || (msg->router_id != state->router_id))
+ if ((msg->metric < BABEL_INFINITY) &&
+ (!state->router_id_seen || (msg->router_id != state->router_id)))
{
len0 = babel_write_router_id(hdr, msg->router_id, state, max_len);
tlv = (struct babel_tlv_update *) NEXT_TLV(tlv);
}
- int len = sizeof(struct babel_tlv_update) + (msg->plen + 7)/8;
+ uint len = sizeof(struct babel_tlv_update) + BYTES(msg->plen);
if (len0 + len > max_len)
return 0;
memset(tlv, 0, sizeof(struct babel_tlv_update));
TLV_HDR(tlv, BABEL_TLV_UPDATE, len);
- tlv->ae = BABEL_AE_IP6;
- tlv->plen = msg->plen;
+
+ if (msg->wildcard)
+ {
+ tlv->ae = BABEL_AE_WILDCARD;
+ tlv->plen = 0;
+ }
+ else
+ {
+ tlv->ae = BABEL_AE_IP6;
+ tlv->plen = msg->plen;
+ put_ip6_px(tlv->addr, msg->prefix, msg->plen);
+ }
+
put_time16(&tlv->interval, msg->interval);
put_u16(&tlv->seqno, msg->seqno);
put_u16(&tlv->metric, msg->metric);
- put_ip6_px(tlv->addr, msg->prefix, msg->plen);
return len0 + len;
}
static int
babel_read_route_request(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_parse_state *state)
+ struct babel_parse_state *state UNUSED)
{
struct babel_tlv_route_request *tlv = (void *) hdr;
struct babel_msg_route_request *msg = &m->route_request;
@@ -599,7 +613,7 @@ babel_read_route_request(struct babel_tlv *hdr, union babel_msg *m,
if (tlv->plen > MAX_PREFIX_LENGTH)
return PARSE_ERROR;
- if (TLV_OPT_LENGTH(tlv) < (tlv->plen + 7)/8)
+ if (TLV_OPT_LENGTH(tlv) < BYTES(tlv->plen))
return PARSE_ERROR;
msg->plen = tlv->plen;
@@ -616,14 +630,14 @@ babel_read_route_request(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_IGNORE;
}
-static int
+static uint
babel_write_route_request(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_write_state *state, int max_len)
+ struct babel_write_state *state UNUSED, uint max_len)
{
struct babel_tlv_route_request *tlv = (void *) hdr;
struct babel_msg_route_request *msg = &m->route_request;
- int len = sizeof(struct babel_tlv_route_request) + (msg->plen + 7)/8;
+ uint len = sizeof(struct babel_tlv_route_request) + BYTES(msg->plen);
if (len > max_len)
return 0;
@@ -674,7 +688,7 @@ babel_read_seqno_request(struct babel_tlv *hdr, union babel_msg *m,
if (tlv->plen > MAX_PREFIX_LENGTH)
return PARSE_ERROR;
- if (TLV_OPT_LENGTH(tlv) < (tlv->plen + 7)/8)
+ if (TLV_OPT_LENGTH(tlv) < BYTES(tlv->plen))
return PARSE_ERROR;
msg->plen = tlv->plen;
@@ -691,14 +705,14 @@ babel_read_seqno_request(struct babel_tlv *hdr, union babel_msg *m,
return PARSE_IGNORE;
}
-static int
+static uint
babel_write_seqno_request(struct babel_tlv *hdr, union babel_msg *m,
- struct babel_write_state *state, int max_len)
+ struct babel_write_state *state UNUSED, uint max_len)
{
struct babel_tlv_seqno_request *tlv = (void *) hdr;
struct babel_msg_seqno_request *msg = &m->seqno_request;
- int len = sizeof(struct babel_tlv_seqno_request) + (msg->plen + 7)/8;
+ uint len = sizeof(struct babel_tlv_seqno_request) + BYTES(msg->plen);
if (len > max_len)
return 0;
@@ -731,11 +745,11 @@ babel_read_tlv(struct babel_tlv *hdr,
return tlv_data[hdr->type].read_tlv(hdr, msg, state);
}
-static int
+static uint
babel_write_tlv(struct babel_tlv *hdr,
union babel_msg *msg,
struct babel_write_state *state,
- int max_len)
+ uint max_len)
{
if ((msg->type <= BABEL_TLV_PADN) ||
(msg->type >= BABEL_TLV_MAX) ||
@@ -779,7 +793,7 @@ babel_send_to(struct babel_iface *ifa, ip_addr dest)
*
* The TLVs in the queue are freed after they are written to the buffer.
*/
-static int
+static uint
babel_write_queue(struct babel_iface *ifa, list *queue)
{
struct babel_proto *p = ifa->proto;
@@ -800,6 +814,9 @@ babel_write_queue(struct babel_iface *ifa, list *queue)
struct babel_msg_node *msg;
WALK_LIST_FIRST(msg, *queue)
{
+ if (pos >= end)
+ break;
+
int len = babel_write_tlv((struct babel_tlv *) pos, &msg->msg, &state, end - pos);
if (!len)
@@ -810,7 +827,7 @@ babel_write_queue(struct babel_iface *ifa, list *queue)
sl_free(p->msg_slab, msg);
}
- int plen = pos - (byte *) pkt;
+ uint plen = pos - (byte *) pkt;
put_u16(&pkt->length, plen - sizeof(struct babel_pkt_header));
return plen;
@@ -1014,7 +1031,7 @@ babel_tx_hook(sock *sk)
static int
-babel_rx_hook(sock *sk, int len)
+babel_rx_hook(sock *sk, uint len)
{
struct babel_iface *ifa = sk->data;
struct babel_proto *p = ifa->proto;
diff --git a/proto/bfd/Makefile b/proto/bfd/Makefile
index 489216d8..402122fc 100644
--- a/proto/bfd/Makefile
+++ b/proto/bfd/Makefile
@@ -2,3 +2,5 @@ src := bfd.c io.c packets.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/bfd/bfd.c b/proto/bfd/bfd.c
index d33424b0..e2c6050b 100644
--- a/proto/bfd/bfd.c
+++ b/proto/bfd/bfd.c
@@ -316,6 +316,7 @@ bfd_session_timeout(struct bfd_session *s)
s->rem_min_rx_int = 1;
s->rem_demand_mode = 0;
s->rem_detect_mult = 0;
+ s->rx_csn_known = 0;
s->poll_active = 0;
s->poll_scheduled = 0;
@@ -429,6 +430,7 @@ bfd_add_session(struct bfd_proto *p, ip_addr addr, ip_addr local, struct iface *
s->rem_min_rx_int = 1;
s->detect_mult = ifa->cf->multiplier;
s->passive = ifa->cf->passive;
+ s->tx_csn = random_u32();
s->tx_timer = tm2_new_init(p->tpool, bfd_tx_timer_hook, s, 0, 0);
s->hold_timer = tm2_new_init(p->tpool, bfd_hold_timer_hook, s, 0, 0);
@@ -796,7 +798,7 @@ bfd_start_neighbor(struct bfd_proto *p, struct bfd_neighbor *n)
}
static void
-bfd_stop_neighbor(struct bfd_proto *p, struct bfd_neighbor *n)
+bfd_stop_neighbor(struct bfd_proto *p UNUSED, struct bfd_neighbor *n)
{
if (n->neigh)
n->neigh->data = NULL;
@@ -853,7 +855,7 @@ void pipe_drain(int fd);
void pipe_kick(int fd);
static int
-bfd_notify_hook(sock *sk, int len)
+bfd_notify_hook(sock *sk, uint len UNUSED)
{
struct bfd_proto *p = sk->data;
struct bfd_session *s;
@@ -1062,7 +1064,7 @@ bfd_preconfig(struct protocol *P UNUSED, struct config *c UNUSED)
}
static void
-bfd_copy_config(struct proto_config *dest, struct proto_config *src)
+bfd_copy_config(struct proto_config *dest, struct proto_config *src UNUSED)
{
struct bfd_config *d = (struct bfd_config *) dest;
// struct bfd_config *s = (struct bfd_config *) src;
diff --git a/proto/bfd/bfd.h b/proto/bfd/bfd.h
index ce7d665b..e2e75753 100644
--- a/proto/bfd/bfd.h
+++ b/proto/bfd/bfd.h
@@ -14,6 +14,7 @@
#include "nest/iface.h"
#include "nest/protocol.h"
#include "nest/route.h"
+#include "nest/password.h"
#include "conf/conf.h"
#include "lib/hash.h"
#include "lib/resource.h"
@@ -52,6 +53,8 @@ struct bfd_iface_config
u32 idle_tx_int;
u8 multiplier;
u8 passive;
+ u8 auth_type; /* Authentication type (BFD_AUTH_*) */
+ list *passwords; /* Passwords for authentication */
};
struct bfd_neighbor
@@ -116,7 +119,7 @@ struct bfd_session
u8 passive;
u8 poll_active;
u8 poll_scheduled;
-
+
u8 loc_state;
u8 rem_state;
u8 loc_diag;
@@ -143,6 +146,11 @@ struct bfd_session
list request_list; /* List of client requests (struct bfd_request) */
bird_clock_t last_state_change; /* Time of last state change */
u8 notify_running; /* 1 if notify hooks are running */
+
+ u8 rx_csn_known; /* Received crypto sequence number is known */
+ u32 rx_csn; /* Last received crypto sequence number */
+ u32 tx_csn; /* Last transmitted crypto sequence number */
+ u32 tx_csn_time; /* Timestamp of last tx_csn change */
};
@@ -174,6 +182,15 @@ extern const char *bfd_state_names[];
#define BFD_FLAG_DEMAND (1 << 1)
#define BFD_FLAG_MULTIPOINT (1 << 0)
+#define BFD_AUTH_NONE 0
+#define BFD_AUTH_SIMPLE 1
+#define BFD_AUTH_KEYED_MD5 2
+#define BFD_AUTH_METICULOUS_KEYED_MD5 3
+#define BFD_AUTH_KEYED_SHA1 4
+#define BFD_AUTH_METICULOUS_KEYED_SHA1 5
+
+extern const u8 bfd_auth_type_to_hash_alg[];
+
static inline void bfd_lock_sessions(struct bfd_proto *p) { pthread_spin_lock(&p->lock); }
static inline void bfd_unlock_sessions(struct bfd_proto *p) { pthread_spin_unlock(&p->lock); }
diff --git a/proto/bfd/config.Y b/proto/bfd/config.Y
index 4affb927..73414362 100644
--- a/proto/bfd/config.Y
+++ b/proto/bfd/config.Y
@@ -22,11 +22,12 @@ extern struct bfd_config *bfd_cf;
CF_DECLS
CF_KEYWORDS(BFD, MIN, IDLE, RX, TX, INTERVAL, MULTIPLIER, PASSIVE,
- INTERFACE, MULTIHOP, NEIGHBOR, DEV, LOCAL)
+ INTERFACE, MULTIHOP, NEIGHBOR, DEV, LOCAL, AUTHENTICATION,
+ NONE, SIMPLE, METICULOUS, KEYED, MD5, SHA1)
%type <iface> bfd_neigh_iface
%type <a> bfd_neigh_local
-%type <i> bfd_neigh_multihop
+%type <i> bfd_neigh_multihop bfd_auth_type
CF_GRAMMAR
@@ -62,12 +63,35 @@ bfd_proto:
bfd_iface_start:
{
this_ipatt = cfg_allocz(sizeof(struct bfd_iface_config));
+ add_tail(&BFD_CFG->patt_list, NODE this_ipatt);
init_list(&this_ipatt->ipn_list);
BFD_IFACE->min_rx_int = BFD_DEFAULT_MIN_RX_INT;
BFD_IFACE->min_tx_int = BFD_DEFAULT_MIN_TX_INT;
BFD_IFACE->idle_tx_int = BFD_DEFAULT_IDLE_TX_INT;
BFD_IFACE->multiplier = BFD_DEFAULT_MULTIPLIER;
+
+ reset_passwords();
+};
+
+bfd_iface_finish:
+{
+ BFD_IFACE->passwords = get_passwords();
+
+ if (!BFD_IFACE->auth_type != !BFD_IFACE->passwords)
+ log(L_WARN "Authentication and password options should be used together");
+
+ if (BFD_IFACE->passwords)
+ {
+ struct password_item *pass;
+ WALK_LIST(pass, *BFD_IFACE->passwords)
+ {
+ if (pass->alg)
+ cf_error("Password algorithm option not available in BFD protocol");
+
+ pass->alg = bfd_auth_type_to_hash_alg[BFD_IFACE->auth_type];
+ }
+ }
};
bfd_iface_item:
@@ -77,6 +101,17 @@ bfd_iface_item:
| IDLE TX INTERVAL expr_us { BFD_IFACE->idle_tx_int = $4; }
| MULTIPLIER expr { BFD_IFACE->multiplier = $2; }
| PASSIVE bool { BFD_IFACE->passive = $2; }
+ | AUTHENTICATION bfd_auth_type { BFD_IFACE->auth_type = $2; }
+ | password_list {}
+ ;
+
+bfd_auth_type:
+ NONE { $$ = BFD_AUTH_NONE; }
+ | SIMPLE { $$ = BFD_AUTH_SIMPLE; }
+ | KEYED MD5 { $$ = BFD_AUTH_KEYED_MD5; }
+ | KEYED SHA1 { $$ = BFD_AUTH_KEYED_SHA1; }
+ | METICULOUS KEYED MD5 { $$ = BFD_AUTH_METICULOUS_KEYED_MD5; }
+ | METICULOUS KEYED SHA1 { $$ = BFD_AUTH_METICULOUS_KEYED_SHA1; }
;
bfd_iface_opts:
@@ -89,10 +124,11 @@ bfd_iface_opt_list:
| '{' bfd_iface_opts '}'
;
-bfd_iface: bfd_iface_start iface_patt_list_nopx bfd_iface_opt_list
-{ add_tail(&BFD_CFG->patt_list, NODE this_ipatt); };
+bfd_iface:
+ bfd_iface_start iface_patt_list_nopx bfd_iface_opt_list bfd_iface_finish;
-bfd_multihop: bfd_iface_start bfd_iface_opt_list
+bfd_multihop:
+ bfd_iface_start bfd_iface_opt_list bfd_iface_finish
{ BFD_CFG->multihop = BFD_IFACE; };
diff --git a/proto/bfd/io.c b/proto/bfd/io.c
index 79ed9af7..8f4f5007 100644
--- a/proto/bfd/io.c
+++ b/proto/bfd/io.c
@@ -589,7 +589,7 @@ sockets_fire(struct birdloop *loop)
times_update(loop);
/* Last fd is internal wakeup fd */
- if (pfd[loop->sock_num].revents & POLLIN)
+ if (pfd[poll_num].revents & POLLIN)
wakeup_drain(loop);
int i;
diff --git a/proto/bfd/packets.c b/proto/bfd/packets.c
index 579064c6..06cde4d3 100644
--- a/proto/bfd/packets.c
+++ b/proto/bfd/packets.c
@@ -5,24 +5,60 @@
*/
#include "bfd.h"
+#include "lib/mac.h"
struct bfd_ctl_packet
{
- u8 vdiag; /* version and diagnostic */
- u8 flags; /* state and flags */
+ u8 vdiag; /* Version and diagnostic */
+ u8 flags; /* State and flags */
u8 detect_mult;
- u8 length;
- u32 snd_id; /* sender ID, aka 'my discriminator' */
- u32 rcv_id; /* receiver ID, aka 'your discriminator' */
+ u8 length; /* Whole packet length */
+ u32 snd_id; /* Sender ID, aka 'my discriminator' */
+ u32 rcv_id; /* Receiver ID, aka 'your discriminator' */
u32 des_min_tx_int;
u32 req_min_rx_int;
u32 req_min_echo_rx_int;
};
+struct bfd_auth
+{
+ u8 type; /* Authentication type (BFD_AUTH_*) */
+ u8 length; /* Authentication section length */
+};
+
+struct bfd_simple_auth
+{
+ u8 type; /* BFD_AUTH_SIMPLE */
+ u8 length; /* Length of bfd_simple_auth + pasword length */
+ u8 key_id; /* Key ID */
+ byte password[0]; /* Password itself, variable length */
+};
+
+#define BFD_MAX_PASSWORD_LENGTH 16
+
+struct bfd_crypto_auth
+{
+ u8 type; /* BFD_AUTH_*_MD5 or BFD_AUTH_*_SHA1 */
+ u8 length; /* Length of bfd_crypto_auth + hash length */
+ u8 key_id; /* Key ID */
+ u8 zero; /* Reserved, zero on transmit */
+ u32 csn; /* Cryptographic sequence number */
+ byte data[0]; /* Authentication key/hash, length 16 or 20 */
+};
+
#define BFD_BASE_LEN sizeof(struct bfd_ctl_packet)
#define BFD_MAX_LEN 64
+#define DROP(DSC,VAL) do { err_dsc = DSC; err_val = VAL; goto drop; } while(0)
+
+#define LOG_PKT(msg, args...) \
+ log(L_REMOTE "%s: " msg, p->p.name, args)
+
+#define LOG_PKT_AUTH(msg, args...) \
+ log(L_AUTH "%s: " msg, p->p.name, args)
+
+
static inline u8 bfd_pack_vdiag(u8 version, u8 diag)
{ return (version << 5) | diag; }
@@ -39,7 +75,7 @@ static inline u8 bfd_pkt_get_diag(struct bfd_ctl_packet *pkt)
static inline u8 bfd_pkt_get_state(struct bfd_ctl_packet *pkt)
{ return pkt->flags >> 6; }
-static inline void bfd_pkt_set_state(struct bfd_ctl_packet *pkt, u8 val)
+static inline void UNUSED bfd_pkt_set_state(struct bfd_ctl_packet *pkt, u8 val)
{ pkt->flags = val << 6; }
@@ -59,6 +95,189 @@ bfd_format_flags(u8 flags, char *buf)
return buf;
}
+const u8 bfd_auth_type_to_hash_alg[] = {
+ [BFD_AUTH_NONE] = ALG_UNDEFINED,
+ [BFD_AUTH_SIMPLE] = ALG_UNDEFINED,
+ [BFD_AUTH_KEYED_MD5] = ALG_MD5,
+ [BFD_AUTH_METICULOUS_KEYED_MD5] = ALG_MD5,
+ [BFD_AUTH_KEYED_SHA1] = ALG_SHA1,
+ [BFD_AUTH_METICULOUS_KEYED_SHA1] = ALG_SHA1,
+};
+
+
+/* Fill authentication section and modifies final length in control section packet */
+static void
+bfd_fill_authentication(struct bfd_proto *p, struct bfd_session *s, struct bfd_ctl_packet *pkt)
+{
+ struct bfd_iface_config *cf = s->ifa->cf;
+ struct password_item *pass = password_find(cf->passwords, 0);
+ uint meticulous = 0;
+
+ if (!pass)
+ {
+ /* FIXME: This should not happen */
+ log(L_ERR "%s: No suitable password found for authentication", p->p.name);
+ return;
+ }
+
+ switch (cf->auth_type)
+ {
+ case BFD_AUTH_SIMPLE:
+ {
+ struct bfd_simple_auth *auth = (void *) (pkt + 1);
+ uint pass_len = MIN(pass->length, BFD_MAX_PASSWORD_LENGTH);
+
+ auth->type = BFD_AUTH_SIMPLE;
+ auth->length = sizeof(struct bfd_simple_auth) + pass_len;
+ auth->key_id = pass->id;
+
+ pkt->flags |= BFD_FLAG_AP;
+ pkt->length += auth->length;
+
+ memcpy(auth->password, pass->password, pass_len);
+ return;
+ }
+
+ case BFD_AUTH_METICULOUS_KEYED_MD5:
+ case BFD_AUTH_METICULOUS_KEYED_SHA1:
+ meticulous = 1;
+
+ case BFD_AUTH_KEYED_MD5:
+ case BFD_AUTH_KEYED_SHA1:
+ {
+ struct bfd_crypto_auth *auth = (void *) (pkt + 1);
+ uint hash_alg = bfd_auth_type_to_hash_alg[cf->auth_type];
+ uint hash_len = mac_type_length(pass->alg);
+
+ /* Increase CSN about one time per second */
+ u32 new_time = (u64) current_time() >> 20;
+ if ((new_time != s->tx_csn_time) || meticulous)
+ {
+ s->tx_csn++;
+ s->tx_csn_time = new_time;
+ }
+
+ DBG("[%I] CSN: %u\n", s->addr, s->last_tx_csn);
+
+ auth->type = cf->auth_type;
+ auth->length = sizeof(struct bfd_crypto_auth) + hash_len;
+ auth->key_id = pass->id;
+ auth->zero = 0;
+ auth->csn = htonl(s->tx_csn);
+
+ pkt->flags |= BFD_FLAG_AP;
+ pkt->length += auth->length;
+
+ strncpy(auth->data, pass->password, hash_len);
+ mac_fill(hash_alg, NULL, 0, (byte *) pkt, pkt->length, auth->data);
+ return;
+ }
+ }
+}
+
+static int
+bfd_check_authentication(struct bfd_proto *p, struct bfd_session *s, struct bfd_ctl_packet *pkt)
+{
+ struct bfd_iface_config *cf = s->ifa->cf;
+ const char *err_dsc = NULL;
+ uint err_val = 0;
+ uint auth_type = 0;
+ uint meticulous = 0;
+
+ if (pkt->flags & BFD_FLAG_AP)
+ {
+ struct bfd_auth *auth = (void *) (pkt + 1);
+
+ if ((pkt->length < (BFD_BASE_LEN + sizeof(struct bfd_auth))) ||
+ (pkt->length < (BFD_BASE_LEN + auth->length)))
+ DROP("packet length mismatch", pkt->length);
+
+ /* Zero is reserved, we use it as BFD_AUTH_NONE internally */
+ if (auth->type == 0)
+ DROP("reserved authentication type", 0);
+
+ auth_type = auth->type;
+ }
+
+ if (auth_type != cf->auth_type)
+ DROP("authentication method mismatch", auth_type);
+
+ switch (auth_type)
+ {
+ case BFD_AUTH_NONE:
+ return 1;
+
+ case BFD_AUTH_SIMPLE:
+ {
+ struct bfd_simple_auth *auth = (void *) (pkt + 1);
+
+ if (auth->length < sizeof(struct bfd_simple_auth))
+ DROP("wrong authentication length", auth->length);
+
+ struct password_item *pass = password_find_by_id(cf->passwords, auth->key_id);
+ if (!pass)
+ DROP("no suitable password found", auth->key_id);
+
+ uint pass_len = MIN(pass->length, BFD_MAX_PASSWORD_LENGTH);
+ uint auth_len = sizeof(struct bfd_simple_auth) + pass_len;
+
+ if ((auth->length != auth_len) || memcmp(auth->password, pass->password, pass_len))
+ DROP("wrong password", pass->id);
+
+ return 1;
+ }
+
+ case BFD_AUTH_METICULOUS_KEYED_MD5:
+ case BFD_AUTH_METICULOUS_KEYED_SHA1:
+ meticulous = 1;
+
+ case BFD_AUTH_KEYED_MD5:
+ case BFD_AUTH_KEYED_SHA1:
+ {
+ struct bfd_crypto_auth *auth = (void *) (pkt + 1);
+ uint hash_alg = bfd_auth_type_to_hash_alg[cf->auth_type];
+ uint hash_len = mac_type_length(hash_alg);
+
+ if (auth->length != (sizeof(struct bfd_crypto_auth) + hash_len))
+ DROP("wrong authentication length", auth->length);
+
+ struct password_item *pass = password_find_by_id(cf->passwords, auth->key_id);
+ if (!pass)
+ DROP("no suitable password found", auth->key_id);
+
+ /* BFD CSNs are in 32-bit circular number space */
+ u32 csn = ntohl(auth->csn);
+ if (s->rx_csn_known &&
+ (((csn - s->rx_csn) > (3 * s->detect_mult)) ||
+ (meticulous && (csn == s->rx_csn))))
+ {
+ /* We want to report both new and old CSN */
+ LOG_PKT_AUTH("Authentication failed for %I - "
+ "wrong sequence number (rcv %u, old %u)",
+ s->addr, csn, s->rx_csn);
+ return 0;
+ }
+
+ byte *auth_data = alloca(hash_len);
+ memcpy(auth_data, auth->data, hash_len);
+ strncpy(auth->data, pass->password, hash_len);
+
+ if (!mac_verify(hash_alg, NULL, 0, (byte *) pkt, pkt->length, auth_data))
+ DROP("wrong authentication code", pass->id);
+
+ s->rx_csn = csn;
+ s->rx_csn_known = 1;
+
+ return 1;
+ }
+ }
+
+drop:
+ LOG_PKT_AUTH("Authentication failed for %I - %s (%u)",
+ s->addr, err_dsc, err_val);
+ return 0;
+}
+
void
bfd_send_ctl(struct bfd_proto *p, struct bfd_session *s, int final)
{
@@ -85,6 +304,9 @@ bfd_send_ctl(struct bfd_proto *p, struct bfd_session *s, int final)
else if (s->poll_active)
pkt->flags |= BFD_FLAG_POLL;
+ if (s->ifa->cf->auth_type)
+ bfd_fill_authentication(p, s, pkt);
+
if (sk->tbuf != sk->tpos)
log(L_WARN "%s: Old packet overwritten in TX buffer", p->p.name);
@@ -94,10 +316,8 @@ bfd_send_ctl(struct bfd_proto *p, struct bfd_session *s, int final)
sk_send_to(sk, pkt->length, s->addr, sk->dport);
}
-#define DROP(DSC,VAL) do { err_dsc = DSC; err_val = VAL; goto drop; } while(0)
-
static int
-bfd_rx_hook(sock *sk, int len)
+bfd_rx_hook(sock *sk, uint len)
{
struct bfd_proto *p = sk->data;
struct bfd_ctl_packet *pkt = (struct bfd_ctl_packet *) sk->rbuf;
@@ -151,10 +371,9 @@ bfd_rx_hook(sock *sk, int len)
return 1;
}
- /* FIXME: better authentication handling and message */
- if (pkt->flags & BFD_FLAG_AP)
- DROP("authentication not supported", 0);
-
+ /* bfd_check_authentication() has its own error logging */
+ if (!bfd_check_authentication(p, s, pkt))
+ return 1;
u32 old_tx_int = s->des_min_tx_int;
u32 old_rx_int = s->rem_min_rx_int;
@@ -173,8 +392,8 @@ bfd_rx_hook(sock *sk, int len)
bfd_session_process_ctl(s, pkt->flags, old_tx_int, old_rx_int);
return 1;
- drop:
- log(L_REMOTE "%s: Bad packet from %I - %s (%u)", p->p.name, sk->faddr, err_dsc, err_val);
+drop:
+ LOG_PKT("Bad packet from %I - %s (%u)", sk->faddr, err_dsc, err_val);
return 1;
}
diff --git a/proto/bgp/Makefile b/proto/bgp/Makefile
index f4958867..00aaef5e 100644
--- a/proto/bgp/Makefile
+++ b/proto/bgp/Makefile
@@ -2,3 +2,5 @@ src := attrs.c bgp.c packets.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/bgp/attrs.c b/proto/bgp/attrs.c
index d85afa8f..52b56efa 100644
--- a/proto/bgp/attrs.c
+++ b/proto/bgp/attrs.c
@@ -2,6 +2,8 @@
* BIRD -- BGP Attributes
*
* (c) 2000 Martin Mares <mj@ucw.cz>
+ * (c) 2008--2016 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2008--2016 CZ.NIC z.s.p.o.
*
* Can be freely distributed and used under the terms of the GNU GPL.
*/
@@ -56,830 +58,1157 @@
* inconsistencies between AGGREGATOR and AS4_AGGREGATOR that are not
* handled by that draft, these are logged and ignored (see
* bgp_reconstruct_4b_attrs()).
+ *
+ * BGP attribute table has several hooks:
+ *
+ * export - Hook that validates and normalizes attribute during export phase.
+ * Receives eattr, may modify it (e.g., sort community lists for canonical
+ * representation), UNSET() it (e.g., skip empty lists), or WITHDRAW() it if
+ * necessary. May assume that eattr has value valid w.r.t. its type, but may be
+ * invalid w.r.t. BGP constraints. Optional.
+ *
+ * encode - Hook that converts internal representation to external one during
+ * packet writing. Receives eattr and puts it in the buffer (including attribute
+ * header). Returns number of bytes, or -1 if not enough space. May assume that
+ * eattr has value valid w.r.t. its type and validated by export hook. Mandatory
+ * for all known attributes that exist internally after export phase (i.e., all
+ * except pseudoattributes MP_(UN)REACH_NLRI).
+ *
+ * decode - Hook that converts external representation to internal one during
+ * packet parsing. Receives attribute data in buffer, validates it and adds
+ * attribute to ea_list. If data are invalid, steps DISCARD(), WITHDRAW() or
+ * bgp_parse_error() may be used to escape. Mandatory for all known attributes.
+ *
+ * format - Optional hook that converts eattr to textual representation.
*/
+// XXXX review pool usage : c->c.proto->pool
-static byte bgp_mandatory_attrs[] = { BA_ORIGIN, BA_AS_PATH
-#ifndef IPV6
-,BA_NEXT_HOP
-#endif
-};
-struct attr_desc {
- char *name;
- int expected_length;
- int expected_flags;
- int type;
- int allow_in_ebgp;
- int (*validate)(struct bgp_proto *p, byte *attr, int len);
- void (*format)(eattr *ea, byte *buf, int buflen);
+struct bgp_attr_desc {
+ const char *name;
+ uint type;
+ uint flags;
+ void (*export)(struct bgp_export_state *s, eattr *a);
+ int (*encode)(struct bgp_write_state *s, eattr *a, byte *buf, uint size);
+ void (*decode)(struct bgp_parse_state *s, uint code, uint flags, byte *data, uint len, ea_list **to);
+ void (*format)(eattr *ea, byte *buf, uint size);
};
-#define IGNORE -1
-#define WITHDRAW -2
+static const struct bgp_attr_desc bgp_attr_table[];
+
+static inline int bgp_attr_known(uint code);
+
+eattr *
+bgp_set_attr(ea_list **attrs, struct linpool *pool, uint code, uint flags, uintptr_t val)
+{
+ ASSERT(bgp_attr_known(code));
+
+ ea_list *a = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
+ eattr *e = &a->attrs[0];
+
+ a->flags = EALF_SORTED;
+ a->count = 1;
+ a->next = *attrs;
+ *attrs = a;
+
+ e->id = EA_CODE(EAP_BGP, code);
+ e->type = bgp_attr_table[code].type;
+ e->flags = flags;
+
+ if (e->type & EAF_EMBEDDED)
+ e->u.data = (u32) val;
+ else
+ e->u.ptr = (struct adata *) val;
+
+ return e;
+}
+
+
+
+#define REPORT(msg, args...) \
+ ({ log(L_REMOTE "%s: " msg, s->proto->p.name, ## args); })
+
+#define DISCARD(msg, args...) \
+ ({ REPORT(msg, ## args); return; })
+
+#define WITHDRAW(msg, args...) \
+ ({ REPORT(msg, ## args); s->err_withdraw = 1; return; })
+
+#define UNSET(a) \
+ ({ a->type = EAF_TYPE_UNDEF; return; })
+
+#define NEW_BGP "Discarding %s attribute received from AS4-aware neighbor"
+#define BAD_EBGP "Discarding %s attribute received from EBGP neighbor"
+#define BAD_LENGTH "Malformed %s attribute - invalid length (%u)"
+#define BAD_VALUE "Malformed %s attribute - invalid value (%u)"
+#define NO_MANDATORY "Missing mandatory %s attribute"
+
+
+static inline int
+bgp_put_attr_hdr3(byte *buf, uint code, uint flags, uint len)
+{
+ *buf++ = flags;
+ *buf++ = code;
+ *buf++ = len;
+ return 3;
+}
+
+static inline int
+bgp_put_attr_hdr4(byte *buf, uint code, uint flags, uint len)
+{
+ *buf++ = flags | BAF_EXT_LEN;
+ *buf++ = code;
+ put_u16(buf, len);
+ return 4;
+}
+
+static inline int
+bgp_put_attr_hdr(byte *buf, uint code, uint flags, uint len)
+{
+ if (len < 256)
+ return bgp_put_attr_hdr3(buf, code, flags, len);
+ else
+ return bgp_put_attr_hdr4(buf, code, flags, len);
+}
static int
-bgp_check_origin(struct bgp_proto *p UNUSED, byte *a, int len UNUSED)
+bgp_encode_u8(struct bgp_write_state *s UNUSED, eattr *a, byte *buf, uint size)
{
- if (*a > 2)
- return 6;
- return 0;
+ if (size < (3+1))
+ return -1;
+
+ bgp_put_attr_hdr3(buf, EA_ID(a->id), a->flags, 1);
+ buf[3] = a->u.data;
+
+ return 3+1;
}
-static void
-bgp_format_origin(eattr *a, byte *buf, int buflen UNUSED)
+static int
+bgp_encode_u32(struct bgp_write_state *s UNUSED, eattr *a, byte *buf, uint size)
{
- static char *bgp_origin_names[] = { "IGP", "EGP", "Incomplete" };
+ if (size < (3+4))
+ return -1;
+
+ bgp_put_attr_hdr3(buf, EA_ID(a->id), a->flags, 4);
+ put_u32(buf+3, a->u.data);
- bsprintf(buf, bgp_origin_names[a->u.data]);
+ return 3+4;
}
static int
-path_segment_contains(byte *p, int bs, u32 asn)
+bgp_encode_u32s(struct bgp_write_state *s UNUSED, eattr *a, byte *buf, uint size)
{
- int i;
- int len = p[1];
- p += 2;
+ uint len = a->u.ptr->length;
- for(i=0; i<len; i++)
- {
- u32 asn2 = (bs == 4) ? get_u32(p) : get_u16(p);
- if (asn2 == asn)
- return 1;
- p += bs;
- }
+ if (size < (4+len))
+ return -1;
- return 0;
+ uint hdr = bgp_put_attr_hdr(buf, EA_ID(a->id), a->flags, len);
+ put_u32s(buf + hdr, (u32 *) a->u.ptr->data, len / 4);
+
+ return hdr + len;
}
-/* Validates path attribute, removes AS_CONFED_* segments, and also returns path length */
static int
-validate_path(struct bgp_proto *p, int as_path, int bs, byte *idata, uint *ilength)
+bgp_put_attr(byte *buf, uint size, uint code, uint flags, byte *data, uint len)
{
- int res = 0;
- u8 *a, *dst;
- int len, plen, copy;
+ if (size < (4+len))
+ return -1;
- dst = a = idata;
- len = *ilength;
+ uint hdr = bgp_put_attr_hdr(buf, code, flags, len);
+ memcpy(buf + hdr, data, len);
- while (len)
- {
- if (len < 2)
- return -1;
-
- plen = 2 + bs * a[1];
- if (len < plen)
- return -1;
-
- switch (a[0])
- {
- case AS_PATH_SET:
- copy = 1;
- res++;
- break;
-
- case AS_PATH_SEQUENCE:
- copy = 1;
- res += a[1];
- break;
-
- case AS_PATH_CONFED_SEQUENCE:
- case AS_PATH_CONFED_SET:
- if (as_path && path_segment_contains(a, bs, p->remote_as))
- {
- log(L_WARN "%s: AS_CONFED_* segment with peer ASN found, misconfigured confederation?", p->p.name);
- return -1;
- }
-
- log(L_WARN "%s: %s_PATH attribute contains AS_CONFED_* segment, skipping segment",
- p->p.name, as_path ? "AS" : "AS4");
- copy = 0;
- break;
-
- default:
- return -1;
- }
-
- if (copy)
- {
- if (dst != a)
- memmove(dst, a, plen);
- dst += plen;
- }
-
- len -= plen;
- a += plen;
- }
+ return hdr + len;
+}
- *ilength = dst - idata;
- return res;
+static int
+bgp_encode_raw(struct bgp_write_state *s UNUSED, eattr *a, byte *buf, uint size)
+{
+ return bgp_put_attr(buf, size, EA_ID(a->id), a->flags, a->u.ptr->data, a->u.ptr->length);
}
-static inline int
-validate_as_path(struct bgp_proto *p, byte *a, int *len)
+
+/*
+ * Attribute hooks
+ */
+
+static void
+bgp_export_origin(struct bgp_export_state *s, eattr *a)
{
- return validate_path(p, 1, p->as4_session ? 4 : 2, a, len);
+ if (a->u.data > 2)
+ WITHDRAW(BAD_VALUE, "ORIGIN", a->u.data);
}
-static inline int
-validate_as4_path(struct bgp_proto *p, struct adata *path)
+static void
+bgp_decode_origin(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
+{
+ if (len != 1)
+ WITHDRAW(BAD_LENGTH, "ORIGIN", len);
+
+ if (data[0] > 2)
+ WITHDRAW(BAD_VALUE, "ORIGIN", data[0]);
+
+ bgp_set_attr_u32(to, s->pool, BA_ORIGIN, flags, data[0]);
+}
+
+static void
+bgp_format_origin(eattr *a, byte *buf, uint size UNUSED)
+{
+ static const char *bgp_origin_names[] = { "IGP", "EGP", "Incomplete" };
+
+ bsprintf(buf, (a->u.data <= 2) ? bgp_origin_names[a->u.data] : "?");
+}
+
+
+static int
+bgp_encode_as_path(struct bgp_write_state *s, eattr *a, byte *buf, uint size)
+{
+ byte *data = a->u.ptr->data;
+ uint len = a->u.ptr->length;
+
+ if (!s->as4_session)
+ {
+ /* Prepare 16-bit AS_PATH (from 32-bit one) in a temporary buffer */
+ byte *src = data;
+ data = alloca(len);
+ len = as_path_32to16(data, src, len);
+ }
+
+ return bgp_put_attr(buf, size, BA_AS_PATH, a->flags, data, len);
+}
+
+static void
+bgp_decode_as_path(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- return validate_path(p, 0, 4, path->data, &path->length);
+ char err[128];
+
+ if (!as_path_valid(data, len, (s->as4_session ? 4 : 2), err, sizeof(err)))
+ WITHDRAW("Malformed AS_PATH attribute - %s", err);
+
+ if (!s->as4_session)
+ {
+ /* Prepare 32-bit AS_PATH (from 16-bit one) in a temporary buffer */
+ byte *src = data;
+ data = alloca(2*len);
+ len = as_path_16to32(data, src, len);
+ }
+
+ bgp_set_attr_data(to, s->pool, BA_AS_PATH, flags, data, len);
}
+
static int
-bgp_check_next_hop(struct bgp_proto *p UNUSED, byte *a, int len)
+bgp_encode_next_hop(struct bgp_write_state *s, eattr *a, byte *buf, uint size)
{
-#ifdef IPV6
- return IGNORE;
-#else
- ip_addr addr;
+ /*
+ * The NEXT_HOP attribute is used only in traditional (IPv4) BGP. In MP-BGP,
+ * the next hop is encoded as a part of the MP_REACH_NLRI attribute, so we
+ * store it and encode it later by AFI-specific hooks.
+ */
+
+ if (s->channel->afi == BGP_AF_IPV4)
+ {
+ ASSERT(a->u.ptr->length == sizeof(ip_addr));
+
+ if (size < (3+4))
+ return -1;
- memcpy(&addr, a, len);
- ipa_ntoh(addr);
- if (ipa_classify(addr) & IADDR_HOST)
+ bgp_put_attr_hdr3(buf, BA_NEXT_HOP, a->flags, 4);
+ put_ip4(buf+3, ipa_to_ip4( *(ip_addr *) a->u.ptr->data ));
+
+ return 3+4;
+ }
+ else
+ {
+ s->mp_next_hop = a;
return 0;
+ }
+}
+
+static void
+bgp_decode_next_hop(struct bgp_parse_state *s, uint code UNUSED, uint flags UNUSED, byte *data, uint len, ea_list **to UNUSED)
+{
+ if (len != 4)
+ WITHDRAW(BAD_LENGTH, "NEXT_HOP", len);
+
+ /* Semantic checks are done later */
+ s->ip_next_hop_len = len;
+ s->ip_next_hop_data = data;
+}
+
+/* TODO: This function should use AF-specific hook */
+static void
+bgp_format_next_hop(eattr *a, byte *buf, uint size UNUSED)
+{
+ ip_addr *nh = (void *) a->u.ptr->data;
+ uint len = a->u.ptr->length;
+
+ ASSERT((len == 16) || (len == 32));
+
+ /* in IPv6, we may have two addresses in NEXT HOP */
+ if ((len == 16) || ipa_zero(nh[1]))
+ bsprintf(buf, "%I", nh[0]);
else
- return 8;
-#endif
+ bsprintf(buf, "%I %I", nh[0], nh[1]);
}
+
static void
-bgp_format_next_hop(eattr *a, byte *buf, int buflen UNUSED)
+bgp_decode_med(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- ip_addr *ipp = (ip_addr *) a->u.ptr->data;
-#ifdef IPV6
- /* in IPv6, we might have two addresses in NEXT HOP */
- if ((a->u.ptr->length == NEXT_HOP_LENGTH) && ipa_nonzero(ipp[1]))
- {
- bsprintf(buf, "%I %I", ipp[0], ipp[1]);
- return;
- }
-#endif
+ if (len != 4)
+ WITHDRAW(BAD_LENGTH, "MULTI_EXIT_DISC", len);
- bsprintf(buf, "%I", ipp[0]);
+ u32 val = get_u32(data);
+ bgp_set_attr_u32(to, s->pool, BA_MULTI_EXIT_DISC, flags, val);
}
-static int
-bgp_check_aggregator(struct bgp_proto *p, byte *a UNUSED, int len)
+
+static void
+bgp_export_local_pref(struct bgp_export_state *s, eattr *a)
{
- int exp_len = p->as4_session ? 8 : 6;
-
- return (len == exp_len) ? 0 : WITHDRAW;
+ if (!s->proto->is_interior)
+ UNSET(a);
}
static void
-bgp_format_aggregator(eattr *a, byte *buf, int buflen UNUSED)
+bgp_decode_local_pref(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- struct adata *ad = a->u.ptr;
- byte *data = ad->data;
- u32 as;
+ if (!s->proto->is_interior)
+ DISCARD(BAD_EBGP, "LOCAL_PREF");
- as = get_u32(data);
- data += 4;
+ if (len != 4)
+ WITHDRAW(BAD_LENGTH, "LOCAL_PREF", len);
- bsprintf(buf, "%d.%d.%d.%d AS%u", data[0], data[1], data[2], data[3], as);
+ u32 val = get_u32(data);
+ bgp_set_attr_u32(to, s->pool, BA_LOCAL_PREF, flags, val);
}
-static int
-bgp_check_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
+
+static void
+bgp_decode_atomic_aggr(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data UNUSED, uint len, ea_list **to)
{
- return ((len % 4) == 0) ? 0 : WITHDRAW;
+ if (len != 0)
+ DISCARD(BAD_LENGTH, "ATOMIC_AGGR", len);
+
+ bgp_set_attr_data(to, s->pool, BA_ATOMIC_AGGR, flags, NULL, 0);
}
static int
-bgp_check_cluster_list(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
+bgp_encode_aggregator(struct bgp_write_state *s, eattr *a, byte *buf, uint size)
{
- return ((len % 4) == 0) ? 0 : 5;
+ byte *data = a->u.ptr->data;
+ uint len = a->u.ptr->length;
+
+ if (!s->as4_session)
+ {
+ /* Prepare 16-bit AGGREGATOR (from 32-bit one) in a temporary buffer */
+ byte *src = data;
+ data = alloca(6);
+ len = aggregator_32to16(data, src);
+ }
+
+ return bgp_put_attr(buf, size, BA_AGGREGATOR, a->flags, data, len);
}
static void
-bgp_format_cluster_list(eattr *a, byte *buf, int buflen)
+bgp_decode_aggregator(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- /* Truncates cluster lists larger than buflen, probably not a problem */
- int_set_format(a->u.ptr, 0, -1, buf, buflen);
+ if (len != (s->as4_session ? 8 : 6))
+ DISCARD(BAD_LENGTH, "AGGREGATOR", len);
+
+ if (!s->as4_session)
+ {
+ /* Prepare 32-bit AGGREGATOR (from 16-bit one) in a temporary buffer */
+ byte *src = data;
+ data = alloca(8);
+ len = aggregator_16to32(data, src);
+ }
+
+ bgp_set_attr_data(to, s->pool, BA_AGGREGATOR, flags, data, len);
}
-static int
-bgp_check_reach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
+static void
+bgp_format_aggregator(eattr *a, byte *buf, uint size UNUSED)
{
-#ifdef IPV6
- p->mp_reach_start = a;
- p->mp_reach_len = len;
-#endif
- return IGNORE;
+ byte *data = a->u.ptr->data;
+
+ bsprintf(buf, "%I4 AS%u", get_ip4(data+4), get_u32(data+0));
}
-static int
-bgp_check_unreach_nlri(struct bgp_proto *p UNUSED, byte *a UNUSED, int len UNUSED)
+
+static void
+bgp_export_community(struct bgp_export_state *s, eattr *a)
{
-#ifdef IPV6
- p->mp_unreach_start = a;
- p->mp_unreach_len = len;
-#endif
- return IGNORE;
+ if (a->u.ptr->length == 0)
+ UNSET(a);
+
+ a->u.ptr = int_set_sort(s->pool, a->u.ptr);
}
-static int
-bgp_check_ext_community(struct bgp_proto *p UNUSED, byte *a UNUSED, int len)
-{
- return ((len % 8) == 0) ? 0 : WITHDRAW;
-}
-
-
-static struct attr_desc bgp_attr_table[] = {
- { NULL, -1, 0, 0, 0, /* Undefined */
- NULL, NULL },
- { "origin", 1, BAF_TRANSITIVE, EAF_TYPE_INT, 1, /* BA_ORIGIN */
- bgp_check_origin, bgp_format_origin },
- { "as_path", -1, BAF_TRANSITIVE, EAF_TYPE_AS_PATH, 1, /* BA_AS_PATH */
- NULL, NULL }, /* is checked by validate_as_path() as a special case */
- { "next_hop", 4, BAF_TRANSITIVE, EAF_TYPE_IP_ADDRESS, 1, /* BA_NEXT_HOP */
- bgp_check_next_hop, bgp_format_next_hop },
- { "med", 4, BAF_OPTIONAL, EAF_TYPE_INT, 1, /* BA_MULTI_EXIT_DISC */
- NULL, NULL },
- { "local_pref", 4, BAF_TRANSITIVE, EAF_TYPE_INT, 0, /* BA_LOCAL_PREF */
- NULL, NULL },
- { "atomic_aggr", 0, BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_ATOMIC_AGGR */
- NULL, NULL },
- { "aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_AGGREGATOR */
- bgp_check_aggregator, bgp_format_aggregator },
- { "community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_INT_SET, 1, /* BA_COMMUNITY */
- bgp_check_community, NULL },
- { "originator_id", 4, BAF_OPTIONAL, EAF_TYPE_ROUTER_ID, 0, /* BA_ORIGINATOR_ID */
- NULL, NULL },
- { "cluster_list", -1, BAF_OPTIONAL, EAF_TYPE_INT_SET, 0, /* BA_CLUSTER_LIST */
- bgp_check_cluster_list, bgp_format_cluster_list },
- { .name = NULL }, /* BA_DPA */
- { .name = NULL }, /* BA_ADVERTISER */
- { .name = NULL }, /* BA_RCID_PATH */
- { "mp_reach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1, /* BA_MP_REACH_NLRI */
- bgp_check_reach_nlri, NULL },
- { "mp_unreach_nlri", -1, BAF_OPTIONAL, EAF_TYPE_OPAQUE, 1, /* BA_MP_UNREACH_NLRI */
- bgp_check_unreach_nlri, NULL },
- { "ext_community", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_EC_SET, 1, /* BA_EXT_COMMUNITY */
- bgp_check_ext_community, NULL },
- { "as4_path", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_AS4_PATH */
- NULL, NULL },
- { "as4_aggregator", -1, BAF_OPTIONAL | BAF_TRANSITIVE, EAF_TYPE_OPAQUE, 1, /* BA_AS4_PATH */
- NULL, NULL }
-};
+static void
+bgp_decode_community(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
+{
+ if (!len || (len % 4))
+ WITHDRAW(BAD_LENGTH, "COMMUNITY", len);
-/* BA_AS4_PATH is type EAF_TYPE_OPAQUE and not type EAF_TYPE_AS_PATH.
- * It does not matter as this attribute does not appear on routes in the routing table.
- */
+ struct adata *ad = lp_alloc_adata(s->pool, len);
+ get_u32s(data, (u32 *) ad->data, len / 4);
+ bgp_set_attr_ptr(to, s->pool, BA_COMMUNITY, flags, ad);
+}
-#define ATTR_KNOWN(code) ((code) < ARRAY_SIZE(bgp_attr_table) && bgp_attr_table[code].name)
-static inline struct adata *
-bgp_alloc_adata(struct linpool *pool, unsigned len)
+static void
+bgp_export_originator_id(struct bgp_export_state *s, eattr *a)
{
- struct adata *ad = lp_alloc(pool, sizeof(struct adata) + len);
- ad->length = len;
- return ad;
+ if (!s->proto->is_internal)
+ UNSET(a);
}
static void
-bgp_set_attr(eattr *e, unsigned attr, uintptr_t val)
+bgp_decode_originator_id(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- ASSERT(ATTR_KNOWN(attr));
- e->id = EA_CODE(EAP_BGP, attr);
- e->type = bgp_attr_table[attr].type;
- e->flags = bgp_attr_table[attr].expected_flags;
- if (e->type & EAF_EMBEDDED)
- e->u.data = val;
- else
- e->u.ptr = (struct adata *) val;
+ if (!s->proto->is_internal)
+ DISCARD(BAD_EBGP, "ORIGINATOR_ID");
+
+ if (len != 4)
+ WITHDRAW(BAD_LENGTH, "ORIGINATOR_ID", len);
+
+ u32 val = get_u32(data);
+ bgp_set_attr_u32(to, s->pool, BA_ORIGINATOR_ID, flags, val);
}
-static byte *
-bgp_set_attr_wa(eattr *e, struct linpool *pool, unsigned attr, unsigned len)
+
+static void
+bgp_export_cluster_list(struct bgp_export_state *s UNUSED, eattr *a)
{
- struct adata *ad = bgp_alloc_adata(pool, len);
- bgp_set_attr(e, attr, (uintptr_t) ad);
- return ad->data;
+ if (!s->proto->is_internal)
+ UNSET(a);
+
+ if (a->u.ptr->length == 0)
+ UNSET(a);
}
-void
-bgp_attach_attr(ea_list **to, struct linpool *pool, unsigned attr, uintptr_t val)
+static void
+bgp_decode_cluster_list(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- ea_list *a = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
- a->next = *to;
- *to = a;
- a->flags = EALF_SORTED;
- a->count = 1;
- bgp_set_attr(a->attrs, attr, val);
+ if (!s->proto->is_internal)
+ DISCARD(BAD_EBGP, "CLUSTER_LIST");
+
+ if (!len || (len % 4))
+ WITHDRAW(BAD_LENGTH, "CLUSTER_LIST", len);
+
+ struct adata *ad = lp_alloc_adata(s->pool, len);
+ get_u32s(data, (u32 *) ad->data, len / 4);
+ bgp_set_attr_ptr(to, s->pool, BA_CLUSTER_LIST, flags, ad);
}
-byte *
-bgp_attach_attr_wa(ea_list **to, struct linpool *pool, unsigned attr, unsigned len)
+static void
+bgp_format_cluster_list(eattr *a, byte *buf, uint size)
{
- struct adata *ad = bgp_alloc_adata(pool, len);
- bgp_attach_attr(to, pool, attr, (uintptr_t) ad);
- return ad->data;
+ /* Truncates cluster lists larger than buflen, probably not a problem */
+ int_set_format(a->u.ptr, 0, -1, buf, size);
}
-static int
-bgp_encode_attr_hdr(byte *dst, uint flags, unsigned code, int len)
+
+static inline u32
+get_af3(byte *buf)
{
- int wlen;
+ return (get_u16(buf) << 16) | buf[2];
+}
- DBG("\tAttribute %02x (%d bytes, flags %02x)\n", code, len, flags);
+static void
+bgp_decode_mp_reach_nlri(struct bgp_parse_state *s, uint code UNUSED, uint flags UNUSED, byte *data, uint len, ea_list **to UNUSED)
+{
+ /*
+ * 2 B MP_REACH_NLRI data - Address Family Identifier
+ * 1 B MP_REACH_NLRI data - Subsequent Address Family Identifier
+ * 1 B MP_REACH_NLRI data - Length of Next Hop Network Address
+ * var MP_REACH_NLRI data - Network Address of Next Hop
+ * 1 B MP_REACH_NLRI data - Reserved (zero)
+ * var MP_REACH_NLRI data - Network Layer Reachability Information
+ */
- if (len < 256)
- {
- *dst++ = flags;
- *dst++ = code;
- *dst++ = len;
- wlen = 3;
- }
- else
- {
- *dst++ = flags | BAF_EXT_LEN;
- *dst++ = code;
- put_u16(dst, len);
- wlen = 4;
- }
+ if ((len < 5) || (len < (5 + (uint) data[3])))
+ bgp_parse_error(s, 9);
- return wlen;
+ s->mp_reach_af = get_af3(data);
+ s->mp_next_hop_len = data[3];
+ s->mp_next_hop_data = data + 4;
+ s->mp_reach_len = len - 5 - s->mp_next_hop_len;
+ s->mp_reach_nlri = data + 5 + s->mp_next_hop_len;
}
+
static void
-aggregator_convert_to_old(struct adata *aggr, byte *dst, int *new_used)
+bgp_decode_mp_unreach_nlri(struct bgp_parse_state *s, uint code UNUSED, uint flags UNUSED, byte *data, uint len, ea_list **to UNUSED)
{
- byte *src = aggr->data;
- *new_used = 0;
+ /*
+ * 2 B MP_UNREACH_NLRI data - Address Family Identifier
+ * 1 B MP_UNREACH_NLRI data - Subsequent Address Family Identifier
+ * var MP_UNREACH_NLRI data - Network Layer Reachability Information
+ */
- u32 as = get_u32(src);
- if (as > 0xFFFF)
- {
- as = AS_TRANS;
- *new_used = 1;
- }
- put_u16(dst, as);
+ if (len < 3)
+ bgp_parse_error(s, 9);
- /* Copy IPv4 address */
- memcpy(dst + 2, src + 4, 4);
+ s->mp_unreach_af = get_af3(data);
+ s->mp_unreach_len = len - 3;
+ s->mp_unreach_nlri = data + 3;
}
+
static void
-aggregator_convert_to_new(struct adata *aggr, byte *dst)
+bgp_export_ext_community(struct bgp_export_state *s, eattr *a)
{
- byte *src = aggr->data;
+ if (a->u.ptr->length == 0)
+ UNSET(a);
- u32 as = get_u16(src);
- put_u32(dst, as);
+ a->u.ptr = ec_set_sort(s->pool, a->u.ptr);
+}
+
+static void
+bgp_decode_ext_community(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
+{
+ if (!len || (len % 8))
+ WITHDRAW(BAD_LENGTH, "EXT_COMMUNITY", len);
- /* Copy IPv4 address */
- memcpy(dst + 4, src + 2, 4);
+ struct adata *ad = lp_alloc_adata(s->pool, len);
+ get_u32s(data, (u32 *) ad->data, len / 4);
+ bgp_set_attr_ptr(to, s->pool, BA_EXT_COMMUNITY, flags, ad);
}
-static int
-bgp_get_attr_len(eattr *a)
+
+static void
+bgp_decode_as4_aggregator(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
{
- int len;
- if (ATTR_KNOWN(EA_ID(a->id)))
- {
- int code = EA_ID(a->id);
- struct attr_desc *desc = &bgp_attr_table[code];
- len = desc->expected_length;
- if (len < 0)
- {
- ASSERT(!(a->type & EAF_EMBEDDED));
- len = a->u.ptr->length;
- }
- }
+ if (s->as4_session)
+ DISCARD(NEW_BGP, "AS4_AGGREGATOR");
+
+ if (len != 8)
+ DISCARD(BAD_LENGTH, "AS4_AGGREGATOR", len);
+
+ bgp_set_attr_data(to, s->pool, BA_AS4_AGGREGATOR, flags, data, len);
+}
+
+static void
+bgp_decode_as4_path(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
+{
+ char err[128];
+
+ if (s->as4_session)
+ DISCARD(NEW_BGP, "AS4_PATH");
+
+ if (len < 6)
+ DISCARD(BAD_LENGTH, "AS4_PATH", len);
+
+ if (!as_path_valid(data, len, 4, err, sizeof(err)))
+ DISCARD("Malformed AS4_PATH attribute - %s", err);
+
+ /* XXXX remove CONFED segments */
+ bgp_set_attr_data(to, s->pool, BA_AS4_PATH, flags, data, len);
+}
+
+static void
+bgp_export_large_community(struct bgp_export_state *s, eattr *a)
+{
+ if (a->u.ptr->length == 0)
+ UNSET(a);
+
+ a->u.ptr = lc_set_sort(s->pool, a->u.ptr);
+}
+
+static void
+bgp_decode_large_community(struct bgp_parse_state *s, uint code UNUSED, uint flags, byte *data, uint len, ea_list **to)
+{
+ if (!len || (len % 12))
+ WITHDRAW(BAD_LENGTH, "LARGE_COMMUNITY", len);
+
+ struct adata *ad = lp_alloc_adata(s->pool, len);
+ get_u32s(data, (u32 *) ad->data, len / 4);
+ bgp_set_attr_ptr(to, s->pool, BA_LARGE_COMMUNITY, flags, ad);
+}
+
+static inline void
+bgp_decode_unknown(struct bgp_parse_state *s, uint code, uint flags, byte *data, uint len, ea_list **to)
+{
+ bgp_set_attr_data(to, s->pool, code, flags, data, len);
+}
+
+
+/*
+ * Attribute table
+ */
+
+static const struct bgp_attr_desc bgp_attr_table[] = {
+ [BA_ORIGIN] = {
+ .name = "origin",
+ .type = EAF_TYPE_INT,
+ .flags = BAF_TRANSITIVE,
+ .export = bgp_export_origin,
+ .encode = bgp_encode_u8,
+ .decode = bgp_decode_origin,
+ .format = bgp_format_origin,
+ },
+ [BA_AS_PATH] = {
+ .name = "as_path",
+ .type = EAF_TYPE_AS_PATH,
+ .flags = BAF_TRANSITIVE,
+ .encode = bgp_encode_as_path,
+ .decode = bgp_decode_as_path,
+ },
+ [BA_NEXT_HOP] = {
+ .name = "next_hop",
+ .type = EAF_TYPE_IP_ADDRESS,
+ .flags = BAF_TRANSITIVE,
+ .encode = bgp_encode_next_hop,
+ .decode = bgp_decode_next_hop,
+ .format = bgp_format_next_hop,
+ },
+ [BA_MULTI_EXIT_DISC] = {
+ .name = "med",
+ .type = EAF_TYPE_INT,
+ .flags = BAF_OPTIONAL,
+ .encode = bgp_encode_u32,
+ .decode = bgp_decode_med,
+ },
+ [BA_LOCAL_PREF] = {
+ .name = "local_pref",
+ .type = EAF_TYPE_INT,
+ .flags = BAF_TRANSITIVE,
+ .export = bgp_export_local_pref,
+ .encode = bgp_encode_u32,
+ .decode = bgp_decode_local_pref,
+ },
+ [BA_ATOMIC_AGGR] = {
+ .name = "atomic_aggr",
+ .type = EAF_TYPE_OPAQUE,
+ .flags = BAF_TRANSITIVE,
+ .encode = bgp_encode_raw,
+ .decode = bgp_decode_atomic_aggr,
+ },
+ [BA_AGGREGATOR] = {
+ .name = "aggregator",
+ .type = EAF_TYPE_OPAQUE,
+ .flags = BAF_OPTIONAL | BAF_TRANSITIVE,
+ .encode = bgp_encode_aggregator,
+ .decode = bgp_decode_aggregator,
+ .format = bgp_format_aggregator,
+ },
+ [BA_COMMUNITY] = {
+ .name = "community",
+ .type = EAF_TYPE_INT_SET,
+ .flags = BAF_OPTIONAL | BAF_TRANSITIVE,
+ .export = bgp_export_community,
+ .encode = bgp_encode_u32s,
+ .decode = bgp_decode_community,
+ },
+ [BA_ORIGINATOR_ID] = {
+ .name = "originator_id",
+ .type = EAF_TYPE_ROUTER_ID,
+ .flags = BAF_OPTIONAL,
+ .export = bgp_export_originator_id,
+ .encode = bgp_encode_u32,
+ .decode = bgp_decode_originator_id,
+ },
+ [BA_CLUSTER_LIST] = {
+ .name = "cluster_list",
+ .type = EAF_TYPE_INT_SET,
+ .flags = BAF_OPTIONAL,
+ .export = bgp_export_cluster_list,
+ .encode = bgp_encode_u32s,
+ .decode = bgp_decode_cluster_list,
+ .format = bgp_format_cluster_list,
+ },
+ [BA_MP_REACH_NLRI] = {
+ .name = "mp_reach_nlri",
+ .type = EAF_TYPE_OPAQUE,
+ .flags = BAF_OPTIONAL,
+ .decode = bgp_decode_mp_reach_nlri,
+ },
+ [BA_MP_UNREACH_NLRI] = {
+ .name = "mp_unreach_nlri",
+ .type = EAF_TYPE_OPAQUE,
+ .flags = BAF_OPTIONAL,
+ .decode = bgp_decode_mp_unreach_nlri,
+ },
+ [BA_EXT_COMMUNITY] = {
+ .name = "ext_community",
+ .type = EAF_TYPE_EC_SET,
+ .flags = BAF_OPTIONAL | BAF_TRANSITIVE,
+ .export = bgp_export_ext_community,
+ .encode = bgp_encode_u32s,
+ .decode = bgp_decode_ext_community,
+ },
+ [BA_AS4_PATH] = {
+ .name = "as4_path",
+ .type = EAF_TYPE_AS_PATH,
+ .flags = BAF_OPTIONAL | BAF_TRANSITIVE,
+ .encode = bgp_encode_raw,
+ .decode = bgp_decode_as4_path,
+ },
+ [BA_AS4_AGGREGATOR] = {
+ .name = "as4_aggregator",
+ .type = EAF_TYPE_OPAQUE,
+ .flags = BAF_OPTIONAL | BAF_TRANSITIVE,
+ .encode = bgp_encode_raw,
+ .decode = bgp_decode_as4_aggregator,
+ .format = bgp_format_aggregator,
+ },
+ [BA_LARGE_COMMUNITY] = {
+ .name = "large_community",
+ .type = EAF_TYPE_LC_SET,
+ .flags = BAF_OPTIONAL | BAF_TRANSITIVE,
+ .export = bgp_export_large_community,
+ .encode = bgp_encode_u32s,
+ .decode = bgp_decode_large_community,
+ },
+};
+
+static inline int
+bgp_attr_known(uint code)
+{
+ return (code < ARRAY_SIZE(bgp_attr_table)) && bgp_attr_table[code].name;
+}
+
+
+/*
+ * Attribute export
+ */
+
+static inline void
+bgp_export_attr(struct bgp_export_state *s, eattr *a, ea_list *to)
+{
+ if (EA_PROTO(a->id) != EAP_BGP)
+ return;
+
+ uint code = EA_ID(a->id);
+
+ if (bgp_attr_known(code))
+ {
+ const struct bgp_attr_desc *desc = &bgp_attr_table[code];
+
+ /* The flags might have been zero if the attr was added by filters */
+ a->flags = (a->flags & BAF_PARTIAL) | desc->flags;
+
+ /* Set partial bit if new opt-trans attribute is attached to non-local route */
+ if ((s->src != NULL) && (a->type & EAF_ORIGINATED) &&
+ (a->flags & BAF_OPTIONAL) && (a->flags & BAF_TRANSITIVE))
+ a->flags |= BAF_PARTIAL;
+
+ /* Call specific hook */
+ CALL(desc->export, s, a);
+
+ /* Attribute might become undefined in hook */
+ if ((a->type & EAF_TYPE_MASK) == EAF_TYPE_UNDEF)
+ return;
+ }
else
- {
- ASSERT((a->type & EAF_TYPE_MASK) == EAF_TYPE_OPAQUE);
- len = a->u.ptr->length;
- }
-
- return len;
+ {
+ /* Don't re-export unknown non-transitive attributes */
+ if (!(a->flags & BAF_TRANSITIVE))
+ return;
+
+ a->flags |= BAF_PARTIAL;
+ }
+
+ /* Append updated attribute */
+ to->attrs[to->count++] = *a;
}
-#define ADVANCE(w, r, l) do { r -= l; w += l; } while (0)
+/**
+ * bgp_export_attrs - export BGP attributes
+ * @s: BGP export state
+ * @attrs: a list of extended attributes
+ *
+ * The bgp_export_attrs() function takes a list of attributes and merges it to
+ * one newly allocated and sorted segment. Attributes are validated and
+ * normalized by type-specific export hooks and attribute flags are updated.
+ * Some attributes may be eliminated (e.g. unknown non-tranitive attributes, or
+ * empty community sets).
+ *
+ * Result: one sorted attribute list segment, or NULL if attributes are unsuitable.
+ */
+static inline ea_list *
+bgp_export_attrs(struct bgp_export_state *s, ea_list *attrs)
+{
+ /* Merge the attribute list */
+ ea_list *new = lp_alloc(s->pool, ea_scan(attrs));
+ ea_merge(attrs, new);
+ ea_sort(new);
+
+ uint i, count;
+ count = new->count;
+ new->count = 0;
+
+ /* Export each attribute */
+ for (i = 0; i < count; i++)
+ bgp_export_attr(s, &new->attrs[i], new);
+
+ if (s->err_withdraw)
+ return NULL;
+
+ return new;
+
+}
+
+
+/*
+ * Attribute encoding
+ */
+
+static inline int
+bgp_encode_attr(struct bgp_write_state *s, eattr *a, byte *buf, uint size)
+{
+ ASSERT(EA_PROTO(a->id) == EAP_BGP);
+
+ uint code = EA_ID(a->id);
+
+ if (bgp_attr_known(code))
+ return bgp_attr_table[code].encode(s, a, buf, size);
+ else
+ return bgp_encode_raw(s, a, buf, size);
+}
/**
* bgp_encode_attrs - encode BGP attributes
- * @p: BGP instance
- * @w: buffer
+ * @s: BGP write state
* @attrs: a list of extended attributes
- * @remains: remaining space in the buffer
+ * @buf: buffer
+ * @end: buffer end
*
* The bgp_encode_attrs() function takes a list of extended attributes
* and converts it to its BGP representation (a part of an Update message).
*
* Result: Length of the attribute block generated or -1 if not enough space.
*/
-uint
-bgp_encode_attrs(struct bgp_proto *p, byte *w, ea_list *attrs, int remains)
+int
+bgp_encode_attrs(struct bgp_write_state *s, ea_list *attrs, byte *buf, byte *end)
{
- uint i, code, type, flags;
- byte *start = w;
- int len, rv;
+ byte *pos = buf;
+ int i, len;
- for(i=0; i<attrs->count; i++)
- {
- eattr *a = &attrs->attrs[i];
- ASSERT(EA_PROTO(a->id) == EAP_BGP);
- code = EA_ID(a->id);
-
-#ifdef IPV6
- /* When talking multiprotocol BGP, the NEXT_HOP attributes are used only temporarily. */
- if (code == BA_NEXT_HOP)
- continue;
-#endif
-
- /* When AS4-aware BGP speaker is talking to non-AS4-aware BGP speaker,
- * we have to convert our 4B AS_PATH to 2B AS_PATH and send our AS_PATH
- * as optional AS4_PATH attribute.
- */
- if ((code == BA_AS_PATH) && (! p->as4_session))
- {
- len = a->u.ptr->length;
-
- if (remains < (len + 4))
- goto err_no_buffer;
-
- /* Using temporary buffer because don't know a length of created attr
- * and therefore a length of a header. Perhaps i should better always
- * use BAF_EXT_LEN. */
-
- byte buf[len];
- int new_used;
- int nl = as_path_convert_to_old(a->u.ptr, buf, &new_used);
-
- DBG("BGP: Encoding old AS_PATH\n");
- rv = bgp_encode_attr_hdr(w, BAF_TRANSITIVE, BA_AS_PATH, nl);
- ADVANCE(w, remains, rv);
- memcpy(w, buf, nl);
- ADVANCE(w, remains, nl);
-
- if (! new_used)
- continue;
-
- if (remains < (len + 4))
- goto err_no_buffer;
-
- /* We should discard AS_CONFED_SEQUENCE or AS_CONFED_SET path segments
- * here but we don't support confederations and such paths we already
- * discarded in bgp_check_as_path().
- */
-
- DBG("BGP: Encoding AS4_PATH\n");
- rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_PATH, len);
- ADVANCE(w, remains, rv);
- memcpy(w, a->u.ptr->data, len);
- ADVANCE(w, remains, len);
-
- continue;
- }
-
- /* The same issue with AGGREGATOR attribute */
- if ((code == BA_AGGREGATOR) && (! p->as4_session))
- {
- int new_used;
-
- len = 6;
- if (remains < (len + 3))
- goto err_no_buffer;
-
- rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AGGREGATOR, len);
- ADVANCE(w, remains, rv);
- aggregator_convert_to_old(a->u.ptr, w, &new_used);
- ADVANCE(w, remains, len);
-
- if (! new_used)
- continue;
-
- len = 8;
- if (remains < (len + 3))
- goto err_no_buffer;
-
- rv = bgp_encode_attr_hdr(w, BAF_OPTIONAL | BAF_TRANSITIVE, BA_AS4_AGGREGATOR, len);
- ADVANCE(w, remains, rv);
- memcpy(w, a->u.ptr->data, len);
- ADVANCE(w, remains, len);
-
- continue;
- }
-
- /* Standard path continues here ... */
-
- type = a->type & EAF_TYPE_MASK;
- flags = a->flags & (BAF_OPTIONAL | BAF_TRANSITIVE | BAF_PARTIAL);
- len = bgp_get_attr_len(a);
-
- /* Skip empty sets */
- if (((type == EAF_TYPE_INT_SET) || (type == EAF_TYPE_EC_SET)) && (len == 0))
- continue;
-
- if (remains < len + 4)
- goto err_no_buffer;
-
- rv = bgp_encode_attr_hdr(w, flags, code, len);
- ADVANCE(w, remains, rv);
-
- switch (type)
- {
- case EAF_TYPE_INT:
- case EAF_TYPE_ROUTER_ID:
- if (len == 4)
- put_u32(w, a->u.data);
- else
- *w = a->u.data;
- break;
- case EAF_TYPE_IP_ADDRESS:
- {
- ip_addr ip = *(ip_addr *)a->u.ptr->data;
- ipa_hton(ip);
- memcpy(w, &ip, len);
- break;
- }
- case EAF_TYPE_INT_SET:
- case EAF_TYPE_EC_SET:
- {
- u32 *z = int_set_get_data(a->u.ptr);
- int i;
- for(i=0; i<len; i+=4)
- put_u32(w+i, *z++);
- break;
- }
- case EAF_TYPE_OPAQUE:
- case EAF_TYPE_AS_PATH:
- memcpy(w, a->u.ptr->data, len);
- break;
- default:
- bug("bgp_encode_attrs: unknown attribute type %02x", a->type);
- }
- ADVANCE(w, remains, len);
- }
- return w - start;
+ for (i = 0; i < attrs->count; i++)
+ {
+ len = bgp_encode_attr(s, &attrs->attrs[i], pos, end - pos);
+
+ if (len < 0)
+ return -1;
- err_no_buffer:
- return -1;
+ pos += len;
+ }
+
+ return pos - buf;
}
+
/*
-static void
-bgp_init_prefix(struct fib_node *N)
+ * Attribute decoding
+ */
+
+static void bgp_process_as4_attrs(ea_list **attrs, struct linpool *pool);
+
+static inline int
+bgp_as_path_loopy(struct bgp_proto *p, ea_list *attrs, u32 asn)
{
- struct bgp_prefix *p = (struct bgp_prefix *) N;
- p->bucket_node.next = NULL;
+ eattr *e = bgp_find_attr(attrs, BA_AS_PATH);
+ int num = p->cf->allow_local_as + 1;
+ return (e && (num > 0) && as_path_contains(e->u.ptr, asn, num));
}
-*/
-static int
-bgp_compare_u32(const u32 *x, const u32 *y)
+static inline int
+bgp_originator_id_loopy(struct bgp_proto *p, ea_list *attrs)
{
- return (*x < *y) ? -1 : (*x > *y) ? 1 : 0;
+ eattr *e = bgp_find_attr(attrs, BA_ORIGINATOR_ID);
+ return (e && (e->u.data == p->local_id));
}
-static inline void
-bgp_normalize_int_set(u32 *dest, u32 *src, unsigned cnt)
+static inline int
+bgp_cluster_list_loopy(struct bgp_proto *p, ea_list *attrs)
{
- memcpy(dest, src, sizeof(u32) * cnt);
- qsort(dest, cnt, sizeof(u32), (int(*)(const void *, const void *)) bgp_compare_u32);
+ eattr *e = bgp_find_attr(attrs, BA_CLUSTER_LIST);
+ return (e && int_set_contains(e->u.ptr, p->rr_cluster_id));
}
-static int
-bgp_compare_ec(const u32 *xp, const u32 *yp)
+static inline void
+bgp_decode_attr(struct bgp_parse_state *s, uint code, uint flags, byte *data, uint len, ea_list **to)
{
- u64 x = ec_get(xp, 0);
- u64 y = ec_get(yp, 0);
- return (x < y) ? -1 : (x > y) ? 1 : 0;
+ /* Handle duplicate attributes; RFC 7606 3 (g) */
+ if (BIT32_TEST(s->attrs_seen, code))
+ {
+ if ((code == BA_MP_REACH_NLRI) || (code == BA_MP_UNREACH_NLRI))
+ bgp_parse_error(s, 1);
+ else
+ DISCARD("Discarding duplicate attribute (code %u)", code);
+ }
+ BIT32_SET(s->attrs_seen, code);
+
+ if (bgp_attr_known(code))
+ {
+ const struct bgp_attr_desc *desc = &bgp_attr_table[code];
+
+ /* Handle conflicting flags; RFC 7606 3 (c) */
+ if ((flags ^ desc->flags) & (BAF_OPTIONAL | BAF_TRANSITIVE))
+ WITHDRAW("Malformed %s attribute - conflicting flags (%02x)", desc->name, flags);
+
+ desc->decode(s, code, flags, data, len, to);
+ }
+ else /* Unknown attribute */
+ {
+ if (!(flags & BAF_OPTIONAL))
+ WITHDRAW("Unknown attribute (code %u) - conflicting flags (%02x)", code, flags);
+
+ bgp_decode_unknown(s, code, flags, data, len, to);
+ }
}
-static inline void
-bgp_normalize_ec_set(struct adata *ad, u32 *src, int internal)
+/**
+ * bgp_decode_attrs - check and decode BGP attributes
+ * @s: BGP parse state
+ * @data: start of attribute block
+ * @len: length of attribute block
+ *
+ * This function takes a BGP attribute block (a part of an Update message), checks
+ * its consistency and converts it to a list of BIRD route attributes represented
+ * by an (uncached) &rta.
+ */
+ea_list *
+bgp_decode_attrs(struct bgp_parse_state *s, byte *data, uint len)
{
- u32 *dst = int_set_get_data(ad);
+ struct bgp_proto *p = s->proto;
+ ea_list *attrs = NULL;
+ uint code, flags, alen;
+ byte *pos = data;
- /* Remove non-transitive communities (EC_TBIT active) on external sessions */
- if (! internal)
+ /* Parse the attributes */
+ while (len)
+ {
+ alen = 0;
+
+ /* Read attribute type */
+ if (len < 2)
+ goto framing_error;
+ flags = pos[0];
+ code = pos[1];
+ ADVANCE(pos, len, 2);
+
+ /* Read attribute length */
+ if (flags & BAF_EXT_LEN)
{
- int len = int_set_get_size(ad);
- u32 *t = dst;
- int i;
-
- for (i=0; i < len; i += 2)
- {
- if (src[i] & EC_TBIT)
- continue;
-
- *t++ = src[i];
- *t++ = src[i+1];
- }
-
- ad->length = (t - dst) * 4;
+ if (len < 2)
+ goto framing_error;
+ alen = get_u16(pos);
+ ADVANCE(pos, len, 2);
}
- else
- memcpy(dst, src, ad->length);
+ else
+ {
+ if (len < 1)
+ goto framing_error;
+ alen = *pos;
+ ADVANCE(pos, len, 1);
+ }
+
+ if (alen > len)
+ goto framing_error;
+
+ DBG("Attr %02x %02x %u\n", code, flags, alen);
+
+ bgp_decode_attr(s, code, flags, pos, alen, &attrs);
+ ADVANCE(pos, len, alen);
+ }
+
+ if (s->err_withdraw)
+ goto withdraw;
+
+ /* If there is no reachability NLRI, we are finished */
+ if (!s->ip_reach_len && !s->mp_reach_len)
+ return NULL;
+
+
+ /* Handle missing mandatory attributes; RFC 7606 3 (d) */
+ if (!BIT32_TEST(s->attrs_seen, BA_ORIGIN))
+ { REPORT(NO_MANDATORY, "ORIGIN"); goto withdraw; }
+
+ if (!BIT32_TEST(s->attrs_seen, BA_AS_PATH))
+ { REPORT(NO_MANDATORY, "AS_PATH"); goto withdraw; }
+
+ /* When receiving attributes from non-AS4-aware BGP speaker, we have to
+ reconstruct AS_PATH and AGGREGATOR attributes; RFC 6793 4.2.3 */
+ if (!p->as4_session)
+ bgp_process_as4_attrs(&attrs, s->pool);
+
+ /* Reject routes with our ASN in AS_PATH attribute */
+ if (bgp_as_path_loopy(p, attrs, p->local_as))
+ goto withdraw;
+
+ /* Reject routes with our Confederation ID in AS_PATH attribute; RFC 5065 4 */
+ if ((p->public_as != p->local_as) && bgp_as_path_loopy(p, attrs, p->public_as))
+ goto withdraw;
+
+ /* Reject routes with our Router ID in ORIGINATOR_ID attribute; RFC 4456 8 */
+ if (p->is_internal && bgp_originator_id_loopy(p, attrs))
+ goto withdraw;
+
+ /* Reject routes with our Cluster ID in CLUSTER_LIST attribute; RFC 4456 8 */
+ if (p->rr_client && bgp_cluster_list_loopy(p, attrs))
+ goto withdraw;
+
+ /* If there is no local preference, define one */
+ if (!BIT32_TEST(s->attrs_seen, BA_LOCAL_PREF))
+ bgp_set_attr_u32(&attrs, s->pool, BA_LOCAL_PREF, 0, p->cf->default_local_pref);
+
+ return attrs;
+
+
+framing_error:
+ /* RFC 7606 4 - handle attribute framing errors */
+ REPORT("Malformed attribute list - framing error (%u/%u) at %d",
+ alen, len, (int) (pos - s->attrs));
+
+withdraw:
+ /* RFC 7606 5.2 - handle missing NLRI during errors */
+ if (!s->ip_reach_len && !s->mp_reach_len)
+ bgp_parse_error(s, 1);
- qsort(dst, ad->length / 8, 8, (int(*)(const void *, const void *)) bgp_compare_ec);
+ s->err_withdraw = 1;
+ return NULL;
}
-static void
-bgp_rehash_buckets(struct bgp_proto *p)
-{
- struct bgp_bucket **old = p->bucket_hash;
- struct bgp_bucket **new;
- unsigned oldn = p->hash_size;
- unsigned i, e, mask;
- struct bgp_bucket *b;
-
- p->hash_size = p->hash_limit;
- DBG("BGP: Rehashing bucket table from %d to %d\n", oldn, p->hash_size);
- p->hash_limit *= 4;
- if (p->hash_limit >= 65536)
- p->hash_limit = ~0;
- new = p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
- mask = p->hash_size - 1;
- for (i=0; i<oldn; i++)
- while (b = old[i])
- {
- old[i] = b->hash_next;
- e = b->hash & mask;
- b->hash_next = new[e];
- if (b->hash_next)
- b->hash_next->hash_prev = b;
- b->hash_prev = NULL;
- new[e] = b;
- }
- mb_free(old);
+
+/*
+ * Route bucket hash table
+ */
+
+#define RBH_KEY(b) b->eattrs, b->hash
+#define RBH_NEXT(b) b->next
+#define RBH_EQ(a1,h1,a2,h2) h1 == h2 && ea_same(a1, a2)
+#define RBH_FN(a,h) h
+
+#define RBH_REHASH bgp_rbh_rehash
+#define RBH_PARAMS /8, *2, 2, 2, 8, 20
+
+
+HASH_DEFINE_REHASH_FN(RBH, struct bgp_bucket)
+
+void
+bgp_init_bucket_table(struct bgp_channel *c)
+{
+ HASH_INIT(c->bucket_hash, c->pool, 8);
+
+ init_list(&c->bucket_queue);
+ c->withdraw_bucket = NULL;
}
static struct bgp_bucket *
-bgp_new_bucket(struct bgp_proto *p, ea_list *new, unsigned hash)
+bgp_get_bucket(struct bgp_channel *c, ea_list *new)
{
- struct bgp_bucket *b;
- unsigned ea_size = sizeof(ea_list) + new->count * sizeof(eattr);
- unsigned ea_size_aligned = BIRD_ALIGN(ea_size, CPU_STRUCT_ALIGN);
- unsigned size = sizeof(struct bgp_bucket) + ea_size_aligned;
- unsigned i;
+ /* Hash and lookup */
+ u32 hash = ea_hash(new);
+ struct bgp_bucket *b = HASH_FIND(c->bucket_hash, RBH, new, hash);
+
+ if (b)
+ return b;
+
+ uint ea_size = sizeof(ea_list) + new->count * sizeof(eattr);
+ uint ea_size_aligned = BIRD_ALIGN(ea_size, CPU_STRUCT_ALIGN);
+ uint size = sizeof(struct bgp_bucket) + ea_size_aligned;
+ uint i;
byte *dest;
- unsigned index = hash & (p->hash_size - 1);
/* Gather total size of non-inline attributes */
- for (i=0; i<new->count; i++)
- {
- eattr *a = &new->attrs[i];
- if (!(a->type & EAF_EMBEDDED))
- size += BIRD_ALIGN(sizeof(struct adata) + a->u.ptr->length, CPU_STRUCT_ALIGN);
- }
+ for (i = 0; i < new->count; i++)
+ {
+ eattr *a = &new->attrs[i];
- /* Create the bucket and hash it */
- b = mb_alloc(p->p.pool, size);
- b->hash_next = p->bucket_hash[index];
- if (b->hash_next)
- b->hash_next->hash_prev = b;
- p->bucket_hash[index] = b;
- b->hash_prev = NULL;
- b->hash = hash;
- add_tail(&p->bucket_queue, &b->send_node);
+ if (!(a->type & EAF_EMBEDDED))
+ size += BIRD_ALIGN(sizeof(struct adata) + a->u.ptr->length, CPU_STRUCT_ALIGN);
+ }
+
+ /* Create the bucket */
+ b = mb_alloc(c->pool, size);
init_list(&b->prefixes);
+ b->hash = hash;
+
+ /* Copy list of extended attributes */
memcpy(b->eattrs, new, ea_size);
- dest = ((byte *)b->eattrs) + ea_size_aligned;
+ dest = ((byte *) b->eattrs) + ea_size_aligned;
/* Copy values of non-inline attributes */
- for (i=0; i<new->count; i++)
+ for (i = 0; i < new->count; i++)
+ {
+ eattr *a = &b->eattrs->attrs[i];
+
+ if (!(a->type & EAF_EMBEDDED))
{
- eattr *a = &b->eattrs->attrs[i];
- if (!(a->type & EAF_EMBEDDED))
- {
- struct adata *oa = a->u.ptr;
- struct adata *na = (struct adata *) dest;
- memcpy(na, oa, sizeof(struct adata) + oa->length);
- a->u.ptr = na;
- dest += BIRD_ALIGN(sizeof(struct adata) + na->length, CPU_STRUCT_ALIGN);
- }
+ struct adata *oa = a->u.ptr;
+ struct adata *na = (struct adata *) dest;
+ memcpy(na, oa, sizeof(struct adata) + oa->length);
+ a->u.ptr = na;
+ dest += BIRD_ALIGN(sizeof(struct adata) + na->length, CPU_STRUCT_ALIGN);
}
+ }
- /* If needed, rehash */
- p->hash_count++;
- if (p->hash_count > p->hash_limit)
- bgp_rehash_buckets(p);
+ /* Insert the bucket to send queue and bucket hash */
+ add_tail(&c->bucket_queue, &b->send_node);
+ HASH_INSERT2(c->bucket_hash, RBH, c->pool, b);
return b;
}
static struct bgp_bucket *
-bgp_get_bucket(struct bgp_proto *p, net *n, ea_list *attrs, int originate)
+bgp_get_withdraw_bucket(struct bgp_channel *c)
{
- ea_list *new;
- unsigned i, cnt, hash, code;
- eattr *a, *d;
- u32 seen = 0;
- struct bgp_bucket *b;
-
- /* Merge the attribute list */
- new = alloca(ea_scan(attrs));
- ea_merge(attrs, new);
- ea_sort(new);
+ if (!c->withdraw_bucket)
+ {
+ c->withdraw_bucket = mb_allocz(c->pool, sizeof(struct bgp_bucket));
+ init_list(&c->withdraw_bucket->prefixes);
+ }
- /* Normalize attributes */
- d = new->attrs;
- cnt = new->count;
- new->count = 0;
- for(i=0; i<cnt; i++)
- {
- a = &new->attrs[i];
- if (EA_PROTO(a->id) != EAP_BGP)
- continue;
- code = EA_ID(a->id);
- if (ATTR_KNOWN(code))
- {
- if (!bgp_attr_table[code].allow_in_ebgp && !p->is_internal)
- continue;
- /* The flags might have been zero if the attr was added by filters */
- a->flags = (a->flags & BAF_PARTIAL) | bgp_attr_table[code].expected_flags;
- if (code < 32)
- seen |= 1 << code;
- }
- else
- {
- /* Don't re-export unknown non-transitive attributes */
- if (!(a->flags & BAF_TRANSITIVE))
- continue;
- }
- *d = *a;
- if ((d->type & EAF_ORIGINATED) && !originate && (d->flags & BAF_TRANSITIVE) && (d->flags & BAF_OPTIONAL))
- d->flags |= BAF_PARTIAL;
- switch (d->type & EAF_TYPE_MASK)
- {
- case EAF_TYPE_INT_SET:
- {
- struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
- z->length = d->u.ptr->length;
- bgp_normalize_int_set((u32 *) z->data, (u32 *) d->u.ptr->data, z->length / 4);
- d->u.ptr = z;
- break;
- }
- case EAF_TYPE_EC_SET:
- {
- struct adata *z = alloca(sizeof(struct adata) + d->u.ptr->length);
- z->length = d->u.ptr->length;
- bgp_normalize_ec_set(z, (u32 *) d->u.ptr->data, p->is_internal);
- d->u.ptr = z;
- break;
- }
- default: ;
- }
- d++;
- new->count++;
- }
+ return c->withdraw_bucket;
+}
- /* Hash */
- hash = ea_hash(new);
- for(b=p->bucket_hash[hash & (p->hash_size - 1)]; b; b=b->hash_next)
- if (b->hash == hash && ea_same(b->eattrs, new))
- {
- DBG("Found bucket.\n");
- return b;
- }
-
- /* Ensure that there are all mandatory attributes */
- for(i=0; i<ARRAY_SIZE(bgp_mandatory_attrs); i++)
- if (!(seen & (1 << bgp_mandatory_attrs[i])))
- {
- log(L_ERR "%s: Mandatory attribute %s missing in route %I/%d", p->p.name, bgp_attr_table[bgp_mandatory_attrs[i]].name, n->n.prefix, n->n.pxlen);
- return NULL;
- }
-
- /* Check if next hop is valid */
- a = ea_find(new, EA_CODE(EAP_BGP, BA_NEXT_HOP));
- if (!a || ipa_equal(p->cf->remote_ip, *(ip_addr *)a->u.ptr->data))
- {
- log(L_ERR "%s: Invalid NEXT_HOP attribute in route %I/%d", p->p.name, n->n.prefix, n->n.pxlen);
- return NULL;
- }
+void
+bgp_free_bucket(struct bgp_channel *c, struct bgp_bucket *b)
+{
+ rem_node(&b->send_node);
+ HASH_REMOVE2(c->bucket_hash, RBH, c->pool, b);
+ mb_free(b);
+}
- /* Create new bucket */
- DBG("Creating bucket.\n");
- return bgp_new_bucket(p, new, hash);
+void
+bgp_defer_bucket(struct bgp_channel *c, struct bgp_bucket *b)
+{
+ rem_node(&b->send_node);
+ add_tail(&c->bucket_queue, &b->send_node);
}
void
-bgp_free_bucket(struct bgp_proto *p, struct bgp_bucket *buck)
+bgp_withdraw_bucket(struct bgp_channel *c, struct bgp_bucket *b)
{
- if (buck->hash_next)
- buck->hash_next->hash_prev = buck->hash_prev;
- if (buck->hash_prev)
- buck->hash_prev->hash_next = buck->hash_next;
- else
- p->bucket_hash[buck->hash & (p->hash_size-1)] = buck->hash_next;
- mb_free(buck);
+ struct bgp_proto *p = (void *) c->c.proto;
+ struct bgp_bucket *wb = bgp_get_withdraw_bucket(c);
+
+ log(L_ERR "%s: Attribute list too long", p->p.name);
+ while (!EMPTY_LIST(b->prefixes))
+ {
+ struct bgp_prefix *px = HEAD(b->prefixes);
+
+ log(L_ERR "%s: - withdrawing %N", p->p.name, &px->net);
+ rem_node(&px->buck_node);
+ add_tail(&wb->prefixes, &px->buck_node);
+ }
}
-/* Prefix hash table */
+/*
+ * Prefix hash table
+ */
-#define PXH_KEY(n1) n1->n.prefix, n1->n.pxlen, n1->path_id
-#define PXH_NEXT(n) n->next
-#define PXH_EQ(p1,l1,i1,p2,l2,i2) ipa_equal(p1, p2) && l1 == l2 && i1 == i2
-#define PXH_FN(p,l,i) ipa_hash32(p) ^ u32_hash((l << 16) ^ i)
+#define PXH_KEY(px) px->net, px->path_id, px->hash
+#define PXH_NEXT(px) px->next
+#define PXH_EQ(n1,i1,h1,n2,i2,h2) h1 == h2 && i1 == i2 && net_equal(n1, n2)
+#define PXH_FN(n,i,h) h
#define PXH_REHASH bgp_pxh_rehash
#define PXH_PARAMS /8, *2, 2, 2, 8, 20
@@ -888,282 +1217,235 @@ bgp_free_bucket(struct bgp_proto *p, struct bgp_bucket *buck)
HASH_DEFINE_REHASH_FN(PXH, struct bgp_prefix)
void
-bgp_init_prefix_table(struct bgp_proto *p, u32 order)
+bgp_init_prefix_table(struct bgp_channel *c)
{
- HASH_INIT(p->prefix_hash, p->p.pool, order);
+ HASH_INIT(c->prefix_hash, c->pool, 8);
- p->prefix_slab = sl_new(p->p.pool, sizeof(struct bgp_prefix));
+ c->prefix_slab = sl_new(c->pool, sizeof(struct bgp_prefix) +
+ net_addr_length[c->c.net_type]);
}
static struct bgp_prefix *
-bgp_get_prefix(struct bgp_proto *p, ip_addr prefix, int pxlen, u32 path_id)
+bgp_get_prefix(struct bgp_channel *c, net_addr *net, u32 path_id)
{
- struct bgp_prefix *bp = HASH_FIND(p->prefix_hash, PXH, prefix, pxlen, path_id);
+ u32 hash = net_hash(net) ^ u32_hash(path_id);
+ struct bgp_prefix *px = HASH_FIND(c->prefix_hash, PXH, net, path_id, hash);
- if (bp)
- return bp;
+ if (px)
+ {
+ rem_node(&px->buck_node);
+ return px;
+ }
- bp = sl_alloc(p->prefix_slab);
- bp->n.prefix = prefix;
- bp->n.pxlen = pxlen;
- bp->path_id = path_id;
- bp->bucket_node.next = NULL;
+ px = sl_alloc(c->prefix_slab);
+ px->buck_node.next = NULL;
+ px->buck_node.prev = NULL;
+ px->hash = hash;
+ px->path_id = path_id;
+ net_copy(px->net, net);
- HASH_INSERT2(p->prefix_hash, PXH, p->p.pool, bp);
+ HASH_INSERT2(c->prefix_hash, PXH, c->pool, px);
- return bp;
+ return px;
}
void
-bgp_free_prefix(struct bgp_proto *p, struct bgp_prefix *bp)
+bgp_free_prefix(struct bgp_channel *c, struct bgp_prefix *px)
{
- HASH_REMOVE2(p->prefix_hash, PXH, p->p.pool, bp);
- sl_free(p->prefix_slab, bp);
+ rem_node(&px->buck_node);
+ HASH_REMOVE2(c->prefix_hash, PXH, c->pool, px);
+ sl_free(c->prefix_slab, px);
}
-void
-bgp_rt_notify(struct proto *P, rtable *tbl UNUSED, net *n, rte *new, rte *old UNUSED, ea_list *attrs)
-{
- struct bgp_proto *p = (struct bgp_proto *) P;
- struct bgp_bucket *buck;
- struct bgp_prefix *px;
- rte *key;
- u32 path_id;
-
- DBG("BGP: Got route %I/%d %s\n", n->n.prefix, n->n.pxlen, new ? "up" : "down");
-
- if (new)
- {
- key = new;
- buck = bgp_get_bucket(p, n, attrs, new->attrs->source != RTS_BGP);
- if (!buck) /* Inconsistent attribute list */
- return;
- }
- else
- {
- key = old;
- if (!(buck = p->withdraw_bucket))
- {
- buck = p->withdraw_bucket = mb_alloc(P->pool, sizeof(struct bgp_bucket));
- init_list(&buck->prefixes);
- }
- }
- path_id = p->add_path_tx ? key->attrs->src->global_id : 0;
- px = bgp_get_prefix(p, n->n.prefix, n->n.pxlen, path_id);
- if (px->bucket_node.next)
- {
- DBG("\tRemoving old entry.\n");
- rem_node(&px->bucket_node);
- }
- add_tail(&buck->prefixes, &px->bucket_node);
- bgp_schedule_packet(p->conn, PKT_UPDATE);
-}
+/*
+ * BGP protocol glue
+ */
-static int
-bgp_create_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool)
+int
+bgp_import_control(struct proto *P, rte **new, ea_list **attrs UNUSED, struct linpool *pool UNUSED)
{
- ea_list *ea = lp_alloc(pool, sizeof(ea_list) + 4*sizeof(eattr));
- rta *rta = e->attrs;
- byte *z;
-
- ea->next = *attrs;
- *attrs = ea;
- ea->flags = EALF_SORTED;
- ea->count = 4;
-
- bgp_set_attr(ea->attrs, BA_ORIGIN,
- ((rta->source == RTS_OSPF_EXT1) || (rta->source == RTS_OSPF_EXT2)) ? ORIGIN_INCOMPLETE : ORIGIN_IGP);
-
- if (p->is_internal)
- bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 0);
- else
- {
- z = bgp_set_attr_wa(ea->attrs+1, pool, BA_AS_PATH, 6);
- z[0] = AS_PATH_SEQUENCE;
- z[1] = 1; /* 1 AS */
- put_u32(z+2, p->local_as);
- }
-
- /* iBGP -> use gw, eBGP multi-hop -> use source_addr,
- eBGP single-hop -> use gw if on the same iface */
- z = bgp_set_attr_wa(ea->attrs+2, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
- if (p->cf->next_hop_self ||
- rta->dest != RTD_ROUTER ||
- ipa_equal(rta->gw, IPA_NONE) ||
- ipa_is_link_local(rta->gw) ||
- (!p->is_internal && !p->cf->next_hop_keep &&
- (!p->neigh || (rta->iface != p->neigh->iface))))
- set_next_hop(z, p->source_addr);
- else
- set_next_hop(z, rta->gw);
-
- bgp_set_attr(ea->attrs+3, BA_LOCAL_PREF, p->cf->default_local_pref);
-
- return 0; /* Leave decision to the filters */
-}
+ rte *e = *new;
+ struct proto *SRC = e->attrs->src->proto;
+ struct bgp_proto *p = (struct bgp_proto *) P;
+ struct bgp_proto *src = (SRC->proto == &proto_bgp) ? (struct bgp_proto *) SRC : NULL;
+ /* Reject our routes */
+ if (src == p)
+ return -1;
-static inline int
-bgp_as_path_loopy(struct bgp_proto *p, rta *a)
-{
- int num = p->cf->allow_local_as + 1;
- eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- return (e && (num > 0) && as_path_contains(e->u.ptr, p->local_as, num));
-}
+ /* Accept non-BGP routes */
+ if (src == NULL)
+ return 0;
-static inline int
-bgp_originator_id_loopy(struct bgp_proto *p, rta *a)
-{
- eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
- return (e && (e->u.data == p->local_id));
-}
+ /* IBGP route reflection, RFC 4456 */
+ if (p->is_internal && src->is_internal && (p->local_as == src->local_as))
+ {
+ /* Rejected unless configured as route reflector */
+ if (!p->rr_client && !src->rr_client)
+ return -1;
+
+ /* Generally, this should be handled when path is received, but we check it
+ also here as rr_cluster_id may be undefined or different in src. */
+ if (p->rr_cluster_id && bgp_cluster_list_loopy(p, e->attrs->eattrs))
+ return -1;
+ }
+
+ /* Handle well-known communities, RFC 1997 */
+ struct eattr *c;
+ if (p->cf->interpret_communities &&
+ (c = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY))))
+ {
+ struct adata *d = c->u.ptr;
+
+ /* Do not export anywhere */
+ if (int_set_contains(d, BGP_COMM_NO_ADVERTISE))
+ return -1;
+
+ /* Do not export outside of AS (or member-AS) */
+ if (!p->is_internal && int_set_contains(d, BGP_COMM_NO_EXPORT_SUBCONFED))
+ return -1;
+
+ /* Do not export outside of AS (or confederation) */
+ if (!p->is_interior && int_set_contains(d, BGP_COMM_NO_EXPORT))
+ return -1;
+ }
-static inline int
-bgp_cluster_list_loopy(struct bgp_proto *p, rta *a)
-{
- eattr *e = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
- return (e && p->rr_client && int_set_contains(e->u.ptr, p->rr_cluster_id));
+ return 0;
}
+static const adata null_adata; /* adata of length 0 */
static inline void
-bgp_path_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 as)
+bgp_path_prepend(ea_list **attrs, struct linpool *pool, int seg, u32 as, int strip)
{
- eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- bgp_attach_attr(attrs, pool, BA_AS_PATH, (uintptr_t) as_path_prepend(pool, a->u.ptr, as));
+ eattr *a = bgp_find_attr(*attrs, BA_AS_PATH);
+ adata *d = as_path_prepend2(pool, a ? a->u.ptr : &null_adata, seg, as, strip);
+ bgp_set_attr_ptr(attrs, pool, BA_AS_PATH, 0, d);
}
static inline void
-bgp_cluster_list_prepend(rte *e, ea_list **attrs, struct linpool *pool, u32 cid)
+bgp_cluster_list_prepend(ea_list **attrs, struct linpool *pool, u32 id)
{
- eattr *a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_CLUSTER_LIST));
- bgp_attach_attr(attrs, pool, BA_CLUSTER_LIST, (uintptr_t) int_set_add(pool, a ? a->u.ptr : NULL, cid));
+ eattr *a = bgp_find_attr(*attrs, BA_CLUSTER_LIST);
+ adata *d = int_set_add(pool, a ? a->u.ptr : NULL, id);
+ bgp_set_attr_ptr(attrs, pool, BA_CLUSTER_LIST, 0, d);
}
-static int
-bgp_update_attrs(struct bgp_proto *p, rte *e, ea_list **attrs, struct linpool *pool, int rr)
+static ea_list *
+bgp_update_attrs(struct bgp_proto *p, struct bgp_channel *c, rte *e, ea_list *attrs, struct linpool *pool)
{
+ struct proto *SRC = e->attrs->src->proto;
+ struct bgp_proto *src = (SRC->proto == &proto_bgp) ? (void *) SRC : NULL;
+ struct bgp_export_state s = { .proto = p, .channel =c, .pool = pool, .src = src, .route = e };
eattr *a;
- if (!p->is_internal && !p->rs_client)
- {
- bgp_path_prepend(e, attrs, pool, p->local_as);
-
- /* The MULTI_EXIT_DISC attribute received from a neighboring AS MUST NOT be
- * propagated to other neighboring ASes.
- * Perhaps it would be better to undefine it.
- */
- a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
- if (a)
- bgp_attach_attr(attrs, pool, BA_MULTI_EXIT_DISC, 0);
- }
-
- /* iBGP -> keep next_hop, eBGP multi-hop -> use source_addr,
- * eBGP single-hop -> keep next_hop if on the same iface.
- * If the next_hop is zero (i.e. link-local), keep only if on the same iface.
- *
- * Note that same-iface-check uses iface from route, which is based on gw.
- */
- a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
- if (a && !p->cf->next_hop_self &&
- (p->cf->next_hop_keep ||
- (p->is_internal && ipa_nonzero(*((ip_addr *) a->u.ptr->data))) ||
- (p->neigh && (e->attrs->iface == p->neigh->iface))))
- {
- /* Leave the original next hop attribute, will check later where does it point */
- }
- else
+ /* ORIGIN attribute - mandatory, attach if missing */
+ if (! bgp_find_attr(attrs, BA_ORIGIN))
+ bgp_set_attr_u32(&attrs, pool, BA_ORIGIN, 0, src ? ORIGIN_INCOMPLETE : ORIGIN_IGP);
+
+ /* AS_PATH attribute - keep or prepend ASN */
+ if (p->is_internal ||
+ (p->rs_client && src && src->rs_client))
+ {
+ /* IBGP or route server -> just ensure there is one */
+ if (! bgp_find_attr(attrs, BA_AS_PATH))
+ bgp_set_attr_ptr(&attrs, pool, BA_AS_PATH, 0, lp_alloc_adata(pool, 0));
+ }
+ else if (p->is_interior)
+ {
+ /* Confederation -> prepend ASN as CONFED_SEQUENCE, keep CONFED_* segments */
+ bgp_path_prepend(&attrs, pool, AS_PATH_CONFED_SEQUENCE, p->public_as, 0);
+ }
+ else /* Regular EBGP (no RS, no confederation) */
+ {
+ /* Regular EBGP -> prepend ASN as regular segment, strip CONFED_* segments */
+ bgp_path_prepend(&attrs, pool, AS_PATH_SEQUENCE, p->public_as, 1);
+
+ /* MULTI_EXIT_DESC attribute - accept only if set in export filter */
+ a = bgp_find_attr(attrs, BA_MULTI_EXIT_DISC);
+ if (a && !(a->type & EAF_FRESH))
+ bgp_unset_attr(&attrs, pool, BA_MULTI_EXIT_DISC);
+ }
+
+ /* NEXT_HOP attribute - delegated to AF-specific hook */
+ a = bgp_find_attr(attrs, BA_NEXT_HOP);
+ bgp_update_next_hop(&s, a, &attrs);
+
+ /* LOCAL_PREF attribute - required for IBGP, attach if missing */
+ if (p->is_interior && ! bgp_find_attr(attrs, BA_LOCAL_PREF))
+ bgp_set_attr_u32(&attrs, pool, BA_LOCAL_PREF, 0, p->cf->default_local_pref);
+
+ /* IBGP route reflection, RFC 4456 */
+ if (src && src->is_internal && p->is_internal && (src->local_as == p->local_as))
+ {
+ /* ORIGINATOR_ID attribute - attach if not already set */
+ if (! bgp_find_attr(attrs, BA_ORIGINATOR_ID))
+ bgp_set_attr_u32(&attrs, pool, BA_ORIGINATOR_ID, 0, src->remote_id);
+
+ /* CLUSTER_LIST attribute - prepend cluster ID */
+ if (src->rr_cluster_id)
+ bgp_cluster_list_prepend(&attrs, pool, src->rr_cluster_id);
+
+ /* Handle different src and dst cluster ID - prepend both ones */
+ if (p->rr_cluster_id && (src->rr_cluster_id != p->rr_cluster_id))
+ bgp_cluster_list_prepend(&attrs, pool, p->rr_cluster_id);
+ }
+
+ /* AS4_* transition attributes, RFC 6793 4.2.2 */
+ if (! p->as4_session)
+ {
+ a = bgp_find_attr(attrs, BA_AS_PATH);
+ if (a && as_path_contains_as4(a->u.ptr))
{
- /* Need to create new one */
- byte *b = bgp_attach_attr_wa(attrs, pool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
- set_next_hop(b, p->source_addr);
+ bgp_set_attr_ptr(&attrs, pool, BA_AS_PATH, 0, as_path_to_old(pool, a->u.ptr));
+ bgp_set_attr_ptr(&attrs, pool, BA_AS4_PATH, 0, as_path_strip_confed(pool, a->u.ptr));
}
- if (rr)
+ a = bgp_find_attr(attrs, BA_AGGREGATOR);
+ if (a && aggregator_contains_as4(a->u.ptr))
{
- /* Handling route reflection, RFC 4456 */
- struct bgp_proto *src = (struct bgp_proto *) e->attrs->src->proto;
-
- a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
- if (!a)
- bgp_attach_attr(attrs, pool, BA_ORIGINATOR_ID, src->remote_id);
-
- /* We attach proper cluster ID according to whether the route is entering or leaving the cluster */
- bgp_cluster_list_prepend(e, attrs, pool, src->rr_client ? src->rr_cluster_id : p->rr_cluster_id);
-
- /* Two RR clients with different cluster ID, hmmm */
- if (src->rr_client && p->rr_client && (src->rr_cluster_id != p->rr_cluster_id))
- bgp_cluster_list_prepend(e, attrs, pool, p->rr_cluster_id);
+ bgp_set_attr_ptr(&attrs, pool, BA_AGGREGATOR, 0, aggregator_to_old(pool, a->u.ptr));
+ bgp_set_attr_ptr(&attrs, pool, BA_AS4_AGGREGATOR, 0, a->u.ptr);
}
+ }
- return 0; /* Leave decision to the filters */
+ /* Apply per-attribute export hooks for validatation and normalization */
+ return bgp_export_attrs(&s, attrs);
}
-static int
-bgp_community_filter(struct bgp_proto *p, rte *e)
+void
+bgp_rt_notify(struct proto *P, struct channel *C, net *n, rte *new, rte *old, ea_list *attrs)
{
- eattr *a;
- struct adata *d;
-
- /* Check if we aren't forbidden to export the route by communities */
- a = ea_find(e->attrs->eattrs, EA_CODE(EAP_BGP, BA_COMMUNITY));
- if (a)
- {
- d = a->u.ptr;
- if (int_set_contains(d, BGP_COMM_NO_ADVERTISE))
- {
- DBG("\tNO_ADVERTISE\n");
- return 1;
- }
- if (!p->is_internal &&
- (int_set_contains(d, BGP_COMM_NO_EXPORT) ||
- int_set_contains(d, BGP_COMM_NO_EXPORT_SUBCONFED)))
- {
- DBG("\tNO_EXPORT\n");
- return 1;
- }
- }
+ struct bgp_proto *p = (void *) P;
+ struct bgp_channel *c = (void *) C;
+ struct bgp_bucket *buck;
+ struct bgp_prefix *px;
+ u32 path;
- return 0;
-}
+ if (new)
+ {
+ attrs = bgp_update_attrs(p, c, new, attrs, bgp_linpool);
-int
-bgp_import_control(struct proto *P, rte **new, ea_list **attrs, struct linpool *pool)
-{
- rte *e = *new;
- struct bgp_proto *p = (struct bgp_proto *) P;
- struct bgp_proto *new_bgp = (e->attrs->src->proto->proto == &proto_bgp) ?
- (struct bgp_proto *) e->attrs->src->proto : NULL;
+ /* If attributes are invalid, we fail back to withdraw */
+ buck = attrs ? bgp_get_bucket(c, attrs) : bgp_get_withdraw_bucket(c);
+ path = new->attrs->src->global_id;
- if (p == new_bgp) /* Poison reverse updates */
- return -1;
- if (new_bgp)
- {
- /* We should check here for cluster list loop, because the receiving BGP instance
- might have different cluster ID */
- if (bgp_cluster_list_loopy(p, e->attrs))
- return -1;
-
- if (p->cf->interpret_communities && bgp_community_filter(p, e))
- return -1;
-
- if (p->local_as == new_bgp->local_as && p->is_internal && new_bgp->is_internal)
- {
- /* Redistribution of internal routes with IBGP */
- if (p->rr_client || new_bgp->rr_client)
- /* Route reflection, RFC 4456 */
- return bgp_update_attrs(p, e, attrs, pool, 1);
- else
- return -1;
- }
- else
- return bgp_update_attrs(p, e, attrs, pool, 0);
- }
+ lp_flush(bgp_linpool);
+ }
else
- return bgp_create_attrs(p, e, attrs, pool);
+ {
+ buck = bgp_get_withdraw_bucket(c);
+ path = old->attrs->src->global_id;
+ }
+
+ px = bgp_get_prefix(c, n->n.addr, c->add_path_tx ? path : 0);
+ add_tail(&buck->prefixes, &px->buck_node);
+
+ bgp_schedule_packet(p->conn, c, PKT_UPDATE);
}
+
static inline u32
bgp_get_neighbor(rte *r)
{
@@ -1179,7 +1461,7 @@ bgp_get_neighbor(rte *r)
static inline int
rte_resolvable(rte *rt)
{
- int rd = rt->attrs->dest;
+ int rd = rt->attrs->dest;
return (rd == RTD_ROUTER) || (rd == RTD_DEVICE) || (rd == RTD_MULTIPATH);
}
@@ -1219,16 +1501,16 @@ bgp_rte_better(rte *new, rte *old)
/* RFC 4271 9.1.2.2. a) Use AS path lengths */
if (new_bgp->cf->compare_path_lengths || old_bgp->cf->compare_path_lengths)
- {
- x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- n = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
- o = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
- if (n < o)
- return 1;
- if (n > o)
- return 0;
- }
+ {
+ x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
+ y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
+ n = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
+ o = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
+ if (n < o)
+ return 1;
+ if (n > o)
+ return 0;
+ }
/* RFC 4271 9.1.2.2. b) Use origins */
x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
@@ -1253,21 +1535,21 @@ bgp_rte_better(rte *new, rte *old)
*/
if (new_bgp->cf->med_metric || old_bgp->cf->med_metric ||
(bgp_get_neighbor(new) == bgp_get_neighbor(old)))
- {
- x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
- y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
- n = x ? x->u.data : new_bgp->cf->default_med;
- o = y ? y->u.data : old_bgp->cf->default_med;
- if (n < o)
- return 1;
- if (n > o)
- return 0;
- }
+ {
+ x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
+ y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
+ n = x ? x->u.data : new_bgp->cf->default_med;
+ o = y ? y->u.data : old_bgp->cf->default_med;
+ if (n < o)
+ return 1;
+ if (n > o)
+ return 0;
+ }
/* RFC 4271 9.1.2.2. d) Prefer external peers */
- if (new_bgp->is_internal > old_bgp->is_internal)
+ if (new_bgp->is_interior > old_bgp->is_interior)
return 0;
- if (new_bgp->is_internal < old_bgp->is_internal)
+ if (new_bgp->is_interior < old_bgp->is_interior)
return 1;
/* RFC 4271 9.1.2.2. e) Compare IGP metrics */
@@ -1279,7 +1561,7 @@ bgp_rte_better(rte *new, rte *old)
return 0;
/* RFC 4271 9.1.2.2. f) Compare BGP identifiers */
- /* RFC 4456 9. a) Use ORIGINATOR_ID instead of local neighor ID */
+ /* RFC 4456 9. a) Use ORIGINATOR_ID instead of local neighbor ID */
x = ea_find(new->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
y = ea_find(old->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGINATOR_ID));
n = x ? x->u.data : new_bgp->remote_id;
@@ -1338,18 +1620,18 @@ bgp_rte_mergable(rte *pri, rte *sec)
/* RFC 4271 9.1.2.2. a) Use AS path lengths */
if (pri_bgp->cf->compare_path_lengths || sec_bgp->cf->compare_path_lengths)
- {
- x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- p = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
- s = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
+ {
+ x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
+ y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
+ p = x ? as_path_getlen(x->u.ptr) : AS_PATH_MAXLEN;
+ s = y ? as_path_getlen(y->u.ptr) : AS_PATH_MAXLEN;
- if (p != s)
- return 0;
+ if (p != s)
+ return 0;
-// if (DELTA(p, s) > pri_bgp->cf->relax_multipath)
-// return 0;
- }
+// if (DELTA(p, s) > pri_bgp->cf->relax_multipath)
+// return 0;
+ }
/* RFC 4271 9.1.2.2. b) Use origins */
x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_ORIGIN));
@@ -1362,14 +1644,14 @@ bgp_rte_mergable(rte *pri, rte *sec)
/* RFC 4271 9.1.2.2. c) Compare MED's */
if (pri_bgp->cf->med_metric || sec_bgp->cf->med_metric ||
(bgp_get_neighbor(pri) == bgp_get_neighbor(sec)))
- {
- x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
- y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
- p = x ? x->u.data : pri_bgp->cf->default_med;
- s = y ? y->u.data : sec_bgp->cf->default_med;
- if (p != s)
- return 0;
- }
+ {
+ x = ea_find(pri->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
+ y = ea_find(sec->attrs->eattrs, EA_CODE(EAP_BGP, BA_MULTI_EXIT_DISC));
+ p = x ? x->u.data : pri_bgp->cf->default_med;
+ s = y ? y->u.data : sec_bgp->cf->default_med;
+ if (p != s)
+ return 0;
+ }
/* RFC 4271 9.1.2.2. d) Prefer external peers */
if (pri_bgp->is_internal != sec_bgp->is_internal)
@@ -1387,7 +1669,6 @@ bgp_rte_mergable(rte *pri, rte *sec)
}
-
static inline int
same_group(rte *r, u32 lpref, u32 lasn)
{
@@ -1432,7 +1713,7 @@ bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
* that this fn is not called for them.
*
* The idea is simple, the implementation is more problematic,
- * mostly because of optimizations in rte_recalculate() that
+ * mostly because of optimizations in rte_recalculate() that
* avoids full recalculation in most cases.
*
* We can assume that at least one of new, old is non-NULL and both
@@ -1444,14 +1725,14 @@ bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
/* If new and old are from different groups, we just process that
as two independent events */
if (new && old && !same_group(old, lpref, lasn))
- {
- int i1, i2;
- i1 = bgp_rte_recalculate(table, net, NULL, old, old_best);
- i2 = bgp_rte_recalculate(table, net, new, NULL, old_best);
- return i1 || i2;
- }
+ {
+ int i1, i2;
+ i1 = bgp_rte_recalculate(table, net, NULL, old, old_best);
+ i2 = bgp_rte_recalculate(table, net, new, NULL, old_best);
+ return i1 || i2;
+ }
- /*
+ /*
* We could find the best-in-group and then make some shortcuts like
* in rte_recalculate, but as we would have to walk through all
* net->routes just to find it, it is probably not worth. So we
@@ -1463,35 +1744,35 @@ bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
new->u.bgp.suppressed = 1;
if (old)
+ {
+ old_is_group_best = !old->u.bgp.suppressed;
+ old->u.bgp.suppressed = 1;
+ int new_is_better = new && bgp_rte_better(new, old);
+
+ /* The first case - replace not best with worse (or remove not best) */
+ if (!old_is_group_best && !new_is_better)
+ return 0;
+
+ /* The second case - replace the best with better */
+ if (old_is_group_best && new_is_better)
{
- old_is_group_best = !old->u.bgp.suppressed;
- old->u.bgp.suppressed = 1;
- int new_is_better = new && bgp_rte_better(new, old);
-
- /* The first case - replace not best with worse (or remove not best) */
- if (!old_is_group_best && !new_is_better)
- return 0;
-
- /* The second case - replace the best with better */
- if (old_is_group_best && new_is_better)
- {
- /* new is best-in-group, the see discussion below - this is
- a special variant of NBG && OBG. From OBG we can deduce
- that same_group(old_best) iff (old == old_best) */
- new->u.bgp.suppressed = 0;
- return (old == old_best);
- }
+ /* new is best-in-group, the see discussion below - this is
+ a special variant of NBG && OBG. From OBG we can deduce
+ that same_group(old_best) iff (old == old_best) */
+ new->u.bgp.suppressed = 0;
+ return (old == old_best);
}
+ }
/* The default case - find a new best-in-group route */
r = new; /* new may not be in the list */
for (s=net->routes; rte_is_valid(s); s=s->next)
if (use_deterministic_med(s) && same_group(s, lpref, lasn))
- {
- s->u.bgp.suppressed = 1;
- if (!r || bgp_rte_better(s, r))
- r = s;
- }
+ {
+ s->u.bgp.suppressed = 1;
+ if (!r || bgp_rte_better(s, r))
+ r = s;
+ }
/* Simple case - the last route in group disappears */
if (!r)
@@ -1530,377 +1811,79 @@ bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best)
return old_is_group_best;
}
-static struct adata *
-bgp_aggregator_convert_to_new(struct adata *old, struct linpool *pool)
-{
- struct adata *newa = lp_alloc(pool, sizeof(struct adata) + 8);
- newa->length = 8;
- aggregator_convert_to_new(old, newa->data);
- return newa;
-}
-
-/* Take last req_as ASNs from path old2 (in 2B format), convert to 4B format
- * and append path old4 (in 4B format).
+/*
+ * Reconstruct AS_PATH and AGGREGATOR according to RFC 6793 4.2.3
*/
-static struct adata *
-bgp_merge_as_paths(struct adata *old2, struct adata *old4, int req_as, struct linpool *pool)
-{
- byte buf[old2->length * 2];
-
- int ol = as_path_convert_to_new(old2, buf, req_as);
- int nl = ol + (old4 ? old4->length : 0);
-
- struct adata *newa = lp_alloc(pool, sizeof(struct adata) + nl);
- newa->length = nl;
- memcpy(newa->data, buf, ol);
- if (old4) memcpy(newa->data + ol, old4->data, old4->length);
-
- return newa;
-}
-
-static int
-as4_aggregator_valid(struct adata *aggr)
-{
- return aggr->length == 8;
-}
-
-
-/* Reconstruct 4B AS_PATH and AGGREGATOR according to RFC 4893 4.2.3 */
-static void
-bgp_reconstruct_4b_atts(struct bgp_proto *p, rta *a, struct linpool *pool)
-{
- eattr *p2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS_PATH));
- eattr *p4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_PATH));
- eattr *a2 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AGGREGATOR));
- eattr *a4 =ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR));
- int a4_removed = 0;
-
- if (a4 && !as4_aggregator_valid(a4->u.ptr))
- {
- log(L_WARN "%s: AS4_AGGREGATOR attribute is invalid, skipping attribute", p->p.name);
- a4 = NULL;
- a4_removed = 1;
- }
-
- if (a2)
- {
- u32 a2_as = get_u16(a2->u.ptr->data);
-
- if (a4)
- {
- if (a2_as != AS_TRANS)
- {
- /* Routes were aggregated by old router and therefore AS4_PATH
- * and AS4_AGGREGATOR is invalid
- *
- * Convert AS_PATH and AGGREGATOR to 4B format and finish.
- */
-
- a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
- p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
-
- return;
- }
- else
- {
- /* Common case, use AS4_AGGREGATOR attribute */
- a2->u.ptr = a4->u.ptr;
- }
- }
- else
- {
- /* Common case, use old AGGREGATOR attribute */
- a2->u.ptr = bgp_aggregator_convert_to_new(a2->u.ptr, pool);
-
- if ((a2_as == AS_TRANS) && !a4_removed)
- log(L_WARN "%s: AGGREGATOR attribute contain AS_TRANS, but AS4_AGGREGATOR is missing", p->p.name);
- }
- }
- else
- if (a4)
- log(L_WARN "%s: AS4_AGGREGATOR attribute received, but AGGREGATOR attribute is missing", p->p.name);
-
- int p2_len = as_path_getlen_int(p2->u.ptr, 2);
- int p4_len = p4 ? validate_as4_path(p, p4->u.ptr) : -1;
-
- if (p4 && (p4_len < 0))
- log(L_WARN "%s: AS4_PATH attribute is malformed, skipping attribute", p->p.name);
-
- if ((p4_len <= 0) || (p2_len < p4_len))
- p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, NULL, AS_PATH_MAXLEN, pool);
- else
- p2->u.ptr = bgp_merge_as_paths(p2->u.ptr, p4->u.ptr, p2_len - p4_len, pool);
-}
-
static void
-bgp_remove_as4_attrs(struct bgp_proto *p, rta *a)
+bgp_process_as4_attrs(ea_list **attrs, struct linpool *pool)
{
- unsigned id1 = EA_CODE(EAP_BGP, BA_AS4_PATH);
- unsigned id2 = EA_CODE(EAP_BGP, BA_AS4_AGGREGATOR);
- ea_list **el = &(a->eattrs);
+ eattr *p2 = bgp_find_attr(*attrs, BA_AS_PATH);
+ eattr *p4 = bgp_find_attr(*attrs, BA_AS4_PATH);
+ eattr *a2 = bgp_find_attr(*attrs, BA_AGGREGATOR);
+ eattr *a4 = bgp_find_attr(*attrs, BA_AS4_AGGREGATOR);
- /* We know that ea_lists constructed in bgp_decode attrs have one attribute per ea_list struct */
- while (*el != NULL)
- {
- unsigned fid = (*el)->attrs[0].id;
-
- if ((fid == id1) || (fid == id2))
- {
- *el = (*el)->next;
- if (p->as4_session)
- log(L_WARN "%s: Unexpected AS4_* attributes received", p->p.name);
- }
- else
- el = &((*el)->next);
- }
-}
+ /* First, unset AS4_* attributes */
+ if (p4) bgp_unset_attr(attrs, pool, BA_AS4_PATH);
+ if (a4) bgp_unset_attr(attrs, pool, BA_AS4_AGGREGATOR);
-/**
- * bgp_decode_attrs - check and decode BGP attributes
- * @conn: connection
- * @attr: start of attribute block
- * @len: length of attribute block
- * @pool: linear pool to make all the allocations in
- * @mandatory: 1 iff presence of mandatory attributes has to be checked
- *
- * This function takes a BGP attribute block (a part of an Update message), checks
- * its consistency and converts it to a list of BIRD route attributes represented
- * by a &rta.
- */
-struct rta *
-bgp_decode_attrs(struct bgp_conn *conn, byte *attr, uint len, struct linpool *pool, int mandatory)
-{
- struct bgp_proto *bgp = conn->bgp;
- rta *a = lp_alloc(pool, sizeof(struct rta));
- uint flags, code, l, i, type;
- int errcode;
- byte *z, *attr_start;
- byte seen[256/8];
- ea_list *ea;
- struct adata *ad;
- int withdraw = 0;
-
- bzero(a, sizeof(rta));
- a->source = RTS_BGP;
- a->scope = SCOPE_UNIVERSE;
- a->cast = RTC_UNICAST;
- /* a->dest = RTD_ROUTER; -- set in bgp_set_next_hop() */
- a->from = bgp->cf->remote_ip;
+ /* Handle AGGREGATOR attribute */
+ if (a2 && a4)
+ {
+ u32 a2_asn = get_u32(a2->u.ptr->data);
- /* Parse the attributes */
- bzero(seen, sizeof(seen));
- DBG("BGP: Parsing attributes\n");
- while (len)
- {
- if (len < 2)
- goto malformed;
- attr_start = attr;
- flags = *attr++;
- code = *attr++;
- len -= 2;
- if (flags & BAF_EXT_LEN)
- {
- if (len < 2)
- goto malformed;
- l = get_u16(attr);
- attr += 2;
- len -= 2;
- }
- else
- {
- if (len < 1)
- goto malformed;
- l = *attr++;
- len--;
- }
- if (l > len)
- goto malformed;
- len -= l;
- z = attr;
- attr += l;
- DBG("Attr %02x %02x %d\n", code, flags, l);
- if (seen[code/8] & (1 << (code%8)))
- goto malformed;
- if (ATTR_KNOWN(code))
- {
- struct attr_desc *desc = &bgp_attr_table[code];
- if (desc->expected_length >= 0 && desc->expected_length != (int) l)
- { errcode = 5; goto err; }
- if ((desc->expected_flags ^ flags) & (BAF_OPTIONAL | BAF_TRANSITIVE))
- { errcode = 4; goto err; }
- if (!desc->allow_in_ebgp && !bgp->is_internal)
- continue;
- if (desc->validate)
- {
- errcode = desc->validate(bgp, z, l);
- if (errcode > 0)
- goto err;
- if (errcode == IGNORE)
- continue;
- if (errcode <= WITHDRAW)
- {
- log(L_WARN "%s: Attribute %s is malformed, withdrawing update",
- bgp->p.name, desc->name);
- withdraw = 1;
- }
- }
- else if (code == BA_AS_PATH)
- {
- /* Special case as it might also trim the attribute */
- if (validate_as_path(bgp, z, &l) < 0)
- { errcode = 11; goto err; }
- }
- type = desc->type;
- }
- else /* Unknown attribute */
- {
- if (!(flags & BAF_OPTIONAL))
- { errcode = 2; goto err; }
- type = EAF_TYPE_OPAQUE;
- }
-
- // Only OPTIONAL and TRANSITIVE attributes may have non-zero PARTIAL flag
- // if (!((flags & BAF_OPTIONAL) && (flags & BAF_TRANSITIVE)) && (flags & BAF_PARTIAL))
- // { errcode = 4; goto err; }
-
- seen[code/8] |= (1 << (code%8));
- ea = lp_alloc(pool, sizeof(ea_list) + sizeof(eattr));
- ea->next = a->eattrs;
- a->eattrs = ea;
- ea->flags = 0;
- ea->count = 1;
- ea->attrs[0].id = EA_CODE(EAP_BGP, code);
- ea->attrs[0].flags = flags;
- ea->attrs[0].type = type;
- if (type & EAF_EMBEDDED)
- ad = NULL;
- else
- {
- ad = lp_alloc(pool, sizeof(struct adata) + l);
- ea->attrs[0].u.ptr = ad;
- ad->length = l;
- memcpy(ad->data, z, l);
- }
- switch (type)
- {
- case EAF_TYPE_ROUTER_ID:
- case EAF_TYPE_INT:
- if (l == 1)
- ea->attrs[0].u.data = *z;
- else
- ea->attrs[0].u.data = get_u32(z);
- break;
- case EAF_TYPE_IP_ADDRESS:
- ipa_ntoh(*(ip_addr *)ad->data);
- break;
- case EAF_TYPE_INT_SET:
- case EAF_TYPE_EC_SET:
- {
- u32 *z = (u32 *) ad->data;
- for(i=0; i<ad->length/4; i++)
- z[i] = ntohl(z[i]);
- break;
- }
- }
- }
-
- if (withdraw)
- goto withdraw;
-
-#ifdef IPV6
- /* If we received MP_REACH_NLRI we should check mandatory attributes */
- if (bgp->mp_reach_len != 0)
- mandatory = 1;
-#endif
-
- /* If there is no (reachability) NLRI, we should exit now */
- if (! mandatory)
- return a;
-
- /* Check if all mandatory attributes are present */
- for(i=0; i < ARRAY_SIZE(bgp_mandatory_attrs); i++)
- {
- code = bgp_mandatory_attrs[i];
- if (!(seen[code/8] & (1 << (code%8))))
- {
- bgp_error(conn, 3, 3, &bgp_mandatory_attrs[i], 1);
- return NULL;
- }
- }
-
- /* When receiving attributes from non-AS4-aware BGP speaker,
- * we have to reconstruct 4B AS_PATH and AGGREGATOR attributes
- */
- if (! bgp->as4_session)
- bgp_reconstruct_4b_atts(bgp, a, pool);
-
- bgp_remove_as4_attrs(bgp, a);
-
- /* If the AS path attribute contains our AS, reject the routes */
- if (bgp_as_path_loopy(bgp, a))
- goto withdraw;
-
- /* Two checks for IBGP loops caused by route reflection, RFC 4456 */
- if (bgp_originator_id_loopy(bgp, a) ||
- bgp_cluster_list_loopy(bgp, a))
- goto withdraw;
-
- /* If there's no local preference, define one */
- if (!(seen[0] & (1 << BA_LOCAL_PREF)))
- bgp_attach_attr(&a->eattrs, pool, BA_LOCAL_PREF, bgp->cf->default_local_pref);
+ /* If routes were aggregated by an old router, then AS4_PATH and
+ AS4_AGGREGATOR are invalid. In that case we give up. */
+ if (a2_asn != AS_TRANS)
+ return;
- return a;
+ /* Use AS4_AGGREGATOR instead of AGGREGATOR */
+ a2->u.ptr = a4->u.ptr;
+ }
-withdraw:
- return NULL;
+ /* Handle AS_PATH attribute */
+ if (p2 && p4)
+ {
+ int p2_len = as_path_getlen(p2->u.ptr);
+ int p4_len = as_path_getlen(p4->u.ptr);
-malformed:
- bgp_error(conn, 3, 1, NULL, 0);
- return NULL;
+ /* AS_PATH is too short, give up */
+ if (p2_len < p4_len)
+ return;
-err:
- bgp_error(conn, 3, errcode, attr_start, z+l-attr_start);
- return NULL;
+ /* Merge AS_PATH and AS4_PATH */
+ as_path_cut(p2->u.ptr, p2_len - p4_len);
+ p2->u.ptr = as_path_merge(pool, p2->u.ptr, p4->u.ptr);
+ }
}
int
bgp_get_attr(eattr *a, byte *buf, int buflen)
{
uint i = EA_ID(a->id);
- struct attr_desc *d;
+ const struct bgp_attr_desc *d;
int len;
- if (ATTR_KNOWN(i))
+ if (bgp_attr_known(i))
+ {
+ d = &bgp_attr_table[i];
+ len = bsprintf(buf, "%s", d->name);
+ buf += len;
+ if (d->format)
{
- d = &bgp_attr_table[i];
- len = bsprintf(buf, "%s", d->name);
- buf += len;
- if (d->format)
- {
- *buf++ = ':';
- *buf++ = ' ';
- d->format(a, buf, buflen - len - 2);
- return GA_FULL;
- }
- return GA_NAME;
+ *buf++ = ':';
+ *buf++ = ' ';
+ d->format(a, buf, buflen - len - 2);
+ return GA_FULL;
}
+ return GA_NAME;
+ }
+
bsprintf(buf, "%02x%s", i, (a->flags & BAF_TRANSITIVE) ? " [t]" : "");
return GA_NAME;
}
void
-bgp_init_bucket_table(struct bgp_proto *p)
-{
- p->hash_size = 256;
- p->hash_limit = p->hash_size * 4;
- p->bucket_hash = mb_allocz(p->p.pool, p->hash_size * sizeof(struct bgp_bucket *));
- init_list(&p->bucket_queue);
- p->withdraw_bucket = NULL;
- // fib_init(&p->prefix_fib, p->p.pool, sizeof(struct bgp_prefix), 0, bgp_init_prefix);
-}
-
-void
bgp_get_route_info(rte *e, byte *buf, ea_list *attrs)
{
eattr *p = ea_find(attrs, EA_CODE(EAP_BGP, BA_AS_PATH));
@@ -1913,14 +1896,14 @@ bgp_get_route_info(rte *e, byte *buf, ea_list *attrs)
buf += bsprintf(buf, "-");
if (e->attrs->hostentry)
- {
- if (!rte_resolvable(e))
- buf += bsprintf(buf, "/-");
- else if (e->attrs->igp_metric >= IGP_METRIC_UNKNOWN)
- buf += bsprintf(buf, "/?");
- else
- buf += bsprintf(buf, "/%d", e->attrs->igp_metric);
- }
+ {
+ if (!rte_resolvable(e))
+ buf += bsprintf(buf, "/-");
+ else if (e->attrs->igp_metric >= IGP_METRIC_UNKNOWN)
+ buf += bsprintf(buf, "/?");
+ else
+ buf += bsprintf(buf, "/%d", e->attrs->igp_metric);
+ }
buf += bsprintf(buf, ") [");
if (p && as_path_get_last(p->u.ptr, &origas))
diff --git a/proto/bgp/bgp.c b/proto/bgp/bgp.c
index 0ae3db7b..2ca153ab 100644
--- a/proto/bgp/bgp.c
+++ b/proto/bgp/bgp.c
@@ -2,6 +2,8 @@
* BIRD -- The Border Gateway Protocol
*
* (c) 2000 Martin Mares <mj@ucw.cz>
+ * (c) 2008--2016 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2008--2016 CZ.NIC z.s.p.o.
*
* Can be freely distributed and used under the terms of the GNU GPL.
*/
@@ -9,48 +11,52 @@
/**
* DOC: Border Gateway Protocol
*
- * The BGP protocol is implemented in three parts: |bgp.c| which takes care of the
- * connection and most of the interface with BIRD core, |packets.c| handling
+ * The BGP protocol is implemented in three parts: |bgp.c| which takes care of
+ * the connection and most of the interface with BIRD core, |packets.c| handling
* both incoming and outgoing BGP packets and |attrs.c| containing functions for
* manipulation with BGP attribute lists.
*
- * As opposed to the other existing routing daemons, BIRD has a sophisticated core
- * architecture which is able to keep all the information needed by BGP in the
- * primary routing table, therefore no complex data structures like a central
- * BGP table are needed. This increases memory footprint of a BGP router with
- * many connections, but not too much and, which is more important, it makes
- * BGP much easier to implement.
+ * As opposed to the other existing routing daemons, BIRD has a sophisticated
+ * core architecture which is able to keep all the information needed by BGP in
+ * the primary routing table, therefore no complex data structures like a
+ * central BGP table are needed. This increases memory footprint of a BGP router
+ * with many connections, but not too much and, which is more important, it
+ * makes BGP much easier to implement.
*
- * Each instance of BGP (corresponding to a single BGP peer) is described by a &bgp_proto
- * structure to which are attached individual connections represented by &bgp_connection
- * (usually, there exists only one connection, but during BGP session setup, there
- * can be more of them). The connections are handled according to the BGP state machine
- * defined in the RFC with all the timers and all the parameters configurable.
+ * Each instance of BGP (corresponding to a single BGP peer) is described by a
+ * &bgp_proto structure to which are attached individual connections represented
+ * by &bgp_connection (usually, there exists only one connection, but during BGP
+ * session setup, there can be more of them). The connections are handled
+ * according to the BGP state machine defined in the RFC with all the timers and
+ * all the parameters configurable.
*
- * In incoming direction, we listen on the connection's socket and each time we receive
- * some input, we pass it to bgp_rx(). It decodes packet headers and the markers and
- * passes complete packets to bgp_rx_packet() which distributes the packet according
- * to its type.
+ * In incoming direction, we listen on the connection's socket and each time we
+ * receive some input, we pass it to bgp_rx(). It decodes packet headers and the
+ * markers and passes complete packets to bgp_rx_packet() which distributes the
+ * packet according to its type.
*
- * In outgoing direction, we gather all the routing updates and sort them to buckets
- * (&bgp_bucket) according to their attributes (we keep a hash table for fast comparison
- * of &rta's and a &fib which helps us to find if we already have another route for
- * the same destination queued for sending, so that we can replace it with the new one
- * immediately instead of sending both updates). There also exists a special bucket holding
- * all the route withdrawals which cannot be queued anywhere else as they don't have any
- * attributes. If we have any packet to send (due to either new routes or the connection
- * tracking code wanting to send a Open, Keepalive or Notification message), we call
- * bgp_schedule_packet() which sets the corresponding bit in a @packet_to_send
- * bit field in &bgp_conn and as soon as the transmit socket buffer becomes empty,
- * we call bgp_fire_tx(). It inspects state of all the packet type bits and calls
- * the corresponding bgp_create_xx() functions, eventually rescheduling the same packet
- * type if we have more data of the same type to send.
+ * In outgoing direction, we gather all the routing updates and sort them to
+ * buckets (&bgp_bucket) according to their attributes (we keep a hash table for
+ * fast comparison of &rta's and a &fib which helps us to find if we already
+ * have another route for the same destination queued for sending, so that we
+ * can replace it with the new one immediately instead of sending both
+ * updates). There also exists a special bucket holding all the route
+ * withdrawals which cannot be queued anywhere else as they don't have any
+ * attributes. If we have any packet to send (due to either new routes or the
+ * connection tracking code wanting to send a Open, Keepalive or Notification
+ * message), we call bgp_schedule_packet() which sets the corresponding bit in a
+ * @packet_to_send bit field in &bgp_conn and as soon as the transmit socket
+ * buffer becomes empty, we call bgp_fire_tx(). It inspects state of all the
+ * packet type bits and calls the corresponding bgp_create_xx() functions,
+ * eventually rescheduling the same packet type if we have more data of the same
+ * type to send.
*
- * The processing of attributes consists of two functions: bgp_decode_attrs() for checking
- * of the attribute blocks and translating them to the language of BIRD's extended attributes
- * and bgp_encode_attrs() which does the converse. Both functions are built around a
- * @bgp_attr_table array describing all important characteristics of all known attributes.
- * Unknown transitive attributes are attached to the route as %EAF_TYPE_OPAQUE byte streams.
+ * The processing of attributes consists of two functions: bgp_decode_attrs()
+ * for checking of the attribute blocks and translating them to the language of
+ * BIRD's extended attributes and bgp_encode_attrs() which does the
+ * converse. Both functions are built around a @bgp_attr_table array describing
+ * all important characteristics of all known attributes. Unknown transitive
+ * attributes are attached to the route as %EAF_TYPE_OPAQUE byte streams.
*
* BGP protocol implements graceful restart in both restarting (local restart)
* and receiving (neighbor restart) roles. The first is handled mostly by the
@@ -80,70 +86,143 @@
struct linpool *bgp_linpool; /* Global temporary pool */
-static sock *bgp_listen_sk; /* Global listening socket */
-static int bgp_counter; /* Number of protocol instances using the listening socket */
+static list bgp_sockets; /* Global list of listening sockets */
+
-static void bgp_close(struct bgp_proto *p, int apply_md5);
static void bgp_connect(struct bgp_proto *p);
static void bgp_active(struct bgp_proto *p);
-static sock *bgp_setup_listen_sk(ip_addr addr, unsigned port, u32 flags);
static void bgp_update_bfd(struct bgp_proto *p, int use_bfd);
+static int bgp_incoming_connection(sock *sk, uint dummy UNUSED);
+static void bgp_listen_sock_err(sock *sk UNUSED, int err);
/**
* bgp_open - open a BGP instance
* @p: BGP instance
*
- * This function allocates and configures shared BGP resources.
- * Should be called as the last step during initialization
- * (when lock is acquired and neighbor is ready).
- * When error, state changed to PS_DOWN, -1 is returned and caller
- * should return immediately.
+ * This function allocates and configures shared BGP resources, mainly listening
+ * sockets. Should be called as the last step during initialization (when lock
+ * is acquired and neighbor is ready). When error, caller should change state to
+ * PS_DOWN and return immediately.
*/
static int
bgp_open(struct bgp_proto *p)
{
- struct config *cfg = p->cf->c.global;
- int errcode;
+ struct bgp_socket *bs = NULL;
+ struct iface *ifa = p->cf->strict_bind ? p->cf->iface : NULL;
+ ip_addr addr = p->cf->strict_bind ? p->cf->local_ip :
+ (ipa_is_ip4(p->cf->remote_ip) ? IPA_NONE4 : IPA_NONE6);
+ uint port = p->cf->local_port;
+
+ /* FIXME: Add some global init? */
+ if (!bgp_linpool)
+ init_list(&bgp_sockets);
- if (!bgp_listen_sk)
- bgp_listen_sk = bgp_setup_listen_sk(cfg->listen_bgp_addr, cfg->listen_bgp_port, cfg->listen_bgp_flags);
+ /* We assume that cf->iface is defined iff cf->local_ip is link-local */
- if (!bgp_listen_sk)
+ WALK_LIST(bs, bgp_sockets)
+ if (ipa_equal(bs->sk->saddr, addr) && (bs->sk->iface == ifa) && (bs->sk->sport == port))
{
- errcode = BEM_NO_SOCKET;
- goto err;
+ bs->uc++;
+ p->sock = bs;
+ return 0;
}
- if (!bgp_linpool)
- bgp_linpool = lp_new(&root_pool, 4080);
+ sock *sk = sk_new(proto_pool);
+ sk->type = SK_TCP_PASSIVE;
+ sk->ttl = 255;
+ sk->saddr = addr;
+ sk->sport = port;
+ sk->flags = 0;
+ sk->tos = IP_PREC_INTERNET_CONTROL;
+ sk->rbsize = BGP_RX_BUFFER_SIZE;
+ sk->tbsize = BGP_TX_BUFFER_SIZE;
+ sk->rx_hook = bgp_incoming_connection;
+ sk->err_hook = bgp_listen_sock_err;
+
+ if (sk_open(sk) < 0)
+ goto err;
- bgp_counter++;
+ bs = mb_allocz(proto_pool, sizeof(struct bgp_socket));
+ bs->sk = sk;
+ bs->uc = 1;
+ p->sock = bs;
- if (p->cf->password)
- if (sk_set_md5_auth(bgp_listen_sk, p->cf->source_addr, p->cf->remote_ip,
- p->cf->iface, p->cf->password, p->cf->setkey) < 0)
- {
- sk_log_error(bgp_listen_sk, p->p.name);
- bgp_close(p, 0);
- errcode = BEM_INVALID_MD5;
- goto err;
- }
+ add_tail(&bgp_sockets, &bs->n);
+
+ if (!bgp_linpool)
+ bgp_linpool = lp_new(proto_pool, 4080);
return 0;
err:
- p->p.disabled = 1;
- bgp_store_error(p, NULL, BE_MISC, errcode);
- proto_notify_state(&p->p, PS_DOWN);
+ sk_log_error(sk, p->p.name);
+ log(L_ERR "%s: Cannot open listening socket", p->p.name);
+ rfree(sk);
return -1;
}
+/**
+ * bgp_close - close a BGP instance
+ * @p: BGP instance
+ *
+ * This function frees and deconfigures shared BGP resources.
+ */
+static void
+bgp_close(struct bgp_proto *p)
+{
+ struct bgp_socket *bs = p->sock;
+
+ ASSERT(bs && bs->uc);
+
+ if (--bs->uc)
+ return;
+
+ rfree(bs->sk);
+ rem_node(&bs->n);
+ mb_free(bs);
+
+ if (!EMPTY_LIST(bgp_sockets))
+ return;
+
+ rfree(bgp_linpool);
+ bgp_linpool = NULL;
+}
+
+static inline int
+bgp_setup_auth(struct bgp_proto *p, int enable)
+{
+ if (p->cf->password)
+ {
+ int rv = sk_set_md5_auth(p->sock->sk,
+ p->cf->local_ip, p->cf->remote_ip, p->cf->iface,
+ enable ? p->cf->password : NULL, p->cf->setkey);
+
+ if (rv < 0)
+ sk_log_error(p->sock->sk, p->p.name);
+
+ return rv;
+ }
+ else
+ return 0;
+}
+
+static inline struct bgp_channel *
+bgp_find_channel(struct bgp_proto *p, u32 afi)
+{
+ struct bgp_channel *c;
+ WALK_LIST(c, p->p.channels)
+ if (c->afi == afi)
+ return c;
+
+ return NULL;
+}
+
static void
bgp_startup(struct bgp_proto *p)
{
BGP_TRACE(D_EVENTS, "Started");
- p->start_state = p->cf->capabilities ? BSS_CONNECT : BSS_CONNECT_NOCAP;
+ p->start_state = BSS_CONNECT;
if (!p->cf->passive)
bgp_active(p);
@@ -159,50 +238,36 @@ bgp_startup_timeout(timer *t)
static void
bgp_initiate(struct bgp_proto *p)
{
- int rv = bgp_open(p);
- if (rv < 0)
- return;
+ int err_val;
+
+ if (bgp_open(p) < 0)
+ { err_val = BEM_NO_SOCKET; goto err1; }
+
+ if (bgp_setup_auth(p, 1) < 0)
+ { err_val = BEM_INVALID_MD5; goto err2; }
if (p->cf->bfd)
bgp_update_bfd(p, p->cf->bfd);
if (p->startup_delay)
- {
- p->start_state = BSS_DELAY;
- BGP_TRACE(D_EVENTS, "Startup delayed by %d seconds due to errors", p->startup_delay);
- bgp_start_timer(p->startup_timer, p->startup_delay);
- }
+ {
+ p->start_state = BSS_DELAY;
+ BGP_TRACE(D_EVENTS, "Startup delayed by %d seconds due to errors", p->startup_delay);
+ bgp_start_timer(p->startup_timer, p->startup_delay);
+ }
else
bgp_startup(p);
-}
-/**
- * bgp_close - close a BGP instance
- * @p: BGP instance
- * @apply_md5: 0 to disable unsetting MD5 auth
- *
- * This function frees and deconfigures shared BGP resources.
- * @apply_md5 is set to 0 when bgp_close is called as a cleanup
- * from failed bgp_open().
- */
-static void
-bgp_close(struct bgp_proto *p, int apply_md5)
-{
- ASSERT(bgp_counter);
- bgp_counter--;
+ return;
- if (p->cf->password && apply_md5)
- if (sk_set_md5_auth(bgp_listen_sk, p->cf->source_addr, p->cf->remote_ip,
- p->cf->iface, NULL, p->cf->setkey) < 0)
- sk_log_error(bgp_listen_sk, p->p.name);
+err2:
+ bgp_close(p);
+err1:
+ p->p.disabled = 1;
+ bgp_store_error(p, NULL, BE_MISC, err_val);
+ proto_notify_state(&p->p, PS_DOWN);
- if (!bgp_counter)
- {
- rfree(bgp_listen_sk);
- bgp_listen_sk = NULL;
- rfree(bgp_linpool);
- bgp_linpool = NULL;
- }
+ return;
}
/**
@@ -210,19 +275,19 @@ bgp_close(struct bgp_proto *p, int apply_md5)
* @t: timer
* @value: time to fire (0 to disable the timer)
*
- * This functions calls tm_start() on @t with time @value and the
- * amount of randomization suggested by the BGP standard. Please use
- * it for all BGP timers.
+ * This functions calls tm_start() on @t with time @value and the amount of
+ * randomization suggested by the BGP standard. Please use it for all BGP
+ * timers.
*/
void
bgp_start_timer(timer *t, int value)
{
if (value)
- {
- /* The randomization procedure is specified in RFC 1771: 9.2.3.3 */
- t->randomize = value / 4;
- tm_start(t, value - t->randomize);
- }
+ {
+ /* The randomization procedure is specified in RFC 1771: 9.2.3.3 */
+ t->randomize = value / 4;
+ tm_start(t, value - t->randomize);
+ }
else
tm_stop(t);
}
@@ -231,8 +296,8 @@ bgp_start_timer(timer *t, int value)
* bgp_close_conn - close a BGP connection
* @conn: connection to close
*
- * This function takes a connection described by the &bgp_conn structure,
- * closes its socket and frees all resources associated with it.
+ * This function takes a connection described by the &bgp_conn structure, closes
+ * its socket and frees all resources associated with it.
*/
void
bgp_close_conn(struct bgp_conn *conn)
@@ -241,16 +306,22 @@ bgp_close_conn(struct bgp_conn *conn)
DBG("BGP: Closing connection\n");
conn->packets_to_send = 0;
- rfree(conn->connect_retry_timer);
- conn->connect_retry_timer = NULL;
+ conn->channels_to_send = 0;
+ rfree(conn->connect_timer);
+ conn->connect_timer = NULL;
rfree(conn->keepalive_timer);
conn->keepalive_timer = NULL;
rfree(conn->hold_timer);
conn->hold_timer = NULL;
- rfree(conn->sk);
- conn->sk = NULL;
rfree(conn->tx_ev);
conn->tx_ev = NULL;
+ rfree(conn->sk);
+ conn->sk = NULL;
+
+ mb_free(conn->local_caps);
+ conn->local_caps = NULL;
+ mb_free(conn->remote_caps);
+ conn->remote_caps = NULL;
}
@@ -258,9 +329,9 @@ bgp_close_conn(struct bgp_conn *conn)
* bgp_update_startup_delay - update a startup delay
* @p: BGP instance
*
- * This function updates a startup delay that is used to postpone next BGP connect.
- * It also handles disable_after_error and might stop BGP instance when error
- * happened and disable_after_error is on.
+ * This function updates a startup delay that is used to postpone next BGP
+ * connect. It also handles disable_after_error and might stop BGP instance
+ * when error happened and disable_after_error is on.
*
* It should be called when BGP protocol error happened.
*/
@@ -277,11 +348,11 @@ bgp_update_startup_delay(struct bgp_proto *p)
p->last_proto_error = now;
if (cf->disable_after_error)
- {
- p->startup_delay = 0;
- p->p.disabled = 1;
- return;
- }
+ {
+ p->startup_delay = 0;
+ p->p.disabled = 1;
+ return;
+ }
if (!p->startup_delay)
p->startup_delay = cf->error_delay_time_min;
@@ -290,32 +361,38 @@ bgp_update_startup_delay(struct bgp_proto *p)
}
static void
-bgp_graceful_close_conn(struct bgp_conn *conn, unsigned subcode)
+bgp_graceful_close_conn(struct bgp_conn *conn, uint subcode)
{
switch (conn->state)
- {
- case BS_IDLE:
- case BS_CLOSE:
- return;
- case BS_CONNECT:
- case BS_ACTIVE:
- bgp_conn_enter_idle_state(conn);
- return;
- case BS_OPENSENT:
- case BS_OPENCONFIRM:
- case BS_ESTABLISHED:
- bgp_error(conn, 6, subcode, NULL, 0);
- return;
- default:
- bug("bgp_graceful_close_conn: Unknown state %d", conn->state);
- }
+ {
+ case BS_IDLE:
+ case BS_CLOSE:
+ return;
+
+ case BS_CONNECT:
+ case BS_ACTIVE:
+ bgp_conn_enter_idle_state(conn);
+ return;
+
+ case BS_OPENSENT:
+ case BS_OPENCONFIRM:
+ case BS_ESTABLISHED:
+ bgp_error(conn, 6, subcode, NULL, 0);
+ return;
+
+ default:
+ bug("bgp_graceful_close_conn: Unknown state %d", conn->state);
+ }
}
static void
bgp_down(struct bgp_proto *p)
{
if (p->start_state > BSS_PREPARE)
- bgp_close(p, 1);
+ {
+ bgp_setup_auth(p, 0);
+ bgp_close(p);
+ }
BGP_TRACE(D_EVENTS, "Down");
proto_notify_state(&p->p, PS_DOWN);
@@ -327,20 +404,20 @@ bgp_decision(void *vp)
struct bgp_proto *p = vp;
DBG("BGP: Decision start\n");
- if ((p->p.proto_state == PS_START)
- && (p->outgoing_conn.state == BS_IDLE)
- && (p->incoming_conn.state != BS_OPENCONFIRM)
- && (!p->cf->passive))
+ if ((p->p.proto_state == PS_START) &&
+ (p->outgoing_conn.state == BS_IDLE) &&
+ (p->incoming_conn.state != BS_OPENCONFIRM) &&
+ !p->cf->passive)
bgp_active(p);
- if ((p->p.proto_state == PS_STOP)
- && (p->outgoing_conn.state == BS_IDLE)
- && (p->incoming_conn.state == BS_IDLE))
+ if ((p->p.proto_state == PS_STOP) &&
+ (p->outgoing_conn.state == BS_IDLE) &&
+ (p->incoming_conn.state == BS_IDLE))
bgp_down(p);
}
void
-bgp_stop(struct bgp_proto *p, unsigned subcode)
+bgp_stop(struct bgp_proto *p, uint subcode)
{
proto_notify_state(&p->p, PS_STOP);
bgp_graceful_close_conn(&p->outgoing_conn, subcode);
@@ -349,7 +426,7 @@ bgp_stop(struct bgp_proto *p, unsigned subcode)
}
static inline void
-bgp_conn_set_state(struct bgp_conn *conn, unsigned new_state)
+bgp_conn_set_state(struct bgp_conn *conn, uint new_state)
{
if (conn->bgp->p.mrtdump & MD_STATES)
mrt_dump_bgp_state_change(conn, conn->state, new_state);
@@ -364,13 +441,17 @@ bgp_conn_enter_openconfirm_state(struct bgp_conn *conn)
bgp_conn_set_state(conn, BS_OPENCONFIRM);
}
+static const struct bgp_af_caps dummy_af_caps = { };
+
void
bgp_conn_enter_established_state(struct bgp_conn *conn)
{
struct bgp_proto *p = conn->bgp;
+ struct bgp_caps *local = conn->local_caps;
+ struct bgp_caps *peer = conn->remote_caps;
+ struct bgp_channel *c;
BGP_TRACE(D_EVENTS, "BGP session established");
- DBG("BGP: UP!!!\n");
/* For multi-hop BGP sessions */
if (ipa_zero(p->source_addr))
@@ -381,30 +462,87 @@ bgp_conn_enter_established_state(struct bgp_conn *conn)
p->conn = conn;
p->last_error_class = 0;
p->last_error_code = 0;
- p->feed_state = BFS_NONE;
- p->load_state = BFS_NONE;
- bgp_init_bucket_table(p);
- bgp_init_prefix_table(p, 8);
- int peer_gr_ready = conn->peer_gr_aware && !(conn->peer_gr_flags & BGP_GRF_RESTART);
+ p->as4_session = conn->as4_session;
+
+ p->route_refresh = peer->route_refresh;
+ p->enhanced_refresh = local->enhanced_refresh && peer->enhanced_refresh;
- if (p->p.gr_recovery && !peer_gr_ready)
- proto_graceful_restart_unlock(&p->p);
+ /* Whether we may handle possible GR of peer (it has some AF GR-able) */
+ p->gr_ready = 0; /* Updated later */
- if (p->p.gr_recovery && (p->cf->gr_mode == BGP_GR_ABLE) && peer_gr_ready)
- p->p.gr_wait = 1;
+ /* Whether peer is ready to handle our GR recovery */
+ int peer_gr_ready = peer->gr_aware && !(peer->gr_flags & BGP_GRF_RESTART);
- if (p->gr_active)
+ if (p->gr_active_num)
tm_stop(p->gr_timer);
- if (p->gr_active && (!conn->peer_gr_able || !(conn->peer_gr_aflags & BGP_GRF_FORWARDING)))
- bgp_graceful_restart_done(p);
+ /* Number of active channels */
+ int num = 0;
+
+ WALK_LIST(c, p->p.channels)
+ {
+ const struct bgp_af_caps *loc = bgp_find_af_caps(local, c->afi);
+ const struct bgp_af_caps *rem = bgp_find_af_caps(peer, c->afi);
+
+ /* Ignore AFIs that were not announced in multiprotocol capability */
+ if (!loc || !loc->ready)
+ loc = &dummy_af_caps;
+
+ if (!rem || !rem->ready)
+ rem = &dummy_af_caps;
+
+ int active = loc->ready && rem->ready;
+ c->c.disabled = !active;
+ c->c.reloadable = p->route_refresh;
+
+ c->index = active ? num++ : 0;
+
+ c->feed_state = BFS_NONE;
+ c->load_state = BFS_NONE;
+
+ /* Channels where peer may do GR */
+ c->gr_ready = active && local->gr_aware && rem->gr_able;
+ p->gr_ready = p->gr_ready || c->gr_ready;
- /* GR capability implies that neighbor will send End-of-RIB */
- if (conn->peer_gr_aware)
- p->load_state = BFS_LOADING;
+ /* Channels not able to recover gracefully */
+ if (p->p.gr_recovery && (!active || !peer_gr_ready))
+ channel_graceful_restart_unlock(&c->c);
- /* proto_notify_state() will likely call bgp_feed_begin(), setting p->feed_state */
+ /* Channels waiting for local convergence */
+ if (p->p.gr_recovery && loc->gr_able && peer_gr_ready)
+ c->c.gr_wait = 1;
+
+ /* Channels where peer is not able to recover gracefully */
+ if (c->gr_active && ! (c->gr_ready && (rem->gr_af_flags & BGP_GRF_FORWARDING)))
+ bgp_graceful_restart_done(c);
+
+ /* GR capability implies that neighbor will send End-of-RIB */
+ if (peer->gr_aware)
+ c->load_state = BFS_LOADING;
+
+ c->add_path_rx = (loc->add_path & BGP_ADD_PATH_RX) && (rem->add_path & BGP_ADD_PATH_TX);
+ c->add_path_tx = (loc->add_path & BGP_ADD_PATH_TX) && (rem->add_path & BGP_ADD_PATH_RX);
+
+ // XXXX reset back to non-ANY?
+ if (c->add_path_tx)
+ c->c.ra_mode = RA_ANY;
+ }
+
+ p->afi_map = mb_alloc(p->p.pool, num * sizeof(u32));
+ p->channel_map = mb_alloc(p->p.pool, num * sizeof(void *));
+ p->channel_count = num;
+
+ WALK_LIST(c, p->p.channels)
+ {
+ if (c->c.disabled)
+ continue;
+
+ p->afi_map[c->index] = c->afi;
+ p->channel_map[c->index] = c;
+ }
+
+ /* proto_notify_state() will likely call bgp_feed_begin(), setting c->feed_state */
bgp_conn_set_state(conn, BS_ESTABLISHED);
proto_notify_state(&p->p, PS_UP);
@@ -468,34 +606,57 @@ bgp_handle_graceful_restart(struct bgp_proto *p)
ASSERT(p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready);
BGP_TRACE(D_EVENTS, "Neighbor graceful restart detected%s",
- p->gr_active ? " - already pending" : "");
- proto_notify_state(&p->p, PS_START);
+ p->gr_active_num ? " - already pending" : "");
+
+ p->gr_active_num = 0;
- if (p->gr_active)
- rt_refresh_end(p->p.main_ahook->table, p->p.main_ahook);
+ struct bgp_channel *c;
+ WALK_LIST(c, p->p.channels)
+ {
+ if (c->gr_ready)
+ {
+ if (c->gr_active)
+ rt_refresh_end(c->c.table, &c->c);
- p->gr_active = 1;
- bgp_start_timer(p->gr_timer, p->conn->peer_gr_time);
- rt_refresh_begin(p->p.main_ahook->table, p->p.main_ahook);
+ c->gr_active = 1;
+ p->gr_active_num++;
+ rt_refresh_begin(c->c.table, &c->c);
+ }
+ else
+ {
+ /* Just flush the routes */
+ rt_refresh_begin(c->c.table, &c->c);
+ rt_refresh_end(c->c.table, &c->c);
+ }
+ }
+
+ proto_notify_state(&p->p, PS_START);
+ bgp_start_timer(p->gr_timer, p->conn->local_caps->gr_time);
}
/**
* bgp_graceful_restart_done - finish active BGP graceful restart
- * @p: BGP instance
+ * @c: BGP channel
*
* This function is called when the active BGP graceful restart of the neighbor
- * should be finished - either successfully (the neighbor sends all paths and
- * reports end-of-RIB on the new session) or unsuccessfully (the neighbor does
- * not support BGP graceful restart on the new session). The function ends
- * routing table refresh cycle and stops BGP restart timer.
+ * should be finished for channel @c - either successfully (the neighbor sends
+ * all paths and reports end-of-RIB for given AFI/SAFI on the new session) or
+ * unsuccessfully (the neighbor does not support BGP graceful restart on the new
+ * session). The function ends the routing table refresh cycle.
*/
void
-bgp_graceful_restart_done(struct bgp_proto *p)
+bgp_graceful_restart_done(struct bgp_channel *c)
{
- BGP_TRACE(D_EVENTS, "Neighbor graceful restart done");
- p->gr_active = 0;
- tm_stop(p->gr_timer);
- rt_refresh_end(p->p.main_ahook->table, p->p.main_ahook);
+ struct bgp_proto *p = (void *) c->c.proto;
+
+ ASSERT(c->gr_active);
+ c->gr_active = 0;
+ p->gr_active_num--;
+
+ if (!p->gr_active_num)
+ BGP_TRACE(D_EVENTS, "Neighbor graceful restart done");
+
+ rt_refresh_end(c->c.table, &c->c);
}
/**
@@ -519,7 +680,7 @@ bgp_graceful_restart_timeout(timer *t)
/**
* bgp_refresh_begin - start incoming enhanced route refresh sequence
- * @p: BGP instance
+ * @c: BGP channel
*
* This function is called when an incoming enhanced route refresh sequence is
* started by the neighbor, demarcated by the BoRR packet. The function updates
@@ -528,18 +689,20 @@ bgp_graceful_restart_timeout(timer *t)
* ensure that these two sequences do not overlap.
*/
void
-bgp_refresh_begin(struct bgp_proto *p)
+bgp_refresh_begin(struct bgp_channel *c)
{
- if (p->load_state == BFS_LOADING)
- { log(L_WARN "%s: BEGIN-OF-RR received before END-OF-RIB, ignoring", p->p.name); return; }
+ struct bgp_proto *p = (void *) c->c.proto;
+
+ if (c->load_state == BFS_LOADING)
+ { log(L_WARN "%s: BEGIN-OF-RR received before END-OF-RIB, ignoring", p->p.name); return; }
- p->load_state = BFS_REFRESHING;
- rt_refresh_begin(p->p.main_ahook->table, p->p.main_ahook);
+ c->load_state = BFS_REFRESHING;
+ rt_refresh_begin(c->c.table, &c->c);
}
/**
* bgp_refresh_end - finish incoming enhanced route refresh sequence
- * @p: BGP instance
+ * @c: BGP channel
*
* This function is called when an incoming enhanced route refresh sequence is
* finished by the neighbor, demarcated by the EoRR packet. The function updates
@@ -547,39 +710,26 @@ bgp_refresh_begin(struct bgp_proto *p)
* during the sequence are removed by the nest.
*/
void
-bgp_refresh_end(struct bgp_proto *p)
+bgp_refresh_end(struct bgp_channel *c)
{
- if (p->load_state != BFS_REFRESHING)
- { log(L_WARN "%s: END-OF-RR received without prior BEGIN-OF-RR, ignoring", p->p.name); return; }
+ struct bgp_proto *p = (void *) c->c.proto;
- p->load_state = BFS_NONE;
- rt_refresh_end(p->p.main_ahook->table, p->p.main_ahook);
+ if (c->load_state != BFS_REFRESHING)
+ { log(L_WARN "%s: END-OF-RR received without prior BEGIN-OF-RR, ignoring", p->p.name); return; }
+
+ c->load_state = BFS_NONE;
+ rt_refresh_end(c->c.table, &c->c);
}
static void
bgp_send_open(struct bgp_conn *conn)
{
- conn->start_state = conn->bgp->start_state;
-
- // Default values, possibly changed by receiving capabilities.
- conn->advertised_as = 0;
- conn->peer_refresh_support = 0;
- conn->peer_as4_support = 0;
- conn->peer_add_path = 0;
- conn->peer_enhanced_refresh_support = 0;
- conn->peer_gr_aware = 0;
- conn->peer_gr_able = 0;
- conn->peer_gr_time = 0;
- conn->peer_gr_flags = 0;
- conn->peer_gr_aflags = 0;
- conn->peer_ext_messages_support = 0;
-
DBG("BGP: Sending open\n");
conn->sk->rx_hook = bgp_rx;
conn->sk->tx_hook = bgp_tx;
- tm_stop(conn->connect_retry_timer);
- bgp_schedule_packet(conn, PKT_OPEN);
+ tm_stop(conn->connect_timer);
+ bgp_schedule_packet(conn, NULL, PKT_OPEN);
bgp_conn_set_state(conn, BS_OPENSENT);
bgp_start_timer(conn->hold_timer, conn->bgp->cf->initial_hold_time);
}
@@ -602,10 +752,10 @@ bgp_connect_timeout(timer *t)
DBG("BGP: connect_timeout\n");
if (p->p.proto_state == PS_START)
- {
- bgp_close_conn(conn);
- bgp_connect(p);
- }
+ {
+ bgp_close_conn(conn);
+ bgp_connect(p);
+ }
else
bgp_conn_enter_idle_state(conn);
}
@@ -669,7 +819,7 @@ bgp_keepalive_timeout(timer *t)
struct bgp_conn *conn = t->data;
DBG("BGP: Keepalive timer\n");
- bgp_schedule_packet(conn, PKT_KEEPALIVE);
+ bgp_schedule_packet(conn, NULL, PKT_KEEPALIVE);
/* Kick TX a bit faster */
if (ev_active(conn->tx_ev))
@@ -679,21 +829,18 @@ bgp_keepalive_timeout(timer *t)
static void
bgp_setup_conn(struct bgp_proto *p, struct bgp_conn *conn)
{
- timer *t;
-
conn->sk = NULL;
conn->bgp = p;
+
conn->packets_to_send = 0;
+ conn->channels_to_send = 0;
+ conn->last_channel = 0;
+ conn->last_channel_count = 0;
+
+ conn->connect_timer = tm_new_set(p->p.pool, bgp_connect_timeout, conn, 0, 0);
+ conn->hold_timer = tm_new_set(p->p.pool, bgp_hold_timeout, conn, 0, 0);
+ conn->keepalive_timer = tm_new_set(p->p.pool, bgp_keepalive_timeout, conn, 0, 0);
- t = conn->connect_retry_timer = tm_new(p->p.pool);
- t->hook = bgp_connect_timeout;
- t->data = conn;
- t = conn->hold_timer = tm_new(p->p.pool);
- t->hook = bgp_hold_timeout;
- t->data = conn;
- t = conn->keepalive_timer = tm_new(p->p.pool);
- t->hook = bgp_keepalive_timeout;
- t->data = conn;
conn->tx_ev = ev_new(p->p.pool);
conn->tx_ev->hook = bgp_kick_tx;
conn->tx_ev->data = conn;
@@ -717,7 +864,7 @@ bgp_active(struct bgp_proto *p)
BGP_TRACE(D_EVENTS, "Connect delayed by %d seconds", delay);
bgp_setup_conn(p, conn);
bgp_conn_set_state(conn, BS_ACTIVE);
- bgp_start_timer(conn->connect_retry_timer, delay);
+ bgp_start_timer(conn->connect_timer, delay);
}
/**
@@ -731,12 +878,11 @@ bgp_active(struct bgp_proto *p)
static void
bgp_connect(struct bgp_proto *p) /* Enter Connect state and start establishing connection */
{
- sock *s;
struct bgp_conn *conn = &p->outgoing_conn;
int hops = p->cf->multihop ? : 1;
DBG("BGP: Connecting\n");
- s = sk_new(p->p.pool);
+ sock *s = sk_new(p->p.pool);
s->type = SK_TCP_ACTIVE;
s->saddr = p->source_addr;
s->daddr = p->cf->remote_ip;
@@ -763,10 +909,10 @@ bgp_connect(struct bgp_proto *p) /* Enter Connect state and start establishing c
goto err;
DBG("BGP: Waiting for connect success\n");
- bgp_start_timer(conn->connect_retry_timer, p->cf->connect_retry_time);
+ bgp_start_timer(conn->connect_timer, p->cf->connect_retry_time);
return;
- err:
+err:
sk_log_error(s, p->p.name);
bgp_sock_err(s, 0);
return;
@@ -780,16 +926,15 @@ bgp_connect(struct bgp_proto *p) /* Enter Connect state and start establishing c
static struct bgp_proto *
bgp_find_proto(sock *sk)
{
- struct proto_config *pc;
+ struct bgp_proto *p;
- WALK_LIST(pc, config->protos)
- if ((pc->protocol == &proto_bgp) && pc->proto)
- {
- struct bgp_proto *p = (struct bgp_proto *) pc->proto;
- if (ipa_equal(p->cf->remote_ip, sk->daddr) &&
- (!ipa_is_link_local(sk->daddr) || (p->cf->iface == sk->iface)))
- return p;
- }
+ WALK_LIST(p, proto_list)
+ if ((p->p.proto == &proto_bgp) &&
+ ipa_equal(p->cf->remote_ip, sk->daddr) &&
+ (!ipa_is_link_local(sk->daddr) || (p->cf->iface == sk->iface)) &&
+ (ipa_zero(p->cf->local_ip) || ipa_equal(p->cf->local_ip, sk->saddr)) &&
+ (p->cf->local_port == sk->sport))
+ return p;
return NULL;
}
@@ -807,7 +952,7 @@ bgp_find_proto(sock *sk)
* closes the new connection by sending a Notification message.
*/
static int
-bgp_incoming_connection(sock *sk, int dummy UNUSED)
+bgp_incoming_connection(sock *sk, uint dummy UNUSED)
{
struct bgp_proto *p;
int acc, hops;
@@ -815,12 +960,12 @@ bgp_incoming_connection(sock *sk, int dummy UNUSED)
DBG("BGP: Incoming connection from %I port %d\n", sk->daddr, sk->dport);
p = bgp_find_proto(sk);
if (!p)
- {
- log(L_WARN "BGP: Unexpected connect from unknown address %I%J (port %d)",
- sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL, sk->dport);
- rfree(sk);
- return 0;
- }
+ {
+ log(L_WARN "BGP: Unexpected connect from unknown address %I%J (port %d)",
+ sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL, sk->dport);
+ rfree(sk);
+ return 0;
+ }
/*
* BIRD should keep multiple incoming connections in OpenSent state (for
@@ -833,26 +978,26 @@ bgp_incoming_connection(sock *sk, int dummy UNUSED)
(p->start_state >= BSS_CONNECT) && (!p->incoming_conn.sk);
if (p->conn && (p->conn->state == BS_ESTABLISHED) && p->gr_ready)
- {
- bgp_store_error(p, NULL, BE_MISC, BEM_GRACEFUL_RESTART);
- bgp_handle_graceful_restart(p);
- bgp_conn_enter_idle_state(p->conn);
- acc = 1;
-
- /* There might be separate incoming connection in OpenSent state */
- if (p->incoming_conn.state > BS_ACTIVE)
- bgp_close_conn(&p->incoming_conn);
- }
+ {
+ bgp_store_error(p, NULL, BE_MISC, BEM_GRACEFUL_RESTART);
+ bgp_handle_graceful_restart(p);
+ bgp_conn_enter_idle_state(p->conn);
+ acc = 1;
+
+ /* There might be separate incoming connection in OpenSent state */
+ if (p->incoming_conn.state > BS_ACTIVE)
+ bgp_close_conn(&p->incoming_conn);
+ }
BGP_TRACE(D_EVENTS, "Incoming connection from %I%J (port %d) %s",
sk->daddr, ipa_is_link_local(sk->daddr) ? sk->iface : NULL,
sk->dport, acc ? "accepted" : "rejected");
if (!acc)
- {
- rfree(sk);
- return 0;
- }
+ {
+ rfree(sk);
+ return 0;
+ }
hops = p->cf->multihop ? : 1;
@@ -864,11 +1009,11 @@ bgp_incoming_connection(sock *sk, int dummy UNUSED)
goto err;
if (p->cf->enable_extended_messages)
- {
- sk->rbsize = BGP_RX_BUFFER_EXT_SIZE;
- sk->tbsize = BGP_TX_BUFFER_EXT_SIZE;
- sk_reallocate(sk);
- }
+ {
+ sk->rbsize = BGP_RX_BUFFER_EXT_SIZE;
+ sk->tbsize = BGP_TX_BUFFER_EXT_SIZE;
+ sk_reallocate(sk);
+ }
bgp_setup_conn(p, &p->incoming_conn);
bgp_setup_sk(&p->incoming_conn, sk);
@@ -891,34 +1036,6 @@ bgp_listen_sock_err(sock *sk UNUSED, int err)
log(L_ERR "BGP: Error on listening socket: %M", err);
}
-static sock *
-bgp_setup_listen_sk(ip_addr addr, unsigned port, u32 flags)
-{
- sock *s = sk_new(&root_pool);
- DBG("BGP: Creating listening socket\n");
- s->type = SK_TCP_PASSIVE;
- s->ttl = 255;
- s->saddr = addr;
- s->sport = port ? port : BGP_PORT;
- s->flags = flags ? 0 : SKF_V6ONLY;
- s->tos = IP_PREC_INTERNET_CONTROL;
- s->rbsize = BGP_RX_BUFFER_SIZE;
- s->tbsize = BGP_TX_BUFFER_SIZE;
- s->rx_hook = bgp_incoming_connection;
- s->err_hook = bgp_listen_sock_err;
-
- if (sk_open(s) < 0)
- goto err;
-
- return s;
-
- err:
- sk_log_error(s, "BGP");
- log(L_ERR "BGP: Cannot open listening socket");
- rfree(s);
- return NULL;
-}
-
static void
bgp_start_neighbor(struct bgp_proto *p)
{
@@ -927,23 +1044,22 @@ bgp_start_neighbor(struct bgp_proto *p)
if (ipa_zero(p->source_addr))
p->source_addr = p->neigh->ifa->ip;
-#ifdef IPV6
+ if (ipa_is_link_local(p->source_addr))
+ p->link_addr = p->source_addr;
+ else
{
+ /* Find some link-local address for given iface */
struct ifa *a;
- p->local_link = IPA_NONE;
+ p->link_addr = IPA_NONE;
WALK_LIST(a, p->neigh->iface->addrs)
if (a->scope == SCOPE_LINK)
- {
- p->local_link = a->ip;
- break;
- }
-
- if (! ipa_nonzero(p->local_link))
- log(L_WARN "%s: Missing link local address on interface %s", p->p.name, p->neigh->iface->name);
+ {
+ p->link_addr = a->ip;
+ break;
+ }
- DBG("BGP: Selected link-level address %I\n", p->local_link);
+ DBG("%s: Selected link-local address %I\n", p->p.name, p->link_addr);
}
-#endif
bgp_initiate(p);
}
@@ -963,34 +1079,34 @@ bgp_neigh_notify(neighbor *n)
int prepare = (ps == PS_START) && (p->start_state == BSS_PREPARE);
if (n->scope <= 0)
+ {
+ if (!prepare)
{
- if (!prepare)
- {
- BGP_TRACE(D_EVENTS, "Neighbor lost");
- bgp_store_error(p, NULL, BE_MISC, BEM_NEIGHBOR_LOST);
- /* Perhaps also run bgp_update_startup_delay(p)? */
- bgp_stop(p, 0);
- }
+ BGP_TRACE(D_EVENTS, "Neighbor lost");
+ bgp_store_error(p, NULL, BE_MISC, BEM_NEIGHBOR_LOST);
+ /* Perhaps also run bgp_update_startup_delay(p)? */
+ bgp_stop(p, 0);
}
+ }
else if (p->cf->check_link && !(n->iface->flags & IF_LINK_UP))
+ {
+ if (!prepare)
{
- if (!prepare)
- {
- BGP_TRACE(D_EVENTS, "Link down");
- bgp_store_error(p, NULL, BE_MISC, BEM_LINK_DOWN);
- if (ps == PS_UP)
- bgp_update_startup_delay(p);
- bgp_stop(p, 0);
- }
+ BGP_TRACE(D_EVENTS, "Link down");
+ bgp_store_error(p, NULL, BE_MISC, BEM_LINK_DOWN);
+ if (ps == PS_UP)
+ bgp_update_startup_delay(p);
+ bgp_stop(p, 0);
}
+ }
else
+ {
+ if (prepare)
{
- if (prepare)
- {
- BGP_TRACE(D_EVENTS, "Neighbor ready");
- bgp_start_neighbor(p);
- }
+ BGP_TRACE(D_EVENTS, "Neighbor ready");
+ bgp_start_neighbor(p);
}
+ }
}
static void
@@ -1000,13 +1116,13 @@ bgp_bfd_notify(struct bfd_request *req)
int ps = p->p.proto_state;
if (req->down && ((ps == PS_START) || (ps == PS_UP)))
- {
- BGP_TRACE(D_EVENTS, "BFD session down");
- bgp_store_error(p, NULL, BE_MISC, BEM_BFD_DOWN);
- if (ps == PS_UP)
- bgp_update_startup_delay(p);
- bgp_stop(p, 0);
- }
+ {
+ BGP_TRACE(D_EVENTS, "BFD session down");
+ bgp_store_error(p, NULL, BE_MISC, BEM_BFD_DOWN);
+ if (ps == PS_UP)
+ bgp_update_startup_delay(p);
+ bgp_stop(p, 0);
+ }
}
static void
@@ -1018,71 +1134,72 @@ bgp_update_bfd(struct bgp_proto *p, int use_bfd)
bgp_bfd_notify, p);
if (!use_bfd && p->bfd_req)
- {
- rfree(p->bfd_req);
- p->bfd_req = NULL;
- }
+ {
+ rfree(p->bfd_req);
+ p->bfd_req = NULL;
+ }
}
-static int
-bgp_reload_routes(struct proto *P)
+static void
+bgp_reload_routes(struct channel *C)
{
- struct bgp_proto *p = (struct bgp_proto *) P;
- if (!p->conn || !p->conn->peer_refresh_support)
- return 0;
+ struct bgp_proto *p = (void *) C->proto;
+ struct bgp_channel *c = (void *) C;
- bgp_schedule_packet(p->conn, PKT_ROUTE_REFRESH);
- return 1;
+ ASSERT(p->conn && p->route_refresh);
+
+ bgp_schedule_packet(p->conn, c, PKT_ROUTE_REFRESH);
}
static void
-bgp_feed_begin(struct proto *P, int initial)
+bgp_feed_begin(struct channel *C, int initial)
{
- struct bgp_proto *p = (struct bgp_proto *) P;
+ struct bgp_proto *p = (void *) C->proto;
+ struct bgp_channel *c = (void *) C;
/* This should not happen */
if (!p->conn)
return;
if (initial && p->cf->gr_mode)
- p->feed_state = BFS_LOADING;
+ c->feed_state = BFS_LOADING;
/* It is refeed and both sides support enhanced route refresh */
- if (!initial && p->cf->enable_refresh &&
- p->conn->peer_enhanced_refresh_support)
- {
- /* BoRR must not be sent before End-of-RIB */
- if (p->feed_state == BFS_LOADING || p->feed_state == BFS_LOADED)
- return;
+ if (!initial && p->enhanced_refresh)
+ {
+ /* BoRR must not be sent before End-of-RIB */
+ if (c->feed_state == BFS_LOADING || c->feed_state == BFS_LOADED)
+ return;
- p->feed_state = BFS_REFRESHING;
- bgp_schedule_packet(p->conn, PKT_BEGIN_REFRESH);
- }
+ c->feed_state = BFS_REFRESHING;
+ bgp_schedule_packet(p->conn, c, PKT_BEGIN_REFRESH);
+ }
}
static void
-bgp_feed_end(struct proto *P)
+bgp_feed_end(struct channel *C)
{
- struct bgp_proto *p = (struct bgp_proto *) P;
+ struct bgp_proto *p = (void *) C->proto;
+ struct bgp_channel *c = (void *) C;
/* This should not happen */
if (!p->conn)
return;
/* Non-demarcated feed ended, nothing to do */
- if (p->feed_state == BFS_NONE)
+ if (c->feed_state == BFS_NONE)
return;
/* Schedule End-of-RIB packet */
- if (p->feed_state == BFS_LOADING)
- p->feed_state = BFS_LOADED;
+ if (c->feed_state == BFS_LOADING)
+ c->feed_state = BFS_LOADED;
/* Schedule EoRR packet */
- if (p->feed_state == BFS_REFRESHING)
- p->feed_state = BFS_REFRESHED;
+ if (c->feed_state == BFS_REFRESHING)
+ c->feed_state = BFS_REFRESHED;
/* Kick TX hook */
- bgp_schedule_packet(p->conn, PKT_UPDATE);
+ bgp_schedule_packet(p->conn, c, PKT_UPDATE);
}
@@ -1093,30 +1210,30 @@ bgp_start_locked(struct object_lock *lock)
struct bgp_config *cf = p->cf;
if (p->p.proto_state != PS_START)
- {
- DBG("BGP: Got lock in different state %d\n", p->p.proto_state);
- return;
- }
+ {
+ DBG("BGP: Got lock in different state %d\n", p->p.proto_state);
+ return;
+ }
DBG("BGP: Got lock\n");
if (cf->multihop)
- {
- /* Multi-hop sessions do not use neighbor entries */
- bgp_initiate(p);
- return;
- }
+ {
+ /* Multi-hop sessions do not use neighbor entries */
+ bgp_initiate(p);
+ return;
+ }
neighbor *n = neigh_find2(&p->p, &cf->remote_ip, cf->iface, NEF_STICKY);
if (!n)
- {
- log(L_ERR "%s: Invalid remote address %I%J", p->p.name, cf->remote_ip, cf->iface);
- /* As we do not start yet, we can just disable protocol */
- p->p.disabled = 1;
- bgp_store_error(p, NULL, BE_MISC, BEM_INVALID_NEXT_HOP);
- proto_notify_state(&p->p, PS_DOWN);
- return;
- }
+ {
+ log(L_ERR "%s: Invalid remote address %I%J", p->p.name, cf->remote_ip, cf->iface);
+ /* As we do not start yet, we can just disable protocol */
+ p->p.disabled = 1;
+ bgp_store_error(p, NULL, BE_MISC, BEM_INVALID_NEXT_HOP);
+ proto_notify_state(&p->p, PS_DOWN);
+ return;
+ }
p->neigh = n;
@@ -1141,9 +1258,7 @@ bgp_start(struct proto *P)
p->neigh = NULL;
p->bfd_req = NULL;
p->gr_ready = 0;
- p->gr_active = 0;
-
- rt_lock_table(p->igp_table);
+ p->gr_active_num = 0;
p->event = ev_new(p->p.pool);
p->event->hook = bgp_decision;
@@ -1162,15 +1277,19 @@ bgp_start(struct proto *P)
p->rr_cluster_id = p->cf->rr_cluster_id ? p->cf->rr_cluster_id : p->local_id;
p->remote_id = 0;
- p->source_addr = p->cf->source_addr;
+ p->source_addr = p->cf->local_ip;
+ /* XXXX */
if (p->p.gr_recovery && p->cf->gr_mode)
- proto_graceful_restart_lock(P);
+ {
+ struct bgp_channel *c;
+ WALK_LIST(c, p->p.channels)
+ channel_graceful_restart_lock(&c->c);
+ }
/*
- * Before attempting to create the connection, we need to lock the
- * port, so that are sure we're the only instance attempting to talk
- * with that neighbor.
+ * Before attempting to create the connection, we need to lock the port,
+ * so that we are the only instance attempting to talk with that neighbor.
*/
lock = p->lock = olock_new(P->pool);
@@ -1191,78 +1310,64 @@ static int
bgp_shutdown(struct proto *P)
{
struct bgp_proto *p = (struct bgp_proto *) P;
- unsigned subcode = 0;
+ uint subcode = 0;
BGP_TRACE(D_EVENTS, "Shutdown requested");
switch (P->down_code)
- {
- case PDC_CF_REMOVE:
- case PDC_CF_DISABLE:
- subcode = 3; // Errcode 6, 3 - peer de-configured
- break;
-
- case PDC_CF_RESTART:
- subcode = 6; // Errcode 6, 6 - other configuration change
- break;
-
- case PDC_CMD_DISABLE:
- case PDC_CMD_SHUTDOWN:
- subcode = 2; // Errcode 6, 2 - administrative shutdown
- break;
-
- case PDC_CMD_RESTART:
- subcode = 4; // Errcode 6, 4 - administrative reset
- break;
-
- case PDC_RX_LIMIT_HIT:
- case PDC_IN_LIMIT_HIT:
- subcode = 1; // Errcode 6, 1 - max number of prefixes reached
- /* log message for compatibility */
- log(L_WARN "%s: Route limit exceeded, shutting down", p->p.name);
- goto limit;
-
- case PDC_OUT_LIMIT_HIT:
- subcode = proto_restart ? 4 : 2; // Administrative reset or shutdown
-
- limit:
- bgp_store_error(p, NULL, BE_AUTO_DOWN, BEA_ROUTE_LIMIT_EXCEEDED);
- if (proto_restart)
- bgp_update_startup_delay(p);
- else
- p->startup_delay = 0;
- goto done;
- }
+ {
+ case PDC_CF_REMOVE:
+ case PDC_CF_DISABLE:
+ subcode = 3; // Errcode 6, 3 - peer de-configured
+ break;
+
+ case PDC_CF_RESTART:
+ subcode = 6; // Errcode 6, 6 - other configuration change
+ break;
+
+ case PDC_CMD_DISABLE:
+ case PDC_CMD_SHUTDOWN:
+ subcode = 2; // Errcode 6, 2 - administrative shutdown
+ break;
+
+ case PDC_CMD_RESTART:
+ subcode = 4; // Errcode 6, 4 - administrative reset
+ break;
+
+ case PDC_RX_LIMIT_HIT:
+ case PDC_IN_LIMIT_HIT:
+ subcode = 1; // Errcode 6, 1 - max number of prefixes reached
+ /* log message for compatibility */
+ log(L_WARN "%s: Route limit exceeded, shutting down", p->p.name);
+ goto limit;
+
+ case PDC_OUT_LIMIT_HIT:
+ subcode = proto_restart ? 4 : 2; // Administrative reset or shutdown
+
+ limit:
+ bgp_store_error(p, NULL, BE_AUTO_DOWN, BEA_ROUTE_LIMIT_EXCEEDED);
+ if (proto_restart)
+ bgp_update_startup_delay(p);
+ else
+ p->startup_delay = 0;
+ goto done;
+ }
bgp_store_error(p, NULL, BE_MAN_DOWN, 0);
p->startup_delay = 0;
- done:
+done:
bgp_stop(p, subcode);
return p->p.proto_state;
}
-static void
-bgp_cleanup(struct proto *P)
-{
- struct bgp_proto *p = (struct bgp_proto *) P;
- rt_unlock_table(p->igp_table);
-}
-
-static rtable *
-get_igp_table(struct bgp_config *cf)
-{
- return cf->igp_table ? cf->igp_table->table : cf->c.table->table;
-}
-
static struct proto *
-bgp_init(struct proto_config *C)
+bgp_init(struct proto_config *CF)
{
- struct proto *P = proto_new(C, sizeof(struct bgp_proto));
- struct bgp_config *c = (struct bgp_config *) C;
+ struct proto *P = proto_new(CF);
struct bgp_proto *p = (struct bgp_proto *) P;
+ struct bgp_config *cf = (struct bgp_config *) CF;
- P->accept_ra_types = c->secondary ? RA_ACCEPTED : RA_OPTIMAL;
P->rt_notify = bgp_rt_notify;
P->import_control = bgp_import_control;
P->neigh_notify = bgp_neigh_notify;
@@ -1271,102 +1376,206 @@ bgp_init(struct proto_config *C)
P->feed_end = bgp_feed_end;
P->rte_better = bgp_rte_better;
P->rte_mergable = bgp_rte_mergable;
- P->rte_recalculate = c->deterministic_med ? bgp_rte_recalculate : NULL;
-
- p->cf = c;
- p->local_as = c->local_as;
- p->remote_as = c->remote_as;
- p->is_internal = (c->local_as == c->remote_as);
- p->rs_client = c->rs_client;
- p->rr_client = c->rr_client;
- p->igp_table = get_igp_table(c);
+ P->rte_recalculate = cf->deterministic_med ? bgp_rte_recalculate : NULL;
+
+ p->cf = cf;
+ p->local_as = cf->local_as;
+ p->remote_as = cf->remote_as;
+ p->public_as = cf->local_as;
+ p->is_internal = (cf->local_as == cf->remote_as);
+ p->is_interior = p->is_internal || cf->confederation_member;
+ p->rs_client = cf->rs_client;
+ p->rr_client = cf->rr_client;
+
+ /* Confederation ID is used for truly external peers */
+ if (cf->confederation && !p->is_interior)
+ p->public_as = cf->confederation;
+
+ /* Add all channels */
+ struct bgp_channel_config *cc;
+ WALK_LIST(cc, CF->channels)
+ proto_add_channel(P, &cc->c);
return P;
}
+static inline rtable *
+get_igp_table(struct bgp_channel_config *cf)
+{
+ return cf->igp_table ? cf->igp_table->table : cf->c.table->table;
+}
+
+static void
+bgp_channel_init(struct channel *C, struct channel_config *CF)
+{
+ struct bgp_channel *c = (void *) C;
+ struct bgp_channel_config *cf = (void *) CF;
+
+ C->ra_mode = cf->secondary ? RA_ACCEPTED : RA_OPTIMAL;
+
+ c->cf = cf;
+ c->afi = cf->afi;
+ c->desc = bgp_get_af_desc(c->afi);
+ c->igp_table = get_igp_table(cf);
+}
+
+static int
+bgp_channel_start(struct channel *C)
+{
+ struct bgp_proto *p = (void *) C->proto;
+ struct bgp_channel *c = (void *) C;
+ ip_addr src = p->source_addr;
+
+ rt_lock_table(c->igp_table);
+
+ c->pool = p->p.pool; // XXXX
+ bgp_init_bucket_table(c);
+ bgp_init_prefix_table(c);
+
+ c->next_hop_addr = c->cf->next_hop_addr;
+ c->link_addr = IPA_NONE;
+ c->packets_to_send = 0;
+
+ /* Try to use source address as next hop address */
+ if (ipa_zero(c->next_hop_addr))
+ {
+ if (bgp_channel_is_ipv4(c) && ipa_is_ip4(src))
+ c->next_hop_addr = src;
+
+ if (bgp_channel_is_ipv6(c) && ipa_is_ip6(src) && !ipa_is_link_local(src))
+ c->next_hop_addr = src;
+ }
+
+ /* Set link-local address for IPv6 single-hop BGP */
+ if (bgp_channel_is_ipv6(c) && p->neigh)
+ {
+ c->link_addr = p->link_addr;
+
+ if (ipa_zero(c->link_addr))
+ log(L_WARN "%s: Missing link-local address", p->p.name);
+ }
+
+ /* No next hop address is valid on IPv6 link-local BGP */
+ if (ipa_zero(c->next_hop_addr) && !ipa_is_link_local(src))
+ log(L_WARN "%s: Missing next hop address", p->p.name);
+
+ return 0; /* XXXX: Currently undefined */
+}
+
+static void
+bgp_channel_shutdown(struct channel *C)
+{
+ struct bgp_channel *c = (void *) C;
+
+ /* XXXX: cleanup bucket and prefix tables */
+
+ c->next_hop_addr = IPA_NONE;
+ c->link_addr = IPA_NONE;
+}
+
+static void
+bgp_channel_cleanup(struct channel *C)
+{
+ struct bgp_channel *c = (void *) C;
+
+ rt_unlock_table(c->igp_table);
+}
void
-bgp_check_config(struct bgp_config *c)
+bgp_postconfig(struct proto_config *CF)
{
- int internal = (c->local_as == c->remote_as);
+ struct bgp_config *cf = (void *) CF;
+ int internal = (cf->local_as == cf->remote_as);
/* Do not check templates at all */
- if (c->c.class == SYM_TEMPLATE)
+ if (cf->c.class == SYM_TEMPLATE)
return;
/* EBGP direct by default, IBGP multihop by default */
- if (c->multihop < 0)
- c->multihop = internal ? 64 : 0;
-
- /* Different default for gw_mode */
- if (!c->gw_mode)
- c->gw_mode = c->multihop ? GW_RECURSIVE : GW_DIRECT;
-
- /* Different default based on rs_client */
- if (!c->missing_lladdr)
- c->missing_lladdr = c->rs_client ? MLL_IGNORE : MLL_SELF;
+ if (cf->multihop < 0)
+ cf->multihop = internal ? 64 : 0;
- /* Disable after error incompatible with restart limit action */
- if (c->c.in_limit && (c->c.in_limit->action == PLA_RESTART) && c->disable_after_error)
- c->c.in_limit->action = PLA_DISABLE;
-
- if (!c->local_as)
+ if (!cf->local_as)
cf_error("Local AS number must be set");
- if (ipa_zero(c->remote_ip))
+ if (ipa_zero(cf->remote_ip))
cf_error("Neighbor must be configured");
- if (!c->remote_as)
+ if (!cf->remote_as)
cf_error("Remote AS number must be set");
// if (ipa_is_link_local(c->remote_ip) && !c->iface)
// cf_error("Link-local neighbor address requires specified interface");
- if (!ipa_is_link_local(c->remote_ip) != !c->iface)
+ if (!ipa_is_link_local(cf->remote_ip) != !cf->iface)
cf_error("Link-local address and interface scope must be used together");
- if (!(c->capabilities && c->enable_as4) && (c->remote_as > 0xFFFF))
+ if (!(cf->capabilities && cf->enable_as4) && (cf->remote_as > 0xFFFF))
cf_error("Neighbor AS number out of range (AS4 not available)");
- if (!internal && c->rr_client)
+ if (!internal && cf->rr_client)
cf_error("Only internal neighbor can be RR client");
- if (internal && c->rs_client)
+ if (internal && cf->rs_client)
cf_error("Only external neighbor can be RS client");
- if (c->multihop && (c->gw_mode == GW_DIRECT))
- cf_error("Multihop BGP cannot use direct gateway mode");
+ if (!cf->confederation && cf->confederation_member)
+ cf_error("Confederation ID must be set for member sessions");
- if (c->multihop && (ipa_is_link_local(c->remote_ip) ||
- ipa_is_link_local(c->source_addr)))
+ if (cf->multihop && (ipa_is_link_local(cf->local_ip) ||
+ ipa_is_link_local(cf->remote_ip)))
cf_error("Multihop BGP cannot be used with link-local addresses");
- if (c->multihop && c->check_link)
+ if (cf->multihop && cf->check_link)
cf_error("Multihop BGP cannot depend on link state");
- if (c->multihop && c->bfd && ipa_zero(c->source_addr))
- cf_error("Multihop BGP with BFD requires specified source address");
+ if (cf->multihop && cf->bfd && ipa_zero(cf->local_ip))
+ cf_error("Multihop BGP with BFD requires specified local address");
+
+
+ struct bgp_channel_config *cc;
+ WALK_LIST(cc, CF->channels)
+ {
+ /* Disable after error incompatible with restart limit action */
+ if ((cc->c.in_limit.action == PLA_RESTART) && cf->disable_after_error)
+ cc->c.in_limit.action = PLA_DISABLE;
+
+ /* Different default based on rs_client */
+ if (!cc->missing_lladdr)
+ cc->missing_lladdr = cf->rs_client ? MLL_IGNORE : MLL_SELF;
+
+ /* Different default for gw_mode */
+ if (!cc->gw_mode)
+ cc->gw_mode = cf->multihop ? GW_RECURSIVE : GW_DIRECT;
- if ((c->gw_mode == GW_RECURSIVE) && c->c.table->sorted)
- cf_error("BGP in recursive mode prohibits sorted table");
+ /* Default based on proto config */
+ if (cc->gr_able == 0xff)
+ cc->gr_able = (cf->gr_mode == BGP_GR_ABLE);
- if (c->deterministic_med && c->c.table->sorted)
- cf_error("BGP with deterministic MED prohibits sorted table");
+ if (cf->multihop && (cc->gw_mode == GW_DIRECT))
+ cf_error("Multihop BGP cannot use direct gateway mode");
- if (c->secondary && !c->c.table->sorted)
- cf_error("BGP with secondary option requires sorted table");
+ if ((cc->gw_mode == GW_RECURSIVE) && cc->c.table->sorted)
+ cf_error("BGP in recursive mode prohibits sorted table");
+
+ if (cf->deterministic_med && cc->c.table->sorted)
+ cf_error("BGP with deterministic MED prohibits sorted table");
+
+ if (cc->secondary && !cc->c.table->sorted)
+ cf_error("BGP with secondary option requires sorted table");
+ }
}
static int
-bgp_reconfigure(struct proto *P, struct proto_config *C)
+bgp_reconfigure(struct proto *P, struct proto_config *CF)
{
- struct bgp_config *new = (struct bgp_config *) C;
- struct bgp_proto *p = (struct bgp_proto *) P;
+ struct bgp_proto *p = (void *) P;
+ struct bgp_config *new = (void *) CF;
struct bgp_config *old = p->cf;
- if (proto_get_router_id(C) != p->local_id)
+ if (proto_get_router_id(CF) != p->local_id)
return 0;
int same = !memcmp(((byte *) old) + sizeof(struct proto_config),
@@ -1374,8 +1583,26 @@ bgp_reconfigure(struct proto *P, struct proto_config *C)
// password item is last and must be checked separately
OFFSETOF(struct bgp_config, password) - sizeof(struct proto_config))
&& ((!old->password && !new->password)
- || (old->password && new->password && !strcmp(old->password, new->password)))
- && (get_igp_table(old) == get_igp_table(new));
+ || (old->password && new->password && !strcmp(old->password, new->password)));
+
+ /* FIXME: Move channel reconfiguration to generic protocol code ? */
+ struct channel *C, *C2;
+ struct bgp_channel_config *cc;
+
+ WALK_LIST(C, p->p.channels)
+ C->stale = 1;
+
+ WALK_LIST(cc, new->c.channels)
+ {
+ C = (struct channel *) bgp_find_channel(p, cc->afi);
+ same = proto_configure_channel(P, &C, &cc->c) && same;
+ C->stale = 0;
+ }
+
+ WALK_LIST_DELSAFE(C, C2, p->p.channels)
+ if (C->stale)
+ same = proto_configure_channel(P, &C, NULL) && same;
+
if (same && (p->start_state > BSS_PREPARE))
bgp_update_bfd(p, new->bfd);
@@ -1387,8 +1614,28 @@ bgp_reconfigure(struct proto *P, struct proto_config *C)
return same;
}
+static int
+bgp_channel_reconfigure(struct channel *C, struct channel_config *CC)
+{
+ struct bgp_channel *c = (void *) C;
+ struct bgp_channel_config *new = (void *) CC;
+ struct bgp_channel_config *old = c->cf;
+
+ if (memcmp(((byte *) old) + sizeof(struct channel_config),
+ ((byte *) new) + sizeof(struct channel_config),
+ /* igp_table item is last and must be checked separately */
+ OFFSETOF(struct bgp_channel_config, igp_table) - sizeof(struct channel_config)))
+ return 0;
+
+ if (get_igp_table(old) != get_igp_table(new))
+ return 0;
+
+ c->cf = new;
+ return 1;
+}
+
static void
-bgp_copy_config(struct proto_config *dest, struct proto_config *src)
+bgp_copy_config(struct proto_config *dest UNUSED, struct proto_config *src UNUSED)
{
/* Just a shallow copy */
}
@@ -1407,14 +1654,14 @@ bgp_copy_config(struct proto_config *dest, struct proto_config *src)
* closes the connection.
*/
void
-bgp_error(struct bgp_conn *c, unsigned code, unsigned subcode, byte *data, int len)
+bgp_error(struct bgp_conn *c, uint code, uint subcode, byte *data, int len)
{
struct bgp_proto *p = c->bgp;
if (c->state == BS_CLOSE)
return;
- bgp_log_error(p, BE_BGP_TX, "Error", code, subcode, data, (len > 0) ? len : -len);
+ bgp_log_error(p, BE_BGP_TX, "Error", code, subcode, data, ABS(len));
bgp_store_error(p, c, BE_BGP_TX, (code << 16) | subcode);
bgp_conn_enter_close_state(c);
@@ -1422,13 +1669,13 @@ bgp_error(struct bgp_conn *c, unsigned code, unsigned subcode, byte *data, int l
c->notify_subcode = subcode;
c->notify_data = data;
c->notify_size = (len > 0) ? len : 0;
- bgp_schedule_packet(c, PKT_NOTIFICATION);
+ bgp_schedule_packet(c, NULL, PKT_NOTIFICATION);
if (code != 6)
- {
- bgp_update_startup_delay(p);
- bgp_stop(p, 0);
- }
+ {
+ bgp_update_startup_delay(p);
+ bgp_stop(p, 0);
+ }
}
/**
@@ -1467,19 +1714,19 @@ static const char *
bgp_last_errmsg(struct bgp_proto *p)
{
switch (p->last_error_class)
- {
- case BE_MISC:
- return bgp_misc_errors[p->last_error_code];
- case BE_SOCKET:
- return (p->last_error_code == 0) ? "Connection closed" : strerror(p->last_error_code);
- case BE_BGP_RX:
- case BE_BGP_TX:
- return bgp_error_dsc(p->last_error_code >> 16, p->last_error_code & 0xFF);
- case BE_AUTO_DOWN:
- return bgp_auto_errors[p->last_error_code];
- default:
- return "";
- }
+ {
+ case BE_MISC:
+ return bgp_misc_errors[p->last_error_code];
+ case BE_SOCKET:
+ return (p->last_error_code == 0) ? "Connection closed" : strerror(p->last_error_code);
+ case BE_BGP_RX:
+ case BE_BGP_TX:
+ return bgp_error_dsc(p->last_error_code >> 16, p->last_error_code & 0xFF);
+ case BE_AUTO_DOWN:
+ return bgp_auto_errors[p->last_error_code];
+ default:
+ return "";
+ }
}
static const char *
@@ -1515,35 +1762,34 @@ bgp_show_proto_info(struct proto *P)
struct bgp_proto *p = (struct bgp_proto *) P;
struct bgp_conn *c = p->conn;
- proto_show_basic_info(P);
-
cli_msg(-1006, " BGP state: %s", bgp_state_dsc(p));
cli_msg(-1006, " Neighbor address: %I%J", p->cf->remote_ip, p->cf->iface);
cli_msg(-1006, " Neighbor AS: %u", p->remote_as);
- if (p->gr_active)
+ if (p->gr_active_num)
cli_msg(-1006, " Neighbor graceful restart active");
if (P->proto_state == PS_START)
- {
- struct bgp_conn *oc = &p->outgoing_conn;
+ {
+ struct bgp_conn *oc = &p->outgoing_conn;
- if ((p->start_state < BSS_CONNECT) &&
- (p->startup_timer->expires))
- cli_msg(-1006, " Error wait: %d/%d",
- p->startup_timer->expires - now, p->startup_delay);
+ if ((p->start_state < BSS_CONNECT) &&
+ (p->startup_timer->expires))
+ cli_msg(-1006, " Error wait: %d/%d",
+ p->startup_timer->expires - now, p->startup_delay);
- if ((oc->state == BS_ACTIVE) &&
- (oc->connect_retry_timer->expires))
- cli_msg(-1006, " Connect delay: %d/%d",
- oc->connect_retry_timer->expires - now, p->cf->connect_delay_time);
+ if ((oc->state == BS_ACTIVE) &&
+ (oc->connect_timer->expires))
+ cli_msg(-1006, " Connect delay: %d/%d",
+ oc->connect_timer->expires - now, p->cf->connect_delay_time);
- if (p->gr_active && p->gr_timer->expires)
- cli_msg(-1006, " Restart timer: %d/-", p->gr_timer->expires - now);
- }
+ if (p->gr_active_num && p->gr_timer->expires)
+ cli_msg(-1006, " Restart timer: %d/-", p->gr_timer->expires - now);
+ }
else if (P->proto_state == PS_UP)
- {
- cli_msg(-1006, " Neighbor ID: %R", p->remote_id);
+ {
+ cli_msg(-1006, " Neighbor ID: %R", p->remote_id);
+/* XXXX
cli_msg(-1006, " Neighbor caps: %s%s%s%s%s%s%s",
c->peer_refresh_support ? " refresh" : "",
c->peer_enhanced_refresh_support ? " enhanced-refresh" : "",
@@ -1561,35 +1807,52 @@ bgp_show_proto_info(struct proto *P)
p->add_path_rx ? " add-path-rx" : "",
p->add_path_tx ? " add-path-tx" : "",
p->ext_messages ? " ext-messages" : "");
- cli_msg(-1006, " Source address: %I", p->source_addr);
- if (P->cf->in_limit)
- cli_msg(-1006, " Route limit: %d/%d",
- p->p.stats.imp_routes + p->p.stats.filt_routes, P->cf->in_limit->limit);
- cli_msg(-1006, " Hold timer: %d/%d",
- tm_remains(c->hold_timer), c->hold_time);
- cli_msg(-1006, " Keepalive timer: %d/%d",
- tm_remains(c->keepalive_timer), c->keepalive_time);
- }
+*/
+ cli_msg(-1006, " Source address: %I", p->source_addr);
+ cli_msg(-1006, " Hold timer: %d/%d",
+ tm_remains(c->hold_timer), c->hold_time);
+ cli_msg(-1006, " Keepalive timer: %d/%d",
+ tm_remains(c->keepalive_timer), c->keepalive_time);
+ }
if ((p->last_error_class != BE_NONE) &&
(p->last_error_class != BE_MAN_DOWN))
- {
- const char *err1 = bgp_err_classes[p->last_error_class];
- const char *err2 = bgp_last_errmsg(p);
- cli_msg(-1006, " Last error: %s%s", err1, err2);
- }
+ {
+ const char *err1 = bgp_err_classes[p->last_error_class];
+ const char *err2 = bgp_last_errmsg(p);
+ cli_msg(-1006, " Last error: %s%s", err1, err2);
+ }
+
+ {
+ /* XXXX ?? */
+ struct channel *c;
+ WALK_LIST(c, p->p.channels)
+ channel_show_info(c);
+ }
}
+struct channel_class channel_bgp = {
+ .channel_size = sizeof(struct bgp_channel),
+ .config_size = sizeof(struct bgp_channel_config),
+ .init = bgp_channel_init,
+ .start = bgp_channel_start,
+ .shutdown = bgp_channel_shutdown,
+ .cleanup = bgp_channel_cleanup,
+ .reconfigure = bgp_channel_reconfigure,
+};
+
struct protocol proto_bgp = {
.name = "BGP",
.template = "bgp%d",
.attr_class = EAP_BGP,
.preference = DEF_PREF_BGP,
+ .channel_mask = NB_IP,
+ .proto_size = sizeof(struct bgp_proto),
.config_size = sizeof(struct bgp_config),
+ .postconfig = bgp_postconfig,
.init = bgp_init,
.start = bgp_start,
.shutdown = bgp_shutdown,
- .cleanup = bgp_cleanup,
.reconfigure = bgp_reconfigure,
.copy_config = bgp_copy_config,
.get_status = bgp_get_status,
diff --git a/proto/bgp/bgp.h b/proto/bgp/bgp.h
index b1cca2d9..4ecb86a0 100644
--- a/proto/bgp/bgp.h
+++ b/proto/bgp/bgp.h
@@ -2,6 +2,8 @@
* BIRD -- The Border Gateway Protocol
*
* (c) 2000 Martin Mares <mj@ucw.cz>
+ * (c) 2008--2016 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2008--2016 CZ.NIC z.s.p.o.
*
* Can be freely distributed and used under the terms of the GNU GPL.
*/
@@ -10,26 +12,66 @@
#define _BIRD_BGP_H_
#include <stdint.h>
+#include <setjmp.h>
+#include "nest/bird.h"
#include "nest/route.h"
#include "nest/bfd.h"
+//#include "lib/lists.h"
#include "lib/hash.h"
+#include "lib/socket.h"
struct linpool;
struct eattr;
+
+/* Address families */
+
+#define BGP_AFI_IPV4 1
+#define BGP_AFI_IPV6 2
+
+#define BGP_SAFI_UNICAST 1
+#define BGP_SAFI_MULTICAST 2
+
+/* Internal AF codes */
+
+#define BGP_AF(A, B) (((u32)(A) << 16) | (u32)(B))
+#define BGP_AFI(A) ((u32)(A) >> 16)
+#define BGP_SAFI(A) ((u32)(A) & 0xFFFF)
+
+#define BGP_AF_IPV4 BGP_AF( BGP_AFI_IPV4, BGP_SAFI_UNICAST )
+#define BGP_AF_IPV6 BGP_AF( BGP_AFI_IPV6, BGP_SAFI_UNICAST )
+#define BGP_AF_IPV4_MC BGP_AF( BGP_AFI_IPV4, BGP_SAFI_MULTICAST )
+#define BGP_AF_IPV6_MC BGP_AF( BGP_AFI_IPV6, BGP_SAFI_MULTICAST )
+
+
+struct bgp_write_state;
+struct bgp_parse_state;
+struct bgp_export_state;
+struct bgp_bucket;
+
+struct bgp_af_desc {
+ u32 afi;
+ u32 net;
+ const char *name;
+ uint (*encode_nlri)(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size);
+ void (*decode_nlri)(struct bgp_parse_state *s, byte *pos, uint len, rta *a);
+ void (*update_next_hop)(struct bgp_export_state *s, eattr *nh, ea_list **to);
+ uint (*encode_next_hop)(struct bgp_write_state *s, eattr *nh, byte *buf, uint size);
+ void (*decode_next_hop)(struct bgp_parse_state *s, byte *pos, uint len, rta *a);
+};
+
+
struct bgp_config {
struct proto_config c;
u32 local_as, remote_as;
+ ip_addr local_ip; /* Source address to use */
ip_addr remote_ip;
- ip_addr source_addr; /* Source address to use */
struct iface *iface; /* Interface for link-local addresses */
+ u16 local_port; /* Local listening port */
u16 remote_port; /* Neighbor destination port */
int multihop; /* Number of hops if multihop */
- int ttl_security; /* Enable TTL security [RFC5082] */
- int next_hop_self; /* Always set next hop to local IP address */
- int next_hop_keep; /* Do not touch next hop attribute */
- int missing_lladdr; /* What we will do when we don' know link-local addr, see MLL_* */
- int gw_mode; /* How we compute route gateway from next_hop attr, see GW_* */
+ int strict_bind; /* Bind listening socket to local address XXXX */
+ int ttl_security; /* Enable TTL security [RFC 5082] */
int compare_path_lengths; /* Use path lengths when selecting best route */
int med_metric; /* Compare MULTI_EXIT_DISC even between routes from differen ASes */
int igp_metric; /* Use IGP metrics when selecting best route */
@@ -37,18 +79,17 @@ struct bgp_config {
int deterministic_med; /* Use more complicated algo to have strict RFC 4271 MED comparison */
u32 default_local_pref; /* Default value for LOCAL_PREF attribute */
u32 default_med; /* Default value for MULTI_EXIT_DISC attribute */
- int capabilities; /* Enable capability handshake [RFC3392] */
- int enable_refresh; /* Enable local support for route refresh [RFC2918] */
- int enable_as4; /* Enable local support for 4B AS numbers [RFC4893] */
+ int capabilities; /* Enable capability handshake [RFC 3392] */
+ int enable_refresh; /* Enable local support for route refresh [RFC 2918] */
+ int enable_as4; /* Enable local support for 4B AS numbers [RFC 4893] */
int enable_extended_messages; /* Enable local support for extended messages [draft] */
u32 rr_cluster_id; /* Route reflector cluster ID, if different from local ID */
int rr_client; /* Whether neighbor is RR client of me */
int rs_client; /* Whether neighbor is RS client of me */
- int advertise_ipv4; /* Whether we should add IPv4 capability advertisement to OPEN message */
+ u32 confederation; /* Confederation ID, or zero if confeds not active */
+ int confederation_member; /* Whether neighbor AS is member of our confederation */
int passive; /* Do not initiate outgoing connection */
int interpret_communities; /* Hardwired handling of well-known communities */
- int secondary; /* Accept also non-best routes (i.e. RA_ACCEPTED) */
- int add_path; /* Use ADD-PATH extension [draft] */
int allow_local_as; /* Allow that number of local ASNs in incoming AS_PATHs */
int gr_mode; /* Graceful restart mode (BGP_GR_*) */
int setkey; /* Set MD5 password to system SA/SP database */
@@ -63,11 +104,27 @@ struct bgp_config {
unsigned disable_after_error; /* Disable the protocol when error is detected */
char *password; /* Password used for MD5 authentication */
- struct rtable_config *igp_table; /* Table used for recursive next hop lookups */
int check_link; /* Use iface link state for liveness detection */
int bfd; /* Use BFD for liveness detection */
};
+struct bgp_channel_config {
+ struct channel_config c;
+
+ u32 afi;
+
+ ip_addr next_hop_addr; /* Local address for NEXT_HOP attribute */
+ u8 next_hop_self; /* Always set next hop to local IP address */
+ u8 next_hop_keep; /* Do not touch next hop attribute */
+ u8 missing_lladdr; /* What we will do when we don' know link-local addr, see MLL_* */
+ u8 gw_mode; /* How we compute route gateway from next_hop attr, see GW_* */
+ u8 secondary; /* Accept also non-best routes (i.e. RA_ACCEPTED) */
+ u8 gr_able; /* Allow full graceful restart for the channel */
+ u8 add_path; /* Use ADD-PATH extension [RFC 7911] */
+
+ struct rtable_config *igp_table; /* Table used for recursive next hop lookups */
+};
+
#define MLL_SELF 1
#define MLL_DROP 2
#define MLL_IGNORE 3
@@ -75,112 +132,226 @@ struct bgp_config {
#define GW_DIRECT 1
#define GW_RECURSIVE 2
-#define ADD_PATH_RX 1
-#define ADD_PATH_TX 2
-#define ADD_PATH_FULL 3
+#define BGP_ADD_PATH_RX 1
+#define BGP_ADD_PATH_TX 2
+#define BGP_ADD_PATH_FULL 3
-#define BGP_GR_ABLE 1
-#define BGP_GR_AWARE 2
+#define BGP_GR_ABLE 1
+#define BGP_GR_AWARE 2
-/* For peer_gr_flags */
+/* For GR capability common flags */
#define BGP_GRF_RESTART 0x80
-/* For peer_gr_aflags */
+/* For GR capability per-AF flags */
#define BGP_GRF_FORWARDING 0x80
+struct bgp_af_caps {
+ u32 afi;
+ u8 ready; /* Multiprotocol capability, RFC 4760 */
+ u8 gr_able; /* Graceful restart support, RFC 4724 */
+ u8 gr_af_flags; /* Graceful restart per-AF flags */
+ u8 add_path; /* Multiple paths support, RFC 7911 */
+};
+
+struct bgp_caps {
+ u32 as4_number; /* Announced ASN */
+
+ u8 as4_support; /* Four-octet AS capability, RFC 6793 */
+ u8 ext_messages; /* Extended message length, RFC draft */
+ u8 route_refresh; /* Route refresh capability, RFC 2918 */
+ u8 enhanced_refresh; /* Enhanced route refresh, RFC 7313 */
+
+ u8 gr_aware; /* Graceful restart capability, RFC 4724 */
+ u8 gr_flags; /* Graceful restart flags */
+ u16 gr_time; /* Graceful restart time in seconds */
+
+ u16 af_count; /* Number of af_data items */
+
+ struct bgp_af_caps af_data[0]; /* Per-AF capability data */
+};
+
+struct bgp_socket {
+ node n; /* Node in global bgp_sockets */
+ sock *sk; /* Real listening socket */
+ u32 uc; /* Use count */
+};
+
struct bgp_conn {
struct bgp_proto *bgp;
struct birdsock *sk;
- uint state; /* State of connection state machine */
- struct timer *connect_retry_timer;
+ u8 state; /* State of connection state machine */
+ u8 as4_session; /* Session uses 4B AS numbers in AS_PATH (both sides support it) */
+ u8 ext_messages; /* Session uses extended message length */
+
+ struct bgp_caps *local_caps;
+ struct bgp_caps *remote_caps;
+ struct timer *connect_timer;
struct timer *hold_timer;
struct timer *keepalive_timer;
struct event *tx_ev;
- int packets_to_send; /* Bitmap of packet types to be sent */
+ u32 packets_to_send; /* Bitmap of packet types to be sent */
+ u32 channels_to_send; /* Bitmap of channels with packets to be sent */
+ u8 last_channel; /* Channel used last time for TX */
+ u8 last_channel_count; /* Number of times the last channel was used in succession */
int notify_code, notify_subcode, notify_size;
byte *notify_data;
- u32 advertised_as; /* Temporary value for AS number received */
- int start_state; /* protocol start_state snapshot when connection established */
- u8 peer_refresh_support; /* Peer supports route refresh [RFC2918] */
- u8 peer_as4_support; /* Peer supports 4B AS numbers [RFC4893] */
- u8 peer_add_path; /* Peer supports ADD-PATH [draft] */
- u8 peer_enhanced_refresh_support; /* Peer supports enhanced refresh [RFC7313] */
- u8 peer_gr_aware;
- u8 peer_gr_able;
- u16 peer_gr_time;
- u8 peer_gr_flags;
- u8 peer_gr_aflags;
- u8 peer_ext_messages_support; /* Peer supports extended message length [draft] */
- unsigned hold_time, keepalive_time; /* Times calculated from my and neighbor's requirements */
+
+ uint hold_time, keepalive_time; /* Times calculated from my and neighbor's requirements */
};
struct bgp_proto {
struct proto p;
struct bgp_config *cf; /* Shortcut to BGP configuration */
u32 local_as, remote_as;
- int start_state; /* Substates that partitions BS_START */
- u8 is_internal; /* Internal BGP connection (local_as == remote_as) */
- u8 as4_session; /* Session uses 4B AS numbers in AS_PATH (both sides support it) */
- u8 add_path_rx; /* Session expects receive of ADD-PATH extended NLRI */
- u8 add_path_tx; /* Session expects transmit of ADD-PATH extended NLRI */
- u8 ext_messages; /* Session allows to use extended messages (both sides support it) */
+ u32 public_as; /* Externally visible ASN (local_as or confederation id) */
u32 local_id; /* BGP identifier of this router */
u32 remote_id; /* BGP identifier of the neighbor */
u32 rr_cluster_id; /* Route reflector cluster ID */
- int rr_client; /* Whether neighbor is RR client of me */
- int rs_client; /* Whether neighbor is RS client of me */
+ int start_state; /* Substates that partitions BS_START */
+ u8 is_internal; /* Internal BGP session (local_as == remote_as) */
+ u8 is_interior; /* Internal or intra-confederation BGP session */
+ u8 as4_session; /* Session uses 4B AS numbers in AS_PATH (both sides support it) */
+ u8 rr_client; /* Whether neighbor is RR client of me */
+ u8 rs_client; /* Whether neighbor is RS client of me */
+ u8 route_refresh; /* Route refresh allowed to send [RFC 2918] */
+ u8 enhanced_refresh; /* Enhanced refresh is negotiated [RFC 7313] */
u8 gr_ready; /* Neighbor could do graceful restart */
- u8 gr_active; /* Neighbor is doing graceful restart */
- u8 feed_state; /* Feed state (TX) for EoR, RR packets, see BFS_* */
- u8 load_state; /* Load state (RX) for EoR, RR packets, see BFS_* */
+ u8 gr_active_num; /* Neighbor is doing GR, number of active channels */
+ u8 channel_count; /* Number of active channels */
+ u32 *afi_map; /* Map channel index -> AFI */
+ struct bgp_channel **channel_map; /* Map channel index -> channel */
struct bgp_conn *conn; /* Connection we have established */
struct bgp_conn outgoing_conn; /* Outgoing connection we're working with */
struct bgp_conn incoming_conn; /* Incoming connection we have neither accepted nor rejected yet */
struct object_lock *lock; /* Lock for neighbor connection */
struct neighbor *neigh; /* Neighbor entry corresponding to remote ip, NULL if multihop */
+ struct bgp_socket *sock; /* Shared listening socket */
struct bfd_request *bfd_req; /* BFD request, if BFD is used */
ip_addr source_addr; /* Local address used as an advertised next hop */
- rtable *igp_table; /* Table used for recursive next hop lookups */
+ ip_addr link_addr; /* Link-local version of source_addr */
struct event *event; /* Event for respawning and shutting process */
struct timer *startup_timer; /* Timer used to delay protocol startup due to previous errors (startup_delay) */
struct timer *gr_timer; /* Timer waiting for reestablishment after graceful restart */
- struct bgp_bucket **bucket_hash; /* Hash table of attribute buckets */
- uint hash_size, hash_count, hash_limit;
- HASH(struct bgp_prefix) prefix_hash; /* Prefixes to be sent */
- slab *prefix_slab; /* Slab holding prefix nodes */
- list bucket_queue; /* Queue of buckets to send */
- struct bgp_bucket *withdraw_bucket; /* Withdrawn routes */
unsigned startup_delay; /* Time to delay protocol startup by due to errors */
bird_clock_t last_proto_error; /* Time of last error that leads to protocol stop */
u8 last_error_class; /* Error class of last error */
u32 last_error_code; /* Error code of last error. BGP protocol errors
are encoded as (bgp_err_code << 16 | bgp_err_subcode) */
-#ifdef IPV6
- byte *mp_reach_start, *mp_unreach_start; /* Multiprotocol BGP attribute notes */
- unsigned mp_reach_len, mp_unreach_len;
- ip_addr local_link; /* Link-level version of source_addr */
-#endif
+};
+
+struct bgp_channel {
+ struct channel c;
+
+ /* Rest are BGP specific data */
+ struct bgp_channel_config *cf;
+ pool *pool; /* XXXX */
+
+ u32 afi;
+ u32 index;
+ const struct bgp_af_desc *desc;
+
+ HASH(struct bgp_bucket) bucket_hash; /* Hash table of route buckets */
+ struct bgp_bucket *withdraw_bucket; /* Withdrawn routes */
+ list bucket_queue; /* Queue of buckets to send (struct bgp_bucket) */
+
+ HASH(struct bgp_prefix) prefix_hash; /* Prefixes to be sent */
+ slab *prefix_slab; /* Slab holding prefix nodes */
+
+ rtable *igp_table; /* Table used for recursive next hop lookups */
+ ip_addr next_hop_addr; /* Local address for NEXT_HOP attribute */
+ ip_addr link_addr; /* Link-local version of next_hop_addr */
+
+ u32 packets_to_send; /* Bitmap of packet types to be sent */
+
+ u8 gr_ready; /* Neighbor could do GR on this AF */
+ u8 gr_active; /* Neighbor is doing GR and keeping fwd state */
+
+ u8 add_path_rx; /* Session expects receive of ADD-PATH extended NLRI */
+ u8 add_path_tx; /* Session expects transmit of ADD-PATH extended NLRI */
+
+ u8 feed_state; /* Feed state (TX) for EoR, RR packets, see BFS_* */
+ u8 load_state; /* Load state (RX) for EoR, RR packets, see BFS_* */
};
struct bgp_prefix {
- struct {
- ip_addr prefix;
- int pxlen;
- } n;
+ node buck_node; /* Node in per-bucket list */
+ struct bgp_prefix *next; /* Node in prefix hash table */
+ u32 hash;
u32 path_id;
- struct bgp_prefix *next;
- node bucket_node; /* Node in per-bucket list */
+ net_addr net[0];
};
struct bgp_bucket {
node send_node; /* Node in send queue */
- struct bgp_bucket *hash_next, *hash_prev; /* Node in bucket hash table */
- unsigned hash; /* Hash over extended attributes */
- list prefixes; /* Prefixes in this buckets */
+ struct bgp_bucket *next; /* Node in bucket hash table */
+ list prefixes; /* Prefixes in this bucket (struct bgp_prefix) */
+ u32 hash; /* Hash over extended attributes */
ea_list eattrs[0]; /* Per-bucket extended attributes */
};
+struct bgp_export_state {
+ struct bgp_proto *proto;
+ struct bgp_channel *channel;
+ struct linpool *pool;
+
+ struct bgp_proto *src;
+ rte *route;
+
+ u32 attrs_seen[1];
+ uint err_withdraw;
+};
+
+struct bgp_write_state {
+ struct bgp_proto *proto;
+ struct bgp_channel *channel;
+ struct linpool *pool;
+
+ int as4_session;
+ int add_path;
+
+ eattr *mp_next_hop;
+};
+
+struct bgp_parse_state {
+ struct bgp_proto *proto;
+ struct bgp_channel *channel;
+ struct linpool *pool;
+
+ int as4_session;
+ int add_path;
+
+ u32 attrs_seen[256/32];
+
+ u32 mp_reach_af;
+ u32 mp_unreach_af;
+
+ uint attr_len;
+ uint ip_reach_len;
+ uint ip_unreach_len;
+ uint ip_next_hop_len;
+ uint mp_reach_len;
+ uint mp_unreach_len;
+ uint mp_next_hop_len;
+
+ byte *attrs;
+ byte *ip_reach_nlri;
+ byte *ip_unreach_nlri;
+ byte *ip_next_hop_data;
+ byte *mp_reach_nlri;
+ byte *mp_unreach_nlri;
+ byte *mp_next_hop_data;
+
+ uint err_withdraw;
+ uint err_subcode;
+ jmp_buf err_jmpbuf;
+
+ /* Cached state for bgp_rte_update() */
+ u32 last_id;
+ struct rte_src *last_src;
+ rta *cached_rta;
+};
+
#define BGP_PORT 179
#define BGP_VERSION 4
#define BGP_HEADER_LENGTH 19
@@ -191,8 +362,21 @@ struct bgp_bucket {
#define BGP_RX_BUFFER_EXT_SIZE 65535
#define BGP_TX_BUFFER_EXT_SIZE 65535
-static inline int bgp_max_packet_length(struct bgp_proto *p)
-{ return p->ext_messages ? BGP_MAX_EXT_MSG_LENGTH : BGP_MAX_MESSAGE_LENGTH; }
+static inline int bgp_channel_is_ipv4(struct bgp_channel *c)
+{ return BGP_AFI(c->afi) == BGP_AFI_IPV4; }
+
+static inline int bgp_channel_is_ipv6(struct bgp_channel *c)
+{ return BGP_AFI(c->afi) == BGP_AFI_IPV6; }
+
+static inline uint bgp_max_packet_length(struct bgp_conn *conn)
+{ return conn->ext_messages ? BGP_MAX_EXT_MSG_LENGTH : BGP_MAX_MESSAGE_LENGTH; }
+
+static inline void
+bgp_parse_error(struct bgp_parse_state *s, uint subcode)
+{
+ s->err_subcode = subcode;
+ longjmp(s->err_jmpbuf, 1);
+}
extern struct linpool *bgp_linpool;
@@ -207,9 +391,9 @@ void bgp_conn_enter_established_state(struct bgp_conn *conn);
void bgp_conn_enter_close_state(struct bgp_conn *conn);
void bgp_conn_enter_idle_state(struct bgp_conn *conn);
void bgp_handle_graceful_restart(struct bgp_proto *p);
-void bgp_graceful_restart_done(struct bgp_proto *p);
-void bgp_refresh_begin(struct bgp_proto *p);
-void bgp_refresh_end(struct bgp_proto *p);
+void bgp_graceful_restart_done(struct bgp_channel *c);
+void bgp_refresh_begin(struct bgp_channel *c);
+void bgp_refresh_end(struct bgp_channel *c);
void bgp_store_error(struct bgp_proto *p, struct bgp_conn *c, u8 class, u32 code);
void bgp_stop(struct bgp_proto *p, unsigned subcode);
@@ -232,46 +416,83 @@ struct rte_source *bgp_get_source(struct bgp_proto *p, u32 path_id);
/* attrs.c */
+static inline eattr *
+bgp_find_attr(ea_list *attrs, uint code)
+{
+ return ea_find(attrs, EA_CODE(EAP_BGP, code));
+}
+
+eattr *
+bgp_set_attr(ea_list **attrs, struct linpool *pool, uint code, uint flags, uintptr_t val);
+
+static inline void
+bgp_set_attr_u32(ea_list **to, struct linpool *pool, uint code, uint flags, u32 val)
+{ bgp_set_attr(to, pool, code, flags, (uintptr_t) val); }
+
+static inline void
+bgp_set_attr_ptr(ea_list **to, struct linpool *pool, uint code, uint flags, struct adata *val)
+{ bgp_set_attr(to, pool, code, flags, (uintptr_t) val); }
+
+static inline void
+bgp_set_attr_data(ea_list **to, struct linpool *pool, uint code, uint flags, void *data, uint len)
+{
+ struct adata *a = lp_alloc_adata(pool, len);
+ memcpy(a->data, data, len);
+ bgp_set_attr(to, pool, code, flags, (uintptr_t) a);
+}
+
+static inline void
+bgp_unset_attr(ea_list **to, struct linpool *pool, uint code)
+{ eattr *e = bgp_set_attr(to, pool, code, 0, 0); e->type = EAF_TYPE_UNDEF; }
+
+
+
+
/* Hack: although BA_NEXT_HOP attribute has type EAF_TYPE_IP_ADDRESS, in IPv6
* we store two addesses in it - a global address and a link local address.
*/
-#ifdef IPV6
+#ifdef XXX
#define NEXT_HOP_LENGTH (2*sizeof(ip_addr))
static inline void set_next_hop(byte *b, ip_addr addr) { ((ip_addr *) b)[0] = addr; ((ip_addr *) b)[1] = IPA_NONE; }
-#else
#define NEXT_HOP_LENGTH sizeof(ip_addr)
static inline void set_next_hop(byte *b, ip_addr addr) { ((ip_addr *) b)[0] = addr; }
#endif
-void bgp_attach_attr(struct ea_list **to, struct linpool *pool, unsigned attr, uintptr_t val);
-byte *bgp_attach_attr_wa(struct ea_list **to, struct linpool *pool, unsigned attr, unsigned len);
-struct rta *bgp_decode_attrs(struct bgp_conn *conn, byte *a, uint len, struct linpool *pool, int mandatory);
-int bgp_get_attr(struct eattr *e, byte *buf, int buflen);
+int bgp_encode_attrs(struct bgp_write_state *s, ea_list *attrs, byte *buf, byte *end);
+ea_list * bgp_decode_attrs(struct bgp_parse_state *s, byte *data, uint len);
+
+void bgp_init_bucket_table(struct bgp_channel *c);
+void bgp_free_bucket(struct bgp_channel *c, struct bgp_bucket *b);
+void bgp_defer_bucket(struct bgp_channel *c, struct bgp_bucket *b);
+void bgp_withdraw_bucket(struct bgp_channel *c, struct bgp_bucket *b);
+
+void bgp_init_prefix_table(struct bgp_channel *c);
+void bgp_free_prefix(struct bgp_channel *c, struct bgp_prefix *bp);
+
int bgp_rte_better(struct rte *, struct rte *);
int bgp_rte_mergable(rte *pri, rte *sec);
int bgp_rte_recalculate(rtable *table, net *net, rte *new, rte *old, rte *old_best);
-void bgp_rt_notify(struct proto *P, rtable *tbl UNUSED, net *n, rte *new, rte *old UNUSED, ea_list *attrs);
+void bgp_rt_notify(struct proto *P, struct channel *C, net *n, rte *new, rte *old, ea_list *attrs);
int bgp_import_control(struct proto *, struct rte **, struct ea_list **, struct linpool *);
-void bgp_init_bucket_table(struct bgp_proto *);
-void bgp_free_bucket(struct bgp_proto *p, struct bgp_bucket *buck);
-void bgp_init_prefix_table(struct bgp_proto *p, u32 order);
-void bgp_free_prefix(struct bgp_proto *p, struct bgp_prefix *bp);
-uint bgp_encode_attrs(struct bgp_proto *p, byte *w, ea_list *attrs, int remains);
+int bgp_get_attr(struct eattr *e, byte *buf, int buflen);
void bgp_get_route_info(struct rte *, byte *buf, struct ea_list *attrs);
-inline static void bgp_attach_attr_ip(struct ea_list **to, struct linpool *pool, unsigned attr, ip_addr a)
-{ *(ip_addr *) bgp_attach_attr_wa(to, pool, attr, sizeof(ip_addr)) = a; }
/* packets.c */
void mrt_dump_bgp_state_change(struct bgp_conn *conn, unsigned old, unsigned new);
-void bgp_schedule_packet(struct bgp_conn *conn, int type);
+const struct bgp_af_desc *bgp_get_af_desc(u32 afi);
+const struct bgp_af_caps *bgp_find_af_caps(struct bgp_caps *caps, u32 afi);
+void bgp_schedule_packet(struct bgp_conn *conn, struct bgp_channel *c, int type);
void bgp_kick_tx(void *vconn);
void bgp_tx(struct birdsock *sk);
-int bgp_rx(struct birdsock *sk, int size);
+int bgp_rx(struct birdsock *sk, uint size);
const char * bgp_error_dsc(unsigned code, unsigned subcode);
void bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned subcode, byte *data, unsigned len);
+void bgp_update_next_hop(struct bgp_export_state *s, eattr *a, ea_list **to);
+
+
/* Packet types */
#define PKT_OPEN 0x01
@@ -305,9 +526,10 @@ void bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsi
#define BA_RCID_PATH 0x0d
#define BA_MP_REACH_NLRI 0x0e /* [RFC2283] */
#define BA_MP_UNREACH_NLRI 0x0f
-#define BA_EXT_COMMUNITY 0x10 /* [RFC4360] */
-#define BA_AS4_PATH 0x11 /* [RFC4893] */
-#define BA_AS4_AGGREGATOR 0x12
+#define BA_EXT_COMMUNITY 0x10 /* RFC 4360 */
+#define BA_AS4_PATH 0x11 /* RFC 6793 */
+#define BA_AS4_AGGREGATOR 0x12 /* RFC 6793 */
+#define BA_LARGE_COMMUNITY 0x20 /* [draft-ietf-idr-large-community] */
/* BGP connection states */
@@ -327,14 +549,12 @@ void bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsi
*
* When BGP protocol is started by core, it goes to BSS_PREPARE. When BGP
* protocol done what is neccessary to start itself (like acquiring the lock),
- * it goes to BSS_CONNECT. When some connection attempt failed because of
- * option or capability error, it goes to BSS_CONNECT_NOCAP.
+ * it goes to BSS_CONNECT.
*/
#define BSS_PREPARE 0 /* Used before ordinary BGP started, i. e. waiting for lock */
#define BSS_DELAY 1 /* Startup delay due to previous errors */
#define BSS_CONNECT 2 /* Ordinary BGP connecting */
-#define BSS_CONNECT_NOCAP 3 /* Legacy BGP connecting (without capabilities) */
/* BGP feed states (TX)
@@ -343,7 +563,7 @@ void bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsi
*
* RFC 7313 specifies that a route refresh should be demarcated by BoRR and EoRR packets.
*
- * These states (stored in p->feed_state) are used to keep track of these
+ * These states (stored in c->feed_state) are used to keep track of these
* requirements. When such feed is started, BFS_LOADING / BFS_REFRESHING is
* set. When it ended, BFS_LOADED / BFS_REFRESHED is set to schedule End-of-RIB
* or EoRR packet. When the packet is sent, the state returned to BFS_NONE.
@@ -399,15 +619,5 @@ void bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsi
#define ORIGIN_EGP 1
#define ORIGIN_INCOMPLETE 2
-/* Address families */
-
-#define BGP_AF_IPV4 1
-#define BGP_AF_IPV6 2
-
-#ifdef IPV6
-#define BGP_AF BGP_AF_IPV6
-#else
-#define BGP_AF BGP_AF_IPV4
-#endif
#endif
diff --git a/proto/bgp/config.Y b/proto/bgp/config.Y
index 33561bff..10a338d8 100644
--- a/proto/bgp/config.Y
+++ b/proto/bgp/config.Y
@@ -13,28 +13,32 @@ CF_HDR
CF_DEFINES
#define BGP_CFG ((struct bgp_config *) this_proto)
+#define BGP_CC ((struct bgp_channel_config *) this_channel)
CF_DECLS
-CF_KEYWORDS(BGP, LOCAL, NEIGHBOR, AS, HOLD, TIME, CONNECT, RETRY,
- KEEPALIVE, MULTIHOP, STARTUP, VIA, NEXT, HOP, SELF, DEFAULT,
- PATH, METRIC, ERROR, START, DELAY, FORGET, WAIT, ENABLE,
- DISABLE, AFTER, BGP_PATH, BGP_LOCAL_PREF, BGP_MED, BGP_ORIGIN,
- BGP_NEXT_HOP, BGP_ATOMIC_AGGR, BGP_AGGREGATOR, BGP_COMMUNITY,
- BGP_EXT_COMMUNITY, SOURCE, ADDRESS, PASSWORD, RR, RS, CLIENT,
- CLUSTER, ID, AS4, ADVERTISE, IPV4, CAPABILITIES, LIMIT, PASSIVE,
- PREFER, OLDER, MISSING, LLADDR, DROP, IGNORE, ROUTE, REFRESH,
- INTERPRET, COMMUNITIES, BGP_ORIGINATOR_ID, BGP_CLUSTER_LIST, IGP,
- TABLE, GATEWAY, DIRECT, RECURSIVE, MED, TTL, SECURITY, DETERMINISTIC,
- SECONDARY, ALLOW, BFD, ADD, PATHS, RX, TX, GRACEFUL, RESTART, AWARE,
- CHECK, LINK, PORT, EXTENDED, MESSAGES, SETKEY)
+CF_KEYWORDS(BGP, LOCAL, NEIGHBOR, AS, HOLD, TIME, CONNECT, RETRY, KEEPALIVE,
+ MULTIHOP, STARTUP, VIA, NEXT, HOP, SELF, DEFAULT, PATH, METRIC, ERROR,
+ START, DELAY, FORGET, WAIT, ENABLE, DISABLE, AFTER, BGP_PATH,
+ BGP_LOCAL_PREF, BGP_MED, BGP_ORIGIN, BGP_NEXT_HOP, BGP_ATOMIC_AGGR,
+ BGP_AGGREGATOR, BGP_COMMUNITY, BGP_EXT_COMMUNITY, BGP_LARGE_COMMUNITY,
+ SOURCE, ADDRESS, PASSWORD, RR, RS, CLIENT, CLUSTER, ID, AS4, ADVERTISE,
+ IPV4, CAPABILITIES, LIMIT, PASSIVE, PREFER, OLDER, MISSING, LLADDR,
+ DROP, IGNORE, ROUTE, REFRESH, INTERPRET, COMMUNITIES, BGP_ORIGINATOR_ID,
+ BGP_CLUSTER_LIST, IGP, TABLE, GATEWAY, DIRECT, RECURSIVE, MED, TTL,
+ SECURITY, DETERMINISTIC, SECONDARY, ALLOW, BFD, ADD, PATHS, RX, TX,
+ GRACEFUL, RESTART, AWARE, CHECK, LINK, PORT, EXTENDED, MESSAGES, SETKEY,
+ STRICT, BIND, CONFEDERATION, MEMBER, MULTICAST)
+
+%type <i32> bgp_afi
CF_GRAMMAR
-CF_ADDTO(proto, bgp_proto '}' { bgp_check_config(BGP_CFG); } )
+CF_ADDTO(proto, bgp_proto '}' )
bgp_proto_start: proto_start BGP {
this_proto = proto_config_new(&proto_bgp, $1);
+ BGP_CFG->local_port = BGP_PORT;
BGP_CFG->remote_port = BGP_PORT;
BGP_CFG->multihop = -1; /* undefined */
BGP_CFG->hold_time = 240;
@@ -49,26 +53,35 @@ bgp_proto_start: proto_start BGP {
BGP_CFG->enable_refresh = 1;
BGP_CFG->enable_as4 = 1;
BGP_CFG->capabilities = 2;
- BGP_CFG->advertise_ipv4 = 1;
BGP_CFG->interpret_communities = 1;
BGP_CFG->default_local_pref = 100;
BGP_CFG->gr_mode = BGP_GR_AWARE;
BGP_CFG->gr_time = 120;
BGP_CFG->setkey = 1;
- }
+ }
+ ;
+
+bgp_loc_opts:
+ /* empty */
+ | bgp_loc_opts PORT expr { BGP_CFG->local_port = $3; if (($3<1) || ($3>65535)) cf_error("Invalid port number"); }
+ | bgp_loc_opts AS expr { BGP_CFG->local_as = $3; }
;
bgp_nbr_opts:
/* empty */
- | bgp_nbr_opts PORT expr { BGP_CFG->remote_port = $3; if (($3<1) || ($3>65535)) cf_error("Invalid port number"); }
+ | bgp_nbr_opts PORT expr { BGP_CFG->remote_port = $3; if (($3<1) || ($3>65535)) cf_error("Invalid port number"); }
| bgp_nbr_opts AS expr { BGP_CFG->remote_as = $3; }
;
bgp_proto:
bgp_proto_start proto_name '{'
| bgp_proto proto_item ';'
- | bgp_proto LOCAL AS expr ';' { BGP_CFG->local_as = $4; }
- | bgp_proto LOCAL ipa AS expr ';' { BGP_CFG->source_addr = $3; BGP_CFG->local_as = $5; }
+ | bgp_proto bgp_proto_channel ';'
+ | bgp_proto LOCAL bgp_loc_opts ';'
+ | bgp_proto LOCAL ipa ipa_scope bgp_loc_opts ';' {
+ BGP_CFG->local_ip = $3;
+ if ($4) BGP_CFG->iface = $4;
+ }
| bgp_proto NEIGHBOR bgp_nbr_opts ';'
| bgp_proto NEIGHBOR ipa ipa_scope bgp_nbr_opts ';' {
if (ipa_nonzero(BGP_CFG->remote_ip))
@@ -78,20 +91,16 @@ bgp_proto:
}
| bgp_proto INTERFACE TEXT ';' { BGP_CFG->iface = if_get_by_name($3); }
| bgp_proto RR CLUSTER ID idval ';' { BGP_CFG->rr_cluster_id = $5; }
- | bgp_proto RR CLIENT ';' { BGP_CFG->rr_client = 1; }
- | bgp_proto RS CLIENT ';' { BGP_CFG->rs_client = 1; }
+ | bgp_proto RR CLIENT bool ';' { BGP_CFG->rr_client = $4; }
+ | bgp_proto RS CLIENT bool ';' { BGP_CFG->rs_client = $4; }
+ | bgp_proto CONFEDERATION expr ';' { BGP_CFG->confederation = $3; }
+ | bgp_proto CONFEDERATION MEMBER bool ';' { BGP_CFG->confederation_member = $4; }
| bgp_proto HOLD TIME expr ';' { BGP_CFG->hold_time = $4; }
| bgp_proto STARTUP HOLD TIME expr ';' { BGP_CFG->initial_hold_time = $5; }
| bgp_proto DIRECT ';' { BGP_CFG->multihop = 0; }
| bgp_proto MULTIHOP ';' { BGP_CFG->multihop = 64; }
| bgp_proto MULTIHOP expr ';' { BGP_CFG->multihop = $3; if (($3<1) || ($3>255)) cf_error("Multihop must be in range 1-255"); }
- | bgp_proto NEXT HOP SELF ';' { BGP_CFG->next_hop_self = 1; BGP_CFG->next_hop_keep = 0; }
- | bgp_proto NEXT HOP KEEP ';' { BGP_CFG->next_hop_keep = 1; BGP_CFG->next_hop_self = 0; }
- | bgp_proto MISSING LLADDR SELF ';' { BGP_CFG->missing_lladdr = MLL_SELF; }
- | bgp_proto MISSING LLADDR DROP ';' { BGP_CFG->missing_lladdr = MLL_DROP; }
- | bgp_proto MISSING LLADDR IGNORE ';' { BGP_CFG->missing_lladdr = MLL_IGNORE; }
- | bgp_proto GATEWAY DIRECT ';' { BGP_CFG->gw_mode = GW_DIRECT; }
- | bgp_proto GATEWAY RECURSIVE ';' { BGP_CFG->gw_mode = GW_RECURSIVE; }
+ | bgp_proto STRICT BIND bool ';' { BGP_CFG->strict_bind = $4; }
| bgp_proto PATH METRIC bool ';' { BGP_CFG->compare_path_lengths = $4; }
| bgp_proto MED METRIC bool ';' { BGP_CFG->med_metric = $4; }
| bgp_proto IGP METRIC bool ';' { BGP_CFG->igp_metric = $4; }
@@ -99,7 +108,7 @@ bgp_proto:
| bgp_proto DETERMINISTIC MED bool ';' { BGP_CFG->deterministic_med = $4; }
| bgp_proto DEFAULT BGP_MED expr ';' { BGP_CFG->default_med = $4; }
| bgp_proto DEFAULT BGP_LOCAL_PREF expr ';' { BGP_CFG->default_local_pref = $4; }
- | bgp_proto SOURCE ADDRESS ipa ';' { BGP_CFG->source_addr = $4; }
+ | bgp_proto SOURCE ADDRESS ipa ';' { BGP_CFG->local_ip = $4; }
| bgp_proto START DELAY TIME expr ';' { BGP_CFG->connect_delay_time = $5; log(L_WARN "%s: Start delay time option is deprecated, use connect delay time", this_proto->name); }
| bgp_proto CONNECT DELAY TIME expr ';' { BGP_CFG->connect_delay_time = $5; }
| bgp_proto CONNECT RETRY TIME expr ';' { BGP_CFG->connect_retry_time = $5; }
@@ -111,26 +120,79 @@ bgp_proto:
| bgp_proto ENABLE AS4 bool ';' { BGP_CFG->enable_as4 = $4; }
| bgp_proto ENABLE EXTENDED MESSAGES bool ';' { BGP_CFG->enable_extended_messages = $5; }
| bgp_proto CAPABILITIES bool ';' { BGP_CFG->capabilities = $3; }
- | bgp_proto ADVERTISE IPV4 bool ';' { BGP_CFG->advertise_ipv4 = $4; }
| bgp_proto PASSWORD text ';' { BGP_CFG->password = $3; }
| bgp_proto SETKEY bool ';' { BGP_CFG->setkey = $3; }
| bgp_proto PASSIVE bool ';' { BGP_CFG->passive = $3; }
| bgp_proto INTERPRET COMMUNITIES bool ';' { BGP_CFG->interpret_communities = $4; }
- | bgp_proto SECONDARY bool ';' { BGP_CFG->secondary = $3; }
- | bgp_proto ADD PATHS RX ';' { BGP_CFG->add_path = ADD_PATH_RX; }
- | bgp_proto ADD PATHS TX ';' { BGP_CFG->add_path = ADD_PATH_TX; }
- | bgp_proto ADD PATHS bool ';' { BGP_CFG->add_path = $4 ? ADD_PATH_FULL : 0; }
| bgp_proto ALLOW LOCAL AS ';' { BGP_CFG->allow_local_as = -1; }
| bgp_proto ALLOW LOCAL AS expr ';' { BGP_CFG->allow_local_as = $5; }
| bgp_proto GRACEFUL RESTART bool ';' { BGP_CFG->gr_mode = $4; }
| bgp_proto GRACEFUL RESTART AWARE ';' { BGP_CFG->gr_mode = BGP_GR_AWARE; }
| bgp_proto GRACEFUL RESTART TIME expr ';' { BGP_CFG->gr_time = $5; }
- | bgp_proto IGP TABLE rtable ';' { BGP_CFG->igp_table = $4; }
| bgp_proto TTL SECURITY bool ';' { BGP_CFG->ttl_security = $4; }
| bgp_proto CHECK LINK bool ';' { BGP_CFG->check_link = $4; }
| bgp_proto BFD bool ';' { BGP_CFG->bfd = $3; cf_check_bfd($3); }
;
+bgp_afi:
+ IPV4 { $$ = BGP_AF_IPV4; }
+ | IPV6 { $$ = BGP_AF_IPV6; }
+ | IPV4 MULTICAST { $$ = BGP_AF_IPV4_MC; }
+ | IPV6 MULTICAST { $$ = BGP_AF_IPV6_MC; }
+ ;
+
+bgp_channel_start: bgp_afi
+{
+ const struct bgp_af_desc *desc = bgp_get_af_desc($1);
+
+ if (!desc)
+ cf_error("Unknown AFI/SAFI");
+
+ this_channel = channel_config_new(&channel_bgp, desc->net, this_proto);
+ BGP_CC->c.name = desc->name;
+ BGP_CC->afi = $1;
+ BGP_CC->gr_able = 0xff; /* undefined */
+};
+
+bgp_channel_item:
+ channel_item
+ | NEXT HOP ADDRESS ipa { BGP_CC->next_hop_addr = $4; }
+ | NEXT HOP SELF { BGP_CC->next_hop_self = 1; BGP_CC->next_hop_keep = 0; }
+ | NEXT HOP KEEP { BGP_CC->next_hop_keep = 1; BGP_CC->next_hop_self = 0; }
+ | MISSING LLADDR SELF { BGP_CC->missing_lladdr = MLL_SELF; }
+ | MISSING LLADDR DROP { BGP_CC->missing_lladdr = MLL_DROP; }
+ | MISSING LLADDR IGNORE { BGP_CC->missing_lladdr = MLL_IGNORE; }
+ | GATEWAY DIRECT { BGP_CC->gw_mode = GW_DIRECT; }
+ | GATEWAY RECURSIVE { BGP_CC->gw_mode = GW_RECURSIVE; }
+ | SECONDARY bool { BGP_CC->secondary = $2; }
+ | GRACEFUL RESTART bool { BGP_CC->gr_able = $3; }
+ | ADD PATHS RX { BGP_CC->add_path = BGP_ADD_PATH_RX; }
+ | ADD PATHS TX { BGP_CC->add_path = BGP_ADD_PATH_TX; }
+ | ADD PATHS bool { BGP_CC->add_path = $3 ? BGP_ADD_PATH_FULL : 0; }
+ | IGP TABLE rtable { BGP_CC->igp_table = $3; }
+ ;
+
+bgp_channel_opts:
+ /* empty */
+ | bgp_channel_opts bgp_channel_item ';'
+ ;
+
+bgp_channel_opt_list:
+ /* empty */
+ | '{' bgp_channel_opts '}'
+ ;
+
+bgp_channel_end:
+{
+ if (!this_channel->table)
+ cf_error("Routing table not specified");
+
+ this_channel = NULL;
+};
+
+bgp_proto_channel: bgp_channel_start bgp_channel_opt_list bgp_channel_end;
+
+
CF_ADDTO(dynamic_attr, BGP_ORIGIN
{ $$ = f_new_dynamic_attr(EAF_TYPE_INT, T_ENUM_BGP_ORIGIN, EA_CODE(EAP_BGP, BA_ORIGIN)); })
CF_ADDTO(dynamic_attr, BGP_PATH
@@ -153,6 +215,8 @@ CF_ADDTO(dynamic_attr, BGP_CLUSTER_LIST
{ $$ = f_new_dynamic_attr(EAF_TYPE_INT_SET, T_CLIST, EA_CODE(EAP_BGP, BA_CLUSTER_LIST)); })
CF_ADDTO(dynamic_attr, BGP_EXT_COMMUNITY
{ $$ = f_new_dynamic_attr(EAF_TYPE_EC_SET, T_ECLIST, EA_CODE(EAP_BGP, BA_EXT_COMMUNITY)); })
+CF_ADDTO(dynamic_attr, BGP_LARGE_COMMUNITY
+ { $$ = f_new_dynamic_attr(EAF_TYPE_LC_SET, T_LCLIST, EA_CODE(EAP_BGP, BA_LARGE_COMMUNITY)); })
diff --git a/proto/bgp/packets.c b/proto/bgp/packets.c
index 72ca3728..66561ee4 100644
--- a/proto/bgp/packets.c
+++ b/proto/bgp/packets.c
@@ -2,12 +2,16 @@
* BIRD -- BGP Packet Processing
*
* (c) 2000 Martin Mares <mj@ucw.cz>
+ * (c) 2008--2016 Ondrej Zajicek <santiago@crfreenet.org>
+ * (c) 2008--2016 CZ.NIC z.s.p.o.
*
* Can be freely distributed and used under the terms of the GNU GPL.
*/
#undef LOCAL_DEBUG
+#include <stdlib.h>
+
#include "nest/bird.h"
#include "nest/iface.h"
#include "nest/protocol.h"
@@ -38,6 +42,46 @@ static byte fsm_err_subcode[BS_MAX] = {
[BS_ESTABLISHED] = 3
};
+
+static struct bgp_channel *
+bgp_get_channel(struct bgp_proto *p, u32 afi)
+{
+ uint i;
+
+ for (i = 0; i < p->channel_count; i++)
+ if (p->afi_map[i] == afi)
+ return p->channel_map[i];
+
+ return NULL;
+}
+
+static inline void
+put_af3(byte *buf, u32 id)
+{
+ put_u16(buf, id >> 16);
+ buf[2] = id & 0xff;
+}
+
+static inline void
+put_af4(byte *buf, u32 id)
+{
+ put_u16(buf, id >> 16);
+ buf[2] = 0;
+ buf[3] = id & 0xff;
+}
+
+static inline u32
+get_af3(byte *buf)
+{
+ return (get_u16(buf) << 16) | buf[2];
+}
+
+static inline u32
+get_af4(byte *buf)
+{
+ return (get_u16(buf) << 16) | buf[3];
+}
+
/*
* MRT Dump format is not semantically specified.
* We will use these values in appropriate fields:
@@ -58,31 +102,41 @@ static byte *
mrt_put_bgp4_hdr(byte *buf, struct bgp_conn *conn, int as4)
{
struct bgp_proto *p = conn->bgp;
+ uint v4 = ipa_is_ip4(p->cf->remote_ip);
if (as4)
- {
- put_u32(buf+0, p->remote_as);
- put_u32(buf+4, p->local_as);
- buf+=8;
- }
+ {
+ put_u32(buf+0, p->remote_as);
+ put_u32(buf+4, p->public_as);
+ buf+=8;
+ }
else
- {
- put_u16(buf+0, (p->remote_as <= 0xFFFF) ? p->remote_as : AS_TRANS);
- put_u16(buf+2, (p->local_as <= 0xFFFF) ? p->local_as : AS_TRANS);
- buf+=4;
- }
+ {
+ put_u16(buf+0, (p->remote_as <= 0xFFFF) ? p->remote_as : AS_TRANS);
+ put_u16(buf+2, (p->public_as <= 0xFFFF) ? p->public_as : AS_TRANS);
+ buf+=4;
+ }
put_u16(buf+0, (p->neigh && p->neigh->iface) ? p->neigh->iface->index : 0);
- put_u16(buf+2, BGP_AF);
+ put_u16(buf+2, v4 ? BGP_AFI_IPV4 : BGP_AFI_IPV6);
buf+=4;
- buf = put_ipa(buf, conn->sk ? conn->sk->daddr : IPA_NONE);
- buf = put_ipa(buf, conn->sk ? conn->sk->saddr : IPA_NONE);
+
+ if (v4)
+ {
+ buf = put_ip4(buf, conn->sk ? ipa_to_ip4(conn->sk->daddr) : IP4_NONE);
+ buf = put_ip4(buf, conn->sk ? ipa_to_ip4(conn->sk->saddr) : IP4_NONE);
+ }
+ else
+ {
+ buf = put_ip6(buf, conn->sk ? ipa_to_ip6(conn->sk->daddr) : IP6_NONE);
+ buf = put_ip6(buf, conn->sk ? ipa_to_ip6(conn->sk->saddr) : IP6_NONE);
+ }
return buf;
}
static void
-mrt_dump_bgp_packet(struct bgp_conn *conn, byte *pkt, unsigned len)
+mrt_dump_bgp_packet(struct bgp_conn *conn, byte *pkt, uint len)
{
byte *buf = alloca(128+len); /* 128 is enough for MRT headers */
byte *bp = buf + MRTDUMP_HDR_LENGTH;
@@ -96,14 +150,14 @@ mrt_dump_bgp_packet(struct bgp_conn *conn, byte *pkt, unsigned len)
}
static inline u16
-convert_state(unsigned state)
+convert_state(uint state)
{
/* Convert state from our BS_* values to values used in MRTDump */
return (state == BS_CLOSE) ? 1 : state + 1;
}
void
-mrt_dump_bgp_state_change(struct bgp_conn *conn, unsigned old, unsigned new)
+mrt_dump_bgp_state_change(struct bgp_conn *conn, uint old, uint new)
{
byte buf[128];
byte *bp = buf + MRTDUMP_HDR_LENGTH;
@@ -127,1300 +181,1675 @@ bgp_create_notification(struct bgp_conn *conn, byte *buf)
return buf + 2 + conn->notify_size;
}
-#ifdef IPV6
-static byte *
-bgp_put_cap_ipv6(struct bgp_proto *p UNUSED, byte *buf)
-{
- *buf++ = 1; /* Capability 1: Multiprotocol extensions */
- *buf++ = 4; /* Capability data length */
- *buf++ = 0; /* We support AF IPv6 */
- *buf++ = BGP_AF_IPV6;
- *buf++ = 0; /* RFU */
- *buf++ = 1; /* and SAFI 1 */
- return buf;
-}
-#else
+/* Capability negotiation as per RFC 5492 */
-static byte *
-bgp_put_cap_ipv4(struct bgp_proto *p UNUSED, byte *buf)
-{
- *buf++ = 1; /* Capability 1: Multiprotocol extensions */
- *buf++ = 4; /* Capability data length */
- *buf++ = 0; /* We support AF IPv4 */
- *buf++ = BGP_AF_IPV4;
- *buf++ = 0; /* RFU */
- *buf++ = 1; /* and SAFI 1 */
- return buf;
-}
-#endif
+#define WALK_AF_CAPS(caps,ac) \
+ for (ac = caps->af_data; ac < &caps->af_data[caps->af_count]; ac++)
-static byte *
-bgp_put_cap_rr(struct bgp_proto *p UNUSED, byte *buf)
+const struct bgp_af_caps *
+bgp_find_af_caps(struct bgp_caps *caps, u32 afi)
{
- *buf++ = 2; /* Capability 2: Support for route refresh */
- *buf++ = 0; /* Capability data length */
- return buf;
-}
+ struct bgp_af_caps *ac;
-static byte *
-bgp_put_cap_ext_msg(struct bgp_proto *p UNUSED, byte *buf)
-{
- *buf++ = 6; /* Capability 6: Support for extended messages */
- *buf++ = 0; /* Capability data length */
- return buf;
+ WALK_AF_CAPS(caps, ac)
+ if (ac->afi == afi)
+ return ac;
+
+ return NULL;
}
-static byte *
-bgp_put_cap_gr1(struct bgp_proto *p, byte *buf)
+static struct bgp_af_caps *
+bgp_get_af_caps(struct bgp_caps *caps, u32 afi)
{
- *buf++ = 64; /* Capability 64: Support for graceful restart */
- *buf++ = 6; /* Capability data length */
+ struct bgp_af_caps *ac;
- put_u16(buf, p->cf->gr_time);
- if (p->p.gr_recovery)
- buf[0] |= BGP_GRF_RESTART;
- buf += 2;
+ WALK_AF_CAPS(caps, ac)
+ if (ac->afi == afi)
+ return ac;
- *buf++ = 0; /* Appropriate AF */
- *buf++ = BGP_AF;
- *buf++ = 1; /* and SAFI 1 */
- *buf++ = p->p.gr_recovery ? BGP_GRF_FORWARDING : 0;
+ ac = &caps->af_data[caps->af_count++];
+ memset(ac, 0, sizeof(struct bgp_af_caps));
+ ac->afi = afi;
- return buf;
+ return ac;
}
-static byte *
-bgp_put_cap_gr2(struct bgp_proto *p, byte *buf)
+static int
+bgp_af_caps_cmp(const void *X, const void *Y)
{
- *buf++ = 64; /* Capability 64: Support for graceful restart */
- *buf++ = 2; /* Capability data length */
- put_u16(buf, 0);
- return buf + 2;
+ const struct bgp_af_caps *x = X, *y = Y;
+ return (x->afi < y->afi) ? -1 : (x->afi > y->afi) ? 1 : 0;
}
-static byte *
-bgp_put_cap_as4(struct bgp_proto *p, byte *buf)
-{
- *buf++ = 65; /* Capability 65: Support for 4-octet AS number */
- *buf++ = 4; /* Capability data length */
- put_u32(buf, p->local_as);
- return buf + 4;
-}
static byte *
-bgp_put_cap_add_path(struct bgp_proto *p, byte *buf)
+bgp_write_capabilities(struct bgp_conn *conn, byte *buf)
{
- *buf++ = 69; /* Capability 69: Support for ADD-PATH */
- *buf++ = 4; /* Capability data length */
+ struct bgp_proto *p = conn->bgp;
+ struct bgp_channel *c;
+ struct bgp_caps *caps;
+ struct bgp_af_caps *ac;
+ uint any_add_path = 0;
+ byte *data;
- *buf++ = 0; /* Appropriate AF */
- *buf++ = BGP_AF;
- *buf++ = 1; /* SAFI 1 */
+ /* Prepare bgp_caps structure */
- *buf++ = p->cf->add_path;
+ int n = list_length(&p->p.channels);
+ caps = mb_allocz(p->p.pool, sizeof(struct bgp_caps) + n * sizeof(struct bgp_af_caps));
+ conn->local_caps = caps;
- return buf;
-}
+ caps->as4_support = p->cf->enable_as4;
+ caps->ext_messages = p->cf->enable_extended_messages;
+ caps->route_refresh = p->cf->enable_refresh;
+ caps->enhanced_refresh = p->cf->enable_refresh;
-static byte *
-bgp_put_cap_err(struct bgp_proto *p UNUSED, byte *buf)
-{
- *buf++ = 70; /* Capability 70: Support for enhanced route refresh */
- *buf++ = 0; /* Capability data length */
- return buf;
-}
+ if (caps->as4_support)
+ caps->as4_number = p->public_as;
+ if (p->cf->gr_mode)
+ {
+ caps->gr_aware = 1;
+ caps->gr_time = p->cf->gr_time;
+ caps->gr_flags = p->p.gr_recovery ? BGP_GRF_RESTART : 0;
+ }
-static byte *
-bgp_create_open(struct bgp_conn *conn, byte *buf)
-{
- struct bgp_proto *p = conn->bgp;
- byte *cap;
- int cap_len;
+ /* Allocate and fill per-AF fields */
+ WALK_LIST(c, p->p.channels)
+ {
+ ac = &caps->af_data[caps->af_count++];
+ ac->afi = c->afi;
+ ac->ready = 1;
- BGP_TRACE(D_PACKETS, "Sending OPEN(ver=%d,as=%d,hold=%d,id=%08x)",
- BGP_VERSION, p->local_as, p->cf->hold_time, p->local_id);
- buf[0] = BGP_VERSION;
- put_u16(buf+1, (p->local_as < 0xFFFF) ? p->local_as : AS_TRANS);
- put_u16(buf+3, p->cf->hold_time);
- put_u32(buf+5, p->local_id);
+ ac->add_path = c->cf->add_path;
+ any_add_path |= ac->add_path;
- if (conn->start_state == BSS_CONNECT_NOCAP)
+ if (c->cf->gr_able)
{
- BGP_TRACE(D_PACKETS, "Skipping capabilities");
- buf[9] = 0;
- return buf + 10;
+ ac->gr_able = 1;
+
+ if (p->p.gr_recovery)
+ ac->gr_af_flags |= BGP_GRF_FORWARDING;
}
+ }
+
+ /* Sort capability fields by AFI/SAFI */
+ qsort(caps->af_data, caps->af_count, sizeof(struct bgp_af_caps), bgp_af_caps_cmp);
- /* Skipped 3 B for length field and Capabilities parameter header */
- cap = buf + 12;
-#ifndef IPV6
- if (p->cf->advertise_ipv4)
- cap = bgp_put_cap_ipv4(p, cap);
-#endif
+ /* Create capability list in buffer */
+
+ WALK_AF_CAPS(caps, ac)
+ if (ac->ready)
+ {
+ *buf++ = 1; /* Capability 1: Multiprotocol extensions */
+ *buf++ = 4; /* Capability data length */
+ put_af4(buf, ac->afi);
+ buf += 4;
+ }
+
+ if (caps->route_refresh)
+ {
+ *buf++ = 2; /* Capability 2: Support for route refresh */
+ *buf++ = 0; /* Capability data length */
+ }
-#ifdef IPV6
- cap = bgp_put_cap_ipv6(p, cap);
-#endif
+ if (caps->ext_messages)
+ {
+ *buf++ = 6; /* Capability 6: Support for extended messages */
+ *buf++ = 0; /* Capability data length */
+ }
- if (p->cf->enable_refresh)
- cap = bgp_put_cap_rr(p, cap);
+ if (caps->gr_aware)
+ {
+ *buf++ = 64; /* Capability 64: Support for graceful restart */
+ *buf++ = 0; /* Capability data length, will be fixed later */
+ data = buf;
- if (p->cf->gr_mode == BGP_GR_ABLE)
- cap = bgp_put_cap_gr1(p, cap);
- else if (p->cf->gr_mode == BGP_GR_AWARE)
- cap = bgp_put_cap_gr2(p, cap);
+ put_u16(buf, caps->gr_time);
+ buf[0] |= caps->gr_flags;
+ buf += 2;
- if (p->cf->enable_as4)
- cap = bgp_put_cap_as4(p, cap);
+ WALK_AF_CAPS(caps, ac)
+ if (ac->gr_able)
+ {
+ put_af3(buf, ac->afi);
+ buf[3] = ac->gr_af_flags;
+ buf += 4;
+ }
- if (p->cf->add_path)
- cap = bgp_put_cap_add_path(p, cap);
+ data[-1] = buf - data;
+ }
- if (p->cf->enable_refresh)
- cap = bgp_put_cap_err(p, cap);
+ if (caps->as4_support)
+ {
+ *buf++ = 65; /* Capability 65: Support for 4-octet AS number */
+ *buf++ = 4; /* Capability data length */
+ put_u32(buf, p->public_as);
+ buf += 4;
+ }
- if (p->cf->enable_extended_messages)
- cap = bgp_put_cap_ext_msg(p, cap);
+ if (any_add_path)
+ {
+ *buf++ = 69; /* Capability 69: Support for ADD-PATH */
+ *buf++ = 0; /* Capability data length, will be fixed later */
+ data = buf;
- cap_len = cap - buf - 12;
- if (cap_len > 0)
- {
- buf[9] = cap_len + 2; /* Optional params len */
- buf[10] = 2; /* Option: Capability list */
- buf[11] = cap_len; /* Option length */
- return cap;
- }
- else
- {
- buf[9] = 0; /* No optional parameters */
- return buf + 10;
- }
-}
+ WALK_AF_CAPS(caps, ac)
+ if (ac->add_path)
+ {
+ put_af3(buf, ac->afi);
+ buf[3] = ac->add_path;
+ buf += 4;
+ }
-static uint
-bgp_encode_prefixes(struct bgp_proto *p, byte *w, struct bgp_bucket *buck, uint remains)
-{
- byte *start = w;
- ip_addr a;
- int bytes;
+ data[-1] = buf - data;
+ }
- while (!EMPTY_LIST(buck->prefixes) && (remains >= (5+sizeof(ip_addr))))
- {
- struct bgp_prefix *px = SKIP_BACK(struct bgp_prefix, bucket_node, HEAD(buck->prefixes));
- DBG("\tDequeued route %I/%d\n", px->n.prefix, px->n.pxlen);
+ if (caps->enhanced_refresh)
+ {
+ *buf++ = 70; /* Capability 70: Support for enhanced route refresh */
+ *buf++ = 0; /* Capability data length */
+ }
- if (p->add_path_tx)
- {
- put_u32(w, px->path_id);
- w += 4;
- remains -= 4;
- }
+ /* FIXME: Should not XXXX 255 */
- *w++ = px->n.pxlen;
- bytes = (px->n.pxlen + 7) / 8;
- a = px->n.prefix;
- ipa_hton(a);
- memcpy(w, &a, bytes);
- w += bytes;
- remains -= bytes + 1;
- rem_node(&px->bucket_node);
- bgp_free_prefix(p, px);
- // fib_delete(&p->prefix_fib, px);
- }
- return w - start;
+ return buf;
}
static void
-bgp_flush_prefixes(struct bgp_proto *p, struct bgp_bucket *buck)
+bgp_read_capabilities(struct bgp_conn *conn, struct bgp_caps *caps, byte *pos, int len)
{
- while (!EMPTY_LIST(buck->prefixes))
- {
- struct bgp_prefix *px = SKIP_BACK(struct bgp_prefix, bucket_node, HEAD(buck->prefixes));
- log(L_ERR "%s: - route %I/%d skipped", p->p.name, px->n.prefix, px->n.pxlen);
- rem_node(&px->bucket_node);
- bgp_free_prefix(p, px);
- // fib_delete(&p->prefix_fib, px);
- }
-}
+ struct bgp_proto *p = conn->bgp;
+ struct bgp_af_caps *ac;
+ int i, cl;
+ u32 af;
-#ifndef IPV6 /* IPv4 version */
+ while (len > 0)
+ {
+ if (len < 2 || len < (2 + pos[1]))
+ goto err;
-static byte *
-bgp_create_update(struct bgp_conn *conn, byte *buf)
-{
- struct bgp_proto *p = conn->bgp;
- struct bgp_bucket *buck;
- int remains = bgp_max_packet_length(p) - BGP_HEADER_LENGTH - 4;
- byte *w;
- int wd_size = 0;
- int r_size = 0;
- int a_size = 0;
-
- w = buf+2;
- if ((buck = p->withdraw_bucket) && !EMPTY_LIST(buck->prefixes))
- {
- DBG("Withdrawn routes:\n");
- wd_size = bgp_encode_prefixes(p, w, buck, remains);
- w += wd_size;
- remains -= wd_size;
- }
- put_u16(buf, wd_size);
+ /* Capability length */
+ cl = pos[1];
- if (remains >= 3072)
+ /* Capability type */
+ switch (pos[0])
{
- while ((buck = (struct bgp_bucket *) HEAD(p->bucket_queue))->send_node.next)
+ case 1: /* Multiprotocol capability, RFC 4760 */
+ if (cl != 4)
+ goto err;
+
+ af = get_af4(pos+2);
+ ac = bgp_get_af_caps(caps, af);
+ ac->ready = 1;
+ break;
+
+ case 2: /* Route refresh capability, RFC 2918 */
+ if (cl != 0)
+ goto err;
+
+ caps->route_refresh = 1;
+ break;
+
+ case 6: /* Extended message length capability, RFC draft */
+ if (cl != 0)
+ goto err;
+
+ caps->ext_messages = 1;
+ break;
+
+ case 64: /* Graceful restart capability, RFC 4724 */
+ if (cl % 4 != 2)
+ goto err;
+
+ /* Only the last instance is valid */
+ WALK_AF_CAPS(caps, ac)
+ {
+ ac->gr_able = 0;
+ ac->gr_af_flags = 0;
+ }
+
+ caps->gr_aware = 1;
+ caps->gr_flags = pos[2] & 0xf0;
+ caps->gr_time = get_u16(pos + 2) & 0x0fff;
+
+ for (i = 2; i < cl; i += 4)
+ {
+ af = get_af3(pos+2+i);
+ ac = bgp_get_af_caps(caps, af);
+ ac->gr_able = 1;
+ ac->gr_af_flags = pos[2+i+3];
+ }
+ break;
+
+ case 65: /* AS4 capability, RFC 4893 */
+ if (cl != 4)
+ goto err;
+
+ caps->as4_support = 1;
+ caps->as4_number = get_u32(pos + 2);
+ break;
+
+ case 69: /* ADD-PATH capability, RFC 7911 */
+ if (cl % 4)
+ goto err;
+
+ for (i = 0; i < cl; i += 4)
+ {
+ byte val = pos[2+i+3];
+ if (!val || (val > BGP_ADD_PATH_FULL))
{
- if (EMPTY_LIST(buck->prefixes))
- {
- DBG("Deleting empty bucket %p\n", buck);
- rem_node(&buck->send_node);
- bgp_free_bucket(p, buck);
- continue;
- }
-
- DBG("Processing bucket %p\n", buck);
- a_size = bgp_encode_attrs(p, w+2, buck->eattrs, 2048);
-
- if (a_size < 0)
- {
- log(L_ERR "%s: Attribute list too long, skipping corresponding routes", p->p.name);
- bgp_flush_prefixes(p, buck);
- rem_node(&buck->send_node);
- bgp_free_bucket(p, buck);
- continue;
- }
-
- put_u16(w, a_size);
- w += a_size + 2;
- r_size = bgp_encode_prefixes(p, w, buck, remains - a_size);
- w += r_size;
+ log(L_WARN "%s: Got ADD-PATH capability with unknown value %u, ignoring",
+ p->p.name, val);
break;
}
+ }
+
+ for (i = 0; i < cl; i += 4)
+ {
+ af = get_af3(pos+2+i);
+ ac = bgp_get_af_caps(caps, af);
+ ac->add_path = pos[2+i+3];
+ }
+ break;
+
+ case 70: /* Enhanced route refresh capability, RFC 7313 */
+ if (cl != 0)
+ goto err;
+
+ caps->enhanced_refresh = 1;
+ break;
+
+ /* We can safely ignore all other capabilities */
}
- if (!a_size) /* Attributes not already encoded */
+
+ ADVANCE(pos, len, 2 + cl);
+ }
+ return;
+
+err:
+ bgp_error(conn, 2, 0, NULL, 0);
+ return;
+}
+
+static int
+bgp_read_options(struct bgp_conn *conn, byte *pos, int len)
+{
+ struct bgp_proto *p = conn->bgp;
+ struct bgp_caps *caps;
+ int ol;
+
+ /* Max number of announced AFIs is limited by max option length (255) */
+ caps = alloca(sizeof(struct bgp_caps) + 64 * sizeof(struct bgp_af_caps));
+ memset(caps, 0, sizeof(struct bgp_caps));
+
+ while (len > 0)
+ {
+ if ((len < 2) || (len < (2 + pos[1])))
+ { bgp_error(conn, 2, 0, NULL, 0); return -1; }
+
+ ol = pos[1];
+ if (pos[0] == 2)
{
- put_u16(w, 0);
- w += 2;
+ /* BGP capabilities, RFC 5492 */
+ if (p->cf->capabilities)
+ bgp_read_capabilities(conn, caps, pos + 2, ol);
}
- if (wd_size || r_size)
+ else
{
- BGP_TRACE_RL(&rl_snd_update, D_PACKETS, "Sending UPDATE");
- return w;
+ /* Unknown option */
+ bgp_error(conn, 2, 4, pos, ol); /* FIXME: ol or ol+2 ? */
+ return -1;
}
- else
- return NULL;
+
+ ADVANCE(pos, len, 2 + ol);
+ }
+
+ uint n = sizeof(struct bgp_caps) + caps->af_count * sizeof(struct bgp_af_caps);
+ conn->remote_caps = mb_allocz(p->p.pool, n);
+ memcpy(conn->remote_caps, caps, n);
+
+ return 0;
}
static byte *
-bgp_create_end_mark(struct bgp_conn *conn, byte *buf)
+bgp_create_open(struct bgp_conn *conn, byte *buf)
{
struct bgp_proto *p = conn->bgp;
- BGP_TRACE(D_PACKETS, "Sending END-OF-RIB");
- put_u32(buf, 0);
- return buf+4;
-}
+ BGP_TRACE(D_PACKETS, "Sending OPEN(ver=%d,as=%d,hold=%d,id=%08x)",
+ BGP_VERSION, p->public_as, p->cf->hold_time, p->local_id);
-#else /* IPv6 version */
+ buf[0] = BGP_VERSION;
+ put_u16(buf+1, (p->public_as < 0xFFFF) ? p->public_as : AS_TRANS);
+ put_u16(buf+3, p->cf->hold_time);
+ put_u32(buf+5, p->local_id);
-static inline int
-same_iface(struct bgp_proto *p, ip_addr *ip)
-{
- neighbor *n = neigh_find(&p->p, ip, 0);
- return n && p->neigh && n->iface == p->neigh->iface;
+ if (p->cf->capabilities)
+ {
+ /* Prepare local_caps and write capabilities to buffer */
+ byte *end = bgp_write_capabilities(conn, buf+12);
+ uint len = end - (buf+12);
+
+ buf[9] = len + 2; /* Optional parameters length */
+ buf[10] = 2; /* Option 2: Capability list */
+ buf[11] = len; /* Option data length */
+
+ return end;
+ }
+ else
+ {
+ /* Prepare empty local_caps */
+ conn->local_caps = mb_allocz(p->p.pool, sizeof(struct bgp_caps));
+
+ buf[9] = 0; /* No optional parameters */
+ return buf + 10;
+ }
+
+ return buf;
}
-static byte *
-bgp_create_update(struct bgp_conn *conn, byte *buf)
+static void
+bgp_rx_open(struct bgp_conn *conn, byte *pkt, uint len)
{
struct bgp_proto *p = conn->bgp;
- struct bgp_bucket *buck;
- int size, second, rem_stored;
- int remains = bgp_max_packet_length(p) - BGP_HEADER_LENGTH - 4;
- byte *w, *w_stored, *tmp, *tstart;
- ip_addr *ipp, ip, ip_ll;
- ea_list *ea;
- eattr *nh;
+ struct bgp_conn *other;
+ u32 asn, hold, id;
- put_u16(buf, 0);
- w = buf+4;
+ /* Check state */
+ if (conn->state != BS_OPENSENT)
+ { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
- if ((buck = p->withdraw_bucket) && !EMPTY_LIST(buck->prefixes))
- {
- DBG("Withdrawn routes:\n");
- tmp = bgp_attach_attr_wa(&ea, bgp_linpool, BA_MP_UNREACH_NLRI, remains-8);
- *tmp++ = 0;
- *tmp++ = BGP_AF_IPV6;
- *tmp++ = 1;
- ea->attrs[0].u.ptr->length = 3 + bgp_encode_prefixes(p, tmp, buck, remains-11);
- size = bgp_encode_attrs(p, w, ea, remains);
- ASSERT(size >= 0);
- w += size;
- remains -= size;
- }
+ /* Check message contents */
+ if (len < 29 || len != 29 + (uint) pkt[28])
+ { bgp_error(conn, 1, 2, pkt+16, 2); return; }
- if (remains >= 3072)
- {
- while ((buck = (struct bgp_bucket *) HEAD(p->bucket_queue))->send_node.next)
- {
- if (EMPTY_LIST(buck->prefixes))
- {
- DBG("Deleting empty bucket %p\n", buck);
- rem_node(&buck->send_node);
- bgp_free_bucket(p, buck);
- continue;
- }
-
- DBG("Processing bucket %p\n", buck);
- rem_stored = remains;
- w_stored = w;
-
- size = bgp_encode_attrs(p, w, buck->eattrs, 2048);
- if (size < 0)
- {
- log(L_ERR "%s: Attribute list too long, skipping corresponding routes", p->p.name);
- bgp_flush_prefixes(p, buck);
- rem_node(&buck->send_node);
- bgp_free_bucket(p, buck);
- continue;
- }
- w += size;
- remains -= size;
-
- /* We have two addresses here in NEXT_HOP eattr. Really.
- Unless NEXT_HOP was modified by filter */
- nh = ea_find(buck->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
- ASSERT(nh);
- second = (nh->u.ptr->length == NEXT_HOP_LENGTH);
- ipp = (ip_addr *) nh->u.ptr->data;
- ip = ipp[0];
- ip_ll = IPA_NONE;
-
- if (ipa_equal(ip, p->source_addr))
- ip_ll = p->local_link;
- else
- {
- /* If we send a route with 'third party' next hop destinated
- * in the same interface, we should also send a link local
- * next hop address. We use the received one (stored in the
- * other part of BA_NEXT_HOP eattr). If we didn't received
- * it (for example it is a static route), we can't use
- * 'third party' next hop and we have to use local IP address
- * as next hop. Sending original next hop address without
- * link local address seems to be a natural way to solve that
- * problem, but it is contrary to RFC 2545 and Quagga does not
- * accept such routes.
- *
- * There are two cases, either we have global IP, or
- * IPA_NONE if the neighbor is link-local. For IPA_NONE,
- * we suppose it is on the same iface, see bgp_update_attrs().
- */
-
- if (ipa_zero(ip) || same_iface(p, &ip))
- {
- if (second && ipa_nonzero(ipp[1]))
- ip_ll = ipp[1];
- else
- {
- switch (p->cf->missing_lladdr)
- {
- case MLL_SELF:
- ip = p->source_addr;
- ip_ll = p->local_link;
- break;
- case MLL_DROP:
- log(L_ERR "%s: Missing link-local next hop address, skipping corresponding routes", p->p.name);
- w = w_stored;
- remains = rem_stored;
- bgp_flush_prefixes(p, buck);
- rem_node(&buck->send_node);
- bgp_free_bucket(p, buck);
- continue;
- case MLL_IGNORE:
- break;
- }
- }
- }
- }
-
- tstart = tmp = bgp_attach_attr_wa(&ea, bgp_linpool, BA_MP_REACH_NLRI, remains-8);
- *tmp++ = 0;
- *tmp++ = BGP_AF_IPV6;
- *tmp++ = 1;
-
- if (ipa_is_link_local(ip))
- ip = IPA_NONE;
-
- if (ipa_nonzero(ip_ll))
- {
- *tmp++ = 32;
- ipa_hton(ip);
- memcpy(tmp, &ip, 16);
- ipa_hton(ip_ll);
- memcpy(tmp+16, &ip_ll, 16);
- tmp += 32;
- }
- else
- {
- *tmp++ = 16;
- ipa_hton(ip);
- memcpy(tmp, &ip, 16);
- tmp += 16;
- }
-
- *tmp++ = 0; /* No SNPA information */
- tmp += bgp_encode_prefixes(p, tmp, buck, remains - (8+3+32+1));
- ea->attrs[0].u.ptr->length = tmp - tstart;
- size = bgp_encode_attrs(p, w, ea, remains);
- ASSERT(size >= 0);
- w += size;
- break;
- }
- }
+ if (pkt[19] != BGP_VERSION)
+ { u16 val = BGP_VERSION; bgp_error(conn, 2, 1, (byte *) &val, 2); return; }
+
+ asn = get_u16(pkt+20);
+ hold = get_u16(pkt+22);
+ id = get_u32(pkt+24);
+ BGP_TRACE(D_PACKETS, "Got OPEN(as=%d,hold=%d,id=%R)", asn, hold, id);
+
+ if (bgp_read_options(conn, pkt+29, pkt[28]) < 0)
+ return;
+
+ if (hold > 0 && hold < 3)
+ { bgp_error(conn, 2, 6, pkt+22, 2); return; }
+
+ /* RFC 6286 2.2 - router ID is nonzero and AS-wide unique */
+ if (!id || (p->is_internal && id == p->local_id))
+ { bgp_error(conn, 2, 3, pkt+24, -4); return; }
+
+ struct bgp_caps *caps = conn->remote_caps;
+
+ if (caps->as4_support)
+ {
+ u32 as4 = caps->as4_number;
+
+ if ((as4 != asn) && (asn != AS_TRANS))
+ log(L_WARN "%s: Peer advertised inconsistent AS numbers", p->p.name);
+
+ if (as4 != p->remote_as)
+ { as4 = htonl(as4); bgp_error(conn, 2, 2, (byte *) &as4, 4); return; }
+ }
+ else
+ {
+ if (asn != p->remote_as)
+ { bgp_error(conn, 2, 2, pkt+20, 2); return; }
+ }
+
+ /* Check the other connection */
+ other = (conn == &p->outgoing_conn) ? &p->incoming_conn : &p->outgoing_conn;
+ switch (other->state)
+ {
+ case BS_CONNECT:
+ case BS_ACTIVE:
+ /* Stop outgoing connection attempts */
+ bgp_conn_enter_idle_state(other);
+ break;
+
+ case BS_IDLE:
+ case BS_OPENSENT:
+ case BS_CLOSE:
+ break;
- size = w - (buf+4);
- put_u16(buf+2, size);
- lp_flush(bgp_linpool);
- if (size)
+ case BS_OPENCONFIRM:
+ /*
+ * Description of collision detection rules in RFC 4271 is confusing and
+ * contradictory, but it is essentially:
+ *
+ * 1. Router with higher ID is dominant
+ * 2. If both have the same ID, router with higher ASN is dominant [RFC6286]
+ * 3. When both connections are in OpenConfirm state, one initiated by
+ * the dominant router is kept.
+ *
+ * The first line in the expression below evaluates whether the neighbor
+ * is dominant, the second line whether the new connection was initiated
+ * by the neighbor. If both are true (or both are false), we keep the new
+ * connection, otherwise we keep the old one.
+ */
+ if (((p->local_id < id) || ((p->local_id == id) && (p->public_as < p->remote_as)))
+ == (conn == &p->incoming_conn))
{
- BGP_TRACE_RL(&rl_snd_update, D_PACKETS, "Sending UPDATE");
- return w;
+ /* Should close the other connection */
+ BGP_TRACE(D_EVENTS, "Connection collision, giving up the other connection");
+ bgp_error(other, 6, 7, NULL, 0);
+ break;
}
- else
- return NULL;
+ /* Fall thru */
+ case BS_ESTABLISHED:
+ /* Should close this connection */
+ BGP_TRACE(D_EVENTS, "Connection collision, giving up this connection");
+ bgp_error(conn, 6, 7, NULL, 0);
+ return;
+
+ default:
+ bug("bgp_rx_open: Unknown state");
+ }
+
+ /* Update our local variables */
+ conn->hold_time = MIN(hold, p->cf->hold_time);
+ conn->keepalive_time = p->cf->keepalive_time ? : conn->hold_time / 3;
+ conn->as4_session = conn->local_caps->as4_support && caps->as4_support;
+ conn->ext_messages = conn->local_caps->ext_messages && caps->ext_messages;
+ p->remote_id = id;
+
+ DBG("BGP: Hold timer set to %d, keepalive to %d, AS to %d, ID to %x, AS4 session to %d\n",
+ conn->hold_time, conn->keepalive_time, p->remote_as, p->remote_id, conn->as4_session);
+
+ bgp_schedule_packet(conn, NULL, PKT_KEEPALIVE);
+ bgp_start_timer(conn->hold_timer, conn->hold_time);
+ bgp_conn_enter_openconfirm_state(conn);
}
-static byte *
-bgp_create_end_mark(struct bgp_conn *conn, byte *buf)
+
+/*
+ * Next hop handling
+ */
+
+#define REPORT(msg, args...) \
+ ({ log(L_REMOTE "%s: " msg, s->proto->p.name, ## args); })
+
+#define WITHDRAW(msg, args...) \
+ ({ REPORT(msg, ## args); s->err_withdraw = 1; return; })
+
+#define BAD_NEXT_HOP "Invalid NEXT_HOP attribute"
+#define NO_NEXT_HOP "Missing NEXT_HOP attribute"
+
+
+static void
+bgp_apply_next_hop(struct bgp_parse_state *s, rta *a, ip_addr gw, ip_addr ll)
{
- struct bgp_proto *p = conn->bgp;
- BGP_TRACE(D_PACKETS, "Sending END-OF-RIB");
+ struct bgp_proto *p = s->proto;
+ struct bgp_channel *c = s->channel;
- put_u16(buf+0, 0);
- put_u16(buf+2, 6); /* length 4-9 */
- buf += 4;
+ if (c->cf->gw_mode == GW_DIRECT)
+ {
+ neighbor *nbr = NULL;
+
+ /* GW_DIRECT -> single_hop -> p->neigh != NULL */
+ if (ipa_nonzero(gw))
+ nbr = neigh_find2(&p->p, &gw, NULL, 0);
+ else if (ipa_nonzero(ll))
+ nbr = neigh_find2(&p->p, &ll, p->neigh->iface, 0);
+
+ if (!nbr || (nbr->scope == SCOPE_HOST))
+ WITHDRAW(BAD_NEXT_HOP);
+
+ a->dest = RTD_ROUTER;
+ a->gw = nbr->addr;
+ a->iface = nbr->iface;
+ a->hostentry = NULL;
+ a->igp_metric = 0;
+ }
+ else /* GW_RECURSIVE */
+ {
+ if (ipa_zero(gw))
+ WITHDRAW(BAD_NEXT_HOP);
- /* Empty MP_UNREACH_NLRI atribute */
- *buf++ = BAF_OPTIONAL;
- *buf++ = BA_MP_UNREACH_NLRI;
- *buf++ = 3; /* Length 7-9 */
- *buf++ = 0; /* AFI */
- *buf++ = BGP_AF_IPV6;
- *buf++ = 1; /* SAFI */
- return buf;
+ rta_set_recursive_next_hop(c->c.table, a, c->igp_table, gw, ll);
+ }
}
-#endif
-
-static inline byte *
-bgp_create_route_refresh(struct bgp_conn *conn, byte *buf)
+static inline int
+bgp_use_next_hop(struct bgp_export_state *s, eattr *a)
{
- struct bgp_proto *p = conn->bgp;
- BGP_TRACE(D_PACKETS, "Sending ROUTE-REFRESH");
+ struct bgp_proto *p = s->proto;
+ ip_addr *nh = (void *) a->u.ptr->data;
- /* Original original route refresh request, RFC 2918 */
- *buf++ = 0;
- *buf++ = BGP_AF;
- *buf++ = BGP_RR_REQUEST;
- *buf++ = 1; /* SAFI */
- return buf;
+ if (s->channel->cf->next_hop_self)
+ return 0;
+
+ if (s->channel->cf->next_hop_keep)
+ return 1;
+
+ /* Keep it when explicitly set in export filter */
+ if (a->type & EAF_FRESH)
+ return 1;
+
+ /* Keep it when exported to internal peers */
+ if (p->is_interior && ipa_nonzero(*nh))
+ return 1;
+
+ /* Keep it when forwarded between single-hop BGPs on the same iface */
+ struct iface *ifa = (s->src && s->src->neigh) ? s->src->neigh->iface : NULL;
+ return p->neigh && (p->neigh->iface == ifa);
}
-static inline byte *
-bgp_create_begin_refresh(struct bgp_conn *conn, byte *buf)
+static inline int
+bgp_use_gateway(struct bgp_export_state *s)
{
- struct bgp_proto *p = conn->bgp;
- BGP_TRACE(D_PACKETS, "Sending BEGIN-OF-RR");
+ struct bgp_proto *p = s->proto;
+ rta *ra = s->route->attrs;
- /* Demarcation of beginning of route refresh (BoRR), RFC 7313 */
- *buf++ = 0;
- *buf++ = BGP_AF;
- *buf++ = BGP_RR_BEGIN;
- *buf++ = 1; /* SAFI */
- return buf;
+ if (s->channel->cf->next_hop_self)
+ return 0;
+
+ /* We need valid global gateway */
+ if ((ra->dest != RTD_ROUTER) || ipa_zero(ra->gw) || ipa_is_link_local(ra->gw))
+ return 0;
+
+ /* Use it when exported to internal peers */
+ if (p->is_interior)
+ return 1;
+
+ /* Use it when forwarded to single-hop BGP peer on on the same iface */
+ return p->neigh && (p->neigh->iface == ra->iface);
}
-static inline byte *
-bgp_create_end_refresh(struct bgp_conn *conn, byte *buf)
+static void
+bgp_update_next_hop_ip(struct bgp_export_state *s, eattr *a, ea_list **to)
{
- struct bgp_proto *p = conn->bgp;
- BGP_TRACE(D_PACKETS, "Sending END-OF-RR");
+ if (!a || !bgp_use_next_hop(s, a))
+ {
+ if (bgp_use_gateway(s))
+ {
+ ip_addr nh[1] = { s->route->attrs->gw };
+ bgp_set_attr_data(to, s->pool, BA_NEXT_HOP, 0, nh, 16);
+ }
+ else
+ {
+ ip_addr nh[2] = { s->channel->next_hop_addr, s->channel->link_addr };
+ bgp_set_attr_data(to, s->pool, BA_NEXT_HOP, 0, nh, ipa_nonzero(nh[1]) ? 32 : 16);
+ }
+ }
- /* Demarcation of ending of route refresh (EoRR), RFC 7313 */
- *buf++ = 0;
- *buf++ = BGP_AF;
- *buf++ = BGP_RR_END;
- *buf++ = 1; /* SAFI */
- return buf;
+ /* Check if next hop is valid */
+ a = bgp_find_attr(*to, BA_NEXT_HOP);
+ if (!a)
+ WITHDRAW(NO_NEXT_HOP);
+
+ ip_addr *nh = (void *) a->u.ptr->data;
+ ip_addr peer = s->proto->cf->remote_ip;
+ uint len = a->u.ptr->length;
+
+ if (ipa_zero(nh[0]) && ((len != 32) || ipa_zero(nh[1])))
+ WITHDRAW(BAD_NEXT_HOP);
+
+ if (ipa_equal(peer, nh[0]) || ((len == 32) && ipa_equal(peer, nh[1])))
+ WITHDRAW(BAD_NEXT_HOP);
}
+/*
+ * UPDATE
+ */
+
static void
-bgp_create_header(byte *buf, uint len, uint type)
+bgp_rte_update(struct bgp_parse_state *s, net_addr *n, u32 path_id, rta *a0)
{
- memset(buf, 0xff, 16); /* Marker */
- put_u16(buf+16, len);
- buf[18] = type;
+ if (path_id != s->last_id)
+ {
+ s->last_src = rt_get_source(&s->proto->p, path_id);
+ s->last_id = path_id;
+
+ rta_free(s->cached_rta);
+ s->cached_rta = NULL;
+ }
+
+ if (!a0)
+ {
+ /* Route withdraw */
+ rte_update2(&s->channel->c, n, NULL, s->last_src);
+ return;
+ }
+
+ /* Prepare cached route attributes */
+ if (s->cached_rta == NULL)
+ {
+ a0->src = s->last_src;
+
+ /* Workaround for rta_lookup() breaking eattrs */
+ ea_list *ea = a0->eattrs;
+ s->cached_rta = rta_lookup(a0);
+ a0->eattrs = ea;
+ }
+
+ rta *a = rta_clone(s->cached_rta);
+ rte *e = rte_get_temp(a);
+
+ e->pflags = 0;
+ e->u.bgp.suppressed = 0;
+ rte_update2(&s->channel->c, n, e, s->last_src);
}
-/**
- * bgp_fire_tx - transmit packets
- * @conn: connection
- *
- * Whenever the transmit buffers of the underlying TCP connection
- * are free and we have any packets queued for sending, the socket functions
- * call bgp_fire_tx() which takes care of selecting the highest priority packet
- * queued (Notification > Keepalive > Open > Update), assembling its header
- * and body and sending it to the connection.
- */
-static int
-bgp_fire_tx(struct bgp_conn *conn)
+
+
+static uint
+bgp_encode_nlri_ip4(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
{
- struct bgp_proto *p = conn->bgp;
- uint s = conn->packets_to_send;
- sock *sk = conn->sk;
- byte *buf, *pkt, *end;
- int type;
+ byte *pos = buf;
- if (!sk)
- {
- conn->packets_to_send = 0;
- return 0;
- }
- buf = sk->tbuf;
- pkt = buf + BGP_HEADER_LENGTH;
+ while (!EMPTY_LIST(buck->prefixes) && (size >= (5 + sizeof(ip4_addr))))
+ {
+ struct bgp_prefix *px = HEAD(buck->prefixes);
+ struct net_addr_ip4 *net = (void *) px->net;
- if (s & (1 << PKT_SCHEDULE_CLOSE))
- {
- /* We can finally close connection and enter idle state */
- bgp_conn_enter_idle_state(conn);
- return 0;
- }
- if (s & (1 << PKT_NOTIFICATION))
+ /* Encode path ID */
+ if (s->add_path)
{
- s = 1 << PKT_SCHEDULE_CLOSE;
- type = PKT_NOTIFICATION;
- end = bgp_create_notification(conn, pkt);
+ put_u32(pos, px->path_id);
+ ADVANCE(pos, size, 4);
}
- else if (s & (1 << PKT_KEEPALIVE))
- {
- s &= ~(1 << PKT_KEEPALIVE);
- type = PKT_KEEPALIVE;
- end = pkt; /* Keepalives carry no data */
- BGP_TRACE(D_PACKETS, "Sending KEEPALIVE");
- bgp_start_timer(conn->keepalive_timer, conn->keepalive_time);
- }
- else if (s & (1 << PKT_OPEN))
+
+ ip4_addr a = ip4_hton(net->prefix);
+ uint b = (net->pxlen + 7) / 8;
+
+ /* Encode prefix length */
+ *pos = net->pxlen;
+ ADVANCE(pos, size, 1);
+
+ /* Encode prefix body */
+ memcpy(pos, &a, b);
+ ADVANCE(pos, size, b);
+
+ bgp_free_prefix(s->channel, px);
+ }
+
+ return pos - buf;
+}
+
+static void
+bgp_decode_nlri_ip4(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
+{
+ while (len)
+ {
+ net_addr_ip4 net;
+ u32 path_id = 0;
+
+ /* Decode path ID */
+ if (s->add_path)
{
- s &= ~(1 << PKT_OPEN);
- type = PKT_OPEN;
- end = bgp_create_open(conn, pkt);
+ if (len < 5)
+ bgp_parse_error(s, 1);
+
+ path_id = get_u32(pos);
+ ADVANCE(pos, len, 4);
}
- else if (s & (1 << PKT_ROUTE_REFRESH))
+
+ /* Decode prefix length */
+ uint l = *pos;
+ uint b = (l + 7) / 8;
+ ADVANCE(pos, len, 1);
+
+ if (l > IP4_MAX_PREFIX_LENGTH)
+ bgp_parse_error(s, 10);
+
+ if (len < b)
+ bgp_parse_error(s, 1);
+
+ /* Decode prefix body */
+ ip4_addr addr = IP4_NONE;
+ memcpy(&addr, pos, b);
+ ADVANCE(pos, len, b);
+
+ net = NET_ADDR_IP4(ip4_ntoh(addr), l);
+ net_normalize_ip4(&net);
+
+ // XXXX validate prefix
+
+ bgp_rte_update(s, (net_addr *) &net, path_id, a);
+ }
+}
+
+static uint
+bgp_encode_next_hop_ip4(struct bgp_write_state *s UNUSED, eattr *a, byte *buf, uint size UNUSED)
+{
+ /* This function is used only for MP-BGP, see bgp_encode_next_hop() for IPv4 BGP */
+
+ ASSERT(a->u.ptr->length == sizeof(ip_addr));
+
+ put_ip4(buf, ipa_to_ip4( *(ip_addr *) a->u.ptr->data ));
+
+ return 4;
+}
+
+static void
+bgp_decode_next_hop_ip4(struct bgp_parse_state *s, byte *data, uint len, rta *a)
+{
+ if (len != 4)
+ bgp_parse_error(s, 9);
+
+ ip_addr nh = ipa_from_ip4(get_ip4(data));
+
+ // XXXX validate next hop
+
+ bgp_set_attr_data(&(a->eattrs), s->pool, BA_NEXT_HOP, 0, &nh, sizeof(nh));
+ bgp_apply_next_hop(s, a, nh, IPA_NONE);
+}
+
+
+static uint
+bgp_encode_nlri_ip6(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, uint size)
+{
+ byte *pos = buf;
+
+ while (!EMPTY_LIST(buck->prefixes) && (size >= (5 + sizeof(ip6_addr))))
+ {
+ struct bgp_prefix *px = HEAD(buck->prefixes);
+ struct net_addr_ip6 *net = (void *) px->net;
+
+ /* Encode path ID */
+ if (s->add_path)
{
- s &= ~(1 << PKT_ROUTE_REFRESH);
- type = PKT_ROUTE_REFRESH;
- end = bgp_create_route_refresh(conn, pkt);
+ put_u32(pos, px->path_id);
+ ADVANCE(pos, size, 4);
}
- else if (s & (1 << PKT_BEGIN_REFRESH))
+
+ ip6_addr a = ip6_hton(net->prefix);
+ uint b = (net->pxlen + 7) / 8;
+
+ /* Encode prefix length */
+ *pos = net->pxlen;
+ ADVANCE(pos, size, 1);
+
+ /* Encode prefix body */
+ memcpy(pos, &a, b);
+ ADVANCE(pos, size, b);
+
+ bgp_free_prefix(s->channel, px);
+ }
+
+ return pos - buf;
+}
+
+static void
+bgp_decode_nlri_ip6(struct bgp_parse_state *s, byte *pos, uint len, rta *a)
+{
+ while (len)
+ {
+ net_addr_ip6 net;
+ u32 path_id = 0;
+
+ /* Decode path ID */
+ if (s->add_path)
{
- s &= ~(1 << PKT_BEGIN_REFRESH);
- type = PKT_ROUTE_REFRESH; /* BoRR is a subtype of RR */
- end = bgp_create_begin_refresh(conn, pkt);
+ if (len < 5)
+ bgp_parse_error(s, 1);
+
+ path_id = get_u32(pos);
+ ADVANCE(pos, len, 4);
}
- else if (s & (1 << PKT_UPDATE))
- {
- type = PKT_UPDATE;
- end = bgp_create_update(conn, pkt);
- if (!end)
- {
- /* No update to send, perhaps we need to send End-of-RIB or EoRR */
+ /* Decode prefix length */
+ uint l = *pos;
+ uint b = (l + 7) / 8;
+ ADVANCE(pos, len, 1);
- conn->packets_to_send = 0;
+ if (l > IP6_MAX_PREFIX_LENGTH)
+ bgp_parse_error(s, 10);
- if (p->feed_state == BFS_LOADED)
- {
- type = PKT_UPDATE;
- end = bgp_create_end_mark(conn, pkt);
- }
+ if (len < b)
+ bgp_parse_error(s, 1);
- else if (p->feed_state == BFS_REFRESHED)
- {
- type = PKT_ROUTE_REFRESH;
- end = bgp_create_end_refresh(conn, pkt);
- }
+ /* Decode prefix body */
+ ip6_addr addr = IP6_NONE;
+ memcpy(&addr, pos, b);
+ ADVANCE(pos, len, b);
- else /* Really nothing to send */
- return 0;
+ net = NET_ADDR_IP6(ip6_ntoh(addr), l);
+ net_normalize_ip6(&net);
- p->feed_state = BFS_NONE;
- }
- }
- else
- return 0;
+ // XXXX validate prefix
- conn->packets_to_send = s;
- bgp_create_header(buf, end - buf, type);
- return sk_send(sk, end - buf);
+ bgp_rte_update(s, (net_addr *) &net, path_id, a);
+ }
}
-/**
- * bgp_schedule_packet - schedule a packet for transmission
- * @conn: connection
- * @type: packet type
- *
- * Schedule a packet of type @type to be sent as soon as possible.
- */
-void
-bgp_schedule_packet(struct bgp_conn *conn, int type)
+static uint
+bgp_encode_next_hop_ip6(struct bgp_write_state *s UNUSED, eattr *a, byte *buf, uint size UNUSED)
{
- DBG("BGP: Scheduling packet type %d\n", type);
- conn->packets_to_send |= 1 << type;
- if (conn->sk && conn->sk->tpos == conn->sk->tbuf && !ev_active(conn->tx_ev))
- ev_schedule(conn->tx_ev);
+ ip_addr *nh = (void *) a->u.ptr->data;
+ uint len = a->u.ptr->length;
+
+ ASSERT((len == 16) || (len == 32));
+
+ put_ip6(buf, ipa_to_ip6(nh[0]));
+
+ if (len == 32)
+ put_ip6(buf+16, ipa_to_ip6(nh[1]));
+
+ return len;
}
-void
-bgp_kick_tx(void *vconn)
+static void
+bgp_decode_next_hop_ip6(struct bgp_parse_state *s, byte *data, uint len, rta *a)
{
- struct bgp_conn *conn = vconn;
+ struct adata *ad = lp_alloc_adata(s->pool, 32);
+ ip_addr *nh = (void *) ad->data;
- DBG("BGP: kicking TX\n");
- while (bgp_fire_tx(conn) > 0)
- ;
+ if ((len != 16) && (len != 32))
+ bgp_parse_error(s, 9);
+
+ nh[0] = ipa_from_ip6(get_ip6(data));
+ nh[1] = (len == 32) ? ipa_from_ip6(get_ip6(data+16)) : IPA_NONE;
+
+ if (ip6_is_link_local(nh[0]))
+ {
+ nh[1] = nh[0];
+ nh[0] = IPA_NONE;
+ }
+
+ if (!ip6_is_link_local(nh[1]))
+ nh[1] = IPA_NONE;
+
+ if (ipa_zero(nh[1]))
+ ad->length = 16;
+
+ // XXXX validate next hop
+
+ bgp_set_attr_ptr(&(a->eattrs), s->pool, BA_NEXT_HOP, 0, ad);
+ bgp_apply_next_hop(s, a, nh[0], nh[1]);
}
-void
-bgp_tx(sock *sk)
+
+static const struct bgp_af_desc bgp_af_table[] = {
+ {
+ .afi = BGP_AF_IPV4,
+ .net = NET_IP4,
+ .name = "ipv4",
+ .encode_nlri = bgp_encode_nlri_ip4,
+ .decode_nlri = bgp_decode_nlri_ip4,
+ .encode_next_hop = bgp_encode_next_hop_ip4,
+ .decode_next_hop = bgp_decode_next_hop_ip4,
+ .update_next_hop = bgp_update_next_hop_ip,
+ },
+ {
+ .afi = BGP_AF_IPV4_MC,
+ .net = NET_IP4,
+ .name = "ipv4-mc",
+ .encode_nlri = bgp_encode_nlri_ip4,
+ .decode_nlri = bgp_decode_nlri_ip4,
+ .encode_next_hop = bgp_encode_next_hop_ip4,
+ .decode_next_hop = bgp_decode_next_hop_ip4,
+ .update_next_hop = bgp_update_next_hop_ip,
+ },
+ {
+ .afi = BGP_AF_IPV6,
+ .net = NET_IP6,
+ .name = "ipv6",
+ .encode_nlri = bgp_encode_nlri_ip6,
+ .decode_nlri = bgp_decode_nlri_ip6,
+ .encode_next_hop = bgp_encode_next_hop_ip6,
+ .decode_next_hop = bgp_decode_next_hop_ip6,
+ .update_next_hop = bgp_update_next_hop_ip,
+ },
+ {
+ .afi = BGP_AF_IPV6_MC,
+ .net = NET_IP6,
+ .name = "ipv6-mc",
+ .encode_nlri = bgp_encode_nlri_ip6,
+ .decode_nlri = bgp_decode_nlri_ip6,
+ .encode_next_hop = bgp_encode_next_hop_ip6,
+ .decode_next_hop = bgp_decode_next_hop_ip6,
+ .update_next_hop = bgp_update_next_hop_ip,
+ },
+};
+
+const struct bgp_af_desc *
+bgp_get_af_desc(u32 afi)
{
- struct bgp_conn *conn = sk->data;
+ uint i;
+ for (i = 0; i < ARRAY_SIZE(bgp_af_table); i++)
+ if (bgp_af_table[i].afi == afi)
+ return &bgp_af_table[i];
- DBG("BGP: TX hook\n");
- while (bgp_fire_tx(conn) > 0)
- ;
+ return NULL;
+}
+
+static inline uint
+bgp_encode_nlri(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
+{
+ return s->channel->desc->encode_nlri(s, buck, buf, end - buf);
}
-/* Capatibility negotiation as per RFC 2842 */
+static inline uint
+bgp_encode_next_hop(struct bgp_write_state *s, eattr *nh, byte *buf)
+{
+ return s->channel->desc->encode_next_hop(s, nh, buf, 255);
+}
void
-bgp_parse_capabilities(struct bgp_conn *conn, byte *opt, int len)
+bgp_update_next_hop(struct bgp_export_state *s, eattr *a, ea_list **to)
{
- // struct bgp_proto *p = conn->bgp;
- int i, cl;
+ s->channel->desc->update_next_hop(s, a, to);
+}
- while (len > 0)
- {
- if (len < 2 || len < 2 + opt[1])
- goto err;
+#define MAX_ATTRS_LENGTH (end-buf+BGP_HEADER_LENGTH - 1024)
- cl = opt[1];
+static byte *
+bgp_create_ip_reach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
+{
+ /*
+ * 2 B Withdrawn Routes Length (zero)
+ * --- IPv4 Withdrawn Routes NLRI (unused)
+ * 2 B Total Path Attribute Length
+ * var Path Attributes
+ * var IPv4 Network Layer Reachability Information
+ */
+
+ int lr, la;
+
+ la = bgp_encode_attrs(s, buck->eattrs, buf+4, buf + MAX_ATTRS_LENGTH);
+ if (la < 0)
+ {
+ /* Attribute list too long */
+ bgp_withdraw_bucket(s->channel, buck);
+ return NULL;
+ }
- switch (opt[0])
- {
- case 2: /* Route refresh capability, RFC 2918 */
- if (cl != 0)
- goto err;
- conn->peer_refresh_support = 1;
- break;
+ put_u16(buf+0, 0);
+ put_u16(buf+2, la);
- case 6: /* Extended message length capability, draft */
- if (cl != 0)
- goto err;
- conn->peer_ext_messages_support = 1;
- break;
+ lr = bgp_encode_nlri(s, buck, buf+4+la, end);
- case 64: /* Graceful restart capability, RFC 4724 */
- if (cl % 4 != 2)
- goto err;
- conn->peer_gr_aware = 1;
- conn->peer_gr_able = 0;
- conn->peer_gr_time = get_u16(opt + 2) & 0x0fff;
- conn->peer_gr_flags = opt[2] & 0xf0;
- conn->peer_gr_aflags = 0;
- for (i = 2; i < cl; i += 4)
- if (opt[2+i+0] == 0 && opt[2+i+1] == BGP_AF && opt[2+i+2] == 1) /* Match AFI/SAFI */
- {
- conn->peer_gr_able = 1;
- conn->peer_gr_aflags = opt[2+i+3];
- }
- break;
+ return buf+4+la+lr;
+}
- case 65: /* AS4 capability, RFC 4893 */
- if (cl != 4)
- goto err;
- conn->peer_as4_support = 1;
- if (conn->bgp->cf->enable_as4)
- conn->advertised_as = get_u32(opt + 2);
- break;
+static byte *
+bgp_create_mp_reach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
+{
+ /*
+ * 2 B IPv4 Withdrawn Routes Length (zero)
+ * --- IPv4 Withdrawn Routes NLRI (unused)
+ * 2 B Total Path Attribute Length
+ * 1 B MP_REACH_NLRI hdr - Attribute Flags
+ * 1 B MP_REACH_NLRI hdr - Attribute Type Code
+ * 2 B MP_REACH_NLRI hdr - Length of Attribute Data
+ * 2 B MP_REACH_NLRI data - Address Family Identifier
+ * 1 B MP_REACH_NLRI data - Subsequent Address Family Identifier
+ * 1 B MP_REACH_NLRI data - Length of Next Hop Network Address
+ * var MP_REACH_NLRI data - Network Address of Next Hop
+ * 1 B MP_REACH_NLRI data - Reserved (zero)
+ * var MP_REACH_NLRI data - Network Layer Reachability Information
+ * var Rest of Path Attributes
+ * --- IPv4 Network Layer Reachability Information (unused)
+ */
+
+ int lh, lr, la; /* Lengths of next hop, NLRI and attributes */
+
+ /* Begin of MP_REACH_NLRI atribute */
+ buf[4] = BAF_OPTIONAL | BAF_EXT_LEN;
+ buf[5] = BA_MP_REACH_NLRI;
+ put_u16(buf+6, 0); /* Will be fixed later */
+ put_af3(buf+8, s->channel->afi);
+ byte *pos = buf+11;
+
+ /* Encode attributes to temporary buffer */
+ byte *abuf = alloca(MAX_ATTRS_LENGTH);
+ la = bgp_encode_attrs(s, buck->eattrs, abuf, abuf + MAX_ATTRS_LENGTH);
+ if (la < 0)
+ {
+ /* Attribute list too long */
+ bgp_withdraw_bucket(s->channel, buck);
+ return NULL;
+ }
- case 69: /* ADD-PATH capability, draft */
- if (cl % 4)
- goto err;
- for (i = 0; i < cl; i += 4)
- if (opt[2+i+0] == 0 && opt[2+i+1] == BGP_AF && opt[2+i+2] == 1) /* Match AFI/SAFI */
- conn->peer_add_path = opt[2+i+3];
- if (conn->peer_add_path > ADD_PATH_FULL)
- goto err;
- break;
+ /* Encode the next hop */
+ lh = bgp_encode_next_hop(s, s->mp_next_hop, pos+1);
+ *pos = lh;
+ pos += 1+lh;
- case 70: /* Enhanced route refresh capability, RFC 7313 */
- if (cl != 0)
- goto err;
- conn->peer_enhanced_refresh_support = 1;
- break;
+ /* Reserved field */
+ *pos++ = 0;
- /* We can safely ignore all other capabilities */
- }
- len -= 2 + cl;
- opt += 2 + cl;
- }
- return;
+ /* Encode the NLRI */
+ lr = bgp_encode_nlri(s, buck, pos, end - la);
+ pos += lr;
- err:
- bgp_error(conn, 2, 0, NULL, 0);
- return;
+ /* End of MP_REACH_NLRI atribute, update data length */
+ put_u16(buf+6, pos-buf-8);
+
+ /* Copy remaining attributes */
+ memcpy(pos, abuf, la);
+ pos += la;
+
+ /* Initial UPDATE fields */
+ put_u16(buf+0, 0);
+ put_u16(buf+2, pos-buf-4);
+
+ return pos;
}
-static int
-bgp_parse_options(struct bgp_conn *conn, byte *opt, int len)
+#undef MAX_ATTRS_LENGTH
+
+static byte *
+bgp_create_ip_unreach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
{
- struct bgp_proto *p = conn->bgp;
- int ol;
+ /*
+ * 2 B Withdrawn Routes Length
+ * var IPv4 Withdrawn Routes NLRI
+ * 2 B Total Path Attribute Length (zero)
+ * --- Path Attributes (unused)
+ * --- IPv4 Network Layer Reachability Information (unused)
+ */
- while (len > 0)
- {
- if (len < 2 || len < 2 + opt[1])
- { bgp_error(conn, 2, 0, NULL, 0); return 0; }
-#ifdef LOCAL_DEBUG
- {
- int i;
- DBG("\tOption %02x:", opt[0]);
- for(i=0; i<opt[1]; i++)
- DBG(" %02x", opt[2+i]);
- DBG("\n");
- }
-#endif
+ uint len = bgp_encode_nlri(s, buck, buf+2, end);
- ol = opt[1];
- switch (opt[0])
- {
- case 2:
- if (conn->start_state == BSS_CONNECT_NOCAP)
- BGP_TRACE(D_PACKETS, "Ignoring received capabilities");
- else
- bgp_parse_capabilities(conn, opt + 2, ol);
- break;
+ put_u16(buf+0, len);
+ put_u16(buf+2+len, 0);
- default:
- /*
- * BGP specs don't tell us to send which option
- * we didn't recognize, but it's common practice
- * to do so. Also, capability negotiation with
- * Cisco routers doesn't work without that.
- */
- bgp_error(conn, 2, 4, opt, ol);
- return 0;
- }
- len -= 2 + ol;
- opt += 2 + ol;
- }
- return 0;
+ return buf+4+len;
}
-static void
-bgp_rx_open(struct bgp_conn *conn, byte *pkt, int len)
+static byte *
+bgp_create_mp_unreach(struct bgp_write_state *s, struct bgp_bucket *buck, byte *buf, byte *end)
{
- struct bgp_conn *other;
- struct bgp_proto *p = conn->bgp;
- unsigned hold;
- u16 base_as;
- u32 id;
+ /*
+ * 2 B Withdrawn Routes Length (zero)
+ * --- IPv4 Withdrawn Routes NLRI (unused)
+ * 2 B Total Path Attribute Length
+ * 1 B MP_UNREACH_NLRI hdr - Attribute Flags
+ * 1 B MP_UNREACH_NLRI hdr - Attribute Type Code
+ * 2 B MP_UNREACH_NLRI hdr - Length of Attribute Data
+ * 2 B MP_UNREACH_NLRI data - Address Family Identifier
+ * 1 B MP_UNREACH_NLRI data - Subsequent Address Family Identifier
+ * var MP_UNREACH_NLRI data - Network Layer Reachability Information
+ * --- IPv4 Network Layer Reachability Information (unused)
+ */
+
+ uint len = bgp_encode_nlri(s, buck, buf+11, end);
- /* Check state */
- if (conn->state != BS_OPENSENT)
- { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
+ put_u16(buf+0, 0);
+ put_u16(buf+2, 7+len);
- /* Check message contents */
- if (len < 29 || len != 29 + pkt[28])
- { bgp_error(conn, 1, 2, pkt+16, 2); return; }
- if (pkt[19] != BGP_VERSION)
- { bgp_error(conn, 2, 1, pkt+19, 1); return; } /* RFC 1771 says 16 bits, draft-09 tells to use 8 */
- conn->advertised_as = base_as = get_u16(pkt+20);
- hold = get_u16(pkt+22);
- id = get_u32(pkt+24);
- BGP_TRACE(D_PACKETS, "Got OPEN(as=%d,hold=%d,id=%08x)", conn->advertised_as, hold, id);
+ /* Begin of MP_UNREACH_NLRI atribute */
+ buf[4] = BAF_OPTIONAL | BAF_EXT_LEN;
+ buf[5] = BA_MP_UNREACH_NLRI;
+ put_u16(buf+6, 3+len);
+ put_af3(buf+8, s->channel->afi);
- if (bgp_parse_options(conn, pkt+29, pkt[28]))
- return;
+ return buf+11+len;
+}
- if (hold > 0 && hold < 3)
- { bgp_error(conn, 2, 6, pkt+22, 2); return; }
+static byte *
+bgp_create_update(struct bgp_channel *c, byte *buf)
+{
+ struct bgp_proto *p = (void *) c->c.proto;
+ struct bgp_bucket *buck;
+ byte *end = buf + (bgp_max_packet_length(p->conn) - BGP_HEADER_LENGTH);
+ byte *res = NULL;
+
+ /* Initialize write state */
+ struct bgp_write_state s = {
+ .proto = p,
+ .channel = c,
+ .pool = bgp_linpool,
+ .as4_session = p->as4_session,
+ .add_path = c->add_path_tx,
+ };
+
+again:
+
+ /* Try unreachable bucket */
+ if ((buck = c->withdraw_bucket) && !EMPTY_LIST(buck->prefixes))
+ {
+ res = (c->afi == BGP_AF_IPV4) ?
+ bgp_create_ip_unreach(&s, buck, buf, end):
+ bgp_create_mp_unreach(&s, buck, buf, end);
- /* RFC 6286 2.2 - router ID is nonzero and AS-wide unique */
- if (!id || (p->is_internal && id == p->local_id))
- { bgp_error(conn, 2, 3, pkt+24, -4); return; }
+ goto done;
+ }
- if ((conn->advertised_as != base_as) && (base_as != AS_TRANS))
- log(L_WARN "%s: Peer advertised inconsistent AS numbers", p->p.name);
+ /* Try reachable buckets */
+ if (!EMPTY_LIST(c->bucket_queue))
+ {
+ buck = HEAD(c->bucket_queue);
- if (conn->advertised_as != p->remote_as)
+ /* Cleanup empty buckets */
+ if (EMPTY_LIST(buck->prefixes))
{
- if (conn->peer_as4_support)
- {
- u32 val = htonl(conn->advertised_as);
- bgp_error(conn, 2, 2, (byte *) &val, 4);
- }
- else
- bgp_error(conn, 2, 2, pkt+20, 2);
-
- return;
+ bgp_free_bucket(c, buck);
+ goto again;
}
- /* Check the other connection */
- other = (conn == &p->outgoing_conn) ? &p->incoming_conn : &p->outgoing_conn;
- switch (other->state)
- {
- case BS_CONNECT:
- case BS_ACTIVE:
- /* Stop outgoing connection attempts */
- bgp_conn_enter_idle_state(other);
- break;
+ res = (c->afi == BGP_AF_IPV4) ?
+ bgp_create_ip_reach(&s, buck, buf, end):
+ bgp_create_mp_reach(&s, buck, buf, end);
- case BS_IDLE:
- case BS_OPENSENT:
- case BS_CLOSE:
- break;
+ if (EMPTY_LIST(buck->prefixes))
+ bgp_free_bucket(c, buck);
+ else
+ bgp_defer_bucket(c, buck);
- case BS_OPENCONFIRM:
- /*
- * Description of collision detection rules in RFC 4271 is confusing and
- * contradictory, but it is essentially:
- *
- * 1. Router with higher ID is dominant
- * 2. If both have the same ID, router with higher ASN is dominant [RFC6286]
- * 3. When both connections are in OpenConfirm state, one initiated by
- * the dominant router is kept.
- *
- * The first line in the expression below evaluates whether the neighbor
- * is dominant, the second line whether the new connection was initiated
- * by the neighbor. If both are true (or both are false), we keep the new
- * connection, otherwise we keep the old one.
- */
- if (((p->local_id < id) || ((p->local_id == id) && (p->local_as < p->remote_as)))
- == (conn == &p->incoming_conn))
- {
- /* Should close the other connection */
- BGP_TRACE(D_EVENTS, "Connection collision, giving up the other connection");
- bgp_error(other, 6, 7, NULL, 0);
- break;
- }
- /* Fall thru */
- case BS_ESTABLISHED:
- /* Should close this connection */
- BGP_TRACE(D_EVENTS, "Connection collision, giving up this connection");
- bgp_error(conn, 6, 7, NULL, 0);
- return;
- default:
- bug("bgp_rx_open: Unknown state");
- }
+ if (!res)
+ goto again;
- /* Update our local variables */
- conn->hold_time = MIN(hold, p->cf->hold_time);
- conn->keepalive_time = p->cf->keepalive_time ? : conn->hold_time / 3;
- p->remote_id = id;
- p->as4_session = p->cf->enable_as4 && conn->peer_as4_support;
- p->add_path_rx = (p->cf->add_path & ADD_PATH_RX) && (conn->peer_add_path & ADD_PATH_TX);
- p->add_path_tx = (p->cf->add_path & ADD_PATH_TX) && (conn->peer_add_path & ADD_PATH_RX);
- p->gr_ready = p->cf->gr_mode && conn->peer_gr_able;
- p->ext_messages = p->cf->enable_extended_messages && conn->peer_ext_messages_support;
+ goto done;
+ }
- if (p->add_path_tx)
- p->p.accept_ra_types = RA_ANY;
+ /* No more prefixes to send */
+ return NULL;
- DBG("BGP: Hold timer set to %d, keepalive to %d, AS to %d, ID to %x, AS4 session to %d\n", conn->hold_time, conn->keepalive_time, p->remote_as, p->remote_id, p->as4_session);
+done:
+ BGP_TRACE_RL(&rl_snd_update, D_PACKETS, "Sending UPDATE");
+ lp_flush(s.pool);
- bgp_schedule_packet(conn, PKT_KEEPALIVE);
- bgp_start_timer(conn->hold_timer, conn->hold_time);
- bgp_conn_enter_openconfirm_state(conn);
+ return res;
}
-
-static inline void
-bgp_rx_end_mark(struct bgp_proto *p)
+static byte *
+bgp_create_ip_end_mark(struct bgp_channel *c UNUSED, byte *buf)
{
- BGP_TRACE(D_PACKETS, "Got END-OF-RIB");
+ /* Empty update packet */
+ put_u32(buf, 0);
+
+ return buf+4;
+}
- if (p->load_state == BFS_LOADING)
- p->load_state = BFS_NONE;
+static byte *
+bgp_create_mp_end_mark(struct bgp_channel *c, byte *buf)
+{
+ put_u16(buf+0, 0);
+ put_u16(buf+2, 6); /* length 4--9 */
- if (p->p.gr_recovery)
- proto_graceful_restart_unlock(&p->p);
+ /* Empty MP_UNREACH_NLRI atribute */
+ buf[4] = BAF_OPTIONAL;
+ buf[5] = BA_MP_UNREACH_NLRI;
+ buf[6] = 3; /* Length 7--9 */
+ put_af3(buf+7, c->afi);
- if (p->gr_active)
- bgp_graceful_restart_done(p);
+ return buf+10;
}
+static byte *
+bgp_create_end_mark(struct bgp_channel *c, byte *buf)
+{
+ struct bgp_proto *p = (void *) c->c.proto;
-#define DECODE_PREFIX(pp, ll) do { \
- if (p->add_path_rx) \
- { \
- if (ll < 5) { err=1; goto done; } \
- path_id = get_u32(pp); \
- pp += 4; \
- ll -= 4; \
- } \
- int b = *pp++; \
- int q; \
- ll--; \
- if (b > BITS_PER_IP_ADDRESS) { err=10; goto done; } \
- q = (b+7) / 8; \
- if (ll < q) { err=1; goto done; } \
- memcpy(&prefix, pp, q); \
- pp += q; \
- ll -= q; \
- ipa_ntoh(prefix); \
- prefix = ipa_and(prefix, ipa_mkmask(b)); \
- pxlen = b; \
-} while (0)
+ BGP_TRACE(D_PACKETS, "Sending END-OF-RIB");
+ return (c->afi == BGP_AF_IPV4) ?
+ bgp_create_ip_end_mark(c, buf):
+ bgp_create_mp_end_mark(c, buf);
+}
static inline void
-bgp_rte_update(struct bgp_proto *p, ip_addr prefix, int pxlen,
- u32 path_id, u32 *last_id, struct rte_src **src,
- rta *a0, rta **a)
+bgp_rx_end_mark(struct bgp_proto *p, u32 afi)
{
- if (path_id != *last_id)
- {
- *src = rt_get_source(&p->p, path_id);
- *last_id = path_id;
+ struct bgp_channel *c = bgp_get_channel(p, afi);
- if (*a)
- {
- rta_free(*a);
- *a = NULL;
- }
- }
+ BGP_TRACE(D_PACKETS, "Got END-OF-RIB");
- /* Prepare cached route attributes */
- if (!*a)
- {
- a0->src = *src;
+ /* XXXX handle unknown AF in MP_*_NLRI */
+ if (!c)
+ return;
- /* Workaround for rta_lookup() breaking eattrs */
- ea_list *ea = a0->eattrs;
- *a = rta_lookup(a0);
- a0->eattrs = ea;
- }
+ if (c->load_state == BFS_LOADING)
+ c->load_state = BFS_NONE;
- net *n = net_get(p->p.table, prefix, pxlen);
- rte *e = rte_get_temp(rta_clone(*a));
- e->net = n;
- e->pflags = 0;
- e->u.bgp.suppressed = 0;
- rte_update2(p->p.main_ahook, n, e, *src);
+ if (p->p.gr_recovery)
+ channel_graceful_restart_unlock(&c->c);
+
+ if (c->gr_active)
+ bgp_graceful_restart_done(c);
}
static inline void
-bgp_rte_withdraw(struct bgp_proto *p, ip_addr prefix, int pxlen,
- u32 path_id, u32 *last_id, struct rte_src **src)
+bgp_decode_nlri(struct bgp_parse_state *s, u32 afi, byte *nlri, uint len, ea_list *ea, byte *nh, uint nh_len)
{
- if (path_id != *last_id)
- {
- *src = rt_find_source(&p->p, path_id);
- *last_id = path_id;
- }
+ struct bgp_channel *c = bgp_get_channel(s->proto, afi);
+ rta *a = NULL;
- net *n = net_find(p->p.table, prefix, pxlen);
- rte_update2( p->p.main_ahook, n, NULL, *src);
-}
-
-static inline int
-bgp_set_next_hop(struct bgp_proto *p, rta *a)
-{
- struct eattr *nh = ea_find(a->eattrs, EA_CODE(EAP_BGP, BA_NEXT_HOP));
- ip_addr *nexthop = (ip_addr *) nh->u.ptr->data;
+ /* XXXX handle unknown AF in MP_*_NLRI */
+ if (!c)
+ return;
-#ifdef IPV6
- int second = (nh->u.ptr->length == NEXT_HOP_LENGTH) && ipa_nonzero(nexthop[1]);
+ s->channel = c;
+ s->add_path = c->add_path_rx;
- /* First address should not be link-local, but may be zero in direct mode */
- if (ipa_is_link_local(*nexthop))
- *nexthop = IPA_NONE;
-#else
- int second = 0;
-#endif
+ s->last_id = 0;
+ s->last_src = s->proto->p.main_source;
- if (p->cf->gw_mode == GW_DIRECT)
- {
- neighbor *ng = NULL;
+ /*
+ * IPv4 BGP and MP-BGP may be used together in one update, therefore we do not
+ * add BA_NEXT_HOP in bgp_decode_attrs(), but we add it here independently for
+ * IPv4 BGP and MP-BGP. We undo the attribute (and possibly others attached by
+ * decode_next_hop hooks) by restoring a->eattrs afterwards.
+ */
- if (ipa_nonzero(*nexthop))
- ng = neigh_find(&p->p, nexthop, 0);
- else if (second) /* GW_DIRECT -> single_hop -> p->neigh != NULL */
- ng = neigh_find2(&p->p, nexthop + 1, p->neigh->iface, 0);
+ if (ea)
+ {
+ a = alloca(sizeof(struct rta));
+ memset(a, 0, sizeof(struct rta));
- /* Fallback */
- if (!ng)
- ng = p->neigh;
+ a->source = RTS_BGP;
+ a->scope = SCOPE_UNIVERSE;
+ a->cast = RTC_UNICAST;
+ a->dest = RTD_UNREACHABLE;
+ a->from = s->proto->cf->remote_ip;
+ a->eattrs = ea;
- if (ng->scope == SCOPE_HOST)
- return 0;
+ c->desc->decode_next_hop(s, nh, nh_len, a);
- a->dest = RTD_ROUTER;
- a->gw = ng->addr;
- a->iface = ng->iface;
- a->hostentry = NULL;
- a->igp_metric = 0;
- }
- else /* GW_RECURSIVE */
- {
- if (ipa_zero(*nexthop))
- return 0;
+ /* Handle withdraw during next hop decoding */
+ if (s->err_withdraw)
+ a = NULL;
+ }
- rta_set_recursive_next_hop(p->p.table, a, p->igp_table, nexthop, nexthop + second);
- }
+ c->desc->decode_nlri(s, nlri, len, a);
- return 1;
+ rta_free(s->cached_rta);
+ s->cached_rta = NULL;
}
-#ifndef IPV6 /* IPv4 version */
-
static void
-bgp_do_rx_update(struct bgp_conn *conn,
- byte *withdrawn, int withdrawn_len,
- byte *nlri, int nlri_len,
- byte *attrs, int attr_len)
+bgp_rx_update(struct bgp_conn *conn, byte *pkt, uint len)
{
struct bgp_proto *p = conn->bgp;
- struct rte_src *src = p->p.main_source;
- rta *a0, *a = NULL;
- ip_addr prefix;
- int pxlen, err = 0;
- u32 path_id = 0;
- u32 last_id = 0;
+ ea_list *ea = NULL;
- /* Check for End-of-RIB marker */
- if (!withdrawn_len && !attr_len && !nlri_len)
- {
- bgp_rx_end_mark(p);
- return;
- }
+ BGP_TRACE_RL(&rl_rcv_update, D_PACKETS, "Got UPDATE");
- /* Withdraw routes */
- while (withdrawn_len)
- {
- DECODE_PREFIX(withdrawn, withdrawn_len);
- DBG("Withdraw %I/%d\n", prefix, pxlen);
+ /* Workaround for some BGP implementations that skip initial KEEPALIVE */
+ if (conn->state == BS_OPENCONFIRM)
+ bgp_conn_enter_established_state(conn);
- bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
- }
+ if (conn->state != BS_ESTABLISHED)
+ { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
- if (!attr_len && !nlri_len) /* shortcut */
- return;
+ bgp_start_timer(conn->hold_timer, conn->hold_time);
- a0 = bgp_decode_attrs(conn, attrs, attr_len, bgp_linpool, nlri_len);
+ /* Initialize parse state */
+ struct bgp_parse_state s = {
+ .proto = p,
+ .pool = bgp_linpool,
+ .as4_session = p->as4_session,
+ };
- if (conn->state != BS_ESTABLISHED) /* fatal error during decoding */
- return;
+ /* Parse error handler */
+ if (setjmp(s.err_jmpbuf))
+ {
+ bgp_error(conn, 3, s.err_subcode, NULL, 0);
+ goto done;
+ }
- if (a0 && nlri_len && !bgp_set_next_hop(p, a0))
- a0 = NULL;
+ /* Check minimal length */
+ if (len < 23)
+ { bgp_error(conn, 1, 2, pkt+16, 2); return; }
- last_id = 0;
- src = p->p.main_source;
+ /* Skip fixed header */
+ uint pos = 19;
- while (nlri_len)
- {
- DECODE_PREFIX(nlri, nlri_len);
- DBG("Add %I/%d\n", prefix, pxlen);
+ /*
+ * UPDATE message format
+ *
+ * 2 B IPv4 Withdrawn Routes Length
+ * var IPv4 Withdrawn Routes NLRI
+ * 2 B Total Path Attribute Length
+ * var Path Attributes
+ * var IPv4 Reachable Routes NLRI
+ */
- if (a0)
- bgp_rte_update(p, prefix, pxlen, path_id, &last_id, &src, a0, &a);
- else /* Forced withdraw as a result of soft error */
- bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
- }
+ s.ip_unreach_len = get_u16(pkt + pos);
+ s.ip_unreach_nlri = pkt + pos + 2;
+ pos += 2 + s.ip_unreach_len;
- done:
- if (a)
- rta_free(a);
+ if (pos + 2 > len)
+ bgp_parse_error(&s, 1);
- if (err)
- bgp_error(conn, 3, err, NULL, 0);
+ s.attr_len = get_u16(pkt + pos);
+ s.attrs = pkt + pos + 2;
+ pos += 2 + s.attr_len;
+
+ if (pos > len)
+ bgp_parse_error(&s, 1);
+
+ s.ip_reach_len = len - pos;
+ s.ip_reach_nlri = pkt + pos;
+
+
+ if (s.attr_len)
+ ea = bgp_decode_attrs(&s, s.attrs, s.attr_len);
+
+ /* Check for End-of-RIB marker */
+ if (!s.attr_len && !s.ip_unreach_len && !s.ip_reach_len)
+ { bgp_rx_end_mark(p, BGP_AF_IPV4); goto done; }
+
+ /* Check for MP End-of-RIB marker */
+ if ((s.attr_len < 8) && !s.ip_unreach_len && !s.ip_reach_len &&
+ !s.mp_reach_len && !s.mp_unreach_len && s.mp_unreach_af) /* XXXX See RFC 7606 5.2 */
+ { bgp_rx_end_mark(p, s.mp_unreach_af); goto done; }
+
+ if (s.ip_unreach_len)
+ bgp_decode_nlri(&s, BGP_AF_IPV4, s.ip_unreach_nlri, s.ip_unreach_len, NULL, NULL, 0);
+
+ if (s.mp_unreach_len)
+ bgp_decode_nlri(&s, s.mp_unreach_af, s.mp_unreach_nlri, s.mp_unreach_len, NULL, NULL, 0);
+
+ if (s.ip_reach_len)
+ bgp_decode_nlri(&s, BGP_AF_IPV4, s.ip_reach_nlri, s.ip_reach_len,
+ ea, s.ip_next_hop_data, s.ip_next_hop_len);
+
+ if (s.mp_reach_len)
+ bgp_decode_nlri(&s, s.mp_reach_af, s.mp_reach_nlri, s.mp_reach_len,
+ ea, s.mp_next_hop_data, s.mp_next_hop_len);
+done:
+ rta_free(s.cached_rta);
+ lp_flush(s.pool);
return;
}
-#else /* IPv6 version */
-
-#define DO_NLRI(name) \
- start = x = p->name##_start; \
- len = len0 = p->name##_len; \
- if (len) \
- { \
- if (len < 3) { err=9; goto done; } \
- af = get_u16(x); \
- sub = x[2]; \
- x += 3; \
- len -= 3; \
- DBG("\tNLRI AF=%d sub=%d len=%d\n", af, sub, len);\
- } \
- else \
- af = 0; \
- if (af == BGP_AF_IPV6)
-static void
-bgp_attach_next_hop(rta *a0, byte *x)
+/*
+ * ROUTE-REFRESH
+ */
+
+static inline byte *
+bgp_create_route_refresh(struct bgp_channel *c, byte *buf)
{
- ip_addr *nh = (ip_addr *) bgp_attach_attr_wa(&a0->eattrs, bgp_linpool, BA_NEXT_HOP, NEXT_HOP_LENGTH);
- memcpy(nh, x+1, 16);
- ipa_ntoh(nh[0]);
+ struct bgp_proto *p = (void *) c->c.proto;
- /* We store received link local address in the other part of BA_NEXT_HOP eattr. */
- if (*x == 32)
- {
- memcpy(nh+1, x+17, 16);
- ipa_ntoh(nh[1]);
- }
- else
- nh[1] = IPA_NONE;
+ BGP_TRACE(D_PACKETS, "Sending ROUTE-REFRESH");
+
+ /* Original route refresh request, RFC 2918 */
+ put_af4(buf, c->afi);
+ buf[2] = BGP_RR_REQUEST;
+
+ return buf+4;
}
+static inline byte *
+bgp_create_begin_refresh(struct bgp_channel *c, byte *buf)
+{
+ struct bgp_proto *p = (void *) c->c.proto;
+
+ BGP_TRACE(D_PACKETS, "Sending BEGIN-OF-RR");
+
+ /* Demarcation of beginning of route refresh (BoRR), RFC 7313 */
+ put_af4(buf, c->afi);
+ buf[2] = BGP_RR_BEGIN;
+
+ return buf+4;
+}
+
+static inline byte *
+bgp_create_end_refresh(struct bgp_channel *c, byte *buf)
+{
+ struct bgp_proto *p = (void *) c->c.proto;
+
+ BGP_TRACE(D_PACKETS, "Sending END-OF-RR");
+
+ /* Demarcation of ending of route refresh (EoRR), RFC 7313 */
+ put_af4(buf, c->afi);
+ buf[2] = BGP_RR_END;
+
+ return buf+4;
+}
static void
-bgp_do_rx_update(struct bgp_conn *conn,
- byte *withdrawn, int withdrawn_len,
- byte *nlri, int nlri_len,
- byte *attrs, int attr_len)
+bgp_rx_route_refresh(struct bgp_conn *conn, byte *pkt, uint len)
{
struct bgp_proto *p = conn->bgp;
- struct rte_src *src = p->p.main_source;
- byte *start, *x;
- int len, len0;
- unsigned af, sub;
- rta *a0, *a = NULL;
- ip_addr prefix;
- int pxlen, err = 0;
- u32 path_id = 0;
- u32 last_id = 0;
-
- p->mp_reach_len = 0;
- p->mp_unreach_len = 0;
- a0 = bgp_decode_attrs(conn, attrs, attr_len, bgp_linpool, 0);
-
- if (conn->state != BS_ESTABLISHED) /* fatal error during decoding */
- return;
- /* Check for End-of-RIB marker */
- if ((attr_len < 8) && !withdrawn_len && !nlri_len && !p->mp_reach_len &&
- (p->mp_unreach_len == 3) && (get_u16(p->mp_unreach_start) == BGP_AF_IPV6))
- {
- bgp_rx_end_mark(p);
- return;
- }
+ if (conn->state != BS_ESTABLISHED)
+ { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
- DO_NLRI(mp_unreach)
- {
- while (len)
- {
- DECODE_PREFIX(x, len);
- DBG("Withdraw %I/%d\n", prefix, pxlen);
- bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
- }
- }
+ if (!conn->local_caps->route_refresh)
+ { bgp_error(conn, 1, 3, pkt+18, 1); return; }
- DO_NLRI(mp_reach)
- {
- /* Create fake NEXT_HOP attribute */
- if (len < 1 || (*x != 16 && *x != 32) || len < *x + 2)
- { err = 9; goto done; }
+ if (len < (BGP_HEADER_LENGTH + 4))
+ { bgp_error(conn, 1, 2, pkt+16, 2); return; }
- if (a0)
- bgp_attach_next_hop(a0, x);
+ if (len > (BGP_HEADER_LENGTH + 4))
+ { bgp_error(conn, 7, 1, pkt, MIN(len, 2048)); return; }
- /* Also ignore one reserved byte */
- len -= *x + 2;
- x += *x + 2;
+ struct bgp_channel *c = bgp_get_channel(p, get_af4(pkt+19));
+ if (!c)
+ {
+ log(L_WARN "%s: Got ROUTE-REFRESH subtype %u for AF %u.%u, ignoring",
+ p->p.name, pkt[21], get_u16(pkt+19), pkt[22]);
+ return;
+ }
- if (a0 && ! bgp_set_next_hop(p, a0))
- a0 = NULL;
+ /* RFC 7313 redefined reserved field as RR message subtype */
+ uint subtype = p->enhanced_refresh ? pkt[21] : BGP_RR_REQUEST;
- last_id = 0;
- src = p->p.main_source;
+ switch (subtype)
+ {
+ case BGP_RR_REQUEST:
+ BGP_TRACE(D_PACKETS, "Got ROUTE-REFRESH");
+ channel_request_feeding(&c->c);
+ break;
- while (len)
- {
- DECODE_PREFIX(x, len);
- DBG("Add %I/%d\n", prefix, pxlen);
+ case BGP_RR_BEGIN:
+ BGP_TRACE(D_PACKETS, "Got BEGIN-OF-RR");
+ bgp_refresh_begin(c);
+ break;
- if (a0)
- bgp_rte_update(p, prefix, pxlen, path_id, &last_id, &src, a0, &a);
- else /* Forced withdraw as a result of soft error */
- bgp_rte_withdraw(p, prefix, pxlen, path_id, &last_id, &src);
- }
- }
+ case BGP_RR_END:
+ BGP_TRACE(D_PACKETS, "Got END-OF-RR");
+ bgp_refresh_end(c);
+ break;
- done:
- if (a)
- rta_free(a);
+ default:
+ log(L_WARN "%s: Got ROUTE-REFRESH message with unknown subtype %u, ignoring",
+ p->p.name, subtype);
+ break;
+ }
+}
- if (err) /* Use subcode 9, not err */
- bgp_error(conn, 3, 9, NULL, 0);
+static inline struct bgp_channel *
+bgp_get_channel_to_send(struct bgp_proto *p, struct bgp_conn *conn)
+{
+ uint i = conn->last_channel;
- return;
+ /* Try the last channel, but at most several times */
+ if ((conn->channels_to_send & (1 << i)) &&
+ (conn->last_channel_count < 16))
+ goto found;
+
+ /* Find channel with non-zero channels_to_send */
+ do
+ {
+ i++;
+ if (i >= p->channel_count)
+ i = 0;
+ }
+ while (! (conn->channels_to_send & (1 << i)));
+
+ /* Use that channel */
+ conn->last_channel = i;
+ conn->last_channel_count = 0;
+
+found:
+ conn->last_channel_count++;
+ return p->channel_map[i];
}
-#endif
+static inline int
+bgp_send(struct bgp_conn *conn, uint type, uint len)
+{
+ sock *sk = conn->sk;
+ byte *buf = sk->tbuf;
-static void
-bgp_rx_update(struct bgp_conn *conn, byte *pkt, int len)
+ memset(buf, 0xff, 16); /* Marker */
+ put_u16(buf+16, len);
+ buf[18] = type;
+
+ return sk_send(sk, len);
+}
+
+/**
+ * bgp_fire_tx - transmit packets
+ * @conn: connection
+ *
+ * Whenever the transmit buffers of the underlying TCP connection
+ * are free and we have any packets queued for sending, the socket functions
+ * call bgp_fire_tx() which takes care of selecting the highest priority packet
+ * queued (Notification > Keepalive > Open > Update), assembling its header
+ * and body and sending it to the connection.
+ */
+static int
+bgp_fire_tx(struct bgp_conn *conn)
{
struct bgp_proto *p = conn->bgp;
- byte *withdrawn, *attrs, *nlri;
- int withdrawn_len, attr_len, nlri_len;
+ struct bgp_channel *c;
+ byte *buf, *pkt, *end;
+ uint s;
- BGP_TRACE_RL(&rl_rcv_update, D_PACKETS, "Got UPDATE");
+ if (!conn->sk)
+ return 0;
- /* Workaround for some BGP implementations that skip initial KEEPALIVE */
- if (conn->state == BS_OPENCONFIRM)
- bgp_conn_enter_established_state(conn);
+ buf = conn->sk->tbuf;
+ pkt = buf + BGP_HEADER_LENGTH;
+ s = conn->packets_to_send;
- if (conn->state != BS_ESTABLISHED)
- { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
- bgp_start_timer(conn->hold_timer, conn->hold_time);
+ if (s & (1 << PKT_SCHEDULE_CLOSE))
+ {
+ /* We can finally close connection and enter idle state */
+ bgp_conn_enter_idle_state(conn);
+ return 0;
+ }
+ if (s & (1 << PKT_NOTIFICATION))
+ {
+ conn->packets_to_send = 1 << PKT_SCHEDULE_CLOSE;
+ end = bgp_create_notification(conn, pkt);
+ return bgp_send(conn, PKT_NOTIFICATION, end - buf);
+ }
+ else if (s & (1 << PKT_KEEPALIVE))
+ {
+ conn->packets_to_send &= ~(1 << PKT_KEEPALIVE);
+ BGP_TRACE(D_PACKETS, "Sending KEEPALIVE");
+ bgp_start_timer(conn->keepalive_timer, conn->keepalive_time);
+ return bgp_send(conn, PKT_KEEPALIVE, BGP_HEADER_LENGTH);
+ }
+ else if (s & (1 << PKT_OPEN))
+ {
+ conn->packets_to_send &= ~(1 << PKT_OPEN);
+ end = bgp_create_open(conn, pkt);
+ return bgp_send(conn, PKT_OPEN, end - buf);
+ }
+ else while (conn->channels_to_send)
+ {
+ c = bgp_get_channel_to_send(p, conn);
+ s = c->packets_to_send;
- /* Find parts of the packet and check sizes */
- if (len < 23)
+ if (s & (1 << PKT_ROUTE_REFRESH))
{
- bgp_error(conn, 1, 2, pkt+16, 2);
- return;
+ c->packets_to_send &= ~(1 << PKT_ROUTE_REFRESH);
+ end = bgp_create_route_refresh(c, pkt);
+ return bgp_send(conn, PKT_ROUTE_REFRESH, end - buf);
}
- withdrawn = pkt + 21;
- withdrawn_len = get_u16(pkt + 19);
- if (withdrawn_len + 23 > len)
- goto malformed;
- attrs = withdrawn + withdrawn_len + 2;
- attr_len = get_u16(attrs - 2);
- if (withdrawn_len + attr_len + 23 > len)
- goto malformed;
- nlri = attrs + attr_len;
- nlri_len = len - withdrawn_len - attr_len - 23;
- if (!attr_len && nlri_len)
- goto malformed;
- DBG("Sizes: withdrawn=%d, attrs=%d, NLRI=%d\n", withdrawn_len, attr_len, nlri_len);
-
- lp_flush(bgp_linpool);
-
- bgp_do_rx_update(conn, withdrawn, withdrawn_len, nlri, nlri_len, attrs, attr_len);
- return;
+ else if (s & (1 << PKT_BEGIN_REFRESH))
+ {
+ /* BoRR is a subtype of RR, but uses separate bit in packets_to_send */
+ c->packets_to_send &= ~(1 << PKT_BEGIN_REFRESH);
+ end = bgp_create_begin_refresh(c, pkt);
+ return bgp_send(conn, PKT_ROUTE_REFRESH, end - buf);
+ }
+ else if (s & (1 << PKT_UPDATE))
+ {
+ end = bgp_create_update(c, pkt);
+ if (end)
+ return bgp_send(conn, PKT_UPDATE, end - buf);
+
+ /* No update to send, perhaps we need to send End-of-RIB or EoRR */
+ c->packets_to_send = 0;
+ conn->channels_to_send &= ~(1 << c->index);
+
+ if (c->feed_state == BFS_LOADED)
+ {
+ c->feed_state = BFS_NONE;
+ end = bgp_create_end_mark(c, pkt);
+ return bgp_send(conn, PKT_UPDATE, end - buf);
+ }
+
+ else if (c->feed_state == BFS_REFRESHED)
+ {
+ c->feed_state = BFS_NONE;
+ end = bgp_create_end_refresh(c, pkt);
+ return bgp_send(conn, PKT_ROUTE_REFRESH, end - buf);
+ }
+ }
+ else if (s)
+ bug("Channel packets_to_send: %x", s);
+
+ c->packets_to_send = 0;
+ conn->channels_to_send &= ~(1 << c->index);
+ }
+
+ return 0;
+}
+
+/**
+ * bgp_schedule_packet - schedule a packet for transmission
+ * @conn: connection
+ * @c: channel
+ * @type: packet type
+ *
+ * Schedule a packet of type @type to be sent as soon as possible.
+ */
+void
+bgp_schedule_packet(struct bgp_conn *conn, struct bgp_channel *c, int type)
+{
+ ASSERT(conn->sk);
+
+ DBG("BGP: Scheduling packet type %d\n", type);
+
+ if (c)
+ {
+ if (! conn->channels_to_send)
+ {
+ conn->last_channel = c->index;
+ conn->last_channel_count = 0;
+ }
+
+ c->packets_to_send |= 1 << type;
+ conn->channels_to_send |= 1 << c->index;
+ }
+ else
+ conn->packets_to_send |= 1 << type;
+
+ if ((conn->sk->tpos == conn->sk->tbuf) && !ev_active(conn->tx_ev))
+ ev_schedule(conn->tx_ev);
+}
+
+void
+bgp_kick_tx(void *vconn)
+{
+ struct bgp_conn *conn = vconn;
+
+ DBG("BGP: kicking TX\n");
+ while (bgp_fire_tx(conn) > 0)
+ ;
+}
+
+void
+bgp_tx(sock *sk)
+{
+ struct bgp_conn *conn = sk->data;
-malformed:
- bgp_error(conn, 3, 1, NULL, 0);
+ DBG("BGP: TX hook\n");
+ while (bgp_fire_tx(conn) > 0)
+ ;
}
+
static struct {
byte major, minor;
byte *msg;
@@ -1477,26 +1906,25 @@ static struct {
* which might be static string or given temporary buffer.
*/
const char *
-bgp_error_dsc(unsigned code, unsigned subcode)
+bgp_error_dsc(uint code, uint subcode)
{
static char buff[32];
- unsigned i;
+ uint i;
+
for (i=0; i < ARRAY_SIZE(bgp_msg_table); i++)
if (bgp_msg_table[i].major == code && bgp_msg_table[i].minor == subcode)
- {
- return bgp_msg_table[i].msg;
- }
+ return bgp_msg_table[i].msg;
- bsprintf(buff, "Unknown error %d.%d", code, subcode);
+ bsprintf(buff, "Unknown error %u.%u", code, subcode);
return buff;
}
void
-bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned subcode, byte *data, unsigned len)
+bgp_log_error(struct bgp_proto *p, u8 class, char *msg, uint code, uint subcode, byte *data, uint len)
{
const byte *name;
byte *t, argbuf[36];
- unsigned i;
+ uint i;
/* Don't report Cease messages generated by myself */
if (code == 6 && class == BE_BGP_TX)
@@ -1512,7 +1940,7 @@ bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned
if ((code == 2) && (subcode == 2) && ((len == 2) || (len == 4)))
{
/* Bad peer AS - we would like to print the AS */
- t += bsprintf(t, "%d", (len == 2) ? get_u16(data) : get_u32(data));
+ t += bsprintf(t, "%u", (len == 2) ? get_u16(data) : get_u32(data));
goto done;
}
if (len > 16)
@@ -1526,50 +1954,28 @@ bgp_log_error(struct bgp_proto *p, u8 class, char *msg, unsigned code, unsigned
}
static void
-bgp_rx_notification(struct bgp_conn *conn, byte *pkt, int len)
+bgp_rx_notification(struct bgp_conn *conn, byte *pkt, uint len)
{
struct bgp_proto *p = conn->bgp;
+
if (len < 21)
- {
- bgp_error(conn, 1, 2, pkt+16, 2);
- return;
- }
+ { bgp_error(conn, 1, 2, pkt+16, 2); return; }
- unsigned code = pkt[19];
- unsigned subcode = pkt[20];
+ uint code = pkt[19];
+ uint subcode = pkt[20];
int err = (code != 6);
bgp_log_error(p, BE_BGP_RX, "Received", code, subcode, pkt+21, len-21);
bgp_store_error(p, conn, BE_BGP_RX, (code << 16) | subcode);
-#ifndef IPV6
- if ((code == 2) && ((subcode == 4) || (subcode == 7))
- /* Error related to capability:
- * 4 - Peer does not support capabilities at all.
- * 7 - Peer request some capability. Strange unless it is IPv6 only peer.
- */
- && (p->cf->capabilities == 2)
- /* Capabilities are not explicitly enabled or disabled, therefore heuristic is used */
- && (conn->start_state == BSS_CONNECT)
- /* Failed connection attempt have used capabilities */
- && (p->cf->remote_as <= 0xFFFF))
- /* Not possible with disabled capabilities */
- {
- /* We try connect without capabilities */
- log(L_WARN "%s: Capability related error received, retry with capabilities disabled", p->p.name);
- p->start_state = BSS_CONNECT_NOCAP;
- err = 0;
- }
-#endif
-
bgp_conn_enter_close_state(conn);
- bgp_schedule_packet(conn, PKT_SCHEDULE_CLOSE);
+ bgp_schedule_packet(conn, NULL, PKT_SCHEDULE_CLOSE);
- if (err)
- {
- bgp_update_startup_delay(p);
- bgp_stop(p, 0);
- }
+ if (err)
+ {
+ bgp_update_startup_delay(p);
+ bgp_stop(p, 0);
+ }
}
static void
@@ -1579,64 +1985,12 @@ bgp_rx_keepalive(struct bgp_conn *conn)
BGP_TRACE(D_PACKETS, "Got KEEPALIVE");
bgp_start_timer(conn->hold_timer, conn->hold_time);
- switch (conn->state)
- {
- case BS_OPENCONFIRM:
- bgp_conn_enter_established_state(conn);
- break;
- case BS_ESTABLISHED:
- break;
- default:
- bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0);
- }
-}
-static void
-bgp_rx_route_refresh(struct bgp_conn *conn, byte *pkt, int len)
-{
- struct bgp_proto *p = conn->bgp;
+ if (conn->state == BS_OPENCONFIRM)
+ { bgp_conn_enter_established_state(conn); return; }
if (conn->state != BS_ESTABLISHED)
- { bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0); return; }
-
- if (!p->cf->enable_refresh)
- { bgp_error(conn, 1, 3, pkt+18, 1); return; }
-
- if (len < (BGP_HEADER_LENGTH + 4))
- { bgp_error(conn, 1, 2, pkt+16, 2); return; }
-
- if (len > (BGP_HEADER_LENGTH + 4))
- { bgp_error(conn, 7, 1, pkt, MIN(len, 2048)); return; }
-
- /* FIXME - we ignore AFI/SAFI values, as we support
- just one value and even an error code for an invalid
- request is not defined */
-
- /* RFC 7313 redefined reserved field as RR message subtype */
- uint subtype = conn->peer_enhanced_refresh_support ? pkt[21] : BGP_RR_REQUEST;
-
- switch (subtype)
- {
- case BGP_RR_REQUEST:
- BGP_TRACE(D_PACKETS, "Got ROUTE-REFRESH");
- proto_request_feeding(&p->p);
- break;
-
- case BGP_RR_BEGIN:
- BGP_TRACE(D_PACKETS, "Got BEGIN-OF-RR");
- bgp_refresh_begin(p);
- break;
-
- case BGP_RR_END:
- BGP_TRACE(D_PACKETS, "Got END-OF-RR");
- bgp_refresh_end(p);
- break;
-
- default:
- log(L_WARN "%s: Got ROUTE-REFRESH message with unknown subtype %u, ignoring",
- p->p.name, subtype);
- break;
- }
+ bgp_error(conn, 5, fsm_err_subcode[conn->state], NULL, 0);
}
@@ -1650,7 +2004,7 @@ bgp_rx_route_refresh(struct bgp_conn *conn, byte *pkt, int len)
* packet handler according to the packet type.
*/
static void
-bgp_rx_packet(struct bgp_conn *conn, byte *pkt, unsigned len)
+bgp_rx_packet(struct bgp_conn *conn, byte *pkt, uint len)
{
byte type = pkt[18];
@@ -1660,14 +2014,14 @@ bgp_rx_packet(struct bgp_conn *conn, byte *pkt, unsigned len)
mrt_dump_bgp_packet(conn, pkt, len);
switch (type)
- {
- case PKT_OPEN: return bgp_rx_open(conn, pkt, len);
- case PKT_UPDATE: return bgp_rx_update(conn, pkt, len);
- case PKT_NOTIFICATION: return bgp_rx_notification(conn, pkt, len);
- case PKT_KEEPALIVE: return bgp_rx_keepalive(conn);
- case PKT_ROUTE_REFRESH: return bgp_rx_route_refresh(conn, pkt, len);
- default: bgp_error(conn, 1, 3, pkt+18, 1);
- }
+ {
+ case PKT_OPEN: return bgp_rx_open(conn, pkt, len);
+ case PKT_UPDATE: return bgp_rx_update(conn, pkt, len);
+ case PKT_NOTIFICATION: return bgp_rx_notification(conn, pkt, len);
+ case PKT_KEEPALIVE: return bgp_rx_keepalive(conn);
+ case PKT_ROUTE_REFRESH: return bgp_rx_route_refresh(conn, pkt, len);
+ default: bgp_error(conn, 1, 3, pkt+18, 1);
+ }
}
/**
@@ -1681,13 +2035,12 @@ bgp_rx_packet(struct bgp_conn *conn, byte *pkt, unsigned len)
* bgp_rx_packet().
*/
int
-bgp_rx(sock *sk, int size)
+bgp_rx(sock *sk, uint size)
{
struct bgp_conn *conn = sk->data;
- struct bgp_proto *p = conn->bgp;
byte *pkt_start = sk->rbuf;
byte *end = pkt_start + size;
- unsigned i, len;
+ uint i, len;
DBG("BGP: RX hook: Got %d bytes\n", size);
while (end >= pkt_start + BGP_HEADER_LENGTH)
@@ -1701,7 +2054,7 @@ bgp_rx(sock *sk, int size)
break;
}
len = get_u16(pkt_start+16);
- if (len < BGP_HEADER_LENGTH || len > bgp_max_packet_length(p))
+ if ((len < BGP_HEADER_LENGTH) || (len > bgp_max_packet_length(conn)))
{
bgp_error(conn, 1, 2, pkt_start+16, 2);
break;
diff --git a/proto/ospf/Makefile b/proto/ospf/Makefile
index fe52ed30..39e74f71 100644
--- a/proto/ospf/Makefile
+++ b/proto/ospf/Makefile
@@ -2,3 +2,5 @@ src := dbdes.c hello.c iface.c lsack.c lsalib.c lsreq.c lsupd.c neighbor.c ospf.
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/ospf/config.Y b/proto/ospf/config.Y
index 297774b5..72928875 100644
--- a/proto/ospf/config.Y
+++ b/proto/ospf/config.Y
@@ -42,6 +42,20 @@ ospf_iface_finish(void)
if ((ip->autype == OSPF_AUTH_NONE) && (ip->passwords != NULL))
log(L_WARN "Password option without authentication option does not make sense");
+
+ if (ip->passwords)
+ {
+ struct password_item *pass;
+ WALK_LIST(pass, *ip->passwords)
+ {
+ if (pass->alg && (ip->autype != OSPF_AUTH_CRYPT))
+ cf_error("Password algorithm option requires cryptographic authentication");
+
+ /* Set default OSPF crypto algorithms */
+ if (!pass->alg && (ip->autype == OSPF_AUTH_CRYPT))
+ pass->alg = ospf_cfg_is_v2() ? ALG_MD5 : ALG_HMAC_SHA256;
+ }
+ }
}
static void
diff --git a/proto/ospf/hello.c b/proto/ospf/hello.c
index 3fbb6167..2c55155d 100644
--- a/proto/ospf/hello.c
+++ b/proto/ospf/hello.c
@@ -105,7 +105,7 @@ ospf_send_hello(struct ospf_iface *ifa, int kind, struct ospf_neighbor *dirn)
}
i = 0;
- max = (ospf_pkt_maxsize(p, ifa) - length) / sizeof(u32);
+ max = (ospf_pkt_maxsize(ifa) - length) / sizeof(u32);
/* Fill all neighbors */
if (kind != OHS_SHUTDOWN)
@@ -222,9 +222,12 @@ ospf_receive_hello(struct ospf_packet *pkt, struct ospf_iface *ifa,
rcv_priority = ps->priority;
int pxlen = u32_masklen(ntohl(ps->netmask));
+ if (pxlen < 0)
+ DROP("prefix garbled", ntohl(ps->netmask));
+
if ((ifa->type != OSPF_IT_VLINK) &&
(ifa->type != OSPF_IT_PTP) &&
- (pxlen != ifa->addr->prefix.pxlen))
+ ((uint) pxlen != ifa->addr->prefix.pxlen))
DROP("prefix length mismatch", pxlen);
neighbors = ps->neighbors;
diff --git a/proto/ospf/iface.c b/proto/ospf/iface.c
index 6ef24ffe..675cf76d 100644
--- a/proto/ospf/iface.c
+++ b/proto/ospf/iface.c
@@ -9,6 +9,7 @@
*/
#include "ospf.h"
+#include "nest/password.h"
const char *ospf_is_names[] = {
@@ -52,6 +53,20 @@ ifa_tx_length(struct ospf_iface *ifa)
}
static inline uint
+ifa_tx_hdrlen(struct ospf_iface *ifa)
+{
+ struct ospf_proto *p = ifa->oa->po;
+
+ uint hlen = ospf_is_v2(p) ? IP4_HEADER_LENGTH : IP6_HEADER_LENGTH;
+
+ /* Relevant just for OSPFv2 */
+ if (ifa->autype == OSPF_AUTH_CRYPT)
+ hlen += max_mac_length(ifa->passwords);
+
+ return hlen;
+}
+
+static inline uint
ifa_bufsize(struct ospf_iface *ifa)
{
uint bsize = ifa->cf->rx_buffer ?: ifa->iface->mtu;
@@ -67,13 +82,7 @@ ifa_flood_queue_size(struct ospf_iface *ifa)
int
ospf_iface_assure_bufsize(struct ospf_iface *ifa, uint plen)
{
- struct ospf_proto *p = ifa->oa->po;
-
- plen += ospf_is_v2(p) ? IP4_HEADER_LENGTH : IP6_HEADER_LENGTH;
-
- /* This is relevant just for OSPFv2 */
- if (ifa->autype == OSPF_AUTH_CRYPT)
- plen += OSPF_AUTH_CRYPT_SIZE;
+ plen += ifa->tx_hdrlen;
if (plen <= ifa->sk->tbsize)
return 0;
@@ -569,6 +578,7 @@ ospf_iface_new(struct ospf_area *oa, struct ifa *addr, struct ospf_iface_patt *i
ifa->stub = ospf_iface_stubby(ip, addr);
ifa->ioprob = OSPF_I_OK;
ifa->tx_length = ifa_tx_length(ifa);
+ ifa->tx_hdrlen = ifa_tx_hdrlen(ifa);
ifa->check_link = ip->check_link;
ifa->ecmp_weight = ip->ecmp_weight;
ifa->check_ttl = (ip->ttl_security == 1);
@@ -680,6 +690,7 @@ ospf_iface_new_vlink(struct ospf_proto *p, struct ospf_iface_patt *ip)
ifa->deadint = ip->deadint;
ifa->inftransdelay = ip->inftransdelay;
ifa->tx_length = ospf_is_v2(p) ? IP4_MIN_MTU : IP6_MIN_MTU;
+ ifa->tx_hdrlen = ifa_tx_hdrlen(ifa);
ifa->autype = ip->autype;
ifa->passwords = ip->passwords;
ifa->instance_id = ip->instance_id;
@@ -820,6 +831,9 @@ ospf_iface_reconfigure(struct ospf_iface *ifa, struct ospf_iface_patt *new)
/* Update passwords */
ifa->passwords = new->passwords;
+ /* Update header length */
+ ifa->tx_hdrlen = ifa_tx_hdrlen(ifa);
+
/* Remaining options are just for proper interfaces */
if (ifa->type == OSPF_IT_VLINK)
return 1;
diff --git a/proto/ospf/lsalib.c b/proto/ospf/lsalib.c
index b4d2faba..b88a114d 100644
--- a/proto/ospf/lsalib.c
+++ b/proto/ospf/lsalib.c
@@ -461,7 +461,7 @@ lsa_validate_sum3_net(struct ospf_lsa_header *lsa, struct ospf_lsa_sum3_net *bod
}
static int
-lsa_validate_sum3_rt(struct ospf_lsa_header *lsa, struct ospf_lsa_sum3_rt *body)
+lsa_validate_sum3_rt(struct ospf_lsa_header *lsa, struct ospf_lsa_sum3_rt *body UNUSED)
{
if (lsa->length != (HDRLEN + sizeof(struct ospf_lsa_sum3_rt)))
return 0;
diff --git a/proto/ospf/lsupd.c b/proto/ospf/lsupd.c
index 65ad8e3d..157d9628 100644
--- a/proto/ospf/lsupd.c
+++ b/proto/ospf/lsupd.c
@@ -105,7 +105,7 @@ invalid:
static inline void
-ospf_lsa_lsrq_down(struct top_hash_entry *req, struct ospf_neighbor *n, struct ospf_neighbor *from)
+ospf_lsa_lsrq_down(struct top_hash_entry *req, struct ospf_neighbor *n)
{
if (req == n->lsrqi)
n->lsrqi = SNODE_NEXT(req);
@@ -188,7 +188,7 @@ ospf_enqueue_lsa(struct ospf_proto *p, struct top_hash_entry *en, struct ospf_if
{
/* If we already have full queue, we send some packets */
uint sent = ospf_flood_lsupd(p, ifa->flood_queue, ifa->flood_queue_used, ifa->flood_queue_used / 2, ifa);
- int i;
+ uint i;
for (i = 0; i < sent; i++)
ifa->flood_queue[i]->ret_count--;
@@ -275,7 +275,7 @@ ospf_flood_lsa(struct ospf_proto *p, struct top_hash_entry *en, struct ospf_neig
/* If same or newer, remove LSA from the link state request list */
if (cmp > CMP_OLDER)
- ospf_lsa_lsrq_down(req, n, from);
+ ospf_lsa_lsrq_down(req, n);
/* If older or same, skip processing of this neighbor */
if (cmp < CMP_NEWER)
@@ -330,7 +330,7 @@ ospf_prepare_lsupd(struct ospf_proto *p, struct ospf_iface *ifa,
pkt = ospf_tx_buffer(ifa);
hlen = ospf_lsupd_hdrlen(p);
- maxsize = ospf_pkt_maxsize(p, ifa);
+ maxsize = ospf_pkt_maxsize(ifa);
ospf_pkt_fill_hdr(ifa, pkt, LSUPD_P);
pos = hlen;
diff --git a/proto/ospf/ospf.h b/proto/ospf/ospf.h
index 4f445f07..e3eae2b5 100644
--- a/proto/ospf/ospf.h
+++ b/proto/ospf/ospf.h
@@ -171,11 +171,7 @@ struct ospf_iface_patt
#define OSPF_RXBUF_MINSIZE 256 /* Minimal allowed size */
u8 instance_id;
- u8 autype; /* Not really used in OSPFv3 */
-#define OSPF_AUTH_NONE 0
-#define OSPF_AUTH_SIMPLE 1
-#define OSPF_AUTH_CRYPT 2
-#define OSPF_AUTH_CRYPT_SIZE 16
+ u8 autype; /* OSPF_AUTH_*, not really used in OSPFv3 */
u8 strictnbma;
u8 check_link;
u8 ecmp_weight;
@@ -325,6 +321,7 @@ struct ospf_iface
u8 marked; /* Used in OSPF reconfigure, 2 for force restart */
u16 rxbuf; /* Buffer size */
u16 tx_length; /* Soft TX packet length limit, usually MTU */
+ u16 tx_hdrlen; /* Expected packet header length, less than tx_length */
u8 check_link; /* Whether iface link change is used */
u8 ecmp_weight; /* Weight used for ECMP */
u8 link_lsa_suppression; /* Suppression of Link-LSA origination */
@@ -415,6 +412,11 @@ struct ospf_neighbor
#define ISM_UNLOOP 5 /* Link up */
#define ISM_DOWN 6 /* Interface down */
+/* OSPF authentication types */
+#define OSPF_AUTH_NONE 0
+#define OSPF_AUTH_SIMPLE 1
+#define OSPF_AUTH_CRYPT 2
+
/* OSPF neighbor states */
#define NEIGHBOR_DOWN 0
@@ -446,7 +448,6 @@ struct ospf_neighbor
#define TRANS_WAIT 2 /* Waiting before the end of translation */
-
/* Generic option flags */
#define OPT_V6 0x01 /* OSPFv3, LSA relevant for IPv6 routing calculation */
#define OPT_E 0x02 /* Related to AS-external LSAs */
@@ -482,7 +483,7 @@ struct ospf_packet
u8 autype; /* Undefined for OSPFv3 */
};
-struct ospf_md5
+struct ospf_auth_crypto
{
u16 zero;
u8 keyid;
@@ -493,7 +494,7 @@ struct ospf_md5
union ospf_auth
{
u8 password[8];
- struct ospf_md5 md5;
+ struct ospf_auth_crypto c32;
};
/* Packet types */
@@ -890,8 +891,7 @@ void ospf_sh_neigh_info(struct ospf_neighbor *n);
/* packet.c */
void ospf_pkt_fill_hdr(struct ospf_iface *ifa, void *buf, u8 h_type);
-uint ospf_pkt_maxsize(struct ospf_proto *p, struct ospf_iface *ifa);
-int ospf_rx_hook(sock * sk, int size);
+int ospf_rx_hook(sock * sk, uint size);
// void ospf_tx_hook(sock * sk);
void ospf_err_hook(sock * sk, int err);
void ospf_verr_hook(sock *sk, int err);
@@ -899,6 +899,9 @@ void ospf_send_to(struct ospf_iface *ifa, ip_addr ip);
void ospf_send_to_agt(struct ospf_iface *ifa, u8 state);
void ospf_send_to_bdr(struct ospf_iface *ifa);
+static inline uint ospf_pkt_maxsize(struct ospf_iface *ifa)
+{ return ifa->tx_length - ifa->tx_hdrlen; }
+
static inline void ospf_send_to_all(struct ospf_iface *ifa)
{ ospf_send_to(ifa, ifa->all_routers); }
diff --git a/proto/ospf/packet.c b/proto/ospf/packet.c
index 7ce6d99f..b84780d3 100644
--- a/proto/ospf/packet.c
+++ b/proto/ospf/packet.c
@@ -11,6 +11,7 @@
#include "ospf.h"
#include "nest/password.h"
#include "lib/md5.h"
+#include "lib/mac.h"
#include "lib/socket.h"
void
@@ -23,7 +24,7 @@ ospf_pkt_fill_hdr(struct ospf_iface *ifa, void *buf, u8 h_type)
pkt->version = ospf_get_version(p);
pkt->type = h_type;
- pkt->length = htons(ospf_pkt_maxsize(p, ifa));
+ pkt->length = htons(ospf_pkt_maxsize(ifa));
pkt->routerid = htonl(p->router_id);
pkt->areaid = htonl(ifa->oa->areaid);
pkt->checksum = 0;
@@ -31,25 +32,12 @@ ospf_pkt_fill_hdr(struct ospf_iface *ifa, void *buf, u8 h_type)
pkt->autype = ifa->autype;
}
-uint
-ospf_pkt_maxsize(struct ospf_proto *p, struct ospf_iface *ifa)
-{
- uint headers = ospf_is_v2(p) ? IP4_HEADER_LENGTH : IP6_HEADER_LENGTH;
-
- /* Relevant just for OSPFv2 */
- if (ifa->autype == OSPF_AUTH_CRYPT)
- headers += OSPF_AUTH_CRYPT_SIZE;
-
- return ifa->tx_length - headers;
-}
-
/* We assume OSPFv2 in ospf_pkt_finalize() */
static void
-ospf_pkt_finalize(struct ospf_iface *ifa, struct ospf_packet *pkt)
+ospf_pkt_finalize(struct ospf_iface *ifa, struct ospf_packet *pkt, uint *plen)
{
- struct password_item *passwd = NULL;
+ struct password_item *pass = NULL;
union ospf_auth *auth = (void *) (pkt + 1);
- uint plen = ntohs(pkt->length);
pkt->checksum = 0;
pkt->autype = ifa->autype;
@@ -61,25 +49,25 @@ ospf_pkt_finalize(struct ospf_iface *ifa, struct ospf_packet *pkt)
switch (ifa->autype)
{
case OSPF_AUTH_SIMPLE:
- passwd = password_find(ifa->passwords, 1);
- if (!passwd)
+ pass = password_find(ifa->passwords, 1);
+ if (!pass)
{
log(L_ERR "No suitable password found for authentication");
return;
}
- strncpy(auth->password, passwd->password, sizeof(auth->password));
+ strncpy(auth->password, pass->password, sizeof(auth->password));
case OSPF_AUTH_NONE:
{
void *body = (void *) (auth + 1);
- uint blen = plen - sizeof(struct ospf_packet) - sizeof(union ospf_auth);
+ uint blen = *plen - sizeof(struct ospf_packet) - sizeof(union ospf_auth);
pkt->checksum = ipsum_calculate(pkt, sizeof(struct ospf_packet), body, blen, NULL);
}
break;
case OSPF_AUTH_CRYPT:
- passwd = password_find(ifa->passwords, 0);
- if (!passwd)
+ pass = password_find(ifa->passwords, 0);
+ if (!pass)
{
log(L_ERR "No suitable password found for authentication");
return;
@@ -100,20 +88,25 @@ ospf_pkt_finalize(struct ospf_iface *ifa, struct ospf_packet *pkt)
ifa->csn_use = now;
- auth->md5.zero = 0;
- auth->md5.keyid = passwd->id;
- auth->md5.len = OSPF_AUTH_CRYPT_SIZE;
- auth->md5.csn = htonl(ifa->csn);
+ uint auth_len = mac_type_length(pass->alg);
+ byte *auth_tail = ((byte *) pkt + *plen);
+ *plen += auth_len;
+
+ ASSERT(*plen < ifa->sk->tbsize);
- void *tail = ((void *) pkt) + plen;
- char password[OSPF_AUTH_CRYPT_SIZE];
- strncpy(password, passwd->password, sizeof(password));
+ auth->c32.zero = 0;
+ auth->c32.keyid = pass->id;
+ auth->c32.len = auth_len;
+ auth->c32.csn = htonl(ifa->csn);
- struct md5_context ctx;
- md5_init(&ctx);
- md5_update(&ctx, (char *) pkt, plen);
- md5_update(&ctx, password, OSPF_AUTH_CRYPT_SIZE);
- memcpy((byte *) tail, md5_final(&ctx), MD5_SIZE);
+ /* Append key for keyed hash, append padding for HMAC (RFC 5709 3.3) */
+ if (pass->alg < ALG_HMAC)
+ strncpy(auth_tail, pass->password, auth_len);
+ else
+ memset32(auth_tail, HMAC_MAGIC, auth_len / 4);
+
+ mac_fill(pass->alg, pass->password, pass->length,
+ (byte *) pkt, *plen, auth_tail);
break;
default:
@@ -124,7 +117,7 @@ ospf_pkt_finalize(struct ospf_iface *ifa, struct ospf_packet *pkt)
/* We assume OSPFv2 in ospf_pkt_checkauth() */
static int
-ospf_pkt_checkauth(struct ospf_neighbor *n, struct ospf_iface *ifa, struct ospf_packet *pkt, int len)
+ospf_pkt_checkauth(struct ospf_neighbor *n, struct ospf_iface *ifa, struct ospf_packet *pkt, uint len)
{
struct ospf_proto *p = ifa->oa->po;
union ospf_auth *auth = (void *) (pkt + 1);
@@ -154,13 +147,19 @@ ospf_pkt_checkauth(struct ospf_neighbor *n, struct ospf_iface *ifa, struct ospf_
return 1;
case OSPF_AUTH_CRYPT:
- if (auth->md5.len != OSPF_AUTH_CRYPT_SIZE)
- DROP("invalid MD5 digest length", auth->md5.len);
+ pass = password_find_by_id(ifa->passwords, auth->c32.keyid);
+ if (!pass)
+ DROP("no suitable password found", auth->c32.keyid);
+
+ uint auth_len = mac_type_length(pass->alg);
- if (plen + OSPF_AUTH_CRYPT_SIZE > len)
- DROP("length mismatch", len);
+ if (plen + auth->c32.len > len)
+ DROP("packet length mismatch", len);
- u32 rcv_csn = ntohl(auth->md5.csn);
+ if (auth->c32.len != auth_len)
+ DROP("wrong authentication length", auth->c32.len);
+
+ u32 rcv_csn = ntohl(auth->c32.csn);
if (n && (rcv_csn < n->csn))
// DROP("lower sequence number", rcv_csn);
{
@@ -171,22 +170,19 @@ ospf_pkt_checkauth(struct ospf_neighbor *n, struct ospf_iface *ifa, struct ospf_
return 0;
}
- pass = password_find_by_id(ifa->passwords, auth->md5.keyid);
- if (!pass)
- DROP("no suitable password found", auth->md5.keyid);
-
- byte *tail = ((byte *) pkt) + plen;
- char received[OSPF_AUTH_CRYPT_SIZE];
- memcpy(received, tail, OSPF_AUTH_CRYPT_SIZE);
- strncpy(tail, pass->password, OSPF_AUTH_CRYPT_SIZE);
+ byte *auth_tail = ((byte *) pkt) + plen;
+ byte *auth_data = alloca(auth_len);
+ memcpy(auth_data, auth_tail, auth_len);
- struct md5_context ctx;
- md5_init(&ctx);
- md5_update(&ctx, (byte *) pkt, plen + OSPF_AUTH_CRYPT_SIZE);
- char *computed = md5_final(&ctx);
+ /* Append key for keyed hash, append padding for HMAC (RFC 5709 3.3) */
+ if (pass->alg < ALG_HMAC)
+ strncpy(auth_tail, pass->password, auth_len);
+ else
+ memset32(auth_tail, HMAC_MAGIC, auth_len / 4);
- if (memcmp(received, computed, OSPF_AUTH_CRYPT_SIZE))
- DROP("wrong MD5 digest", pass->id);
+ if (!mac_verify(pass->alg, pass->password, pass->length,
+ (byte *) pkt, plen + auth_len, auth_data))
+ DROP("wrong authentication code", pass->id);
if (n)
n->csn = rcv_csn;
@@ -214,7 +210,7 @@ drop:
* non generic functions.
*/
int
-ospf_rx_hook(sock *sk, int len)
+ospf_rx_hook(sock *sk, uint len)
{
/* We want just packets from sk->iface. Unfortunately, on BSD we cannot filter
out other packets at kernel level and we receive all packets on all sockets */
@@ -472,15 +468,10 @@ ospf_send_to(struct ospf_iface *ifa, ip_addr dst)
{
sock *sk = ifa->sk;
struct ospf_packet *pkt = (struct ospf_packet *) sk->tbuf;
- int plen = ntohs(pkt->length);
+ uint plen = ntohs(pkt->length);
if (ospf_is_v2(ifa->oa->po))
- {
- if (ifa->autype == OSPF_AUTH_CRYPT)
- plen += OSPF_AUTH_CRYPT_SIZE;
-
- ospf_pkt_finalize(ifa, pkt);
- }
+ ospf_pkt_finalize(ifa, pkt, &plen);
int done = sk_send_to(sk, plen, dst, 0);
if (!done)
diff --git a/proto/ospf/rt.c b/proto/ospf/rt.c
index 5538f4c8..054841ca 100644
--- a/proto/ospf/rt.c
+++ b/proto/ospf/rt.c
@@ -671,7 +671,7 @@ link_back(struct ospf_area *oa, struct top_hash_entry *en, struct top_hash_entry
which may be later used as the next hop. */
/* In OSPFv2, en->lb is set here. In OSPFv3, en->lb is just cleared here,
- it is set in process_prefixes() to any global addres in the area */
+ it is set in process_prefixes() to any global address in the area */
en->lb = IPA_NONE;
en->lb_id = 0;
@@ -923,7 +923,7 @@ ospf_rt_sum_tr(struct ospf_area *oa)
}
}
-/* Decide about originating or flushing summary LSAs for condended area networks */
+/* Decide about originating or flushing summary LSAs for condensed area networks */
static int
decide_anet_lsa(struct ospf_area *oa, struct area_net *anet, struct ospf_area *anet_oa)
{
@@ -1921,7 +1921,7 @@ rt_sync(struct ospf_proto *p)
/* This is used for forced reload of routes */
int reload = (p->calcrt == 2);
- OSPF_TRACE(D_EVENTS, "Starting routing table synchronisation");
+ OSPF_TRACE(D_EVENTS, "Starting routing table synchronization");
DBG("Now syncing my rt table with nest's\n");
FIB_ITERATE_INIT(&fit, fib);
diff --git a/proto/ospf/topology.c b/proto/ospf/topology.c
index 86e39d75..aaaf2e8e 100644
--- a/proto/ospf/topology.c
+++ b/proto/ospf/topology.c
@@ -513,6 +513,7 @@ ospf_update_lsadb(struct ospf_proto *p)
}
}
+
static u32
ort_to_lsaid(struct ospf_proto *p, ort *nf)
{
@@ -610,7 +611,7 @@ lsab_offset(struct ospf_proto *p, uint offset)
return ((byte *) p->lsab) + offset;
}
-static inline void *
+static inline void * UNUSED
lsab_end(struct ospf_proto *p)
{
return ((byte *) p->lsab) + p->lsab_used;
@@ -1558,7 +1559,7 @@ static void
add_link_lsa(struct ospf_proto *p, struct ospf_lsa_link *ll, int offset, int *pxc)
{
u32 *pxb = ll->rest;
- int j;
+ uint j;
for (j = 0; j < ll->pxcount; pxb = prefix_advance(pxb), j++)
{
diff --git a/proto/pipe/Makefile b/proto/pipe/Makefile
index c258a3e5..5093da98 100644
--- a/proto/pipe/Makefile
+++ b/proto/pipe/Makefile
@@ -2,3 +2,5 @@ src := pipe.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/pipe/pipe.c b/proto/pipe/pipe.c
index d40b3f91..8924c200 100644
--- a/proto/pipe/pipe.c
+++ b/proto/pipe/pipe.c
@@ -191,7 +191,7 @@ pipe_reconfigure(struct proto *P, struct proto_config *CF)
}
static void
-pipe_copy_config(struct proto_config *dest, struct proto_config *src)
+pipe_copy_config(struct proto_config *dest UNUSED, struct proto_config *src UNUSED)
{
/* Just a shallow copy, not many items here */
}
diff --git a/proto/radv/Makefile b/proto/radv/Makefile
index 3584a5f3..05317eff 100644
--- a/proto/radv/Makefile
+++ b/proto/radv/Makefile
@@ -2,3 +2,5 @@ src := packets.c radv.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/radv/packets.c b/proto/radv/packets.c
index 915b412f..f4352155 100644
--- a/proto/radv/packets.c
+++ b/proto/radv/packets.c
@@ -156,12 +156,12 @@ radv_process_domain(struct radv_dnssl_config *cf)
char *dom = cf->domain;
char *dom_end = dom; /* Just to */
u8 *dlen_save = &cf->dlen_first;
- int len;
+ uint len;
while (dom_end)
{
dom_end = strchr(dom, '.');
- len = dom_end ? (dom_end - dom) : strlen(dom);
+ len = dom_end ? (uint)(dom_end - dom) : strlen(dom);
if (len < 1 || len > 63)
return -1;
@@ -349,7 +349,7 @@ radv_send_ra(struct radv_iface *ifa, int shutdown)
static int
-radv_rx_hook(sock *sk, int size)
+radv_rx_hook(sock *sk, uint size)
{
struct radv_iface *ifa = sk->data;
struct proto_radv *ra = ifa->ra;
diff --git a/proto/radv/radv.c b/proto/radv/radv.c
index 4c845f7a..d7d975ab 100644
--- a/proto/radv/radv.c
+++ b/proto/radv/radv.c
@@ -240,7 +240,7 @@ radv_if_notify(struct proto *p, unsigned flags, struct iface *iface)
}
static void
-radv_ifa_notify(struct proto *p, unsigned flags, struct ifa *a)
+radv_ifa_notify(struct proto *p, unsigned flags UNUSED, struct ifa *a)
{
struct proto_radv *ra = (struct proto_radv *) p;
@@ -311,7 +311,7 @@ radv_check_active(struct proto_radv *ra)
if (!radv_trigger_valid(cf))
return 1;
- struct channel *c =ra->p.main_channel;
+ struct channel *c = ra->p.main_channel;
return rt_examine(c->table, &cf->trigger, &ra->p, c->out_filter);
}
diff --git a/proto/rip/Makefile b/proto/rip/Makefile
index 6e645cc2..7feabcd8 100644
--- a/proto/rip/Makefile
+++ b/proto/rip/Makefile
@@ -2,3 +2,5 @@ src := packets.c rip.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/rip/config.Y b/proto/rip/config.Y
index 61a2a101..b3ccdf39 100644
--- a/proto/rip/config.Y
+++ b/proto/rip/config.Y
@@ -104,15 +104,29 @@ rip_iface_start:
rip_iface_finish:
{
+ /* Default mode is broadcast for RIPv1, multicast for RIPv2 and RIPng */
+ if (!RIP_IFACE->mode)
+ RIP_IFACE->mode = (rip_cfg_is_v2() && (RIP_IFACE->version == RIP_V1)) ?
+ RIP_IM_BROADCAST : RIP_IM_MULTICAST;
+
RIP_IFACE->passwords = get_passwords();
if (!RIP_IFACE->auth_type != !RIP_IFACE->passwords)
log(L_WARN "Authentication and password options should be used together");
- /* Default mode is broadcast for RIPv1, multicast for RIPv2 and RIPng */
- if (!RIP_IFACE->mode)
- RIP_IFACE->mode = (rip_cfg_is_v2() && (RIP_IFACE->version == RIP_V1)) ?
- RIP_IM_BROADCAST : RIP_IM_MULTICAST;
+ if (RIP_IFACE->passwords)
+ {
+ struct password_item *pass;
+ WALK_LIST(pass, *RIP_IFACE->passwords)
+ {
+ if (pass->alg && (RIP_IFACE->auth_type != RIP_AUTH_CRYPTO))
+ cf_error("Password algorithm option requires cryptographic authentication");
+
+ /* Set default crypto algorithm (MD5) */
+ if (!pass->alg && (RIP_IFACE->auth_type == RIP_AUTH_CRYPTO))
+ pass->alg = ALG_MD5;
+ }
+ }
RIP_CFG->min_timeout_time = MIN_(RIP_CFG->min_timeout_time, RIP_IFACE->timeout_time);
RIP_CFG->max_garbage_time = MAX_(RIP_CFG->max_garbage_time, RIP_IFACE->garbage_time);
@@ -153,7 +167,7 @@ rip_auth:
NONE { $$ = RIP_AUTH_NONE; }
| PLAINTEXT { $$ = RIP_AUTH_PLAIN; }
| CRYPTOGRAPHIC { $$ = RIP_AUTH_CRYPTO; }
- | MD5 { $$ = RIP_AUTH_CRYPTO; }
+ | MD5 { $$ = RIP_AUTH_CRYPTO; } /* For backward compatibility */
;
rip_iface_opts:
diff --git a/proto/rip/packets.c b/proto/rip/packets.c
index f89bb178..9dc492b7 100644
--- a/proto/rip/packets.c
+++ b/proto/rip/packets.c
@@ -12,16 +12,14 @@
#undef LOCAL_DEBUG
#include "rip.h"
-#include "lib/md5.h"
+#include "lib/mac.h"
#define RIP_CMD_REQUEST 1 /* want info */
#define RIP_CMD_RESPONSE 2 /* responding to request */
#define RIP_BLOCK_LENGTH 20
-
#define RIP_PASSWD_LENGTH 16
-#define RIP_MD5_LENGTH 16
#define RIP_AF_IPV4 2
#define RIP_AF_AUTH 0xffff
@@ -74,7 +72,7 @@ struct rip_auth_tail
{
u16 must_be_ffff;
u16 must_be_0001;
- byte auth_data[];
+ byte auth_data[0];
};
/* Internal representation of RTE block data */
@@ -132,7 +130,7 @@ rip_put_block(struct rip_proto *p, byte *pos, struct rip_block *rte)
}
static inline void
-rip_put_next_hop(struct rip_proto *p, byte *pos, struct rip_block *rte)
+rip_put_next_hop(struct rip_proto *p UNUSED, byte *pos, struct rip_block *rte)
{
struct rip_block_ng *block = (void *) pos;
block->prefix = ip6_hton(ipa_to_ip6(rte->next_hop));
@@ -221,16 +219,24 @@ rip_fill_authentication(struct rip_proto *p, struct rip_iface *ifa, struct rip_p
auth->auth_type = htons(RIP_AUTH_CRYPTO);
auth->packet_len = htons(*plen);
auth->key_id = pass->id;
- auth->auth_len = sizeof(struct rip_auth_tail) + RIP_MD5_LENGTH;
+ auth->auth_len = mac_type_length(pass->alg);
auth->seq_num = ifa->csn_ready ? htonl(ifa->csn) : 0;
auth->unused1 = 0;
auth->unused2 = 0;
ifa->csn_ready = 1;
+ if (pass->alg < ALG_HMAC)
+ auth->auth_len += sizeof(struct rip_auth_tail);
+
/*
* Note that RFC 4822 is unclear whether auth_len should cover whole
* authentication trailer or just auth_data length.
*
+ * FIXME: We should use just auth_data length by default. Currently we put
+ * the whole auth trailer length in keyed hash case to keep old behavior,
+ * but we put just auth_data length in the new HMAC case. Note that Quagga
+ * has config option for this.
+ *
* Crypto sequence numbers are increased by sender in rip_update_csn().
* First CSN should be zero, this is handled by csn_ready.
*/
@@ -238,14 +244,18 @@ rip_fill_authentication(struct rip_proto *p, struct rip_iface *ifa, struct rip_p
struct rip_auth_tail *tail = (void *) ((byte *) pkt + *plen);
tail->must_be_ffff = htons(0xffff);
tail->must_be_0001 = htons(0x0001);
- strncpy(tail->auth_data, pass->password, RIP_MD5_LENGTH);
- *plen += sizeof(struct rip_auth_tail) + RIP_MD5_LENGTH;
+ uint auth_len = mac_type_length(pass->alg);
+ *plen += sizeof(struct rip_auth_tail) + auth_len;
- struct md5_context ctx;
- md5_init(&ctx);
- md5_update(&ctx, (byte *) pkt, *plen);
- memcpy(tail->auth_data, md5_final(&ctx), RIP_MD5_LENGTH);
+ /* Append key for keyed hash, append padding for HMAC (RFC 4822 2.5) */
+ if (pass->alg < ALG_HMAC)
+ strncpy(tail->auth_data, pass->password, auth_len);
+ else
+ memset32(tail->auth_data, HMAC_MAGIC, auth_len / 4);
+
+ mac_fill(pass->alg, pass->password, pass->length,
+ (byte *) pkt, *plen, tail->auth_data);
return;
default:
@@ -288,13 +298,25 @@ rip_check_authentication(struct rip_proto *p, struct rip_iface *ifa, struct rip_
DROP("no suitable password found", auth->key_id);
uint data_len = ntohs(auth->packet_len);
- uint auth_len = sizeof(struct rip_auth_tail) + RIP_MD5_LENGTH;
+ uint auth_len = mac_type_length(pass->alg);
+ uint auth_len2 = sizeof(struct rip_auth_tail) + auth_len;
- if (data_len + auth_len != *plen)
- DROP("packet length mismatch", data_len);
+ /*
+ * Ideally, first check should be check for internal consistency:
+ * (data_len + sizeof(struct rip_auth_tail) + auth->auth_len) != *plen
+ *
+ * Second one should check expected code length:
+ * auth->auth_len != auth_len
+ *
+ * But as auth->auth_len has two interpretations, we simplify this
+ */
- if ((auth->auth_len != RIP_MD5_LENGTH) && (auth->auth_len != auth_len))
- DROP("authentication data length mismatch", auth->auth_len);
+ if (data_len + auth_len2 != *plen)
+ DROP("packet length mismatch", *plen);
+
+ /* Warning: two interpretations of auth_len field */
+ if ((auth->auth_len != auth_len) && (auth->auth_len != auth_len2))
+ DROP("wrong authentication length", auth->auth_len);
struct rip_auth_tail *tail = (void *) ((byte *) pkt + data_len);
if ((tail->must_be_ffff != htons(0xffff)) || (tail->must_be_0001 != htons(0x0001)))
@@ -312,17 +334,18 @@ rip_check_authentication(struct rip_proto *p, struct rip_iface *ifa, struct rip_
return 0;
}
- char received[RIP_MD5_LENGTH];
- memcpy(received, tail->auth_data, RIP_MD5_LENGTH);
- strncpy(tail->auth_data, pass->password, RIP_MD5_LENGTH);
+ byte *auth_data = alloca(auth_len);
+ memcpy(auth_data, tail->auth_data, auth_len);
- struct md5_context ctx;
- md5_init(&ctx);
- md5_update(&ctx, (byte *) pkt, *plen);
- char *computed = md5_final(&ctx);
+ /* Append key for keyed hash, append padding for HMAC (RFC 4822 2.5) */
+ if (pass->alg < ALG_HMAC)
+ strncpy(tail->auth_data, pass->password, auth_len);
+ else
+ memset32(tail->auth_data, HMAC_MAGIC, auth_len / 4);
- if (memcmp(received, computed, RIP_MD5_LENGTH))
- DROP("wrong MD5 digest", pass->id);
+ if (!mac_verify(pass->alg, pass->password, pass->length,
+ (byte *) pkt, *plen, auth_data))
+ DROP("wrong authentication code", pass->id);
*plen = data_len;
n->csn = rcv_csn;
@@ -632,7 +655,7 @@ rip_receive_response(struct rip_proto *p, struct rip_iface *ifa, struct rip_pack
}
static int
-rip_rx_hook(sock *sk, int len)
+rip_rx_hook(sock *sk, uint len)
{
struct rip_iface *ifa = sk->data;
struct rip_proto *p = ifa->rip;
diff --git a/proto/rip/rip.c b/proto/rip/rip.c
index 131c09ce..d87a078c 100644
--- a/proto/rip/rip.c
+++ b/proto/rip/rip.c
@@ -162,7 +162,6 @@ rip_announce_rte(struct rip_proto *p, struct rip_entry *en)
{
/* ECMP route */
struct mpnh *nhs = NULL;
- struct mpnh **nhp = &nhs;
int num = 0;
for (rt = en->routes; rt && (num < p->ecmp); rt = rt->next)
@@ -174,9 +173,7 @@ rip_announce_rte(struct rip_proto *p, struct rip_entry *en)
nh->gw = rt->next_hop;
nh->iface = rt->from->nbr->iface;
nh->weight = rt->from->ifa->cf->ecmp_weight;
- nh->next = NULL;
- *nhp = nh;
- nhp = &(nh->next);
+ mpnh_insert(&nhs, nh);
num++;
if (rt->tag != rt_tag)
@@ -578,7 +575,7 @@ rip_iface_update_buffers(struct rip_iface *ifa)
ifa->tx_plen = tbsize - headers;
if (ifa->cf->auth_type == RIP_AUTH_CRYPTO)
- ifa->tx_plen -= RIP_AUTH_TAIL_LENGTH;
+ ifa->tx_plen -= RIP_AUTH_TAIL_LENGTH + max_mac_length(ifa->cf->passwords);
}
static inline void
@@ -690,12 +687,11 @@ rip_reconfigure_iface(struct rip_proto *p, struct rip_iface *ifa, struct rip_ifa
ifa->cf = new;
+ rip_iface_update_buffers(ifa);
+
if (ifa->next_regular > (now + new->update_time))
ifa->next_regular = now + (random() % new->update_time) + 1;
- if ((new->tx_length != old->tx_length) || (new->rx_buffer != old->rx_buffer))
- rip_iface_update_buffers(ifa);
-
if (new->check_link != old->check_link)
rip_iface_update_state(ifa);
@@ -1014,7 +1010,7 @@ rip_prepare_attrs(struct linpool *pool, ea_list *next, u8 metric, u16 tag)
}
static int
-rip_import_control(struct proto *P, struct rte **rt, struct ea_list **attrs, struct linpool *pool)
+rip_import_control(struct proto *P UNUSED, struct rte **rt, struct ea_list **attrs, struct linpool *pool)
{
/* Prepare attributes with initial values */
if ((*rt)->attrs->source != RTS_RIP)
@@ -1148,7 +1144,7 @@ rip_reconfigure(struct proto *P, struct proto_config *CF)
}
static void
-rip_get_route_info(rte *rte, byte *buf, ea_list *attrs)
+rip_get_route_info(rte *rte, byte *buf, ea_list *attrs UNUSED)
{
buf += bsprintf(buf, " (%d/%d)", rte->pref, rte->u.rip.metric);
diff --git a/proto/rip/rip.h b/proto/rip/rip.h
index 7ec7e24d..03dc9138 100644
--- a/proto/rip/rip.h
+++ b/proto/rip/rip.h
@@ -34,7 +34,7 @@
#define RIP_NG_PORT 521 /* RIPng */
#define RIP_MAX_PKT_LENGTH 532 /* 512 + IP4_HEADER_LENGTH */
-#define RIP_AUTH_TAIL_LENGTH 20 /* 4 + MD5 length */
+#define RIP_AUTH_TAIL_LENGTH 4 /* Without auth_data */
#define RIP_DEFAULT_ECMP_LIMIT 16
#define RIP_DEFAULT_INFINITY 16
diff --git a/proto/static/Makefile b/proto/static/Makefile
index 3ace39cf..e38f9b74 100644
--- a/proto/static/Makefile
+++ b/proto/static/Makefile
@@ -2,3 +2,5 @@ src := static.c
obj := $(src-o-files)
$(all-daemon)
$(cf-local)
+
+tests_objs := $(tests_objs) $(src-o-files) \ No newline at end of file
diff --git a/proto/static/static.c b/proto/static/static.c
index 28cb1e77..fb547537 100644
--- a/proto/static/static.c
+++ b/proto/static/static.c
@@ -80,7 +80,6 @@ static_install(struct proto *p, struct static_route *r, struct iface *ifa)
{
struct static_route *r2;
struct mpnh *nhs = NULL;
- struct mpnh **nhp = &nhs;
for (r2 = r->mp_next; r2; r2 = r2->mp_next)
if (r2->installed)
@@ -89,9 +88,7 @@ static_install(struct proto *p, struct static_route *r, struct iface *ifa)
nh->gw = r2->via;
nh->iface = r2->neigh->iface;
nh->weight = r2->weight;
- nh->next = NULL;
- *nhp = nh;
- nhp = &(nh->next);
+ mpnh_insert(&nhs, nh);
}
/* There is at least one nexthop */
@@ -107,7 +104,7 @@ static_install(struct proto *p, struct static_route *r, struct iface *ifa)
}
if (r->dest == RTDX_RECURSIVE)
- rta_set_recursive_next_hop(p->main_channel->table, &a, p_igp_table(p), &r->via, &r->via);
+ rta_set_recursive_next_hop(p->main_channel->table, &a, p_igp_table(p), r->via, IPA_NONE);
/* We skip rta_lookup() here */
@@ -247,7 +244,7 @@ static_add(struct proto *p, struct static_config *cf, struct static_route *r)
}
static void
-static_rte_cleanup(struct proto *p, struct static_route *r)
+static_rte_cleanup(struct proto *p UNUSED, struct static_route *r)
{
struct static_route *r2;
@@ -443,7 +440,7 @@ static_if_notify(struct proto *p, unsigned flags, struct iface *i)
}
int
-static_rte_mergable(rte *pri, rte *sec)
+static_rte_mergable(rte *pri UNUSED, rte *sec UNUSED)
{
return 1;
}
diff --git a/sysdep/autoconf.h.in b/sysdep/autoconf.h.in
index a68f3e90..4887c433 100644
--- a/sysdep/autoconf.h.in
+++ b/sysdep/autoconf.h.in
@@ -68,6 +68,9 @@
/* We have stdint.h */
#undef HAVE_STDINT_H
+/* We have execinfo.h */
+#undef HAVE_EXECINFO_H
+
/* We have LibSSH */
#undef HAVE_LIBSSH
diff --git a/sysdep/bsd/Makefile b/sysdep/bsd/Makefile
index ddc87239..dfa32747 100644
--- a/sysdep/bsd/Makefile
+++ b/sysdep/bsd/Makefile
@@ -3,3 +3,4 @@ obj := $(src-o-files)
$(all-daemon)
$(conf-y-targets): $(s)krt-sock.Y
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/sysdep/bsd/krt-sock.c b/sysdep/bsd/krt-sock.c
index 56026bdd..d2372a3d 100644
--- a/sysdep/bsd/krt-sock.c
+++ b/sysdep/bsd/krt-sock.c
@@ -933,7 +933,7 @@ kif_do_scan(struct kif_proto *p)
/* Kernel sockets */
static int
-krt_sock_hook(sock *sk, int size UNUSED)
+krt_sock_hook(sock *sk, uint size UNUSED)
{
struct ks_msg msg;
int l = read(sk->fd, (char *)&msg, sizeof(msg));
@@ -946,8 +946,14 @@ krt_sock_hook(sock *sk, int size UNUSED)
return 0;
}
+static void
+krt_sock_err_hook(sock *sk, int e UNUSED)
+{
+ krt_sock_hook(sk, 0);
+}
+
static sock *
-krt_sock_open(pool *pool, void *data, int table_id)
+krt_sock_open(pool *pool, void *data, int table_id UNUSED)
{
sock *sk;
int fd;
@@ -967,6 +973,7 @@ krt_sock_open(pool *pool, void *data, int table_id)
sk = sk_new(pool);
sk->type = SK_MAGIC;
sk->rx_hook = krt_sock_hook;
+ sk->err_hook = krt_sock_err_hook;
sk->fd = fd;
sk->data = data;
@@ -1113,7 +1120,7 @@ kif_sys_shutdown(struct kif_proto *p)
struct ifa *
-kif_get_primary_ip(struct iface *i)
+kif_get_primary_ip(struct iface *i UNUSED)
{
#if 0
static int fd = -1;
diff --git a/sysdep/bsd/krt-sys.h b/sysdep/bsd/krt-sys.h
index 870cdf2c..ed667e80 100644
--- a/sysdep/bsd/krt-sys.h
+++ b/sysdep/bsd/krt-sys.h
@@ -48,4 +48,5 @@ static inline void krt_sys_postconfig(struct krt_config *x UNUSED) { }
static inline int krt_sys_get_attr(eattr *a UNUSED, byte *buf UNUSED, int buflen UNUSED) { return GA_UNKNOWN; }
+
#endif
diff --git a/sysdep/bsd/sysio.h b/sysdep/bsd/sysio.h
index 57c45bcf..0c5f8fbb 100644
--- a/sysdep/bsd/sysio.h
+++ b/sysdep/bsd/sysio.h
@@ -28,6 +28,7 @@
#endif
+#undef SA_LEN
#define SA_LEN(x) (x).sa.sa_len
@@ -133,12 +134,12 @@ sk_process_cmsg4_ttl(sock *s, struct cmsghdr *cm)
s->rcv_ttl = * (byte *) CMSG_DATA(cm);
}
+#ifdef IP_SENDSRCADDR
static inline void
sk_prepare_cmsgs4(sock *s, struct msghdr *msg, void *cbuf, size_t cbuflen)
{
/* Unfortunately, IP_SENDSRCADDR does not work for raw IP sockets on BSD kernels */
-#ifdef IP_SENDSRCADDR
struct cmsghdr *cm;
struct in_addr *sa;
int controllen = 0;
@@ -156,10 +157,13 @@ sk_prepare_cmsgs4(sock *s, struct msghdr *msg, void *cbuf, size_t cbuflen)
*sa = ipa_to_in4(s->saddr);
msg->msg_controllen = controllen;
-#endif
}
+#else
+static inline void
+sk_prepare_cmsgs4(sock *s UNUSED, struct msghdr *msg UNUSED, void *cbuf UNUSED, size_t cbuflen UNUSED) { }
+#endif
-static void
+static void UNUSED
sk_prepare_ip_header(sock *s, void *hdr, int dlen)
{
struct ip *ip = hdr;
@@ -200,7 +204,7 @@ sk_prepare_ip_header(sock *s, void *hdr, int dlen)
#endif
int
-sk_set_md5_auth(sock *s, ip_addr local, ip_addr remote, struct iface *ifa, char *passwd, int setkey UNUSED)
+sk_set_md5_auth(sock *s, ip_addr local UNUSED, ip_addr remote UNUSED, struct iface *ifa UNUSED, char *passwd, int setkey UNUSED)
{
#ifdef USE_MD5SIG_SETKEY
if (setkey)
@@ -235,20 +239,20 @@ sk_set_min_ttl4(sock *s, int ttl)
}
static inline int
-sk_set_min_ttl6(sock *s, int ttl)
+sk_set_min_ttl6(sock *s, int ttl UNUSED)
{
ERR_MSG("Kernel does not support IPv6 TTL security");
}
static inline int
-sk_disable_mtu_disc4(sock *s)
+sk_disable_mtu_disc4(sock *s UNUSED)
{
/* TODO: Set IP_DONTFRAG to 0 ? */
return 0;
}
static inline int
-sk_disable_mtu_disc6(sock *s)
+sk_disable_mtu_disc6(sock *s UNUSED)
{
/* TODO: Set IPV6_DONTFRAG to 0 ? */
return 0;
diff --git a/sysdep/config.h b/sysdep/config.h
index a8d58349..c7f63e69 100644
--- a/sysdep/config.h
+++ b/sysdep/config.h
@@ -7,7 +7,7 @@
#define _BIRD_CONFIG_H_
/* BIRD version */
-#define BIRD_VERSION "1.6.0"
+#define BIRD_VERSION "1.6.2"
/* Include parameters determined by configure script */
#include "sysdep/autoconf.h"
diff --git a/sysdep/linux/Makefile b/sysdep/linux/Makefile
index 23cf1d9d..188ac8de 100644
--- a/sysdep/linux/Makefile
+++ b/sysdep/linux/Makefile
@@ -2,3 +2,5 @@ src := netlink.c
obj := $(src-o-files)
$(all-daemon)
$(conf-y-targets): $(s)netlink.Y
+
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/sysdep/linux/krt-sys.h b/sysdep/linux/krt-sys.h
index 7fd5f139..76ae29b7 100644
--- a/sysdep/linux/krt-sys.h
+++ b/sysdep/linux/krt-sys.h
@@ -27,13 +27,16 @@ static inline void kif_sys_postconfig(struct kif_config *c UNUSED) { }
static inline void kif_sys_init_config(struct kif_config *c UNUSED) { }
static inline void kif_sys_copy_config(struct kif_config *d UNUSED, struct kif_config *s UNUSED) { }
-static inline struct ifa * kif_get_primary_ip(struct iface *i) { return NULL; }
+static inline struct ifa * kif_get_primary_ip(struct iface *i UNUSED) { return NULL; }
/* Kernel routes */
+#define KRT_ALLOW_MERGE_PATHS 1
+
#define EA_KRT_PREFSRC EA_CODE(EAP_KRT, 0x10)
#define EA_KRT_REALM EA_CODE(EAP_KRT, 0x11)
+#define EA_KRT_SCOPE EA_CODE(EAP_KRT, 0x12)
#define KRT_METRICS_MAX 0x10 /* RTAX_QUICKACK+1 */
@@ -86,6 +89,7 @@ static inline struct ifa * kif_get_primary_ip(struct iface *i) { return NULL; }
struct krt_params {
u32 table_id; /* Kernel table ID we sync with */
+ u32 metric; /* Kernel metric used for all routes */
};
struct krt_state {
diff --git a/sysdep/linux/netlink.Y b/sysdep/linux/netlink.Y
index e9c225a2..f577244d 100644
--- a/sysdep/linux/netlink.Y
+++ b/sysdep/linux/netlink.Y
@@ -10,8 +10,8 @@ CF_HDR
CF_DECLS
-CF_KEYWORDS(KERNEL, TABLE, KRT_PREFSRC, KRT_REALM, KRT_MTU, KRT_WINDOW, KRT_RTT,
- KRT_RTTVAR, KRT_SSTRESH, KRT_CWND, KRT_ADVMSS, KRT_REORDERING,
+CF_KEYWORDS(KERNEL, TABLE, METRIC, KRT_PREFSRC, KRT_REALM, KRT_SCOPE, KRT_MTU, KRT_WINDOW,
+ KRT_RTT, KRT_RTTVAR, KRT_SSTRESH, KRT_CWND, KRT_ADVMSS, KRT_REORDERING,
KRT_HOPLIMIT, KRT_INITCWND, KRT_RTO_MIN, KRT_INITRWND, KRT_QUICKACK,
KRT_LOCK_MTU, KRT_LOCK_WINDOW, KRT_LOCK_RTT, KRT_LOCK_RTTVAR,
KRT_LOCK_SSTRESH, KRT_LOCK_CWND, KRT_LOCK_ADVMSS, KRT_LOCK_REORDERING,
@@ -22,13 +22,13 @@ CF_GRAMMAR
CF_ADDTO(kern_proto, kern_proto kern_sys_item ';')
kern_sys_item:
- KERNEL TABLE expr {
- THIS_KRT->sys.table_id = $3;
- }
+ KERNEL TABLE expr { THIS_KRT->sys.table_id = $3; }
+ | METRIC expr { THIS_KRT->sys.metric = $2; }
;
CF_ADDTO(dynamic_attr, KRT_PREFSRC { $$ = f_new_dynamic_attr(EAF_TYPE_IP_ADDRESS, T_IP, EA_KRT_PREFSRC); })
CF_ADDTO(dynamic_attr, KRT_REALM { $$ = f_new_dynamic_attr(EAF_TYPE_INT, T_INT, EA_KRT_REALM); })
+CF_ADDTO(dynamic_attr, KRT_SCOPE { $$ = f_new_dynamic_attr(EAF_TYPE_INT, T_INT, EA_KRT_SCOPE); })
CF_ADDTO(dynamic_attr, KRT_MTU { $$ = f_new_dynamic_attr(EAF_TYPE_INT, T_INT, EA_KRT_MTU); })
CF_ADDTO(dynamic_attr, KRT_WINDOW { $$ = f_new_dynamic_attr(EAF_TYPE_INT, T_INT, EA_KRT_WINDOW); })
diff --git a/sysdep/linux/netlink.c b/sysdep/linux/netlink.c
index 8146072b..ee2cd125 100644
--- a/sysdep/linux/netlink.c
+++ b/sysdep/linux/netlink.c
@@ -20,7 +20,6 @@
#include "nest/route.h"
#include "nest/protocol.h"
#include "nest/iface.h"
-#include "lib/alloca.h"
#include "sysdep/unix/timer.h"
#include "sysdep/unix/unix.h"
#include "sysdep/unix/krt.h"
@@ -39,6 +38,10 @@
#define MSG_TRUNC 0x20
#endif
+#ifndef IFA_FLAGS
+#define IFA_FLAGS 8
+#endif
+
#ifndef IFF_LOWER_UP
#define IFF_LOWER_UP 0x10000
#endif
@@ -48,6 +51,45 @@
#endif
+#define krt_ecmp6(p) ((p)->af == AF_INET6)
+
+/*
+ * Structure nl_parse_state keeps state of received route processing. Ideally,
+ * we could just independently parse received Netlink messages and immediately
+ * propagate received routes to the rest of BIRD, but Linux kernel represents
+ * and announces IPv6 ECMP routes not as one route with multiple next hops (like
+ * RTA_MULTIPATH in IPv4 ECMP), but as a set of routes with the same prefix.
+ *
+ * Therefore, BIRD keeps currently processed route in nl_parse_state structure
+ * and postpones its propagation until we expect it to be final; i.e., when
+ * non-matching route is received or when the scan ends. When another matching
+ * route is received, it is merged with the already processed route to form an
+ * ECMP route. Note that merging is done only for IPv6 (merge == 1), but the
+ * postponing is done in both cases (for simplicity). All IPv4 routes are just
+ * considered non-matching.
+ *
+ * This is ignored for asynchronous notifications (every notification is handled
+ * as a separate route). It is not an issue for our routes, as we ignore such
+ * notifications anyways. But importing alien IPv6 ECMP routes does not work
+ * properly.
+ */
+
+struct nl_parse_state
+{
+ struct linpool *pool;
+ int scan;
+ int merge;
+
+ net *net;
+ rta *attrs;
+ struct krt_proto *proto;
+ s8 new;
+ s8 krt_src;
+ u8 krt_type;
+ u8 krt_proto;
+ u32 krt_metric;
+};
+
/*
* Synchronous Netlink interface
*/
@@ -63,6 +105,13 @@ struct nl_sock
#define NL_RX_SIZE 8192
+#define NL_OP_DELETE 0
+#define NL_OP_ADD (NLM_F_CREATE|NLM_F_EXCL)
+#define NL_OP_REPLACE (NLM_F_CREATE|NLM_F_REPLACE)
+#define NL_OP_APPEND (NLM_F_CREATE|NLM_F_APPEND)
+
+static linpool *nl_linpool;
+
static struct nl_sock nl_scan = {.fd = -1}; /* Netlink socket for synchronous scan */
static struct nl_sock nl_req = {.fd = -1}; /* Netlink socket for requests */
@@ -166,7 +215,7 @@ nl_get_reply(struct nl_sock *nl)
static struct tbf rl_netlink_err = TBF_DEFAULT_LOG_LIMITS;
static int
-nl_error(struct nlmsghdr *h)
+nl_error(struct nlmsghdr *h, int ignore_esrch)
{
struct nlmsgerr *e;
int ec;
@@ -178,7 +227,7 @@ nl_error(struct nlmsghdr *h)
}
e = (struct nlmsgerr *) NLMSG_DATA(h);
ec = -e->error;
- if (ec)
+ if (ec && !(ignore_esrch && (ec == ESRCH)))
log_rl(&rl_netlink_err, L_WARN "Netlink: %s", strerror(ec));
return ec;
}
@@ -192,14 +241,14 @@ nl_get_scan(void)
return NULL;
if (h->nlmsg_type == NLMSG_ERROR)
{
- nl_error(h);
+ nl_error(h, 0);
return NULL;
}
return h;
}
static int
-nl_exchange(struct nlmsghdr *pkt)
+nl_exchange(struct nlmsghdr *pkt, int ignore_esrch)
{
struct nlmsghdr *h;
@@ -211,7 +260,7 @@ nl_exchange(struct nlmsghdr *pkt)
break;
log(L_WARN "nl_exchange: Unexpected reply received");
}
- return nl_error(h) ? -1 : 0;
+ return nl_error(h, ignore_esrch) ? -1 : 0;
}
/*
@@ -248,17 +297,19 @@ static struct nl_want_attrs ifla_attr_want[BIRD_IFLA_MAX] = {
};
-#define BIRD_IFA_MAX (IFA_ANYCAST+1)
+#define BIRD_IFA_MAX (IFA_FLAGS+1)
static struct nl_want_attrs ifa_attr_want4[BIRD_IFA_MAX] = {
[IFA_ADDRESS] = { 1, 1, sizeof(ip4_addr) },
[IFA_LOCAL] = { 1, 1, sizeof(ip4_addr) },
[IFA_BROADCAST] = { 1, 1, sizeof(ip4_addr) },
+ [IFA_FLAGS] = { 1, 1, sizeof(u32) },
};
static struct nl_want_attrs ifa_attr_want6[BIRD_IFA_MAX] = {
[IFA_ADDRESS] = { 1, 1, sizeof(ip6_addr) },
[IFA_LOCAL] = { 1, 1, sizeof(ip6_addr) },
+ [IFA_FLAGS] = { 1, 1, sizeof(u32) },
};
@@ -452,7 +503,7 @@ nl_parse_multipath(struct krt_proto *p, struct rtattr *ra)
struct rtattr *a[BIRD_RTA_MAX];
struct rtnexthop *nh = RTA_DATA(ra);
struct mpnh *rv, *first, **last;
- int len = RTA_PAYLOAD(ra);
+ unsigned len = RTA_PAYLOAD(ra);
first = NULL;
last = &first;
@@ -627,6 +678,7 @@ nl_parse_addr4(struct ifaddrmsg *i, int scan, int new)
{
struct rtattr *a[BIRD_IFA_MAX];
struct iface *ifi;
+ u32 ifa_flags;
int scope;
if (!nl_parse_attrs(IFA_RTA(i), ifa_attr_want4, a, sizeof(a)))
@@ -650,10 +702,15 @@ nl_parse_addr4(struct ifaddrmsg *i, int scan, int new)
return;
}
+ if (a[IFA_FLAGS])
+ ifa_flags = rta_get_u32(a[IFA_FLAGS]);
+ else
+ ifa_flags = i->ifa_flags;
+
struct ifa ifa;
bzero(&ifa, sizeof(ifa));
ifa.iface = ifi;
- if (i->ifa_flags & IFA_F_SECONDARY)
+ if (ifa_flags & IFA_F_SECONDARY)
ifa.flags |= IA_SECONDARY;
ifa.ip = rta_get_ipa(a[IFA_LOCAL]);
@@ -730,6 +787,7 @@ nl_parse_addr6(struct ifaddrmsg *i, int scan, int new)
{
struct rtattr *a[BIRD_IFA_MAX];
struct iface *ifi;
+ u32 ifa_flags;
int scope;
if (!nl_parse_attrs(IFA_RTA(i), ifa_attr_want6, a, sizeof(a)))
@@ -748,14 +806,22 @@ nl_parse_addr6(struct ifaddrmsg *i, int scan, int new)
return;
}
+ if (a[IFA_FLAGS])
+ ifa_flags = rta_get_u32(a[IFA_FLAGS]);
+ else
+ ifa_flags = i->ifa_flags;
+
struct ifa ifa;
bzero(&ifa, sizeof(ifa));
ifa.iface = ifi;
- if (i->ifa_flags & IFA_F_SECONDARY)
+ if (ifa_flags & IFA_F_SECONDARY)
ifa.flags |= IA_SECONDARY;
- /* IFA_LOCAL can be unset for IPv6 interfaces */
+ /* Ignore tentative addresses silently */
+ if (ifa_flags & IFA_F_TENTATIVE)
+ return;
+ /* IFA_LOCAL can be unset for IPv6 interfaces */
ifa.ip = rta_get_ipa(a[IFA_LOCAL] ? : a[IFA_ADDRESS]);
if (i->ifa_prefixlen > IP6_MAX_PREFIX_LENGTH)
@@ -916,12 +982,13 @@ nh_bufsize(struct mpnh *nh)
}
static int
-nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int new)
+nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int op, int dest, ip_addr gw, struct iface *iface)
{
eattr *ea;
net *net = e->net;
rta *a = e->attrs;
int bufsize = 128 + KRT_METRICS_MAX*8 + nh_bufsize(a->nexthops);
+ u32 priority = 0;
struct {
struct nlmsghdr h;
@@ -932,13 +999,13 @@ nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int new)
int rsize = sizeof(*r) + bufsize;
r = alloca(rsize);
- DBG("nl_send_route(%N,new=%d)\n", net->n.addr, new);
+ DBG("nl_send_route(%N,op=%x)\n", net->n.addr, op);
bzero(&r->h, sizeof(r->h));
bzero(&r->r, sizeof(r->r));
- r->h.nlmsg_type = new ? RTM_NEWROUTE : RTM_DELROUTE;
+ r->h.nlmsg_type = op ? RTM_NEWROUTE : RTM_DELROUTE;
r->h.nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg));
- r->h.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | (new ? NLM_F_CREATE|NLM_F_EXCL : 0);
+ r->h.nlmsg_flags = op | NLM_F_REQUEST | NLM_F_ACK;
r->r.rtm_family = p->af;
r->r.rtm_dst_len = net_pxlen(net->n.addr);
@@ -946,18 +1013,37 @@ nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int new)
r->r.rtm_scope = RT_SCOPE_UNIVERSE;
nl_add_attr_ipa(&r->h, rsize, RTA_DST, net_prefix(net->n.addr));
+ /*
+ * Strange behavior for RTM_DELROUTE:
+ * 1) rtm_family is ignored in IPv6, works for IPv4
+ * 2) not setting RTA_PRIORITY is different from setting default value (on IPv6)
+ * 3) not setting RTA_PRIORITY is equivalent to setting 0, which is wildcard
+ */
+
if (krt_table_id(p) < 256)
r->r.rtm_table = krt_table_id(p);
else
nl_add_attr_u32(&r->h, rsize, RTA_TABLE, krt_table_id(p));
- /* For route delete, we do not specify route attributes */
- if (!new)
- return nl_exchange(&r->h);
+ if (a->source == RTS_DUMMY)
+ priority = e->u.krt.metric;
+ else if (KRT_CF->sys.metric)
+ priority = KRT_CF->sys.metric;
+ else if ((op != NL_OP_DELETE) && (ea = ea_find(eattrs, EA_KRT_METRIC)))
+ priority = ea->u.data;
+ if (priority)
+ nl_add_attr_u32(&r->h, sizeof(r), RTA_PRIORITY, priority);
- if (ea = ea_find(eattrs, EA_KRT_METRIC))
- nl_add_attr_u32(&r->h, rsize, RTA_PRIORITY, ea->u.data);
+ /* For route delete, we do not specify remaining route attributes */
+ if (op == NL_OP_DELETE)
+ goto dest;
+
+ /* Default scope is LINK for device routes, UNIVERSE otherwise */
+ if (ea = ea_find(eattrs, EA_KRT_SCOPE))
+ r->r.rtm_scope = ea->u.data;
+ else
+ r->r.rtm_scope = (dest == RTD_DEVICE) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE;
if (ea = ea_find(eattrs, EA_KRT_PREFSRC))
nl_add_attr_ipa(&r->h, rsize, RTA_PREFSRC, *(ip_addr *)ea->u.ptr->data);
@@ -981,18 +1067,18 @@ nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int new)
nl_add_metrics(&r->h, rsize, metrics, KRT_METRICS_MAX);
+dest:
/* a->iface != NULL checked in krt_capable() for router and device routes */
-
- switch (a->dest)
+ switch (dest)
{
case RTD_ROUTER:
r->r.rtm_type = RTN_UNICAST;
- nl_add_attr_u32(&r->h, rsize, RTA_OIF, a->iface->index);
- nl_add_attr_ipa(&r->h, rsize, RTA_GATEWAY, a->gw);
+ nl_add_attr_u32(&r->h, rsize, RTA_OIF, iface->index);
+ nl_add_attr_ipa(&r->h, rsize, RTA_GATEWAY, gw);
break;
case RTD_DEVICE:
r->r.rtm_type = RTN_UNICAST;
- nl_add_attr_u32(&r->h, rsize, RTA_OIF, a->iface->index);
+ nl_add_attr_u32(&r->h, rsize, RTA_OIF, iface->index);
break;
case RTD_BLACKHOLE:
r->r.rtm_type = RTN_BLACKHOLE;
@@ -1007,11 +1093,50 @@ nl_send_route(struct krt_proto *p, rte *e, struct ea_list *eattrs, int new)
r->r.rtm_type = RTN_UNICAST;
nl_add_multipath(&r->h, rsize, a->nexthops);
break;
+ case RTD_NONE:
+ break;
default:
bug("krt_capable inconsistent with nl_send_route");
}
- return nl_exchange(&r->h);
+ /* Ignore missing for DELETE */
+ return nl_exchange(&r->h, (op == NL_OP_DELETE));
+}
+
+static inline int
+nl_add_rte(struct krt_proto *p, rte *e, struct ea_list *eattrs)
+{
+ rta *a = e->attrs;
+ int err = 0;
+
+ if (krt_ecmp6(p) && (a->dest == RTD_MULTIPATH))
+ {
+ struct mpnh *nh = a->nexthops;
+
+ err = nl_send_route(p, e, eattrs, NL_OP_ADD, RTD_ROUTER, nh->gw, nh->iface);
+ if (err < 0)
+ return err;
+
+ for (nh = nh->next; nh; nh = nh->next)
+ err += nl_send_route(p, e, eattrs, NL_OP_APPEND, RTD_ROUTER, nh->gw, nh->iface);
+
+ return err;
+ }
+
+ return nl_send_route(p, e, eattrs, NL_OP_ADD, a->dest, a->gw, a->iface);
+}
+
+static inline int
+nl_delete_rte(struct krt_proto *p, rte *e, struct ea_list *eattrs)
+{
+ int err = 0;
+
+ /* For IPv6, we just repeatedly request DELETE until we get error */
+ do
+ err = nl_send_route(p, e, eattrs, NL_OP_DELETE, RTD_NONE, IPA_NONE, NULL);
+ while (krt_ecmp6(p) && !err);
+
+ return err;
}
void
@@ -1020,17 +1145,21 @@ krt_replace_rte(struct krt_proto *p, net *n, rte *new, rte *old, struct ea_list
int err = 0;
/*
- * NULL for eattr of the old route is a little hack, but we don't
- * get proper eattrs for old in rt_notify() anyway. NULL means no
- * extended route attributes and therefore matches if the kernel
- * route has any of them.
+ * We could use NL_OP_REPLACE, but route replace on Linux has some problems:
+ *
+ * 1) Does not check for matching rtm_protocol
+ * 2) Has broken semantics for IPv6 ECMP
+ * 3) Crashes some kernel version when used for IPv6 ECMP
+ *
+ * So we use NL_OP_DELETE and then NL_OP_ADD. We also do not trust the old
+ * route value, so we do not try to optimize IPv6 ECMP reconfigurations.
*/
if (old)
- nl_send_route(p, old, NULL, 0);
+ nl_delete_rte(p, old, eattrs);
if (new)
- err = nl_send_route(p, new, eattrs, 1);
+ err = nl_add_rte(p, new, eattrs);
if (err < 0)
n->n.flags |= KRF_SYNC_ERROR;
@@ -1039,10 +1168,80 @@ krt_replace_rte(struct krt_proto *p, net *n, rte *new, rte *old, struct ea_list
}
+static inline struct mpnh *
+nl_alloc_mpnh(struct nl_parse_state *s, ip_addr gw, struct iface *iface, byte weight)
+{
+ struct mpnh *nh = lp_alloc(s->pool, sizeof(struct mpnh));
+
+ nh->gw = gw;
+ nh->iface = iface;
+ nh->next = NULL;
+ nh->weight = weight;
+
+ return nh;
+}
+
+static int
+nl_mergable_route(struct nl_parse_state *s, net *net, struct krt_proto *p, uint priority, uint krt_type)
+{
+ /* Route merging must be active */
+ if (!s->merge)
+ return 0;
+
+ /* Saved and new route must have same network, proto/table, and priority */
+ if ((s->net != net) || (s->proto != p) || (s->krt_metric != priority))
+ return 0;
+
+ /* Both must be regular unicast routes */
+ if ((s->krt_type != RTN_UNICAST) || (krt_type != RTN_UNICAST))
+ return 0;
+
+ return 1;
+}
+
+static void
+nl_announce_route(struct nl_parse_state *s)
+{
+ rte *e = rte_get_temp(s->attrs);
+ e->net = s->net;
+ e->u.krt.src = s->krt_src;
+ e->u.krt.proto = s->krt_proto;
+ e->u.krt.seen = 0;
+ e->u.krt.best = 0;
+ e->u.krt.metric = s->krt_metric;
+
+ if (s->scan)
+ krt_got_route(s->proto, e);
+ else
+ krt_got_route_async(s->proto, e, s->new);
+
+ s->net = NULL;
+ s->attrs = NULL;
+ s->proto = NULL;
+ lp_flush(s->pool);
+}
+
+static inline void
+nl_parse_begin(struct nl_parse_state *s, int scan, int merge)
+{
+ memset(s, 0, sizeof (struct nl_parse_state));
+ s->pool = nl_linpool;
+ s->scan = scan;
+ s->merge = merge;
+}
+
+static inline void
+nl_parse_end(struct nl_parse_state *s)
+{
+ if (s->net)
+ nl_announce_route(s);
+}
+
+
#define SKIP(ARG...) do { DBG("KRT: Ignoring route - " ARG); return; } while(0)
static void
-nl_parse_route(struct nlmsghdr *h, int scan)
+nl_parse_route(struct nl_parse_state *s, struct nlmsghdr *h)
{
struct krt_proto *p;
struct rtmsg *i;
@@ -1052,6 +1251,8 @@ nl_parse_route(struct nlmsghdr *h, int scan)
net_addr dst;
u32 oif = ~0;
u32 table_id;
+ u32 priority = 0;
+ u32 def_scope = RT_SCOPE_UNIVERSE;
int src;
if (!(i = nl_checkin(h, sizeof(*i))))
@@ -1069,9 +1270,9 @@ nl_parse_route(struct nlmsghdr *h, int scan)
net_fill_ip4(&dst, IP4_NONE, 0);
break;
- case AF_INET6:
- if (!nl_parse_attrs(RTM_RTA(i), rtm_attr_want6, a, sizeof(a)))
- return;
+ case AF_INET6:
+ if (!nl_parse_attrs(RTM_RTA(i), rtm_attr_want6, a, sizeof(a)))
+ return;
if (a[RTA_DST])
net_fill_ip6(&dst, rta_get_ip6(a[RTA_DST]), i->rtm_dst_len);
@@ -1096,24 +1297,22 @@ nl_parse_route(struct nlmsghdr *h, int scan)
if (!p)
SKIP("unknown table %d\n", table);
-
if (a[RTA_IIF])
SKIP("IIF set\n");
if (i->rtm_tos != 0) /* We don't support TOS */
SKIP("TOS %02x\n", i->rtm_tos);
- if (scan && !new)
+ if (s->scan && !new)
SKIP("RTM_DELROUTE in scan\n");
+ if (a[RTA_PRIORITY])
+ priority = rta_get_u32(a[RTA_PRIORITY]);
+
int c = net_classify(&dst);
if ((c < 0) || !(c & IADDR_HOST) || ((c & IADDR_SCOPE_MASK) <= SCOPE_LINK))
SKIP("strange class/scope\n");
- // ignore rtm_scope, it is not a real scope
- // if (i->rtm_scope != RT_SCOPE_UNIVERSE)
- // SKIP("scope %u\n", i->rtm_scope);
-
switch (i->rtm_protocol)
{
case RTPROT_UNSPEC:
@@ -1128,7 +1327,7 @@ nl_parse_route(struct nlmsghdr *h, int scan)
return;
case RTPROT_BIRD:
- if (!scan)
+ if (!s->scan)
SKIP("echo\n");
src = KRT_SRC_BIRD;
break;
@@ -1140,12 +1339,14 @@ nl_parse_route(struct nlmsghdr *h, int scan)
net *net = net_get(p->p.main_channel->table, &dst);
- rta ra = {
- .src= p->p.main_source,
- .source = RTS_INHERIT,
- .scope = SCOPE_UNIVERSE,
- .cast = RTC_UNICAST
- };
+ if (s->net && !nl_mergable_route(s, net, p, priority, i->rtm_type))
+ nl_announce_route(s);
+
+ rta *ra = lp_allocz(s->pool, sizeof(rta));
+ ra->src = p->p.main_source;
+ ra->source = RTS_INHERIT;
+ ra->scope = SCOPE_UNIVERSE;
+ ra->cast = RTC_UNICAST;
switch (i->rtm_type)
{
@@ -1153,9 +1354,9 @@ nl_parse_route(struct nlmsghdr *h, int scan)
if (a[RTA_MULTIPATH] && (i->rtm_family == AF_INET))
{
- ra.dest = RTD_MULTIPATH;
- ra.nexthops = nl_parse_multipath(p, a[RTA_MULTIPATH]);
- if (!ra.nexthops)
+ ra->dest = RTD_MULTIPATH;
+ ra->nexthops = nl_parse_multipath(p, a[RTA_MULTIPATH]);
+ if (!ra->nexthops)
{
log(L_ERR "KRT: Received strange multipath route %N", net->n.addr);
return;
@@ -1164,8 +1365,8 @@ nl_parse_route(struct nlmsghdr *h, int scan)
break;
}
- ra.iface = if_find_by_index(oif);
- if (!ra.iface)
+ ra->iface = if_find_by_index(oif);
+ if (!ra->iface)
{
log(L_ERR "KRT: Received route %N with unknown ifindex %u", net->n.addr, oif);
return;
@@ -1173,37 +1374,38 @@ nl_parse_route(struct nlmsghdr *h, int scan)
if (a[RTA_GATEWAY])
{
- ra.dest = RTD_ROUTER;
- ra.gw = rta_get_ipa(a[RTA_GATEWAY]);
+ ra->dest = RTD_ROUTER;
+ ra->gw = rta_get_ipa(a[RTA_GATEWAY]);
/* Silently skip strange 6to4 routes */
const net_addr_ip6 sit = NET_ADDR_IP6(IP6_NONE, 96);
- if ((i->rtm_family == AF_INET6) && ipa_in_netX(ra.gw, (net_addr *) &sit))
+ if ((i->rtm_family == AF_INET6) && ipa_in_netX(ra->gw, (net_addr *) &sit))
return;
neighbor *nbr;
- nbr = neigh_find2(&p->p, &ra.gw, ra.iface,
+ nbr = neigh_find2(&p->p, &ra->gw, ra->iface,
(i->rtm_flags & RTNH_F_ONLINK) ? NEF_ONLINK : 0);
if (!nbr || (nbr->scope == SCOPE_HOST))
{
- log(L_ERR "KRT: Received route %N with strange next-hop %I", net->n.addr, ra.gw);
+ log(L_ERR "KRT: Received route %N with strange next-hop %I", net->n.addr, ra->gw);
return;
}
}
else
{
- ra.dest = RTD_DEVICE;
+ ra->dest = RTD_DEVICE;
+ def_scope = RT_SCOPE_LINK;
}
break;
case RTN_BLACKHOLE:
- ra.dest = RTD_BLACKHOLE;
+ ra->dest = RTD_BLACKHOLE;
break;
case RTN_UNREACHABLE:
- ra.dest = RTD_UNREACHABLE;
+ ra->dest = RTD_UNREACHABLE;
break;
case RTN_PROHIBIT:
- ra.dest = RTD_PROHIBIT;
+ ra->dest = RTD_PROHIBIT;
break;
/* FIXME: What about RTN_THROW? */
default:
@@ -1211,39 +1413,41 @@ nl_parse_route(struct nlmsghdr *h, int scan)
return;
}
- rte *e = rte_get_temp(&ra);
- e->net = net;
- e->u.krt.src = src;
- e->u.krt.proto = i->rtm_protocol;
- e->u.krt.seen = 0;
- e->u.krt.best = 0;
- e->u.krt.metric = 0;
-
- if (a[RTA_PRIORITY])
- e->u.krt.metric = rta_get_u32(a[RTA_PRIORITY]);
+ if (i->rtm_scope != def_scope)
+ {
+ ea_list *ea = lp_alloc(s->pool, sizeof(ea_list) + sizeof(eattr));
+ ea->next = ra->eattrs;
+ ra->eattrs = ea;
+ ea->flags = EALF_SORTED;
+ ea->count = 1;
+ ea->attrs[0].id = EA_KRT_SCOPE;
+ ea->attrs[0].flags = 0;
+ ea->attrs[0].type = EAF_TYPE_INT;
+ ea->attrs[0].u.data = i->rtm_scope;
+ }
if (a[RTA_PREFSRC])
{
ip_addr ps = rta_get_ipa(a[RTA_PREFSRC]);
- ea_list *ea = alloca(sizeof(ea_list) + sizeof(eattr));
- ea->next = ra.eattrs;
- ra.eattrs = ea;
+ ea_list *ea = lp_alloc(s->pool, sizeof(ea_list) + sizeof(eattr));
+ ea->next = ra->eattrs;
+ ra->eattrs = ea;
ea->flags = EALF_SORTED;
ea->count = 1;
ea->attrs[0].id = EA_KRT_PREFSRC;
ea->attrs[0].flags = 0;
ea->attrs[0].type = EAF_TYPE_IP_ADDRESS;
- ea->attrs[0].u.ptr = alloca(sizeof(struct adata) + sizeof(ps));
+ ea->attrs[0].u.ptr = lp_alloc(s->pool, sizeof(struct adata) + sizeof(ps));
ea->attrs[0].u.ptr->length = sizeof(ps);
memcpy(ea->attrs[0].u.ptr->data, &ps, sizeof(ps));
}
if (a[RTA_FLOW])
{
- ea_list *ea = alloca(sizeof(ea_list) + sizeof(eattr));
- ea->next = ra.eattrs;
- ra.eattrs = ea;
+ ea_list *ea = lp_alloc(s->pool, sizeof(ea_list) + sizeof(eattr));
+ ea->next = ra->eattrs;
+ ra->eattrs = ea;
ea->flags = EALF_SORTED;
ea->count = 1;
ea->attrs[0].id = EA_KRT_REALM;
@@ -1255,7 +1459,7 @@ nl_parse_route(struct nlmsghdr *h, int scan)
if (a[RTA_METRICS])
{
u32 metrics[KRT_METRICS_MAX];
- ea_list *ea = alloca(sizeof(ea_list) + KRT_METRICS_MAX * sizeof(eattr));
+ ea_list *ea = lp_alloc(s->pool, sizeof(ea_list) + KRT_METRICS_MAX * sizeof(eattr));
int t, n = 0;
if (nl_parse_metrics(a[RTA_METRICS], metrics, ARRAY_SIZE(metrics)) < 0)
@@ -1276,37 +1480,69 @@ nl_parse_route(struct nlmsghdr *h, int scan)
if (n > 0)
{
- ea->next = ra.eattrs;
+ ea->next = ra->eattrs;
ea->flags = EALF_SORTED;
ea->count = n;
- ra.eattrs = ea;
+ ra->eattrs = ea;
}
}
- if (scan)
- krt_got_route(p, e);
+ /*
+ * Ideally, now we would send the received route to the rest of kernel code.
+ * But IPv6 ECMP routes are sent as a sequence of routes, so we postpone it
+ * and merge next hops until the end of the sequence.
+ */
+
+ if (!s->net)
+ {
+ /* Store the new route */
+ s->net = net;
+ s->attrs = ra;
+ s->proto = p;
+ s->new = new;
+ s->krt_src = src;
+ s->krt_type = i->rtm_type;
+ s->krt_proto = i->rtm_protocol;
+ s->krt_metric = priority;
+ }
else
- krt_got_route_async(p, e, new);
+ {
+ /* Merge next hops with the stored route */
+ rta *a = s->attrs;
+
+ if (a->dest != RTD_MULTIPATH)
+ {
+ a->dest = RTD_MULTIPATH;
+ a->nexthops = nl_alloc_mpnh(s, a->gw, a->iface, 0);
+ }
+
+ mpnh_insert(&a->nexthops, nl_alloc_mpnh(s, ra->gw, ra->iface, 0));
+ }
}
void
krt_do_scan(struct krt_proto *p UNUSED) /* CONFIG_ALL_TABLES_AT_ONCE => p is NULL */
{
struct nlmsghdr *h;
+ struct nl_parse_state s;
+ nl_parse_begin(&s, 1, 0);
nl_request_dump(AF_INET, RTM_GETROUTE);
while (h = nl_get_scan())
if (h->nlmsg_type == RTM_NEWROUTE || h->nlmsg_type == RTM_DELROUTE)
- nl_parse_route(h, 1);
+ nl_parse_route(&s, h);
else
log(L_DEBUG "nl_scan_fire: Unknown packet received (type=%d)", h->nlmsg_type);
+ nl_parse_end(&s);
+ nl_parse_begin(&s, 1, 1);
nl_request_dump(AF_INET6, RTM_GETROUTE);
while (h = nl_get_scan())
if (h->nlmsg_type == RTM_NEWROUTE || h->nlmsg_type == RTM_DELROUTE)
- nl_parse_route(h, 1);
+ nl_parse_route(&s, h);
else
log(L_DEBUG "nl_scan_fire: Unknown packet received (type=%d)", h->nlmsg_type);
+ nl_parse_end(&s);
}
/*
@@ -1319,12 +1555,16 @@ static byte *nl_async_rx_buffer; /* Receive buffer */
static void
nl_async_msg(struct nlmsghdr *h)
{
+ struct nl_parse_state s;
+
switch (h->nlmsg_type)
{
case RTM_NEWROUTE:
case RTM_DELROUTE:
DBG("KRT: Received async route notification (%d)\n", h->nlmsg_type);
- nl_parse_route(h, 0);
+ nl_parse_begin(&s, 0, 0);
+ nl_parse_route(&s, h);
+ nl_parse_end(&s);
break;
case RTM_NEWLINK:
case RTM_DELLINK:
@@ -1344,7 +1584,7 @@ nl_async_msg(struct nlmsghdr *h)
}
static int
-nl_async_hook(sock *sk, int size UNUSED)
+nl_async_hook(sock *sk, uint size UNUSED)
{
struct iovec iov = { nl_async_rx_buffer, NL_RX_SIZE };
struct sockaddr_nl sa;
@@ -1397,6 +1637,12 @@ nl_async_hook(sock *sk, int size UNUSED)
}
static void
+nl_async_err_hook(sock *sk, int e UNUSED)
+{
+ nl_async_hook(sk, 0);
+}
+
+static void
nl_open_async(void)
{
sock *sk;
@@ -1433,6 +1679,7 @@ nl_open_async(void)
sk = nl_async_sk = sk_new(krt_pool);
sk->type = SK_MAGIC;
sk->rx_hook = nl_async_hook;
+ sk->err_hook = nl_async_err_hook;
sk->fd = fd;
if (sk_open(sk) < 0)
bug("Netlink: sk_open failed");
@@ -1446,6 +1693,7 @@ nl_open_async(void)
void
krt_sys_io_init(void)
{
+ nl_linpool = lp_new(krt_pool, 4080);
HASH_INIT(nl_table_map, krt_pool, 6);
}
@@ -1478,19 +1726,21 @@ krt_sys_shutdown(struct krt_proto *p)
int
krt_sys_reconfigure(struct krt_proto *p UNUSED, struct krt_config *n, struct krt_config *o)
{
- return n->sys.table_id == o->sys.table_id;
+ return (n->sys.table_id == o->sys.table_id) && (n->sys.metric == o->sys.metric);
}
void
krt_sys_init_config(struct krt_config *cf)
{
cf->sys.table_id = RT_TABLE_MAIN;
+ cf->sys.metric = 0;
}
void
krt_sys_copy_config(struct krt_config *d, struct krt_config *s)
{
d->sys.table_id = s->sys.table_id;
+ d->sys.metric = s->sys.metric;
}
static const char *krt_metrics_names[KRT_METRICS_MAX] = {
@@ -1515,6 +1765,10 @@ krt_sys_get_attr(eattr *a, byte *buf, int buflen UNUSED)
bsprintf(buf, "realm");
return GA_NAME;
+ case EA_KRT_SCOPE:
+ bsprintf(buf, "scope");
+ return GA_NAME;
+
case EA_KRT_LOCK:
buf += bsprintf(buf, "lock:");
ea_format_bitfield(a, buf, buflen, krt_metrics_names, 2, KRT_METRICS_MAX);
diff --git a/sysdep/linux/syspriv.h b/sysdep/linux/syspriv.h
index d2ba95dd..8b210f06 100644
--- a/sysdep/linux/syspriv.h
+++ b/sysdep/linux/syspriv.h
@@ -1,4 +1,11 @@
+#ifndef _BIRD_SYSPRIV_H_
+#define _BIRD_SYSPRIV_H_
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <unistd.h>
#include <sys/prctl.h>
#include <linux/capability.h>
@@ -70,3 +77,5 @@ drop_uid(uid_t uid)
if (setresuid(uid, uid, uid) < 0)
die("setresuid: %m");
}
+
+#endif /* _BIRD_SYSPRIV_H_ */
diff --git a/sysdep/unix/Makefile b/sysdep/unix/Makefile
index c5d55431..f592399c 100644
--- a/sysdep/unix/Makefile
+++ b/sysdep/unix/Makefile
@@ -3,3 +3,6 @@ obj := $(src-o-files)
$(all-daemon)
$(cf-local)
$(conf-y-targets): $(s)krt.Y
+
+src := $(filter-out main.c, $(src))
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/sysdep/unix/io.c b/sysdep/unix/io.c
index e3e2f5f8..c8916378 100644
--- a/sysdep/unix/io.c
+++ b/sysdep/unix/io.c
@@ -9,7 +9,9 @@
/* Unfortunately, some glibc versions hide parts of RFC 3542 API
if _GNU_SOURCE is not defined. */
-#define _GNU_SOURCE 1
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
#include <stdio.h>
#include <stdlib.h>
@@ -507,11 +509,11 @@ tm_format_datetime(char *x, struct timeformat *fmt_spec, bird_clock_t t)
* Sockaddr helper functions
*/
-static inline int sockaddr_length(int af)
+static inline int UNUSED sockaddr_length(int af)
{ return (af == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6); }
static inline void
-sockaddr_fill4(struct sockaddr_in *sa, ip_addr a, struct iface *ifa, uint port)
+sockaddr_fill4(struct sockaddr_in *sa, ip_addr a, uint port)
{
memset(sa, 0, sizeof(struct sockaddr_in));
#ifdef HAVE_SIN_LEN
@@ -542,7 +544,7 @@ void
sockaddr_fill(sockaddr *sa, int af, ip_addr a, struct iface *ifa, uint port)
{
if (af == AF_INET)
- sockaddr_fill4((struct sockaddr_in *) sa, a, ifa, port);
+ sockaddr_fill4((struct sockaddr_in *) sa, a, port);
else if (af == AF_INET6)
sockaddr_fill6((struct sockaddr_in6 *) sa, a, ifa, port);
else
@@ -550,7 +552,7 @@ sockaddr_fill(sockaddr *sa, int af, ip_addr a, struct iface *ifa, uint port)
}
static inline void
-sockaddr_read4(struct sockaddr_in *sa, ip_addr *a, struct iface **ifa, uint *port)
+sockaddr_read4(struct sockaddr_in *sa, ip_addr *a, uint *port)
{
*port = ntohs(sa->sin_port);
*a = ipa_from_in4(sa->sin_addr);
@@ -573,7 +575,7 @@ sockaddr_read(sockaddr *sa, int af, ip_addr *a, struct iface **ifa, uint *port)
goto fail;
if (af == AF_INET)
- sockaddr_read4((struct sockaddr_in *) sa, a, ifa, port);
+ sockaddr_read4((struct sockaddr_in *) sa, a, port);
else if (af == AF_INET6)
sockaddr_read6((struct sockaddr_in6 *) sa, a, ifa, port);
else
@@ -770,7 +772,7 @@ sk_set_tos6(sock *s, int tos)
}
static inline int
-sk_set_high_port(sock *s)
+sk_set_high_port(sock *s UNUSED)
{
/* Port range setting is optional, ignore it if not supported */
@@ -1293,7 +1295,7 @@ sk_setup(sock *s)
if (sk_is_ipv6(s))
{
- if (s->type != SK_IP)
+ if ((s->type == SK_TCP_PASSIVE) || (s->type == SK_TCP_ACTIVE) || (s->type == SK_UDP))
if (setsockopt(fd, SOL_IPV6, IPV6_V6ONLY, &y, sizeof(y)) < 0)
ERR("IPV6_V6ONLY");
@@ -2247,6 +2249,20 @@ int sk_is_ipv6(sock *s)
{ return s->af == AF_INET6; }
void
+sk_err(sock *s, int revents)
+{
+ int se = 0, sse = sizeof(se);
+ if ((s->type != SK_MAGIC) && (revents & POLLERR))
+ if (getsockopt(s->fd, SOL_SOCKET, SO_ERROR, &se, &sse) < 0)
+ {
+ log(L_ERR "IO: Socket error: SO_ERROR: %m");
+ se = 0;
+ }
+
+ s->err_hook(s, se);
+}
+
+void
sk_dump_all(void)
{
node *n;
@@ -2557,7 +2573,7 @@ io_loop(void)
int steps;
steps = MAX_STEPS;
- if (s->fast_rx && (pfd[s->index].revents & (POLLIN | POLLHUP | POLLERR)) && s->rx_hook)
+ if (s->fast_rx && (pfd[s->index].revents & POLLIN) && s->rx_hook)
do
{
steps--;
@@ -2579,6 +2595,7 @@ io_loop(void)
goto next;
}
while (e && steps);
+
current_sock = sk_next(s);
next: ;
}
@@ -2602,18 +2619,26 @@ io_loop(void)
goto next2;
}
- if (!s->fast_rx && (pfd[s->index].revents & (POLLIN | POLLHUP | POLLERR)) && s->rx_hook)
+ if (!s->fast_rx && (pfd[s->index].revents & POLLIN) && s->rx_hook)
{
count++;
io_log_event(s->rx_hook, s->data);
sk_read(s, pfd[s->index].revents);
if (s != current_sock)
- goto next2;
+ goto next2;
}
+
+ if (pfd[s->index].revents & (POLLHUP | POLLERR))
+ {
+ sk_err(s, pfd[s->index].revents);
+ goto next2;
+ }
+
current_sock = sk_next(s);
next2: ;
}
+
stored_sock = current_sock;
}
}
diff --git a/sysdep/unix/krt.Y b/sysdep/unix/krt.Y
index 91317d97..33dc4a19 100644
--- a/sysdep/unix/krt.Y
+++ b/sysdep/unix/krt.Y
@@ -29,6 +29,8 @@ CF_DECLS
CF_KEYWORDS(KERNEL, PERSIST, SCAN, TIME, LEARN, DEVICE, ROUTES, GRACEFUL, RESTART, KRT_SOURCE, KRT_METRIC, MERGE, PATHS)
+%type <i> kern_mp_limit
+
CF_GRAMMAR
/* Kernel syncer protocol */
@@ -43,6 +45,11 @@ kern_proto_start: proto_start KERNEL {
CF_ADDTO(kern_proto, kern_proto_start proto_name '{')
CF_ADDTO(kern_proto, kern_proto kern_item ';')
+kern_mp_limit:
+ /* empty */ { $$ = KRT_DEFAULT_ECMP_LIMIT; }
+ | LIMIT expr { $$ = $2; if (($2 <= 0) || ($2 > 255)) cf_error("Merge paths limit must be in range 1-255"); }
+ ;
+
kern_item:
proto_item
| proto_channel { this_proto->net_type = $1->net_type; }
@@ -55,13 +62,18 @@ kern_item:
THIS_KRT->learn = $2;
#ifndef KRT_ALLOW_LEARN
if ($2)
- cf_error("Learning of kernel routes not supported in this configuration");
+ cf_error("Learning of kernel routes not supported on this platform");
#endif
}
| DEVICE ROUTES bool { THIS_KRT->devroutes = $3; }
| GRACEFUL RESTART bool { THIS_KRT->graceful_restart = $3; }
- | MERGE PATHS bool { krt_set_merge_paths(this_channel, $3, KRT_DEFAULT_ECMP_LIMIT); }
- | MERGE PATHS bool LIMIT expr { krt_set_merge_paths(this_channel, $3, $5); }
+ | MERGE PATHS bool kern_mp_limit {
+ krt_set_merge_paths(this_channel, $3, $4);
+#ifndef KRT_ALLOW_MERGE_PATHS
+ if ($3)
+ cf_error("Path merging not supported on this platform");
+#endif
+ }
;
/* Kernel interface protocol */
diff --git a/sysdep/unix/krt.c b/sysdep/unix/krt.c
index 6531bb28..e899671d 100644
--- a/sysdep/unix/krt.c
+++ b/sysdep/unix/krt.c
@@ -604,7 +604,7 @@ krt_export_net(struct krt_proto *p, net *net, rte **rt_free, ea_list **tmpa)
rte *rt;
if (c->ra_mode == RA_MERGED)
- return rt_export_merged(c, net, rt_free, tmpa, 1);
+ return rt_export_merged(c, net, rt_free, tmpa, krt_filter_lp, 1);
rt = net->routes;
*rt_free = NULL;
@@ -899,7 +899,7 @@ krt_scan_timer_start(struct krt_proto *p)
}
static void
-krt_scan_timer_stop(struct krt_proto *p)
+krt_scan_timer_stop(struct krt_proto *p UNUSED)
{
krt_scan_count--;
@@ -988,7 +988,7 @@ krt_store_tmp_attrs(rte *rt, struct ea_list *attrs)
}
static int
-krt_import_control(struct proto *P, rte **new, ea_list **attrs, struct linpool *pool)
+krt_import_control(struct proto *P, rte **new, ea_list **attrs UNUSED, struct linpool *pool UNUSED)
{
struct krt_proto *p = (struct krt_proto *) P;
rte *e = *new;
diff --git a/sysdep/unix/log.c b/sysdep/unix/log.c
index 9c56eb24..42c933ef 100644
--- a/sysdep/unix/log.c
+++ b/sysdep/unix/log.c
@@ -20,6 +20,7 @@
#include <stdarg.h>
#include <time.h>
#include <unistd.h>
+#include <errno.h>
#include "nest/bird.h"
#include "nest/cli.h"
@@ -209,6 +210,7 @@ bug(const char *msg, ...)
va_start(args, msg);
vlog(L_BUG[0], msg, args);
+ va_end(args);
abort();
}
@@ -226,6 +228,7 @@ die(const char *msg, ...)
va_start(args, msg);
vlog(L_FATAL[0], msg, args);
+ va_end(args);
exit(1);
}
@@ -285,18 +288,22 @@ log_switch(int debug, list *l, char *new_syslog_name)
current_log_list = l;
#ifdef HAVE_SYSLOG
- char *old_syslog_name = current_syslog_name;
- current_syslog_name = new_syslog_name;
-
- if (old_syslog_name && new_syslog_name &&
- !strcmp(old_syslog_name, new_syslog_name))
+ if (current_syslog_name && new_syslog_name &&
+ !strcmp(current_syslog_name, new_syslog_name))
return;
- if (old_syslog_name)
+ if (current_syslog_name)
+ {
closelog();
+ xfree(current_syslog_name);
+ current_syslog_name = NULL;
+ }
if (new_syslog_name)
- openlog(new_syslog_name, LOG_CONS | LOG_NDELAY, LOG_DAEMON);
+ {
+ current_syslog_name = xstrdup(new_syslog_name);
+ openlog(current_syslog_name, LOG_CONS | LOG_NDELAY, LOG_DAEMON);
+ }
#endif
}
@@ -312,7 +319,11 @@ log_init_debug(char *f)
else if (!*f)
dbgf = stderr;
else if (!(dbgf = fopen(f, "a")))
- log(L_ERR "Error opening debug file `%s': %m", f);
+ {
+ /* Cannot use die() nor log() here, logging is not yet initialized */
+ fprintf(stderr, "bird: Unable to open debug file %s: %s\n", f, strerror(errno));
+ exit(1);
+ }
if (dbgf)
setvbuf(dbgf, NULL, _IONBF, 0);
}
diff --git a/sysdep/unix/main.c b/sysdep/unix/main.c
index 1f47680e..c1b92b7e 100644
--- a/sysdep/unix/main.c
+++ b/sysdep/unix/main.c
@@ -8,7 +8,9 @@
#undef LOCAL_DEBUG
-#define _GNU_SOURCE 1
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
#include <stdio.h>
#include <stdlib.h>
@@ -73,7 +75,7 @@ async_dump(void)
#else
static inline void
-drop_uid(uid_t uid)
+drop_uid(uid_t uid UNUSED)
{
die("Cannot change user on this platform");
}
@@ -419,7 +421,7 @@ cli_get_command(cli *c)
}
static int
-cli_rx(sock *s, int size UNUSED)
+cli_rx(sock *s, uint size UNUSED)
{
cli_kick(s->data);
return 0;
@@ -439,7 +441,7 @@ cli_err(sock *s, int err)
}
static int
-cli_connect(sock *s, int size UNUSED)
+cli_connect(sock *s, uint size UNUSED)
{
cli *c;
@@ -621,7 +623,7 @@ signal_init(void)
* Parsing of command-line arguments
*/
-static char *opt_list = "c:dD:ps:P:u:g:flR";
+static char *opt_list = "c:dD:ps:P:u:g:flRh";
static int parse_and_exit;
char *bird_name;
static char *use_user;
@@ -629,10 +631,43 @@ static char *use_group;
static int run_in_foreground = 0;
static void
-usage(void)
+display_usage(void)
+{
+ fprintf(stderr, "Usage: %s [--version] [--help] [-c <config-file>] [OPTIONS]\n", bird_name);
+}
+
+static void
+display_help(void)
+{
+ display_usage();
+
+ fprintf(stderr,
+ "\n"
+ "Options: \n"
+ " -c <config-file> Use given configuration file instead\n"
+ " of prefix/etc/bird.conf\n"
+ " -d Enable debug messages and run bird in foreground\n"
+ " -D <debug-file> Log debug messages to given file instead of stderr\n"
+ " -f Run bird in foreground\n"
+ " -g <group> Use given group ID\n"
+ " -h, --help Display this information\n"
+ " -l Look for a configuration file and a communication socket\n"
+ " file in the current working directory\n"
+ " -p Test configuration file and exit without start\n"
+ " -P <pid-file> Create a PID file with given filename\n"
+ " -R Apply graceful restart recovery after start\n"
+ " -s <control-socket> Use given filename for a control socket\n"
+ " -u <user> Drop privileges and use given user ID\n"
+ " --version Display version of BIRD\n");
+
+ exit(0);
+}
+
+static void
+display_version(void)
{
- fprintf(stderr, "Usage: %s [-c <config-file>] [-d] [-D <debug-file>] [-p] [-s <control-socket>] [-P <pid-file>] [-u <user>] [-g <group>] [-f] [-l] [-R]\n", bird_name);
- exit(1);
+ fprintf(stderr, "BIRD version " BIRD_VERSION "\n");
+ exit(0);
}
static inline char *
@@ -706,12 +741,9 @@ parse_args(int argc, char **argv)
if (argc == 2)
{
if (!strcmp(argv[1], "--version"))
- {
- fprintf(stderr, "BIRD version " BIRD_VERSION "\n");
- exit(0);
- }
+ display_version();
if (!strcmp(argv[1], "--help"))
- usage();
+ display_help();
}
while ((c = getopt(argc, argv, opt_list)) >= 0)
switch (c)
@@ -755,11 +787,19 @@ parse_args(int argc, char **argv)
case 'R':
graceful_restart_recovery();
break;
+ case 'h':
+ display_help();
+ break;
default:
- usage();
+ fputc('\n', stderr);
+ display_usage();
+ exit(1);
}
if (optind < argc)
- usage();
+ {
+ display_usage();
+ exit(1);
+ }
}
/*
diff --git a/test/Makefile b/test/Makefile
new file mode 100644
index 00000000..2cee9234
--- /dev/null
+++ b/test/Makefile
@@ -0,0 +1,3 @@
+src := birdtest.c bt-utils.c
+obj := $(src-o-files)
+tests_objs := $(tests_objs) $(src-o-files)
diff --git a/test/birdtest.c b/test/birdtest.c
new file mode 100644
index 00000000..73cb9901
--- /dev/null
+++ b/test/birdtest.c
@@ -0,0 +1,502 @@
+/*
+ * BIRD -- Unit Test Framework (BIRD Test)
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include <stdarg.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+
+#include <sys/ioctl.h>
+#include <sys/resource.h>
+#include <sys/wait.h>
+
+#include "test/birdtest.h"
+#include "lib/string.h"
+
+#ifdef HAVE_EXECINFO_H
+#include <execinfo.h>
+#endif
+
+#define BACKTRACE_MAX_LINES 100
+
+#define sprintf_concat(s, format, ...) \
+ snprintf(s + strlen(s), sizeof(s) - strlen(s), format, ##__VA_ARGS__)
+
+static const char *request;
+static int list_tests;
+static int do_core;
+static int no_fork;
+static int no_timeout;
+static int is_terminal; /* Whether stdout is a live terminal or pipe redirect */
+
+uint bt_verbose;
+const char *bt_filename;
+const char *bt_test_id;
+
+int bt_result; /* Overall program run result */
+int bt_suite_result; /* One suit result */
+char bt_out_fmt_buf[1024]; /* Temporary memory buffer for output of testing function */
+
+long int
+bt_random(void)
+{
+ /* Seeded in bt_init() */
+ long int rand_low, rand_high;
+
+ rand_low = random();
+ rand_high = random();
+ return (rand_low & 0xffff) | ((rand_high & 0xffff) << 16);
+}
+
+void
+bt_init(int argc, char *argv[])
+{
+ int c;
+
+ srandom(BT_RANDOM_SEED);
+
+ bt_verbose = 0;
+ bt_filename = argv[0];
+ bt_result = 1;
+ bt_test_id = NULL;
+ is_terminal = isatty(fileno(stdout));
+
+ while ((c = getopt(argc, argv, "lcftv")) >= 0)
+ switch (c)
+ {
+ case 'l':
+ list_tests = 1;
+ break;
+
+ case 'c':
+ do_core = 1;
+ break;
+
+ case 'f':
+ no_fork = 1;
+ break;
+
+ case 't':
+ no_timeout = 1;
+ break;
+
+ case 'v':
+ bt_verbose++;
+ break;
+
+ default:
+ goto usage;
+ }
+
+ /* Optional requested test_id */
+ if ((optind + 1) == argc)
+ request = argv[optind++];
+
+ if (optind != argc)
+ goto usage;
+
+ if (do_core)
+ {
+ struct rlimit rl = {RLIM_INFINITY, RLIM_INFINITY};
+ int rv = setrlimit(RLIMIT_CORE, &rl);
+ bt_syscall(rv < 0, "setrlimit RLIMIT_CORE");
+ }
+
+ return;
+
+ usage:
+ printf("Usage: %s [-l] [-c] [-f] [-t] [-vvv] [<test_suit_name>]\n", argv[0]);
+ printf("Options: \n");
+ printf(" -l List all test suite names and descriptions \n");
+ printf(" -c Force unlimit core dumps (needs root privileges) \n");
+ printf(" -f No forking \n");
+ printf(" -t No timeout limit \n");
+ printf(" -v More verbosity, maximum is 3 -vvv \n");
+ exit(3);
+}
+
+static void
+bt_dump_backtrace(void)
+{
+#ifdef HAVE_EXECINFO_H
+ void *buf[BACKTRACE_MAX_LINES];
+ char **pp_backtrace;
+ int lines, j;
+
+ if (!bt_verbose)
+ return;
+
+ lines = backtrace(buf, BACKTRACE_MAX_LINES);
+ bt_log("backtrace() returned %d addresses", lines);
+
+ pp_backtrace = backtrace_symbols(buf, lines);
+ if (pp_backtrace == NULL)
+ {
+ perror("backtrace_symbols");
+ exit(EXIT_FAILURE);
+ }
+
+ for (j = 0; j < lines; j++)
+ bt_log("%s", pp_backtrace[j]);
+
+ free(pp_backtrace);
+#endif /* HAVE_EXECINFO_H */
+}
+
+static
+int bt_run_test_fn(int (*fn)(const void *), const void *fn_arg, int timeout)
+{
+ int result;
+ alarm(timeout);
+
+ if (fn_arg)
+ result = fn(fn_arg);
+ else
+ result = ((int (*)(void))fn)();
+
+ if (!bt_suite_result)
+ result = 0;
+
+ return result;
+}
+
+static uint
+get_num_terminal_cols(void)
+{
+ struct winsize w = {};
+ ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
+ uint cols = w.ws_col;
+ return (cols > 0 ? cols : 80);
+}
+
+/**
+ * bt_log_result - pretty print of test result
+ * @result: 1 or 0
+ * @fmt: a description message (could be long, over more lines)
+ * @argptr: variable argument list
+ *
+ * This function is used for pretty printing of test results on all verbose
+ * levels.
+ */
+static void
+bt_log_result(int result, const char *fmt, va_list argptr)
+{
+ static char msg_buf[BT_BUFFER_SIZE];
+ char *pos;
+
+ snprintf(msg_buf, sizeof(msg_buf), "%s%s%s%s",
+ bt_filename,
+ bt_test_id ? ": " : "",
+ bt_test_id ? bt_test_id : "",
+ (fmt && strlen(fmt) > 0) ? ": " : "");
+ pos = msg_buf + strlen(msg_buf);
+
+ vsnprintf(pos, sizeof(msg_buf) - (pos - msg_buf), fmt, argptr);
+
+ int chrs = 0;
+ for (int i = 0; i < strlen(msg_buf); i += get_num_terminal_cols())
+ {
+ if (i)
+ printf("\n");
+ char *stop = msg_buf + i + get_num_terminal_cols();
+ char backup = *stop;
+ *stop = 0;
+ chrs = printf("%s", msg_buf + i);
+ *stop = backup;
+ }
+
+ int offset = get_num_terminal_cols() - chrs - BT_PROMPT_OK_FAIL_STRLEN;
+ if (offset < 0)
+ {
+ printf("\n");
+ offset = get_num_terminal_cols() - BT_PROMPT_OK_FAIL_STRLEN;
+ }
+
+ for (int i = 0; i < offset; i++)
+ putchar(' ');
+
+ const char *result_str = is_terminal ? BT_PROMPT_OK : BT_PROMPT_OK_NO_COLOR;
+ if (!result)
+ result_str = is_terminal ? BT_PROMPT_FAIL : BT_PROMPT_FAIL_NO_COLOR;
+
+ printf("%s\n", result_str);
+}
+
+/**
+ * bt_log_overall_result - pretty print of suite case result
+ * @result: 1 or 0
+ * @fmt: a description message (could be long, over more lines)
+ * ...: variable argument list
+ *
+ * This function is used for pretty printing of test suite case result.
+ */
+static void
+bt_log_overall_result(int result, const char *fmt, ...)
+{
+ va_list argptr;
+ va_start(argptr, fmt);
+ bt_log_result(result, fmt, argptr);
+ va_end(argptr);
+}
+
+/**
+ * bt_log_suite_result - pretty print of suite case result
+ * @result: 1 or 0
+ * @fmt: a description message (could be long, over more lines)
+ * ...: variable argument list
+ *
+ * This function is used for pretty printing of test suite case result.
+ */
+void
+bt_log_suite_result(int result, const char *fmt, ...)
+{
+ if(bt_verbose >= BT_VERBOSE_SUITE || !result)
+ {
+ va_list argptr;
+ va_start(argptr, fmt);
+ bt_log_result(result, fmt, argptr);
+ va_end(argptr);
+ }
+}
+
+/**
+ * bt_log_suite_case_result - pretty print of suite result
+ * @result: 1 or 0
+ * @fmt: a description message (could be long, over more lines)
+ * ...: variable argument list
+ *
+ * This function is used for pretty printing of test suite result.
+ */
+void
+bt_log_suite_case_result(int result, const char *fmt, ...)
+{
+ if(bt_verbose >= BT_VERBOSE_SUITE_CASE)
+ {
+ va_list argptr;
+ va_start(argptr, fmt);
+ bt_log_result(result, fmt, argptr);
+ va_end(argptr);
+ }
+}
+
+int
+bt_test_suite_base(int (*fn)(const void *), const char *id, const void *fn_arg, int forked, int timeout, const char *dsc, ...)
+{
+ if (list_tests)
+ {
+ printf("%28s - ", id);
+ va_list args;
+ va_start(args, dsc);
+ vprintf(dsc, args);
+ va_end(args);
+ printf("\n");
+ return 1;
+ }
+
+ if (no_fork)
+ forked = 0;
+
+ if (no_timeout)
+ timeout = 0;
+
+ if (request && strcmp(id, request))
+ return 1;
+
+ bt_suite_result = 1;
+ bt_test_id = id;
+
+ if (bt_verbose >= BT_VERBOSE_ABSOLUTELY_ALL)
+ bt_log("Starting");
+
+ if (!forked)
+ {
+ bt_suite_result = bt_run_test_fn(fn, fn_arg, timeout);
+ }
+ else
+ {
+ pid_t pid = fork();
+ bt_syscall(pid < 0, "fork");
+
+ if (pid == 0)
+ {
+ /* child of fork */
+ _exit(bt_run_test_fn(fn, fn_arg, timeout));
+ }
+
+ int s;
+ int rv = waitpid(pid, &s, 0);
+ bt_syscall(rv < 0, "waitpid");
+
+ if (WIFEXITED(s))
+ {
+ /* Normal exit */
+ bt_suite_result = WEXITSTATUS(s);
+ }
+ else if (WIFSIGNALED(s))
+ {
+ /* Stopped by signal */
+ bt_suite_result = 0;
+
+ int sn = WTERMSIG(s);
+ if (sn == SIGALRM)
+ {
+ bt_log("Timeout expired");
+ }
+ else if (sn == SIGSEGV)
+ {
+ bt_log("Segmentation fault");
+ bt_dump_backtrace();
+ }
+ else if (sn != SIGABRT)
+ bt_log("Signal %d received", sn);
+ }
+
+ if (WCOREDUMP(s) && bt_verbose)
+ bt_log("Core dumped");
+ }
+
+ if (!bt_suite_result)
+ bt_result = 0;
+
+ bt_log_suite_result(bt_suite_result, NULL);
+ bt_test_id = NULL;
+
+ return bt_suite_result;
+}
+
+int
+bt_exit_value(void)
+{
+ if (!list_tests || (list_tests && !bt_result))
+ bt_log_overall_result(bt_result, "");
+ return bt_result ? EXIT_SUCCESS : EXIT_FAILURE;
+}
+
+/**
+ * bt_assert_batch__ - test a batch of inputs/outputs tests
+ * @opts: includes all necessary data
+ *
+ * Should be called using macro bt_assert_batch().
+ * Returns 1 or 0.
+ */
+int
+bt_assert_batch__(struct bt_batch *opts)
+{
+ int i;
+ for (i = 0; i < opts->ndata; i++)
+ {
+ int bt_suit_case_result = opts->test_fn(opts->out_buf, opts->data[i].in, opts->data[i].out);
+
+ if (bt_suit_case_result == 0)
+ bt_suite_result = 0;
+
+ char b[BT_BUFFER_SIZE];
+ snprintf(b, sizeof(b), "%s(", opts->test_fn_name);
+
+ opts->in_fmt(b+strlen(b), sizeof(b)-strlen(b), opts->data[i].in);
+ sprintf_concat(b, ") gives ");
+ opts->out_fmt(b+strlen(b), sizeof(b)-strlen(b), opts->out_buf);
+
+ if (bt_suit_case_result == 0)
+ {
+ sprintf_concat(b, ", but expecting is ");
+ opts->out_fmt(b+strlen(b), sizeof(b)-strlen(b), opts->data[i].out);
+ }
+
+ bt_log_suite_case_result(bt_suit_case_result, "%s", b);
+ }
+
+ return bt_suite_result;
+}
+
+/**
+ * bt_fmt_str - formating string into output buffer
+ * @buf: buffer for write
+ * @size: empty size in @buf
+ * @data: null-byte terminated string
+ *
+ * This function can be used with bt_assert_batch() function.
+ * Input @data should be const char * string.
+ */
+void
+bt_fmt_str(char *buf, size_t size, const void *data)
+{
+ const byte *s = data;
+
+ snprintf(buf, size, "\"");
+ while (*s)
+ {
+ snprintf(buf+strlen(buf), size-strlen(buf), bt_is_char(*s) ? "%c" : "\\%03u", *s);
+ s++;
+ }
+ snprintf(buf+strlen(buf), size-strlen(buf), "\"");
+}
+
+/**
+ * bt_fmt_unsigned - formating unsigned int into output buffer
+ * @buf: buffer for write
+ * @size: empty size in @buf
+ * @data: unsigned number
+ *
+ * This function can be used with bt_assert_batch() function.
+ */
+void
+bt_fmt_unsigned(char *buf, size_t size, const void *data)
+{
+ const uint *n = data;
+ snprintf(buf, size, "0x%x (%u)", *n, *n);
+}
+
+/**
+ * bt_fmt_ipa - formating ip_addr into output buffer
+ * @buf: buffer for write
+ * @size: empty size in @buf
+ * @data: should be struct ip_addr *
+ *
+ * This function can be used with bt_assert_batch() function.
+ */
+void
+bt_fmt_ipa(char *buf, size_t size, const void *data)
+{
+ const ip_addr *ip = data;
+ bsnprintf(buf, size, "%I", *ip);
+}
+
+int
+bt_is_char(byte c)
+{
+ return (c >= (byte) 32 && c <= (byte) 126);
+}
+
+/*
+ * Mock-ups of all necessary public functions in main.c
+ */
+
+char *bird_name;
+void async_config(void) {}
+void async_dump(void) {}
+void async_shutdown(void) {}
+void cmd_check_config(char *name UNUSED) {}
+void cmd_reconfig(char *name UNUSED, int type UNUSED, int timeout UNUSED) {}
+void cmd_reconfig_confirm(void) {}
+void cmd_reconfig_undo(void) {}
+void cmd_shutdown(void) {}
+void cmd_reconfig_undo_notify(void) {}
+
+#include "nest/bird.h"
+#include "lib/net.h"
+#include "conf/conf.h"
+void sysdep_preconfig(struct config *c UNUSED) {}
+int sysdep_commit(struct config *new UNUSED, struct config *old UNUSED) { return 0; }
+void sysdep_shutdown_done(void) {}
+
+#include "nest/cli.h"
+int cli_get_command(cli *c UNUSED) { return 0; }
+void cli_write_trigger(cli *c UNUSED) {}
+cli *cmd_reconfig_stored_cli;
diff --git a/test/birdtest.h b/test/birdtest.h
new file mode 100644
index 00000000..4443bfc1
--- /dev/null
+++ b/test/birdtest.h
@@ -0,0 +1,179 @@
+/*
+ * BIRD -- Unit Test Framework (BIRD Test)
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#ifndef _BIRDTEST_H_
+#define _BIRDTEST_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+#include <errno.h>
+#include <sys/types.h>
+
+#include "nest/bird.h"
+
+
+extern int bt_result;
+extern int bt_suite_result;
+extern char bt_out_fmt_buf[1024];
+
+extern uint bt_verbose;
+#define BT_VERBOSE_NO 0
+#define BT_VERBOSE_SUITE 1
+#define BT_VERBOSE_SUITE_CASE 2
+#define BT_VERBOSE_ABSOLUTELY_ALL 3
+
+extern const char *bt_filename;
+extern const char *bt_test_id;
+
+void bt_init(int argc, char *argv[]);
+int bt_exit_value(void);
+int bt_test_suite_base(int (*test_fn)(const void *), const char *test_id, const void *test_fn_argument, int forked, int timeout, const char *dsc, ...);
+long int bt_random(void);
+
+void bt_log_suite_result(int result, const char *fmt, ...);
+void bt_log_suite_case_result(int result, const char *fmt, ...);
+
+#define BT_TIMEOUT 5 /* Default timeout in seconds */
+#define BT_FORKING 1 /* Forking is enabled in default */
+
+#define BT_RANDOM_SEED 982451653
+
+#define BT_BUFFER_SIZE 10000
+
+#define BT_PROMPT_GREEN "\e[1;32m"
+#define BT_PROMPT_RED "\e[1;31m"
+#define BT_PROMPT_NORMAL "\e[0m"
+#define BT_PROMPT_OK " [" BT_PROMPT_GREEN " OK " BT_PROMPT_NORMAL "] "
+#define BT_PROMPT_OK_NO_COLOR " [" " OK " "] "
+#define BT_PROMPT_FAIL " [" BT_PROMPT_RED "FAIL" BT_PROMPT_NORMAL "] "
+#define BT_PROMPT_FAIL_NO_COLOR " [" "FAIL" "] "
+#define BT_PROMPT_OK_FAIL_STRLEN 8 /* strlen ' [FAIL] ' */
+
+#define bt_test_suite(fn, dsc, ...) \
+ bt_test_suite_extra(fn, BT_FORKING, BT_TIMEOUT, dsc, ##__VA_ARGS__)
+
+#define bt_test_suite_extra(fn, f, t, dsc, ...) \
+ bt_test_suite_base((int (*)(const void *))fn, #fn, NULL, f, t, dsc, ##__VA_ARGS__)
+
+#define bt_test_suite_arg(fn, arg, dsc, ...) \
+ bt_test_suite_arg_extra(fn, arg, BT_FORKING, BT_TIMEOUT, dsc, ##__VA_ARGS__)
+
+#define bt_test_suite_arg_extra(fn, arg, f, t, dsc, ...) \
+ bt_test_suite_base(fn, #fn, arg, f, t, dsc, ##__VA_ARGS__)
+
+#define bt_abort() \
+ bt_abort_msg("Aborted at %s:%d", __FILE__, __LINE__)
+
+#define bt_abort_msg(format, ...) \
+ do \
+ { \
+ bt_log(format, ##__VA_ARGS__); \
+ abort(); \
+ } while (0)
+
+#define bt_log(format, ...) \
+ do \
+ { \
+ if (bt_test_id) \
+ printf("%s: %s: " format "\n", bt_filename, bt_test_id, ##__VA_ARGS__); \
+ else \
+ printf("%s: " format "\n", bt_filename, ##__VA_ARGS__); \
+ } while(0)
+
+#define bt_debug(format, ...) \
+ do \
+ { \
+ if (bt_verbose >= BT_VERBOSE_ABSOLUTELY_ALL) \
+ printf(format, ##__VA_ARGS__); \
+ } while (0)
+
+#define bt_assert(test) \
+ bt_assert_msg(test, "Assertion (%s) at %s:%d", #test, __FILE__, __LINE__)
+
+#define bt_assert_msg(test, format, ...) \
+ do \
+ { \
+ int bt_suit_case_result = 1; \
+ if ((test) == 0) \
+ { \
+ bt_result = 0; \
+ bt_suite_result = 0; \
+ bt_suit_case_result = 0; \
+ } \
+ bt_log_suite_case_result(bt_suit_case_result, format, ##__VA_ARGS__); \
+ } while (0)
+
+#define bt_syscall(test, format, ...) \
+ do \
+ { \
+ if (test) \
+ { \
+ bt_log(format ": %s", ##__VA_ARGS__, strerror(errno)); \
+ exit(3); \
+ } \
+ } while (0)
+
+#define bt_sprintf_concat(s, format, ...) \
+ snprintf(s + strlen(s), sizeof(s) - strlen(s), format, ##__VA_ARGS__)
+
+struct bt_pair {
+ const void *in;
+ const void *out;
+};
+
+/* Data structure used by bt_assert_batch() function */
+struct bt_batch {
+ /* in_fmt / out_fmt - formating data
+ * @buf: buffer for write stringified @data
+ * @size: empty size in @buf
+ * @data: data for stringify
+ *
+ * There are some build-in functions, see bt_fmt_* functions */
+ void (*in_fmt)(char *buf, size_t size, const void *data);
+ void (*out_fmt)(char *buf, size_t size, const void *data);
+
+ /* Temporary output buffer */
+ void *out_buf;
+
+ /* test_fn - testing function
+ * @out: output data from tested function
+ * @in: data for input
+ * @expected_out: expected data from tested function
+ *
+ * Input arguments should not be stringified using in_fmt() or out_fmt()
+ * function already. This function should return only 0 or 1 */
+ int (*test_fn)(void *out, const void *in, const void *expected_out);
+
+ /* Name of testing function @test_fn */
+ const char *test_fn_name;
+
+ /* Number of items in data */
+ int ndata;
+
+ /* Array of input and expected output pairs */
+ struct bt_pair *data;
+};
+
+void bt_fmt_str(char *buf, size_t size, const void *data);
+void bt_fmt_unsigned(char *buf, size_t size, const void *data);
+void bt_fmt_ipa(char *buf, size_t size, const void *data);
+int bt_assert_batch__(struct bt_batch *opts);
+int bt_is_char(byte c);
+
+#define bt_assert_batch(data__, fn__, in_fmt__, out_fmt__) \
+ bt_assert_batch__(& (struct bt_batch) { \
+ .data = data__, \
+ .ndata = ARRAY_SIZE(data__), \
+ .test_fn = fn__, \
+ .test_fn_name = #fn__, \
+ .in_fmt = in_fmt__, \
+ .out_fmt = out_fmt__, \
+ .out_buf = bt_out_fmt_buf, /* Global memory for this usage */ \
+ })
+
+#endif /* _BIRDTEST_H_ */
diff --git a/test/bt-utils.c b/test/bt-utils.c
new file mode 100644
index 00000000..aaeb77b8
--- /dev/null
+++ b/test/bt-utils.c
@@ -0,0 +1,223 @@
+/*
+ * BIRD Test -- Utils for testing parsing configuration file
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#include <stdlib.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include "test/birdtest.h"
+#include "test/bt-utils.h"
+
+#include "nest/bird.h"
+#include "nest/route.h"
+#include "nest/protocol.h"
+
+#include "sysdep/unix/unix.h"
+#include "sysdep/unix/krt.h"
+
+#include "nest/iface.h"
+#include "nest/locks.h"
+
+#include "filter/filter.h"
+
+#define BETWEEN(a, b, c) (((a) >= (b)) && ((a) <= (c)))
+
+static const byte *bt_config_parse_pos;
+static uint bt_config_parse_remain_len;
+
+/* This is cf_read_hook for hard-coded text configuration */
+static int
+cf_static_read(byte *dest, uint max_len, int fd UNUSED)
+{
+ if (max_len > bt_config_parse_remain_len)
+ max_len = bt_config_parse_remain_len;
+ memcpy(dest, bt_config_parse_pos, max_len);
+ bt_config_parse_pos += max_len;
+ bt_config_parse_remain_len -= max_len;
+ return max_len;
+}
+
+/* This is cf_read_hook for reading configuration files,
+ * function is copied from main.c, cf_read() */
+static int
+cf_file_read(byte *dest, uint max_len, int fd)
+{
+ int l = read(fd, dest, max_len);
+ if (l < 0)
+ cf_error("Read error");
+ return l;
+}
+
+void
+bt_bird_init(void)
+{
+ if(bt_verbose)
+ log_init_debug("");
+ log_switch(bt_verbose != 0, NULL, NULL);
+
+ resource_init();
+ olock_init();
+ io_init();
+ rt_init();
+ if_init();
+ config_init();
+
+ protos_build();
+ proto_build(&proto_unix_kernel);
+ proto_build(&proto_unix_iface);
+}
+
+void bt_bird_cleanup(void)
+{
+ for (int i = 0; i < EAP_MAX; i++)
+ attr_class_to_protocol[i] = NULL;
+
+ config = new_config = NULL;
+}
+
+static char *
+bt_load_file(const char *filename, int quiet)
+{
+ FILE *f = fopen(filename, "rb");
+ if (!quiet)
+ bt_assert_msg(f != NULL, "Open %s", filename);
+
+ if (f == NULL)
+ return NULL;
+
+ fseek(f, 0, SEEK_END);
+ long file_size_ = ftell(f);
+ fseek(f, 0, SEEK_SET);
+
+ if (file_size_ < 0)
+ return NULL;
+
+ size_t file_size = file_size_;
+ size_t read_size = 0;
+
+ char *file_body = mb_allocz(&root_pool, file_size+1);
+
+ /* XXX: copied from cf-lex.c */
+ errno=0;
+ while ((read_size += fread(file_body+read_size, 1, file_size-read_size, f)) != file_size && ferror(f))
+ {
+ bt_debug("iteration \n");
+ if(errno != EINTR)
+ {
+ bt_abort_msg("errno: %d", errno);
+ break;
+ }
+ errno=0;
+ clearerr(f);
+ }
+ fclose(f);
+
+ if (!quiet)
+ bt_assert_msg(read_size == file_size, "Read %s", filename);
+
+ return file_body;
+}
+
+static void
+bt_show_cfg_error(const struct config *cfg)
+{
+ int lino = 0;
+ int lino_delta = 5;
+ int lino_err = cfg->err_lino;
+
+ const char *str = bt_load_file(cfg->err_file_name, 1);
+
+ while (str && *str)
+ {
+ lino++;
+ if (BETWEEN(lino, lino_err - lino_delta, lino_err + lino_delta))
+ bt_debug("%4u%s", lino, (lino_err == lino ? " >> " : " "));
+ do
+ {
+ if (BETWEEN(lino, lino_err - lino_delta, lino_err + lino_delta))
+ bt_debug("%c", *str);
+ } while (*str && *(str++) != '\n');
+ }
+ bt_debug("\n");
+}
+
+static struct config *
+bt_config_parse__(struct config *cfg)
+{
+ bt_assert_msg(config_parse(cfg) == 1, "Parse %s", cfg->file_name);
+
+ if (cfg->err_msg)
+ {
+ bt_debug("Parse error %s, line %d: %s\n", cfg->err_file_name, cfg->err_lino, cfg->err_msg);
+ bt_show_cfg_error(cfg);
+ return NULL;
+ }
+
+ config_commit(cfg, RECONFIG_HARD, 0);
+ new_config = cfg;
+
+ return cfg;
+}
+
+struct config *
+bt_config_parse(const char *cfg_str)
+{
+ struct config *cfg = config_alloc("configuration");
+
+ bt_config_parse_pos = cfg_str;
+ bt_config_parse_remain_len = strlen(cfg_str);
+ cf_read_hook = cf_static_read;
+
+ return bt_config_parse__(cfg);
+}
+
+struct config *
+bt_config_file_parse(const char *filepath)
+{
+ struct config *cfg = config_alloc(filepath);
+
+ cfg->file_fd = open(filepath, O_RDONLY);
+ bt_assert_msg(cfg->file_fd > 0, "Open %s", filepath);
+ if (cfg->file_fd < 0)
+ return NULL;
+
+ cf_read_hook = cf_file_read;
+
+ return bt_config_parse__(cfg);
+}
+
+/*
+ * Returns @base raised to the power of @power.
+ */
+uint
+bt_naive_pow(uint base, uint power)
+{
+ uint result = 1;
+ uint i;
+ for (i = 0; i < power; i++)
+ result *= base;
+ return result;
+}
+
+/**
+ * bytes_to_hex - transform data into hexadecimal representation
+ * @buf: preallocated string buffer
+ * @in_data: data for transformation
+ * @size: the length of @in_data
+ *
+ * This function transforms @in_data of length @size into hexadecimal
+ * representation and writes it into @buf.
+ */
+void
+bt_bytes_to_hex(char *buf, const byte *in_data, size_t size)
+{
+ size_t i;
+ for(i = 0; i < size; i++)
+ sprintf(buf + i*2, "%02x", in_data[i]);
+}
+
diff --git a/test/bt-utils.h b/test/bt-utils.h
new file mode 100644
index 00000000..13d267cc
--- /dev/null
+++ b/test/bt-utils.h
@@ -0,0 +1,35 @@
+/*
+ * BIRD Test -- Utils for testing parsing configuration file
+ *
+ * (c) 2015 CZ.NIC z.s.p.o.
+ *
+ * Can be freely distributed and used under the terms of the GNU GPL.
+ */
+
+#ifndef _BIRDTEST_UTILS_H_
+#define _BIRDTEST_UTILS_H_
+
+#include "sysdep/config.h"
+
+#define PRIip4 "%d.%d.%d.%d"
+#define ARGip4(x) (_I(x) >> 24) & 0xff, (_I(x) >> 16) & 0xff, (_I(x) >> 8) & 0xff, _I(x) & 0xff
+
+#define PRIip6 "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X"
+#define ARGip6_HIGH(x,i) (((x).addr[(i)] >> 16) & 0xffff)
+#define ARGip6_LOW(x,i) ((x).addr[(i)] & 0xffff)
+#define ARGip6_BOTH(x,i) ARGip6_HIGH(x,i), ARGip6_LOW(x,i)
+#define ARGip6(x) ARGip6_BOTH((x), 0), ARGip6_BOTH((x), 1), ARGip6_BOTH((x), 2), ARGip6_BOTH((x), 3)
+
+#define BT_CONFIG_PARSE_ROUTER_ID "router id 1.1.1.1; \n"
+#define BT_CONFIG_PARSE_STATIC_PROTO "protocol static { ipv4; } \n"
+#define BT_CONFIG_SIMPLE BT_CONFIG_PARSE_ROUTER_ID BT_CONFIG_PARSE_STATIC_PROTO
+
+uint bt_naive_pow(uint base, uint power);
+void bt_bytes_to_hex(char *buf, const byte *in_data, size_t size);
+
+void bt_bird_init(void);
+void bt_bird_cleanup(void);
+struct config *bt_config_parse(const char *cfg);
+struct config *bt_config_file_parse(const char *filepath);
+
+#endif /* _BIRDTEST_UTILS_H_ */