rde.c revision 1.85
1/*	$OpenBSD: rde.c,v 1.85 2020/03/29 11:59:11 denis Exp $ */
2
3/*
4 * Copyright (c) 2004, 2005 Claudio Jeker <claudio@openbsd.org>
5 * Copyright (c) 2004 Esben Norby <norby@openbsd.org>
6 * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 */
20
21#include <sys/types.h>
22#include <sys/socket.h>
23#include <sys/queue.h>
24#include <net/if_types.h>
25#include <netinet/in.h>
26#include <arpa/inet.h>
27#include <err.h>
28#include <errno.h>
29#include <stdlib.h>
30#include <signal.h>
31#include <string.h>
32#include <pwd.h>
33#include <unistd.h>
34#include <event.h>
35
36#include "ospf6.h"
37#include "ospf6d.h"
38#include "ospfe.h"
39#include "log.h"
40#include "rde.h"
41
42#define MINIMUM(a, b)	(((a) < (b)) ? (a) : (b))
43
44void		 rde_sig_handler(int sig, short, void *);
45__dead void	 rde_shutdown(void);
46void		 rde_dispatch_imsg(int, short, void *);
47void		 rde_dispatch_parent(int, short, void *);
48void		 rde_dump_area(struct area *, int, pid_t);
49
50void		 rde_send_summary(pid_t);
51void		 rde_send_summary_area(struct area *, pid_t);
52void		 rde_nbr_init(u_int32_t);
53void		 rde_nbr_free(void);
54struct rde_nbr	*rde_nbr_new(u_int32_t, struct rde_nbr *);
55void		 rde_nbr_del(struct rde_nbr *);
56
57void		 rde_req_list_add(struct rde_nbr *, struct lsa_hdr *);
58int		 rde_req_list_exists(struct rde_nbr *, struct lsa_hdr *);
59void		 rde_req_list_del(struct rde_nbr *, struct lsa_hdr *);
60void		 rde_req_list_free(struct rde_nbr *);
61
62struct iface	*rde_asext_lookup(struct in6_addr, int);
63void		 rde_asext_get(struct kroute *);
64void		 rde_asext_put(struct kroute *);
65
66int		 comp_asext(struct lsa *, struct lsa *);
67struct lsa	*orig_asext_lsa(struct kroute *, u_int16_t);
68struct lsa	*orig_sum_lsa(struct rt_node *, struct area *, u_int8_t, int);
69struct lsa	*orig_intra_lsa_net(struct area *, struct iface *,
70		 struct vertex *);
71struct lsa	*orig_intra_lsa_rtr(struct area *, struct vertex *);
72void		 append_prefix_lsa(struct lsa **, u_int16_t *,
73		    struct lsa_prefix *);
74
75/* A 32-bit value != any ifindex.
76 * We assume ifindex is bound by [1, USHRT_MAX] inclusive. */
77#define	LS_ID_INTRA_RTR	0x01000000
78
79/* Tree of prefixes with global scope on given a link,
80 * see orig_intra_lsa_*() */
81struct prefix_node {
82	RB_ENTRY(prefix_node)	 entry;
83	struct lsa_prefix	*prefix;
84};
85RB_HEAD(prefix_tree, prefix_node);
86RB_PROTOTYPE(prefix_tree, prefix_node, entry, prefix_compare);
87int		 prefix_compare(struct prefix_node *, struct prefix_node *);
88void		 prefix_tree_add(struct prefix_tree *, struct lsa_link *);
89
90struct ospfd_conf	*rdeconf = NULL, *nconf = NULL;
91struct imsgev		*iev_ospfe;
92struct imsgev		*iev_main;
93struct rde_nbr		*nbrself;
94struct lsa_tree		 asext_tree;
95
96/* ARGSUSED */
97void
98rde_sig_handler(int sig, short event, void *arg)
99{
100	/*
101	 * signal handler rules don't apply, libevent decouples for us
102	 */
103
104	switch (sig) {
105	case SIGINT:
106	case SIGTERM:
107		rde_shutdown();
108		/* NOTREACHED */
109	default:
110		fatalx("unexpected signal");
111	}
112}
113
114/* route decision engine */
115pid_t
116rde(struct ospfd_conf *xconf, int pipe_parent2rde[2], int pipe_ospfe2rde[2],
117    int pipe_parent2ospfe[2])
118{
119	struct event		 ev_sigint, ev_sigterm;
120	struct timeval		 now;
121	struct passwd		*pw;
122	pid_t			 pid;
123
124	switch (pid = fork()) {
125	case -1:
126		fatal("cannot fork");
127		/* NOTREACHED */
128	case 0:
129		break;
130	default:
131		return (pid);
132	}
133
134	rdeconf = xconf;
135
136	if ((pw = getpwnam(OSPF6D_USER)) == NULL)
137		fatal("getpwnam");
138
139	if (chroot(pw->pw_dir) == -1)
140		fatal("chroot");
141	if (chdir("/") == -1)
142		fatal("chdir(\"/\")");
143
144	setproctitle("route decision engine");
145	/*
146	 * XXX needed with fork+exec
147	 * log_init(debug, LOG_DAEMON);
148	 * log_setverbose(verbose);
149	 */
150
151	ospfd_process = PROC_RDE_ENGINE;
152	log_procinit(log_procnames[ospfd_process]);
153
154	if (setgroups(1, &pw->pw_gid) ||
155	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
156	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
157		fatal("can't drop privileges");
158
159	if (pledge("stdio", NULL) == -1)
160		fatal("pledge");
161
162	event_init();
163	rde_nbr_init(NBR_HASHSIZE);
164	lsa_init(&asext_tree);
165
166	/* setup signal handler */
167	signal_set(&ev_sigint, SIGINT, rde_sig_handler, NULL);
168	signal_set(&ev_sigterm, SIGTERM, rde_sig_handler, NULL);
169	signal_add(&ev_sigint, NULL);
170	signal_add(&ev_sigterm, NULL);
171	signal(SIGPIPE, SIG_IGN);
172	signal(SIGHUP, SIG_IGN);
173
174	/* setup pipes */
175	close(pipe_ospfe2rde[0]);
176	close(pipe_parent2rde[0]);
177	close(pipe_parent2ospfe[0]);
178	close(pipe_parent2ospfe[1]);
179
180	if ((iev_ospfe = malloc(sizeof(struct imsgev))) == NULL ||
181	    (iev_main = malloc(sizeof(struct imsgev))) == NULL)
182		fatal(NULL);
183	imsg_init(&iev_ospfe->ibuf, pipe_ospfe2rde[1]);
184	iev_ospfe->handler = rde_dispatch_imsg;
185	imsg_init(&iev_main->ibuf, pipe_parent2rde[1]);
186	iev_main->handler = rde_dispatch_parent;
187
188	/* setup event handler */
189	iev_ospfe->events = EV_READ;
190	event_set(&iev_ospfe->ev, iev_ospfe->ibuf.fd, iev_ospfe->events,
191	    iev_ospfe->handler, iev_ospfe);
192	event_add(&iev_ospfe->ev, NULL);
193
194	iev_main->events = EV_READ;
195	event_set(&iev_main->ev, iev_main->ibuf.fd, iev_main->events,
196	    iev_main->handler, iev_main);
197	event_add(&iev_main->ev, NULL);
198
199	evtimer_set(&rdeconf->ev, spf_timer, rdeconf);
200	cand_list_init();
201	rt_init();
202
203	/* remove unneeded stuff from config */
204	conf_clear_redist_list(&rdeconf->redist_list);
205
206	gettimeofday(&now, NULL);
207	rdeconf->uptime = now.tv_sec;
208
209	event_dispatch();
210
211	rde_shutdown();
212	/* NOTREACHED */
213
214	return (0);
215}
216
217__dead void
218rde_shutdown(void)
219{
220	struct area	*a;
221	struct vertex	*v, *nv;
222
223	/* close pipes */
224	msgbuf_clear(&iev_ospfe->ibuf.w);
225	close(iev_ospfe->ibuf.fd);
226	msgbuf_clear(&iev_main->ibuf.w);
227	close(iev_main->ibuf.fd);
228
229	stop_spf_timer(rdeconf);
230	cand_list_clr();
231	rt_clear();
232
233	while ((a = LIST_FIRST(&rdeconf->area_list)) != NULL) {
234		LIST_REMOVE(a, entry);
235		area_del(a);
236	}
237	for (v = RB_MIN(lsa_tree, &asext_tree); v != NULL; v = nv) {
238		nv = RB_NEXT(lsa_tree, &asext_tree, v);
239		vertex_free(v);
240	}
241	rde_nbr_free();
242
243	free(iev_ospfe);
244	free(iev_main);
245	free(rdeconf);
246
247	log_info("route decision engine exiting");
248	_exit(0);
249}
250
251int
252rde_imsg_compose_ospfe(int type, u_int32_t peerid, pid_t pid, void *data,
253    u_int16_t datalen)
254{
255	return (imsg_compose_event(iev_ospfe, type, peerid, pid, -1,
256	    data, datalen));
257}
258
259/* ARGSUSED */
260void
261rde_dispatch_imsg(int fd, short event, void *bula)
262{
263	struct imsgev		*iev = bula;
264	struct imsgbuf		*ibuf = &iev->ibuf;
265	struct imsg		 imsg;
266	struct in_addr		 aid;
267	struct ls_req_hdr	 req_hdr;
268	struct lsa_hdr		 lsa_hdr, *db_hdr;
269	struct rde_nbr		 rn, *nbr;
270	struct timespec		 tp;
271	struct lsa		*lsa;
272	struct area		*area;
273	struct vertex		*v;
274	char			*buf;
275	ssize_t			 n;
276	time_t			 now;
277	int			 r, state, self, shut = 0, verbose;
278	u_int16_t		 l;
279
280	if (event & EV_READ) {
281		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
282			fatal("imsg_read error");
283		if (n == 0)	/* connection closed */
284			shut = 1;
285	}
286	if (event & EV_WRITE) {
287		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
288			fatal("msgbuf_write");
289		if (n == 0)	/* connection closed */
290			shut = 1;
291	}
292
293	clock_gettime(CLOCK_MONOTONIC, &tp);
294	now = tp.tv_sec;
295
296	for (;;) {
297		if ((n = imsg_get(ibuf, &imsg)) == -1)
298			fatal("rde_dispatch_imsg: imsg_get error");
299		if (n == 0)
300			break;
301
302		switch (imsg.hdr.type) {
303		case IMSG_NEIGHBOR_UP:
304			if (imsg.hdr.len - IMSG_HEADER_SIZE != sizeof(rn))
305				fatalx("invalid size of OE request");
306			memcpy(&rn, imsg.data, sizeof(rn));
307
308			if (rde_nbr_new(imsg.hdr.peerid, &rn) == NULL)
309				fatalx("rde_dispatch_imsg: "
310				    "neighbor already exists");
311			break;
312		case IMSG_NEIGHBOR_DOWN:
313			rde_nbr_del(rde_nbr_find(imsg.hdr.peerid));
314			break;
315		case IMSG_NEIGHBOR_CHANGE:
316			if (imsg.hdr.len - IMSG_HEADER_SIZE != sizeof(state))
317				fatalx("invalid size of OE request");
318			memcpy(&state, imsg.data, sizeof(state));
319
320			nbr = rde_nbr_find(imsg.hdr.peerid);
321			if (nbr == NULL)
322				break;
323
324			if (state != nbr->state &&
325			    (nbr->state & NBR_STA_FULL ||
326			    state & NBR_STA_FULL)) {
327				nbr->state = state;
328				area_track(nbr->area);
329				orig_intra_area_prefix_lsas(nbr->area);
330			}
331
332			nbr->state = state;
333			if (nbr->state & NBR_STA_FULL)
334				rde_req_list_free(nbr);
335			break;
336		case IMSG_AREA_CHANGE:
337			if (imsg.hdr.len - IMSG_HEADER_SIZE != sizeof(state))
338				fatalx("invalid size of OE request");
339
340			LIST_FOREACH(area, &rdeconf->area_list, entry) {
341				if (area->id.s_addr == imsg.hdr.peerid)
342					break;
343			}
344			if (area == NULL)
345				break;
346			memcpy(&state, imsg.data, sizeof(state));
347			area->active = state;
348			break;
349		case IMSG_DB_SNAPSHOT:
350			nbr = rde_nbr_find(imsg.hdr.peerid);
351			if (nbr == NULL)
352				break;
353
354			lsa_snap(nbr);
355
356			imsg_compose_event(iev_ospfe, IMSG_DB_END, imsg.hdr.peerid,
357			    0, -1, NULL, 0);
358			break;
359		case IMSG_DD:
360			nbr = rde_nbr_find(imsg.hdr.peerid);
361			if (nbr == NULL)
362				break;
363
364			buf = imsg.data;
365			for (l = imsg.hdr.len - IMSG_HEADER_SIZE;
366			    l >= sizeof(lsa_hdr); l -= sizeof(lsa_hdr)) {
367				memcpy(&lsa_hdr, buf, sizeof(lsa_hdr));
368				buf += sizeof(lsa_hdr);
369
370				v = lsa_find(nbr->iface, lsa_hdr.type,
371				    lsa_hdr.ls_id, lsa_hdr.adv_rtr);
372				if (v == NULL)
373					db_hdr = NULL;
374				else
375					db_hdr = &v->lsa->hdr;
376
377				if (lsa_newer(&lsa_hdr, db_hdr) > 0) {
378					/*
379					 * only request LSAs that are
380					 * newer or missing
381					 */
382					rde_req_list_add(nbr, &lsa_hdr);
383					imsg_compose_event(iev_ospfe, IMSG_DD,
384					    imsg.hdr.peerid, 0, -1, &lsa_hdr,
385					    sizeof(lsa_hdr));
386				}
387			}
388			if (l != 0)
389				log_warnx("rde_dispatch_imsg: peerid %u, "
390				    "trailing garbage in Database Description "
391				    "packet", imsg.hdr.peerid);
392
393			imsg_compose_event(iev_ospfe, IMSG_DD_END,
394			    imsg.hdr.peerid, 0, -1, NULL, 0);
395			break;
396		case IMSG_LS_REQ:
397			nbr = rde_nbr_find(imsg.hdr.peerid);
398			if (nbr == NULL)
399				break;
400
401			buf = imsg.data;
402			for (l = imsg.hdr.len - IMSG_HEADER_SIZE;
403			    l >= sizeof(req_hdr); l -= sizeof(req_hdr)) {
404				memcpy(&req_hdr, buf, sizeof(req_hdr));
405				buf += sizeof(req_hdr);
406
407				if ((v = lsa_find(nbr->iface,
408				    req_hdr.type, req_hdr.ls_id,
409				    req_hdr.adv_rtr)) == NULL) {
410					imsg_compose_event(iev_ospfe,
411					    IMSG_LS_BADREQ, imsg.hdr.peerid,
412					    0, -1, NULL, 0);
413					continue;
414				}
415				imsg_compose_event(iev_ospfe, IMSG_LS_UPD,
416				    imsg.hdr.peerid, 0, -1, v->lsa,
417				    ntohs(v->lsa->hdr.len));
418			}
419			if (l != 0)
420				log_warnx("rde_dispatch_imsg: peerid %u, "
421				    "trailing garbage in LS Request "
422				    "packet", imsg.hdr.peerid);
423			break;
424		case IMSG_LS_UPD:
425			nbr = rde_nbr_find(imsg.hdr.peerid);
426			if (nbr == NULL)
427				break;
428
429			lsa = malloc(imsg.hdr.len - IMSG_HEADER_SIZE);
430			if (lsa == NULL)
431				fatal(NULL);
432			memcpy(lsa, imsg.data, imsg.hdr.len - IMSG_HEADER_SIZE);
433
434			if (!lsa_check(nbr, lsa,
435			    imsg.hdr.len - IMSG_HEADER_SIZE)) {
436				free(lsa);
437				break;
438			}
439
440			v = lsa_find(nbr->iface, lsa->hdr.type, lsa->hdr.ls_id,
441			    lsa->hdr.adv_rtr);
442			if (v == NULL)
443				db_hdr = NULL;
444			else
445				db_hdr = &v->lsa->hdr;
446
447			if (nbr->self) {
448				lsa_merge(nbr, lsa, v);
449				/* lsa_merge frees the right lsa */
450				break;
451			}
452
453			r = lsa_newer(&lsa->hdr, db_hdr);
454			if (r > 0) {
455				/* new LSA newer than DB */
456				if (v && v->flooded &&
457				    v->changed + MIN_LS_ARRIVAL >= now) {
458					free(lsa);
459					break;
460				}
461
462				rde_req_list_del(nbr, &lsa->hdr);
463
464				if (!(self = lsa_self(nbr, lsa, v)))
465					if (lsa_add(nbr, lsa))
466						/* delayed lsa */
467						break;
468
469				/* flood and perhaps ack LSA */
470				imsg_compose_event(iev_ospfe, IMSG_LS_FLOOD,
471				    imsg.hdr.peerid, 0, -1, lsa,
472				    ntohs(lsa->hdr.len));
473
474				/* reflood self originated LSA */
475				if (self && v)
476					imsg_compose_event(iev_ospfe,
477					    IMSG_LS_FLOOD, v->peerid, 0, -1,
478					    v->lsa, ntohs(v->lsa->hdr.len));
479				/* new LSA was not added so free it */
480				if (self)
481					free(lsa);
482			} else if (r < 0) {
483				/*
484				 * point 6 of "The Flooding Procedure"
485				 * We are violating the RFC here because
486				 * it does not make sense to reset a session
487				 * because an equal LSA is already in the table.
488				 * Only if the LSA sent is older than the one
489				 * in the table we should reset the session.
490				 */
491				if (rde_req_list_exists(nbr, &lsa->hdr)) {
492					imsg_compose_event(iev_ospfe,
493					    IMSG_LS_BADREQ, imsg.hdr.peerid,
494					    0, -1, NULL, 0);
495					free(lsa);
496					break;
497				}
498
499				/* lsa no longer needed */
500				free(lsa);
501
502				/* new LSA older than DB */
503				if (ntohl(db_hdr->seq_num) == MAX_SEQ_NUM &&
504				    ntohs(db_hdr->age) == MAX_AGE)
505					/* seq-num wrap */
506					break;
507
508				if (v->changed + MIN_LS_ARRIVAL >= now)
509					break;
510
511				/* directly send current LSA, no ack */
512				imsg_compose_event(iev_ospfe, IMSG_LS_UPD,
513				    imsg.hdr.peerid, 0, -1, v->lsa,
514				    ntohs(v->lsa->hdr.len));
515			} else {
516				/* LSA equal send direct ack */
517				imsg_compose_event(iev_ospfe, IMSG_LS_ACK,
518				    imsg.hdr.peerid, 0, -1, &lsa->hdr,
519				    sizeof(lsa->hdr));
520				free(lsa);
521			}
522			break;
523		case IMSG_LS_MAXAGE:
524			nbr = rde_nbr_find(imsg.hdr.peerid);
525			if (nbr == NULL)
526				break;
527
528			if (imsg.hdr.len != IMSG_HEADER_SIZE +
529			    sizeof(struct lsa_hdr))
530				fatalx("invalid size of OE request");
531			memcpy(&lsa_hdr, imsg.data, sizeof(lsa_hdr));
532
533			if (rde_nbr_loading(nbr->area))
534				break;
535
536			v = lsa_find(nbr->iface, lsa_hdr.type, lsa_hdr.ls_id,
537			    lsa_hdr.adv_rtr);
538			if (v == NULL)
539				db_hdr = NULL;
540			else
541				db_hdr = &v->lsa->hdr;
542
543			/*
544			 * only delete LSA if the one in the db is not newer
545			 */
546			if (lsa_newer(db_hdr, &lsa_hdr) <= 0)
547				lsa_del(nbr, &lsa_hdr);
548			break;
549		case IMSG_CTL_SHOW_DATABASE:
550		case IMSG_CTL_SHOW_DB_EXT:
551		case IMSG_CTL_SHOW_DB_LINK:
552		case IMSG_CTL_SHOW_DB_NET:
553		case IMSG_CTL_SHOW_DB_RTR:
554		case IMSG_CTL_SHOW_DB_INTRA:
555		case IMSG_CTL_SHOW_DB_SELF:
556		case IMSG_CTL_SHOW_DB_SUM:
557		case IMSG_CTL_SHOW_DB_ASBR:
558			if (imsg.hdr.len != IMSG_HEADER_SIZE &&
559			    imsg.hdr.len != IMSG_HEADER_SIZE + sizeof(aid)) {
560				log_warnx("rde_dispatch_imsg: wrong imsg len");
561				break;
562			}
563			if (imsg.hdr.len == IMSG_HEADER_SIZE) {
564				LIST_FOREACH(area, &rdeconf->area_list, entry) {
565					rde_dump_area(area, imsg.hdr.type,
566					    imsg.hdr.pid);
567				}
568				lsa_dump(&asext_tree, imsg.hdr.type,
569				    imsg.hdr.pid);
570			} else {
571				memcpy(&aid, imsg.data, sizeof(aid));
572				if ((area = area_find(rdeconf, aid)) != NULL) {
573					rde_dump_area(area, imsg.hdr.type,
574					    imsg.hdr.pid);
575					if (!area->stub)
576						lsa_dump(&asext_tree,
577						    imsg.hdr.type,
578						    imsg.hdr.pid);
579				}
580			}
581			imsg_compose_event(iev_ospfe, IMSG_CTL_END, 0,
582			    imsg.hdr.pid, -1, NULL, 0);
583			break;
584		case IMSG_CTL_SHOW_RIB:
585			LIST_FOREACH(area, &rdeconf->area_list, entry) {
586				imsg_compose_event(iev_ospfe, IMSG_CTL_AREA,
587				    0, imsg.hdr.pid, -1, area, sizeof(*area));
588
589				rt_dump(area->id, imsg.hdr.pid, RIB_RTR);
590				rt_dump(area->id, imsg.hdr.pid, RIB_NET);
591			}
592			aid.s_addr = 0;
593			rt_dump(aid, imsg.hdr.pid, RIB_EXT);
594
595			imsg_compose_event(iev_ospfe, IMSG_CTL_END, 0,
596			    imsg.hdr.pid, -1, NULL, 0);
597			break;
598		case IMSG_CTL_SHOW_SUM:
599			rde_send_summary(imsg.hdr.pid);
600			LIST_FOREACH(area, &rdeconf->area_list, entry)
601				rde_send_summary_area(area, imsg.hdr.pid);
602			imsg_compose_event(iev_ospfe, IMSG_CTL_END, 0,
603			    imsg.hdr.pid, -1, NULL, 0);
604			break;
605		case IMSG_IFINFO:
606			if (imsg.hdr.len != IMSG_HEADER_SIZE +
607			    sizeof(int))
608				fatalx("IFINFO imsg with wrong len");
609
610			nbr = rde_nbr_find(imsg.hdr.peerid);
611			if (nbr == NULL)
612				fatalx("IFINFO imsg with bad peerid");
613			memcpy(&nbr->iface->state, imsg.data, sizeof(int));
614
615			/* Resend LSAs if interface state changes. */
616			orig_intra_area_prefix_lsas(nbr->area);
617			break;
618		case IMSG_CTL_LOG_VERBOSE:
619			/* already checked by ospfe */
620			memcpy(&verbose, imsg.data, sizeof(verbose));
621			log_setverbose(verbose);
622			break;
623		default:
624			log_debug("rde_dispatch_imsg: unexpected imsg %d",
625			    imsg.hdr.type);
626			break;
627		}
628		imsg_free(&imsg);
629	}
630	if (!shut)
631		imsg_event_add(iev);
632	else {
633		/* this pipe is dead, so remove the event handler */
634		event_del(&iev->ev);
635		event_loopexit(NULL);
636	}
637}
638
639/* ARGSUSED */
640void
641rde_dispatch_parent(int fd, short event, void *bula)
642{
643	static struct area	*narea;
644	struct area		*area;
645	struct iface		*iface, *ifp, *i;
646	struct ifaddrchange	*ifc;
647	struct iface_addr	*ia, *nia;
648	struct imsg		 imsg;
649	struct kroute		 kr;
650	struct imsgev		*iev = bula;
651	struct imsgbuf		*ibuf = &iev->ibuf;
652	ssize_t			 n;
653	int			 shut = 0, link_ok, prev_link_ok, orig_lsa;
654	unsigned int		 ifindex;
655
656	if (event & EV_READ) {
657		if ((n = imsg_read(ibuf)) == -1 && errno != EAGAIN)
658			fatal("imsg_read error");
659		if (n == 0)	/* connection closed */
660			shut = 1;
661	}
662	if (event & EV_WRITE) {
663		if ((n = msgbuf_write(&ibuf->w)) == -1 && errno != EAGAIN)
664			fatal("msgbuf_write");
665		if (n == 0)	/* connection closed */
666			shut = 1;
667	}
668
669	for (;;) {
670		if ((n = imsg_get(ibuf, &imsg)) == -1)
671			fatal("rde_dispatch_parent: imsg_get error");
672		if (n == 0)
673			break;
674
675		switch (imsg.hdr.type) {
676		case IMSG_NETWORK_ADD:
677			if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof(kr)) {
678				log_warnx("rde_dispatch_parent: "
679				    "wrong imsg len");
680				break;
681			}
682			memcpy(&kr, imsg.data, sizeof(kr));
683			rde_asext_get(&kr);
684			break;
685		case IMSG_NETWORK_DEL:
686			if (imsg.hdr.len != IMSG_HEADER_SIZE + sizeof(kr)) {
687				log_warnx("rde_dispatch_parent: "
688				    "wrong imsg len");
689				break;
690			}
691			memcpy(&kr, imsg.data, sizeof(kr));
692			rde_asext_put(&kr);
693			break;
694		case IMSG_IFINFO:
695			if (imsg.hdr.len != IMSG_HEADER_SIZE +
696			    sizeof(struct iface))
697				fatalx("IFINFO imsg with wrong len");
698
699			ifp = imsg.data;
700
701			LIST_FOREACH(area, &rdeconf->area_list, entry) {
702				orig_lsa = 0;
703				LIST_FOREACH(i, &area->iface_list, entry) {
704					if (strcmp(i->dependon,
705					    ifp->name) == 0) {
706						i->depend_ok =
707						    ifstate_is_up(ifp);
708						if (ifstate_is_up(i))
709							orig_lsa = 1;
710					}
711				}
712				if (orig_lsa)
713					orig_intra_area_prefix_lsas(area);
714			}
715
716			if (!(ifp->cflags & F_IFACE_CONFIGURED))
717				break;
718			iface = if_find(ifp->ifindex);
719			if (iface == NULL)
720				fatalx("interface lost in rde");
721
722			prev_link_ok = (iface->flags & IFF_UP) &&
723			    LINK_STATE_IS_UP(iface->linkstate);
724
725			if_update(iface, ifp->mtu, ifp->flags, ifp->if_type,
726			    ifp->linkstate, ifp->baudrate, ifp->rdomain);
727
728			/* Resend LSAs if interface state changes. */
729			link_ok = (iface->flags & IFF_UP) &&
730			          LINK_STATE_IS_UP(iface->linkstate);
731			if (prev_link_ok == link_ok)
732				break;
733
734			orig_intra_area_prefix_lsas(iface->area);
735
736			break;
737		case IMSG_IFADD:
738			if ((iface = malloc(sizeof(struct iface))) == NULL)
739				fatal(NULL);
740			memcpy(iface, imsg.data, sizeof(struct iface));
741
742			LIST_INIT(&iface->nbr_list);
743			TAILQ_INIT(&iface->ls_ack_list);
744			RB_INIT(&iface->lsa_tree);
745
746			LIST_INSERT_HEAD(&iface->area->iface_list, iface, entry);
747			break;
748		case IMSG_IFDELETE:
749			if (imsg.hdr.len != IMSG_HEADER_SIZE +
750			    sizeof(ifindex))
751				fatalx("IFDELETE imsg with wrong len");
752
753			memcpy(&ifindex, imsg.data, sizeof(ifindex));
754			iface = if_find(ifindex);
755			if (iface == NULL)
756				fatalx("interface lost in rde");
757
758			LIST_REMOVE(iface, entry);
759			if_del(iface);
760			break;
761		case IMSG_IFADDRNEW:
762			if (imsg.hdr.len != IMSG_HEADER_SIZE +
763			    sizeof(struct ifaddrchange))
764				fatalx("IFADDRNEW imsg with wrong len");
765			ifc = imsg.data;
766
767			iface = if_find(ifc->ifindex);
768			if (iface == NULL)
769				fatalx("IFADDRNEW interface lost in rde");
770
771			if ((ia = calloc(1, sizeof(struct iface_addr))) ==
772			    NULL)
773				fatal("rde_dispatch_parent IFADDRNEW");
774			ia->addr = ifc->addr;
775			ia->dstbrd = ifc->dstbrd;
776			ia->prefixlen = ifc->prefixlen;
777
778			TAILQ_INSERT_TAIL(&iface->ifa_list, ia, entry);
779			if (iface->area)
780				orig_intra_area_prefix_lsas(iface->area);
781			break;
782		case IMSG_IFADDRDEL:
783			if (imsg.hdr.len != IMSG_HEADER_SIZE +
784			    sizeof(struct ifaddrchange))
785				fatalx("IFADDRDEL imsg with wrong len");
786			ifc = imsg.data;
787
788			iface = if_find(ifc->ifindex);
789			if (iface == NULL)
790				fatalx("IFADDRDEL interface lost in rde");
791
792			for (ia = TAILQ_FIRST(&iface->ifa_list); ia != NULL;
793			    ia = nia) {
794				nia = TAILQ_NEXT(ia, entry);
795
796				if (IN6_ARE_ADDR_EQUAL(&ia->addr,
797				    &ifc->addr)) {
798					TAILQ_REMOVE(&iface->ifa_list, ia,
799					    entry);
800					free(ia);
801					break;
802				}
803			}
804			if (iface->area)
805				orig_intra_area_prefix_lsas(iface->area);
806			break;
807		case IMSG_RECONF_CONF:
808			if ((nconf = malloc(sizeof(struct ospfd_conf))) ==
809			    NULL)
810				fatal(NULL);
811			memcpy(nconf, imsg.data, sizeof(struct ospfd_conf));
812
813			LIST_INIT(&nconf->area_list);
814			LIST_INIT(&nconf->cand_list);
815			break;
816		case IMSG_RECONF_AREA:
817			if ((narea = area_new()) == NULL)
818				fatal(NULL);
819			memcpy(narea, imsg.data, sizeof(struct area));
820
821			LIST_INIT(&narea->iface_list);
822			LIST_INIT(&narea->nbr_list);
823			RB_INIT(&narea->lsa_tree);
824
825			LIST_INSERT_HEAD(&nconf->area_list, narea, entry);
826			break;
827		case IMSG_RECONF_END:
828			merge_config(rdeconf, nconf);
829			nconf = NULL;
830			break;
831		default:
832			log_debug("rde_dispatch_parent: unexpected imsg %d",
833			    imsg.hdr.type);
834			break;
835		}
836		imsg_free(&imsg);
837	}
838	if (!shut)
839		imsg_event_add(iev);
840	else {
841		/* this pipe is dead, so remove the event handler */
842		event_del(&iev->ev);
843		event_loopexit(NULL);
844	}
845}
846
847void
848rde_dump_area(struct area *area, int imsg_type, pid_t pid)
849{
850	struct iface	*iface;
851
852	/* dump header */
853	imsg_compose_event(iev_ospfe, IMSG_CTL_AREA, 0, pid, -1,
854	    area, sizeof(*area));
855
856	/* dump link local lsa */
857	LIST_FOREACH(iface, &area->iface_list, entry) {
858		imsg_compose_event(iev_ospfe, IMSG_CTL_IFACE,
859		    0, pid, -1, iface, sizeof(*iface));
860		lsa_dump(&iface->lsa_tree, imsg_type, pid);
861	}
862
863	/* dump area lsa */
864	lsa_dump(&area->lsa_tree, imsg_type, pid);
865}
866
867u_int32_t
868rde_router_id(void)
869{
870	return (rdeconf->rtr_id.s_addr);
871}
872
873void
874rde_send_change_kroute(struct rt_node *r)
875{
876	int			 krcount = 0;
877	struct kroute		 kr;
878	struct rt_nexthop	*rn;
879	struct ibuf		*wbuf;
880
881	if ((wbuf = imsg_create(&iev_main->ibuf, IMSG_KROUTE_CHANGE, 0, 0,
882	    sizeof(kr))) == NULL) {
883		return;
884	}
885
886	TAILQ_FOREACH(rn, &r->nexthop, entry) {
887		if (rn->invalid)
888			continue;
889		krcount++;
890
891		bzero(&kr, sizeof(kr));
892		kr.prefix = r->prefix;
893		kr.nexthop = rn->nexthop;
894		if (IN6_IS_ADDR_LINKLOCAL(&rn->nexthop) ||
895		    IN6_IS_ADDR_MC_LINKLOCAL(&rn->nexthop))
896			kr.scope = rn->ifindex;
897		kr.ifindex = rn->ifindex;
898		kr.prefixlen = r->prefixlen;
899		kr.ext_tag = r->ext_tag;
900		imsg_add(wbuf, &kr, sizeof(kr));
901	}
902	if (krcount == 0)
903		fatalx("rde_send_change_kroute: no valid nexthop found");
904
905	imsg_close(&iev_main->ibuf, wbuf);
906	imsg_event_add(iev_main);
907}
908
909void
910rde_send_delete_kroute(struct rt_node *r)
911{
912	struct kroute	 kr;
913
914	bzero(&kr, sizeof(kr));
915	kr.prefix = r->prefix;
916	kr.prefixlen = r->prefixlen;
917
918	imsg_compose_event(iev_main, IMSG_KROUTE_DELETE, 0, 0, -1,
919	    &kr, sizeof(kr));
920}
921
922void
923rde_send_summary(pid_t pid)
924{
925	static struct ctl_sum	 sumctl;
926	struct timeval		 now;
927	struct area		*area;
928	struct vertex		*v;
929
930	bzero(&sumctl, sizeof(struct ctl_sum));
931
932	sumctl.rtr_id.s_addr = rde_router_id();
933	sumctl.spf_delay = rdeconf->spf_delay;
934	sumctl.spf_hold_time = rdeconf->spf_hold_time;
935
936	LIST_FOREACH(area, &rdeconf->area_list, entry)
937		sumctl.num_area++;
938
939	RB_FOREACH(v, lsa_tree, &asext_tree)
940		sumctl.num_ext_lsa++;
941
942	gettimeofday(&now, NULL);
943	if (rdeconf->uptime < now.tv_sec)
944		sumctl.uptime = now.tv_sec - rdeconf->uptime;
945	else
946		sumctl.uptime = 0;
947
948	rde_imsg_compose_ospfe(IMSG_CTL_SHOW_SUM, 0, pid, &sumctl,
949	    sizeof(sumctl));
950}
951
952void
953rde_send_summary_area(struct area *area, pid_t pid)
954{
955	static struct ctl_sum_area	 sumareactl;
956	struct iface			*iface;
957	struct rde_nbr			*nbr;
958	struct lsa_tree			*tree = &area->lsa_tree;
959	struct vertex			*v;
960
961	bzero(&sumareactl, sizeof(struct ctl_sum_area));
962
963	sumareactl.area.s_addr = area->id.s_addr;
964	sumareactl.num_spf_calc = area->num_spf_calc;
965
966	LIST_FOREACH(iface, &area->iface_list, entry)
967		sumareactl.num_iface++;
968
969	LIST_FOREACH(nbr, &area->nbr_list, entry)
970		if (nbr->state == NBR_STA_FULL && !nbr->self)
971			sumareactl.num_adj_nbr++;
972
973	RB_FOREACH(v, lsa_tree, tree)
974		sumareactl.num_lsa++;
975
976	rde_imsg_compose_ospfe(IMSG_CTL_SHOW_SUM_AREA, 0, pid, &sumareactl,
977	    sizeof(sumareactl));
978}
979
980LIST_HEAD(rde_nbr_head, rde_nbr);
981
982struct nbr_table {
983	struct rde_nbr_head	*hashtbl;
984	u_int32_t		 hashmask;
985} rdenbrtable;
986
987#define RDE_NBR_HASH(x)		\
988	&rdenbrtable.hashtbl[(x) & rdenbrtable.hashmask]
989
990void
991rde_nbr_init(u_int32_t hashsize)
992{
993	struct rde_nbr_head	*head;
994	u_int32_t		 hs, i;
995
996	for (hs = 1; hs < hashsize; hs <<= 1)
997		;
998	rdenbrtable.hashtbl = calloc(hs, sizeof(struct rde_nbr_head));
999	if (rdenbrtable.hashtbl == NULL)
1000		fatal("rde_nbr_init");
1001
1002	for (i = 0; i < hs; i++)
1003		LIST_INIT(&rdenbrtable.hashtbl[i]);
1004
1005	rdenbrtable.hashmask = hs - 1;
1006
1007	if ((nbrself = calloc(1, sizeof(*nbrself))) == NULL)
1008		fatal("rde_nbr_init");
1009
1010	nbrself->id.s_addr = rde_router_id();
1011	nbrself->peerid = NBR_IDSELF;
1012	nbrself->state = NBR_STA_DOWN;
1013	nbrself->self = 1;
1014	head = RDE_NBR_HASH(NBR_IDSELF);
1015	LIST_INSERT_HEAD(head, nbrself, hash);
1016}
1017
1018void
1019rde_nbr_free(void)
1020{
1021	free(nbrself);
1022	free(rdenbrtable.hashtbl);
1023}
1024
1025struct rde_nbr *
1026rde_nbr_find(u_int32_t peerid)
1027{
1028	struct rde_nbr_head	*head;
1029	struct rde_nbr		*nbr;
1030
1031	head = RDE_NBR_HASH(peerid);
1032
1033	LIST_FOREACH(nbr, head, hash) {
1034		if (nbr->peerid == peerid)
1035			return (nbr);
1036	}
1037
1038	return (NULL);
1039}
1040
1041struct rde_nbr *
1042rde_nbr_new(u_int32_t peerid, struct rde_nbr *new)
1043{
1044	struct rde_nbr_head	*head;
1045	struct rde_nbr		*nbr;
1046	struct area		*area;
1047	struct iface		*iface;
1048
1049	if (rde_nbr_find(peerid))
1050		return (NULL);
1051	if ((area = area_find(rdeconf, new->area_id)) == NULL)
1052		fatalx("rde_nbr_new: unknown area");
1053
1054	if ((iface = if_find(new->ifindex)) == NULL)
1055		fatalx("rde_nbr_new: unknown interface");
1056
1057	if ((nbr = calloc(1, sizeof(*nbr))) == NULL)
1058		fatal("rde_nbr_new");
1059
1060	memcpy(nbr, new, sizeof(*nbr));
1061	nbr->peerid = peerid;
1062	nbr->area = area;
1063	nbr->iface = iface;
1064
1065	TAILQ_INIT(&nbr->req_list);
1066
1067	head = RDE_NBR_HASH(peerid);
1068	LIST_INSERT_HEAD(head, nbr, hash);
1069	LIST_INSERT_HEAD(&area->nbr_list, nbr, entry);
1070
1071	return (nbr);
1072}
1073
1074void
1075rde_nbr_del(struct rde_nbr *nbr)
1076{
1077	if (nbr == NULL)
1078		return;
1079
1080	rde_req_list_free(nbr);
1081
1082	LIST_REMOVE(nbr, entry);
1083	LIST_REMOVE(nbr, hash);
1084
1085	free(nbr);
1086}
1087
1088int
1089rde_nbr_loading(struct area *area)
1090{
1091	struct rde_nbr		*nbr;
1092	int			 checkall = 0;
1093
1094	if (area == NULL) {
1095		area = LIST_FIRST(&rdeconf->area_list);
1096		checkall = 1;
1097	}
1098
1099	while (area != NULL) {
1100		LIST_FOREACH(nbr, &area->nbr_list, entry) {
1101			if (nbr->self)
1102				continue;
1103			if (nbr->state & NBR_STA_XCHNG ||
1104			    nbr->state & NBR_STA_LOAD)
1105				return (1);
1106		}
1107		if (!checkall)
1108			break;
1109		area = LIST_NEXT(area, entry);
1110	}
1111
1112	return (0);
1113}
1114
1115struct rde_nbr *
1116rde_nbr_self(struct area *area)
1117{
1118	struct rde_nbr		*nbr;
1119
1120	LIST_FOREACH(nbr, &area->nbr_list, entry)
1121		if (nbr->self)
1122			return (nbr);
1123
1124	/* this may not happen */
1125	fatalx("rde_nbr_self: area without self");
1126	return (NULL);
1127}
1128
1129/*
1130 * LSA req list
1131 */
1132void
1133rde_req_list_add(struct rde_nbr *nbr, struct lsa_hdr *lsa)
1134{
1135	struct rde_req_entry	*le;
1136
1137	if ((le = calloc(1, sizeof(*le))) == NULL)
1138		fatal("rde_req_list_add");
1139
1140	TAILQ_INSERT_TAIL(&nbr->req_list, le, entry);
1141	le->type = lsa->type;
1142	le->ls_id = lsa->ls_id;
1143	le->adv_rtr = lsa->adv_rtr;
1144}
1145
1146int
1147rde_req_list_exists(struct rde_nbr *nbr, struct lsa_hdr *lsa_hdr)
1148{
1149	struct rde_req_entry	*le;
1150
1151	TAILQ_FOREACH(le, &nbr->req_list, entry) {
1152		if ((lsa_hdr->type == le->type) &&
1153		    (lsa_hdr->ls_id == le->ls_id) &&
1154		    (lsa_hdr->adv_rtr == le->adv_rtr))
1155			return (1);
1156	}
1157	return (0);
1158}
1159
1160void
1161rde_req_list_del(struct rde_nbr *nbr, struct lsa_hdr *lsa_hdr)
1162{
1163	struct rde_req_entry	*le;
1164
1165	TAILQ_FOREACH(le, &nbr->req_list, entry) {
1166		if ((lsa_hdr->type == le->type) &&
1167		    (lsa_hdr->ls_id == le->ls_id) &&
1168		    (lsa_hdr->adv_rtr == le->adv_rtr)) {
1169			TAILQ_REMOVE(&nbr->req_list, le, entry);
1170			free(le);
1171			return;
1172		}
1173	}
1174}
1175
1176void
1177rde_req_list_free(struct rde_nbr *nbr)
1178{
1179	struct rde_req_entry	*le;
1180
1181	while ((le = TAILQ_FIRST(&nbr->req_list)) != NULL) {
1182		TAILQ_REMOVE(&nbr->req_list, le, entry);
1183		free(le);
1184	}
1185}
1186
1187/*
1188 * as-external LSA handling
1189 */
1190struct iface *
1191rde_asext_lookup(struct in6_addr prefix, int plen)
1192{
1193
1194	struct area		*area;
1195	struct iface		*iface;
1196	struct iface_addr	*ia;
1197	struct in6_addr		 ina, inb;
1198
1199	LIST_FOREACH(area, &rdeconf->area_list, entry) {
1200		LIST_FOREACH(iface, &area->iface_list, entry) {
1201			TAILQ_FOREACH(ia, &iface->ifa_list, entry) {
1202				if (IN6_IS_ADDR_LINKLOCAL(&ia->addr))
1203					continue;
1204
1205				inet6applymask(&ina, &ia->addr, ia->prefixlen);
1206				inet6applymask(&inb, &prefix, ia->prefixlen);
1207				if (IN6_ARE_ADDR_EQUAL(&ina, &inb) &&
1208				    (plen == -1 || plen == ia->prefixlen))
1209					return (iface);
1210			}
1211		}
1212	}
1213	return (NULL);
1214}
1215
1216void
1217rde_asext_get(struct kroute *kr)
1218{
1219	struct vertex	*v;
1220	struct lsa	*lsa;
1221
1222	if (rde_asext_lookup(kr->prefix, kr->prefixlen)) {
1223		/* already announced as (stub) net LSA */
1224		log_debug("rde_asext_get: %s/%d is net LSA",
1225		    log_in6addr(&kr->prefix), kr->prefixlen);
1226		return;
1227	}
1228
1229	/* update of seqnum is done by lsa_merge */
1230	if ((lsa = orig_asext_lsa(kr, DEFAULT_AGE))) {
1231		v = lsa_find(NULL, lsa->hdr.type, lsa->hdr.ls_id,
1232		    lsa->hdr.adv_rtr);
1233		lsa_merge(nbrself, lsa, v);
1234	}
1235}
1236
1237void
1238rde_asext_put(struct kroute *kr)
1239{
1240	struct vertex	*v;
1241	struct lsa	*lsa;
1242	/*
1243	 * just try to remove the LSA. If the prefix is announced as
1244	 * stub net LSA lsa_find() will fail later and nothing will happen.
1245	 */
1246
1247	/* remove by reflooding with MAX_AGE */
1248	if ((lsa = orig_asext_lsa(kr, MAX_AGE))) {
1249		v = lsa_find(NULL, lsa->hdr.type, lsa->hdr.ls_id,
1250		    lsa->hdr.adv_rtr);
1251
1252		/*
1253		 * if v == NULL no LSA is in the table and
1254		 * nothing has to be done.
1255		 */
1256		if (v)
1257			lsa_merge(nbrself, lsa, v);
1258		else
1259			free(lsa);
1260	}
1261}
1262
1263/*
1264 * summary LSA stuff
1265 */
1266void
1267rde_summary_update(struct rt_node *rte, struct area *area)
1268{
1269	struct vertex		*v = NULL;
1270//XXX	struct lsa		*lsa;
1271	u_int16_t		 type = 0;
1272
1273	/* first check if we actually need to announce this route */
1274	if (!(rte->d_type == DT_NET || rte->flags & OSPF_RTR_E))
1275		return;
1276	/* never create summaries for as-ext LSA */
1277	if (rte->p_type == PT_TYPE1_EXT || rte->p_type == PT_TYPE2_EXT)
1278		return;
1279	/* no need for summary LSA in the originating area */
1280	if (rte->area.s_addr == area->id.s_addr)
1281		return;
1282	/* no need to originate inter-area routes to the backbone */
1283	if (rte->p_type == PT_INTER_AREA && area->id.s_addr == INADDR_ANY)
1284		return;
1285	/* TODO nexthop check, nexthop part of area -> no summary */
1286	if (rte->cost >= LS_INFINITY)
1287		return;
1288	/* TODO AS border router specific checks */
1289	/* TODO inter-area network route stuff */
1290	/* TODO intra-area stuff -- condense LSA ??? */
1291
1292	if (rte->d_type == DT_NET) {
1293		type = LSA_TYPE_INTER_A_PREFIX;
1294	} else if (rte->d_type == DT_RTR) {
1295		type = LSA_TYPE_INTER_A_ROUTER;
1296	} else
1297
1298#if 0 /* XXX a lot todo */
1299	/* update lsa but only if it was changed */
1300	v = lsa_find(area, type, rte->prefix.s_addr, rde_router_id());
1301	lsa = orig_sum_lsa(rte, area, type, rte->invalid);
1302	lsa_merge(rde_nbr_self(area), lsa, v);
1303
1304	if (v == NULL)
1305		v = lsa_find(area, type, rte->prefix.s_addr, rde_router_id());
1306#endif
1307
1308	/* suppressed/deleted routes are not found in the second lsa_find */
1309	if (v)
1310		v->cost = rte->cost;
1311}
1312
1313/*
1314 * Functions for self-originated LSAs
1315 */
1316
1317/* Prefix LSAs have variable size. We have to be careful to copy the right
1318 * amount of bytes, and to realloc() the right amount of memory. */
1319void
1320append_prefix_lsa(struct lsa **lsa, u_int16_t *len, struct lsa_prefix *prefix)
1321{
1322	struct lsa_prefix	*copy;
1323	unsigned int		 lsa_prefix_len;
1324	unsigned int		 new_len;
1325	char			*new_lsa;
1326
1327	lsa_prefix_len = sizeof(struct lsa_prefix)
1328	    + LSA_PREFIXSIZE(prefix->prefixlen);
1329
1330	new_len = *len + lsa_prefix_len;
1331
1332	/* Make sure we have enough space for this prefix. */
1333	if ((new_lsa = realloc(*lsa, new_len)) == NULL)
1334		fatalx("append_prefix_lsa");
1335
1336	/* Append prefix to LSA. */
1337	copy = (struct lsa_prefix *)(new_lsa + *len);
1338	memcpy(copy, prefix, lsa_prefix_len);
1339
1340	*lsa = (struct lsa *)new_lsa;
1341	*len = new_len;
1342}
1343
1344int
1345prefix_compare(struct prefix_node *a, struct prefix_node *b)
1346{
1347	struct lsa_prefix	*p;
1348	struct lsa_prefix	*q;
1349	int			 i;
1350	int			 len;
1351
1352	p = a->prefix;
1353	q = b->prefix;
1354
1355	len = MINIMUM(LSA_PREFIXSIZE(p->prefixlen), LSA_PREFIXSIZE(q->prefixlen));
1356
1357	i = memcmp(p + 1, q + 1, len);
1358	if (i)
1359		return (i);
1360	if (p->prefixlen < q->prefixlen)
1361		return (-1);
1362	if (p->prefixlen > q->prefixlen)
1363		return (1);
1364	return (0);
1365}
1366
1367void
1368prefix_tree_add(struct prefix_tree *tree, struct lsa_link *lsa)
1369{
1370	struct prefix_node	*old;
1371	struct prefix_node	*new;
1372	struct in6_addr		 addr;
1373	unsigned int		 len;
1374	unsigned int		 i;
1375	char			*cur_prefix;
1376
1377	cur_prefix = (char *)(lsa + 1);
1378
1379	for (i = 0; i < ntohl(lsa->numprefix); i++) {
1380		if ((new = calloc(1, sizeof(*new))) == NULL)
1381			fatal("prefix_tree_add");
1382		new->prefix = (struct lsa_prefix *)cur_prefix;
1383
1384		len = sizeof(*new->prefix)
1385		    + LSA_PREFIXSIZE(new->prefix->prefixlen);
1386
1387		bzero(&addr, sizeof(addr));
1388		memcpy(&addr, new->prefix + 1,
1389		    LSA_PREFIXSIZE(new->prefix->prefixlen));
1390
1391		new->prefix->metric = 0;
1392
1393		if (!(IN6_IS_ADDR_LINKLOCAL(&addr)) &&
1394		    (new->prefix->options & OSPF_PREFIX_NU) == 0 &&
1395		    (new->prefix->options & OSPF_PREFIX_LA) == 0) {
1396			old = RB_INSERT(prefix_tree, tree, new);
1397			if (old != NULL) {
1398				old->prefix->options |= new->prefix->options;
1399				free(new);
1400			}
1401		} else
1402			free(new);
1403
1404		cur_prefix = cur_prefix + len;
1405	}
1406}
1407
1408RB_GENERATE(prefix_tree, prefix_node, entry, prefix_compare)
1409
1410struct lsa *
1411orig_intra_lsa_net(struct area *area, struct iface *iface, struct vertex *old)
1412{
1413	struct lsa		*lsa;
1414	struct vertex		*v;
1415	struct rde_nbr		*nbr;
1416	struct prefix_node	*node;
1417	struct prefix_tree	 tree;
1418	int			 num_full_nbr;
1419	u_int16_t		 len;
1420	u_int16_t		 numprefix;
1421
1422	log_debug("orig_intra_lsa_net: area %s, interface %s",
1423	    inet_ntoa(area->id), iface->name);
1424
1425	RB_INIT(&tree);
1426
1427	if (iface->state & IF_STA_DR) {
1428		num_full_nbr = 0;
1429		LIST_FOREACH(nbr, &area->nbr_list, entry) {
1430			if (nbr->self ||
1431			    nbr->iface->ifindex != iface->ifindex ||
1432			    (nbr->state & NBR_STA_FULL) == 0)
1433				continue;
1434			num_full_nbr++;
1435			v = lsa_find(iface, htons(LSA_TYPE_LINK),
1436			    htonl(nbr->iface_id), nbr->id.s_addr);
1437			if (v)
1438				prefix_tree_add(&tree, &v->lsa->data.link);
1439		}
1440		if (num_full_nbr == 0) {
1441			/* There are no adjacent neighbors on link.
1442			 * If a copy of this LSA already exists in DB,
1443			 * it needs to be flushed. orig_intra_lsa_rtr()
1444			 * will take care of prefixes configured on
1445			 * this interface. */
1446			if (!old)
1447				return NULL;
1448		} else {
1449			/* Add our own prefixes configured for this link. */
1450			v = lsa_find(iface, htons(LSA_TYPE_LINK),
1451			    htonl(iface->ifindex), rde_router_id());
1452			if (v)
1453				prefix_tree_add(&tree, &v->lsa->data.link);
1454		}
1455	/* Continue only if a copy of this LSA already exists in DB.
1456	 * It needs to be flushed. */
1457	} else if (!old)
1458		return NULL;
1459
1460	len = sizeof(struct lsa_hdr) + sizeof(struct lsa_intra_prefix);
1461	if ((lsa = calloc(1, len)) == NULL)
1462		fatal("orig_intra_lsa_net");
1463
1464	lsa->data.pref_intra.ref_type = htons(LSA_TYPE_NETWORK);
1465	lsa->data.pref_intra.ref_ls_id = htonl(iface->ifindex);
1466	lsa->data.pref_intra.ref_adv_rtr = rde_router_id();
1467
1468	numprefix = 0;
1469	RB_FOREACH(node, prefix_tree, &tree) {
1470		append_prefix_lsa(&lsa, &len, node->prefix);
1471		numprefix++;
1472	}
1473
1474	lsa->data.pref_intra.numprefix = htons(numprefix);
1475
1476	while (!RB_EMPTY(&tree))
1477		free(RB_REMOVE(prefix_tree, &tree, RB_ROOT(&tree)));
1478
1479	/* LSA header */
1480	/* If numprefix is zero, originate with MAX_AGE to flush LSA. */
1481	lsa->hdr.age = numprefix == 0 ? htons(MAX_AGE) : htons(DEFAULT_AGE);
1482	lsa->hdr.type = htons(LSA_TYPE_INTRA_A_PREFIX);
1483	lsa->hdr.ls_id = htonl(iface->ifindex);
1484	lsa->hdr.adv_rtr = rde_router_id();
1485	lsa->hdr.seq_num = htonl(INIT_SEQ_NUM);
1486	lsa->hdr.len = htons(len);
1487	lsa->hdr.ls_chksum = htons(iso_cksum(lsa, len, LS_CKSUM_OFFSET));
1488
1489	return lsa;
1490}
1491
1492struct lsa *
1493orig_intra_lsa_rtr(struct area *area, struct vertex *old)
1494{
1495	char			lsa_prefix_buf[sizeof(struct lsa_prefix)
1496				    + sizeof(struct in6_addr)];
1497	struct lsa		*lsa;
1498	struct lsa_prefix	*lsa_prefix;
1499	struct in6_addr		*prefix;
1500	struct iface		*iface;
1501	struct iface_addr	*ia;
1502	struct rde_nbr		*nbr;
1503	u_int16_t		 len;
1504	u_int16_t		 numprefix;
1505
1506	len = sizeof(struct lsa_hdr) + sizeof(struct lsa_intra_prefix);
1507	if ((lsa = calloc(1, len)) == NULL)
1508		fatal("orig_intra_lsa_rtr");
1509
1510	lsa->data.pref_intra.ref_type = htons(LSA_TYPE_ROUTER);
1511	lsa->data.pref_intra.ref_ls_id = 0;
1512	lsa->data.pref_intra.ref_adv_rtr = rde_router_id();
1513
1514	numprefix = 0;
1515	LIST_FOREACH(iface, &area->iface_list, entry) {
1516		if (!((iface->flags & IFF_UP) &&
1517		    LINK_STATE_IS_UP(iface->linkstate)) &&
1518		    !(iface->if_type == IFT_CARP))
1519			/* interface or link state down
1520			 * and not a carp interface */
1521			continue;
1522
1523		if (iface->if_type == IFT_CARP &&
1524		    (iface->linkstate == LINK_STATE_UNKNOWN ||
1525		    iface->linkstate == LINK_STATE_INVALID))
1526			/* carp interface in state invalid or unknown */
1527			continue;
1528
1529		if ((iface->state & IF_STA_DOWN) &&
1530		    !(iface->cflags & F_IFACE_PASSIVE))
1531			/* passive interfaces stay in state DOWN */
1532			continue;
1533
1534		/* Broadcast links with adjacencies are handled
1535		 * by orig_intra_lsa_net(), ignore. */
1536		if (iface->type == IF_TYPE_BROADCAST ||
1537		    iface->type == IF_TYPE_NBMA) {
1538			if (iface->state & IF_STA_WAITING)
1539				/* Skip, we're still waiting for
1540				 * adjacencies to form. */
1541				continue;
1542
1543			LIST_FOREACH(nbr, &area->nbr_list, entry)
1544				if (!nbr->self &&
1545				    nbr->iface->ifindex == iface->ifindex &&
1546				    nbr->state & NBR_STA_FULL)
1547					break;
1548			if (nbr)
1549				continue;
1550		}
1551
1552		lsa_prefix = (struct lsa_prefix *)lsa_prefix_buf;
1553
1554		TAILQ_FOREACH(ia, &iface->ifa_list, entry) {
1555			if (IN6_IS_ADDR_LINKLOCAL(&ia->addr))
1556				continue;
1557
1558			bzero(lsa_prefix_buf, sizeof(lsa_prefix_buf));
1559
1560			if (iface->type == IF_TYPE_POINTOMULTIPOINT ||
1561			    iface->state & IF_STA_LOOPBACK) {
1562				lsa_prefix->prefixlen = 128;
1563				lsa_prefix->metric = 0;
1564			} else if ((iface->if_type == IFT_CARP &&
1565				   iface->linkstate == LINK_STATE_DOWN) ||
1566				   !(iface->depend_ok)) {
1567				/* carp interfaces in state backup are
1568				 * announced with high metric for faster
1569				 * failover. */
1570				lsa_prefix->prefixlen = ia->prefixlen;
1571				lsa_prefix->metric = MAX_METRIC;
1572			} else {
1573				lsa_prefix->prefixlen = ia->prefixlen;
1574				lsa_prefix->metric = htons(iface->metric);
1575			}
1576
1577			if (lsa_prefix->prefixlen == 128)
1578				lsa_prefix->options |= OSPF_PREFIX_LA;
1579
1580			log_debug("orig_intra_lsa_rtr: area %s, interface %s: "
1581			    "%s/%d, metric %d", inet_ntoa(area->id),
1582			    iface->name, log_in6addr(&ia->addr),
1583			    lsa_prefix->prefixlen, ntohs(lsa_prefix->metric));
1584
1585			prefix = (struct in6_addr *)(lsa_prefix + 1);
1586			inet6applymask(prefix, &ia->addr,
1587			    lsa_prefix->prefixlen);
1588			append_prefix_lsa(&lsa, &len, lsa_prefix);
1589			numprefix++;
1590		}
1591
1592		/* TOD: Add prefixes of directly attached hosts, too */
1593		/* TOD: Add prefixes for virtual links */
1594	}
1595
1596	/* If no prefixes were included, continue only if a copy of this
1597	 * LSA already exists in DB. It needs to be flushed. */
1598	if (numprefix == 0 && !old) {
1599		free(lsa);
1600		return NULL;
1601	}
1602
1603	lsa->data.pref_intra.numprefix = htons(numprefix);
1604
1605	/* LSA header */
1606	/* If numprefix is zero, originate with MAX_AGE to flush LSA. */
1607	lsa->hdr.age = numprefix == 0 ? htons(MAX_AGE) : htons(DEFAULT_AGE);
1608	lsa->hdr.type = htons(LSA_TYPE_INTRA_A_PREFIX);
1609	lsa->hdr.ls_id = htonl(LS_ID_INTRA_RTR);
1610	lsa->hdr.adv_rtr = rde_router_id();
1611	lsa->hdr.seq_num = htonl(INIT_SEQ_NUM);
1612	lsa->hdr.len = htons(len);
1613	lsa->hdr.ls_chksum = htons(iso_cksum(lsa, len, LS_CKSUM_OFFSET));
1614
1615	return lsa;
1616}
1617
1618void
1619orig_intra_area_prefix_lsas(struct area *area)
1620{
1621	struct lsa	*lsa;
1622	struct vertex	*old;
1623	struct iface	*iface;
1624
1625	LIST_FOREACH(iface, &area->iface_list, entry) {
1626		if (iface->type == IF_TYPE_BROADCAST ||
1627		    iface->type == IF_TYPE_NBMA) {
1628			old = lsa_find(iface, htons(LSA_TYPE_INTRA_A_PREFIX),
1629			    htonl(iface->ifindex), rde_router_id());
1630			lsa = orig_intra_lsa_net(area, iface, old);
1631			if (lsa)
1632				lsa_merge(rde_nbr_self(area), lsa, old);
1633		}
1634	}
1635
1636	old = lsa_find_tree(&area->lsa_tree, htons(LSA_TYPE_INTRA_A_PREFIX),
1637		htonl(LS_ID_INTRA_RTR), rde_router_id());
1638	lsa = orig_intra_lsa_rtr(area, old);
1639	if (lsa)
1640		lsa_merge(rde_nbr_self(area), lsa, old);
1641}
1642
1643int
1644comp_asext(struct lsa *a, struct lsa *b)
1645{
1646	/* compare prefixes, if they are equal or not */
1647	if (a->data.asext.prefix.prefixlen != b->data.asext.prefix.prefixlen)
1648		return (-1);
1649	return (memcmp(
1650	    (char *)a + sizeof(struct lsa_hdr) + sizeof(struct lsa_asext),
1651	    (char *)b + sizeof(struct lsa_hdr) + sizeof(struct lsa_asext),
1652	    LSA_PREFIXSIZE(a->data.asext.prefix.prefixlen)));
1653}
1654
1655struct lsa *
1656orig_asext_lsa(struct kroute *kr, u_int16_t age)
1657{
1658	struct lsa	*lsa;
1659	u_int32_t	 ext_tag;
1660	u_int16_t	 len, ext_off;
1661
1662	len = sizeof(struct lsa_hdr) + sizeof(struct lsa_asext) +
1663	    LSA_PREFIXSIZE(kr->prefixlen);
1664
1665	/*
1666	 * nexthop -- on connected routes we are the nexthop,
1667	 * on all other cases we should announce the true nexthop
1668	 * unless that nexthop is outside of the ospf cloud.
1669	 * XXX for now we don't do this.
1670	 */
1671
1672	ext_off = len;
1673	if (kr->ext_tag) {
1674		len += sizeof(ext_tag);
1675	}
1676	if ((lsa = calloc(1, len)) == NULL)
1677		fatal("orig_asext_lsa");
1678
1679	log_debug("orig_asext_lsa: %s/%d age %d",
1680	    log_in6addr(&kr->prefix), kr->prefixlen, age);
1681
1682	/* LSA header */
1683	lsa->hdr.age = htons(age);
1684	lsa->hdr.type = htons(LSA_TYPE_EXTERNAL);
1685	lsa->hdr.adv_rtr = rdeconf->rtr_id.s_addr;
1686	lsa->hdr.seq_num = htonl(INIT_SEQ_NUM);
1687	lsa->hdr.len = htons(len);
1688
1689	lsa->data.asext.prefix.prefixlen = kr->prefixlen;
1690	memcpy((char *)lsa + sizeof(struct lsa_hdr) + sizeof(struct lsa_asext),
1691	    &kr->prefix, LSA_PREFIXSIZE(kr->prefixlen));
1692
1693	lsa->hdr.ls_id = lsa_find_lsid(&asext_tree, comp_asext, lsa);
1694
1695	if (age == MAX_AGE) {
1696		/* inherit metric and ext_tag from the current LSA,
1697		 * some routers don't like to get withdraws that are
1698		 * different from what they have in their table.
1699		 */
1700		struct vertex *v;
1701		v = lsa_find(NULL, lsa->hdr.type, lsa->hdr.ls_id,
1702		    lsa->hdr.adv_rtr);
1703		if (v != NULL) {
1704			kr->metric = ntohl(v->lsa->data.asext.metric);
1705			if (kr->metric & LSA_ASEXT_T_FLAG) {
1706				memcpy(&ext_tag, (char *)v->lsa + ext_off,
1707				    sizeof(ext_tag));
1708				kr->ext_tag = ntohl(ext_tag);
1709			}
1710			kr->metric &= LSA_METRIC_MASK;
1711		}
1712	}
1713
1714	if (kr->ext_tag) {
1715		lsa->data.asext.metric = htonl(kr->metric | LSA_ASEXT_T_FLAG);
1716		ext_tag = htonl(kr->ext_tag);
1717		memcpy((char *)lsa + ext_off, &ext_tag, sizeof(ext_tag));
1718	} else {
1719		lsa->data.asext.metric = htonl(kr->metric);
1720	}
1721
1722	lsa->hdr.ls_chksum = 0;
1723	lsa->hdr.ls_chksum = htons(iso_cksum(lsa, len, LS_CKSUM_OFFSET));
1724
1725	return (lsa);
1726}
1727
1728struct lsa *
1729orig_sum_lsa(struct rt_node *rte, struct area *area, u_int8_t type, int invalid)
1730{
1731#if 0 /* XXX a lot todo */
1732	struct lsa	*lsa;
1733	u_int16_t	 len;
1734
1735	len = sizeof(struct lsa_hdr) + sizeof(struct lsa_sum);
1736	if ((lsa = calloc(1, len)) == NULL)
1737		fatal("orig_sum_lsa");
1738
1739	/* LSA header */
1740	lsa->hdr.age = htons(invalid ? MAX_AGE : DEFAULT_AGE);
1741	lsa->hdr.type = type;
1742	lsa->hdr.adv_rtr = rdeconf->rtr_id.s_addr;
1743	lsa->hdr.seq_num = htonl(INIT_SEQ_NUM);
1744	lsa->hdr.len = htons(len);
1745
1746	/* prefix and mask */
1747	/*
1748	 * TODO ls_id must be unique, for overlapping routes this may
1749	 * not be true. In this case a hack needs to be done to
1750	 * make the ls_id unique.
1751	 */
1752	lsa->hdr.ls_id = rte->prefix.s_addr;
1753	if (type == LSA_TYPE_SUM_NETWORK)
1754		lsa->data.sum.mask = prefixlen2mask(rte->prefixlen);
1755	else
1756		lsa->data.sum.mask = 0;	/* must be zero per RFC */
1757
1758	lsa->data.sum.metric = htonl(rte->cost & LSA_METRIC_MASK);
1759
1760	lsa->hdr.ls_chksum = 0;
1761	lsa->hdr.ls_chksum =
1762	    htons(iso_cksum(lsa, len, LS_CKSUM_OFFSET));
1763
1764	return (lsa);
1765#endif
1766	return NULL;
1767}
1768