xref: /freebsd/contrib/bsnmp/snmp_mibII/mibII.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 /*
2  * Copyright (c) 2001-2003
3  *	Fraunhofer Institute for Open Communication Systems (FhG Fokus).
4  *	All rights reserved.
5  *
6  * Author: Harti Brandt <harti@freebsd.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * $Begemot: mibII.c 516 2006-10-27 15:54:02Z brandt_h $
30  *
31  * Implementation of the standard interfaces and ip MIB.
32  */
33 #include "mibII.h"
34 #include "mibII_oid.h"
35 #include <net/if.h>
36 #include <net/if_types.h>
37 
38 
39 /*****************************/
40 
41 /* our module */
42 static struct lmodule *module;
43 
44 /* routing socket */
45 static int route;
46 static void *route_fd;
47 
48 /* if-index allocator */
49 static uint32_t next_if_index = 1;
50 
51 /* currently fetching the arp table */
52 static int in_update_arp;
53 
54 /* OR registrations */
55 static u_int ifmib_reg;
56 static u_int ipmib_reg;
57 static u_int tcpmib_reg;
58 static u_int udpmib_reg;
59 static u_int ipForward_reg;
60 
61 /*****************************/
62 
63 /* list of all IP addresses */
64 struct mibifa_list mibifa_list = TAILQ_HEAD_INITIALIZER(mibifa_list);
65 
66 /* list of all interfaces */
67 struct mibif_list mibif_list = TAILQ_HEAD_INITIALIZER(mibif_list);
68 
69 /* list of dynamic interface names */
70 struct mibdynif_list mibdynif_list = SLIST_HEAD_INITIALIZER(mibdynif_list);
71 
72 /* list of all interface index mappings */
73 struct mibindexmap_list mibindexmap_list = STAILQ_HEAD_INITIALIZER(mibindexmap_list);
74 
75 /* list of all stacking entries */
76 struct mibifstack_list mibifstack_list = TAILQ_HEAD_INITIALIZER(mibifstack_list);
77 
78 /* list of all receive addresses */
79 struct mibrcvaddr_list mibrcvaddr_list = TAILQ_HEAD_INITIALIZER(mibrcvaddr_list);
80 
81 /* list of all NetToMedia entries */
82 struct mibarp_list mibarp_list = TAILQ_HEAD_INITIALIZER(mibarp_list);
83 
84 /* number of interfaces */
85 int32_t mib_if_number;
86 
87 /* last change of table */
88 uint64_t mib_iftable_last_change;
89 
90 /* last change of stack table */
91 uint64_t mib_ifstack_last_change;
92 
93 /* if this is set, one of our lists may be bad. refresh them when idle */
94 int mib_iflist_bad;
95 
96 /* network socket */
97 int mib_netsock;
98 
99 /* last time refreshed */
100 uint64_t mibarpticks;
101 
102 /* info on system clocks */
103 struct clockinfo clockinfo;
104 
105 /* list of all New if registrations */
106 static struct newifreg_list newifreg_list = TAILQ_HEAD_INITIALIZER(newifreg_list);
107 
108 /* baud rate of fastest interface */
109 uint64_t mibif_maxspeed;
110 
111 /* user-forced update interval */
112 u_int mibif_force_hc_update_interval;
113 
114 /* current update interval */
115 u_int mibif_hc_update_interval;
116 
117 /* HC update timer handle */
118 static void *hc_update_timer;
119 
120 /* Idle poll timer */
121 static void *mibII_poll_timer;
122 
123 /* interfaces' data poll interval */
124 u_int mibII_poll_ticks;
125 
126 /* Idle poll hook */
127 static void mibII_idle(void *arg __unused);
128 
129 /*****************************/
130 
131 static const struct asn_oid oid_ifMIB = OIDX_ifMIB;
132 static const struct asn_oid oid_ipMIB = OIDX_ipMIB;
133 static const struct asn_oid oid_tcpMIB = OIDX_tcpMIB;
134 static const struct asn_oid oid_udpMIB = OIDX_udpMIB;
135 static const struct asn_oid oid_ipForward = OIDX_ipForward;
136 static const struct asn_oid oid_linkDown = OIDX_linkDown;
137 static const struct asn_oid oid_linkUp = OIDX_linkUp;
138 static const struct asn_oid oid_ifIndex = OIDX_ifIndex;
139 
140 /*****************************/
141 
142 /*
143  * Find an interface
144  */
145 struct mibif *
146 mib_find_if(u_int idx)
147 {
148 	struct mibif *ifp;
149 
150 	TAILQ_FOREACH(ifp, &mibif_list, link)
151 		if (ifp->index == idx)
152 			return (ifp);
153 	return (NULL);
154 }
155 
156 struct mibif *
157 mib_find_if_sys(u_int sysindex)
158 {
159 	struct mibif *ifp;
160 
161 	TAILQ_FOREACH(ifp, &mibif_list, link)
162 		if (ifp->sysindex == sysindex)
163 			return (ifp);
164 	return (NULL);
165 }
166 
167 struct mibif *
168 mib_find_if_name(const char *name)
169 {
170 	struct mibif *ifp;
171 
172 	TAILQ_FOREACH(ifp, &mibif_list, link)
173 		if (strcmp(ifp->name, name) == 0)
174 			return (ifp);
175 	return (NULL);
176 }
177 
178 /*
179  * Check whether an interface is dynamic. The argument may include the
180  * unit number. This assumes, that the name part does NOT contain digits.
181  */
182 int
183 mib_if_is_dyn(const char *name)
184 {
185 	size_t len;
186 	struct mibdynif *d;
187 
188 	for (len = 0; name[len] != '\0' && isalpha(name[len]) ; len++)
189 		;
190 	SLIST_FOREACH(d, &mibdynif_list, link)
191 		if (strlen(d->name) == len && strncmp(d->name, name, len) == 0)
192 			return (1);
193 	return (0);
194 }
195 
196 /* set an interface name to dynamic mode */
197 void
198 mib_if_set_dyn(const char *name)
199 {
200 	struct mibdynif *d;
201 
202 	SLIST_FOREACH(d, &mibdynif_list, link)
203 		if (strcmp(name, d->name) == 0)
204 			return;
205 	if ((d = malloc(sizeof(*d))) == NULL)
206 		err(1, NULL);
207 	strlcpy(d->name, name, sizeof(d->name));
208 	SLIST_INSERT_HEAD(&mibdynif_list, d, link);
209 }
210 
211 /*
212  * register for interface creations
213  */
214 int
215 mib_register_newif(int (*func)(struct mibif *), const struct lmodule *mod)
216 {
217 	struct newifreg *reg;
218 
219 	TAILQ_FOREACH(reg, &newifreg_list, link)
220 		if (reg->mod == mod) {
221 			reg->func = func;
222 			return (0);
223 		}
224 	if ((reg = malloc(sizeof(*reg))) == NULL) {
225 		syslog(LOG_ERR, "newifreg: %m");
226 		return (-1);
227 	}
228 	reg->mod = mod;
229 	reg->func = func;
230 	TAILQ_INSERT_TAIL(&newifreg_list, reg, link);
231 
232 	return (0);
233 }
234 
235 void
236 mib_unregister_newif(const struct lmodule *mod)
237 {
238 	struct newifreg *reg;
239 
240 	TAILQ_FOREACH(reg, &newifreg_list, link)
241 		if (reg->mod == mod) {
242 			TAILQ_REMOVE(&newifreg_list, reg, link);
243 			free(reg);
244 			return;
245 		}
246 
247 }
248 
249 struct mibif *
250 mib_first_if(void)
251 {
252 	return (TAILQ_FIRST(&mibif_list));
253 }
254 struct mibif *
255 mib_next_if(const struct mibif *ifp)
256 {
257 	return (TAILQ_NEXT(ifp, link));
258 }
259 
260 /*
261  * Change the admin status of an interface
262  */
263 int
264 mib_if_admin(struct mibif *ifp, int up)
265 {
266 	struct ifreq ifr;
267 
268 	strlcpy(ifr.ifr_name, ifp->name, sizeof(ifr.ifr_name));
269 	if (ioctl(mib_netsock, SIOCGIFFLAGS, &ifr) == -1) {
270 		syslog(LOG_ERR, "SIOCGIFFLAGS(%s): %m", ifp->name);
271 		return (-1);
272 	}
273 	if (up)
274 		ifr.ifr_flags |= IFF_UP;
275 	else
276 		ifr.ifr_flags &= ~IFF_UP;
277 	if (ioctl(mib_netsock, SIOCSIFFLAGS, &ifr) == -1) {
278 		syslog(LOG_ERR, "SIOCSIFFLAGS(%s): %m", ifp->name);
279 		return (-1);
280 	}
281 
282 	(void)mib_fetch_ifmib(ifp);
283 
284 	return (0);
285 }
286 
287 /*
288  * Generate a link up/down trap
289  */
290 static void
291 link_trap(struct mibif *ifp, int up)
292 {
293 	struct snmp_value ifindex;
294 
295 	ifindex.var = oid_ifIndex;
296 	ifindex.var.subs[ifindex.var.len++] = ifp->index;
297 	ifindex.syntax = SNMP_SYNTAX_INTEGER;
298 	ifindex.v.integer = ifp->index;
299 
300 	snmp_send_trap(up ? &oid_linkUp : &oid_linkDown, &ifindex,
301 	    (struct snmp_value *)NULL);
302 }
303 
304 /**
305  * Fetch the GENERIC IFMIB and update the HC counters
306  */
307 static int
308 fetch_generic_mib(struct mibif *ifp, const struct ifmibdata *old)
309 {
310 	int name[6];
311 	size_t len;
312 	struct mibif_private *p = ifp->private;
313 
314 	name[0] = CTL_NET;
315 	name[1] = PF_LINK;
316 	name[2] = NETLINK_GENERIC;
317 	name[3] = IFMIB_IFDATA;
318 	name[4] = ifp->sysindex;
319 	name[5] = IFDATA_GENERAL;
320 
321 	len = sizeof(ifp->mib);
322 	if (sysctl(name, nitems(name), &ifp->mib, &len, NULL, 0) == -1) {
323 		if (errno != ENOENT)
324 			syslog(LOG_WARNING, "sysctl(ifmib, %s) failed %m",
325 			    ifp->name);
326 		return (-1);
327 	}
328 
329 	/*
330 	 * Assume that one of the two following compounds is optimized away
331 	 */
332 	if (ULONG_MAX >= 0xffffffffffffffffULL) {
333 		p->hc_inoctets = ifp->mib.ifmd_data.ifi_ibytes;
334 		p->hc_outoctets = ifp->mib.ifmd_data.ifi_obytes;
335 		p->hc_omcasts = ifp->mib.ifmd_data.ifi_omcasts;
336 		p->hc_opackets = ifp->mib.ifmd_data.ifi_opackets;
337 		p->hc_imcasts = ifp->mib.ifmd_data.ifi_imcasts;
338 		p->hc_ipackets = ifp->mib.ifmd_data.ifi_ipackets;
339 
340 	} else if (ULONG_MAX >= 0xffffffff) {
341 
342 #define	UPDATE(HC, MIB)							\
343 		if (old->ifmd_data.MIB > ifp->mib.ifmd_data.MIB)	\
344 			p->HC += (0x100000000ULL +			\
345 			    ifp->mib.ifmd_data.MIB) -			\
346 			    old->ifmd_data.MIB;				\
347 		else							\
348 			p->HC += ifp->mib.ifmd_data.MIB -		\
349 			    old->ifmd_data.MIB;
350 
351 		UPDATE(hc_inoctets, ifi_ibytes)
352 		UPDATE(hc_outoctets, ifi_obytes)
353 		UPDATE(hc_omcasts, ifi_omcasts)
354 		UPDATE(hc_opackets, ifi_opackets)
355 		UPDATE(hc_imcasts, ifi_imcasts)
356 		UPDATE(hc_ipackets, ifi_ipackets)
357 
358 #undef	UPDATE
359 	} else
360 		abort();
361 	return (0);
362 }
363 
364 /**
365  * Update the 64-bit interface counters
366  */
367 static void
368 update_hc_counters(void *arg __unused)
369 {
370 	struct mibif *ifp;
371 	struct ifmibdata oldmib;
372 
373 	TAILQ_FOREACH(ifp, &mibif_list, link) {
374 		oldmib = ifp->mib;
375 		(void)fetch_generic_mib(ifp, &oldmib);
376 	}
377 }
378 
379 /**
380  * Recompute the poll timer for the HC counters
381  */
382 void
383 mibif_reset_hc_timer(void)
384 {
385 	u_int ticks;
386 
387 	if ((ticks = mibif_force_hc_update_interval) == 0) {
388 		if (mibif_maxspeed <= IF_Mbps(10)) {
389 			/* at 10Mbps overflow needs 3436 seconds */
390 			ticks = 3000 * 100;	/* 50 minutes */
391 		} else if (mibif_maxspeed <= IF_Mbps(100)) {
392 			/* at 100Mbps overflow needs 343 seconds */
393 			ticks = 300 * 100;	/* 5 minutes */
394 		} else if (mibif_maxspeed < IF_Mbps(622)) {
395 			/* at 622Mbps overflow needs 53 seconds */
396 			ticks = 40 * 100;	/* 40 seconds */
397 		} else if (mibif_maxspeed <= IF_Mbps(1000)) {
398 			/* at 1Gbps overflow needs  34 seconds */
399 			ticks = 20 * 100;	/* 20 seconds */
400 		} else {
401 			/* at 10Gbps overflow needs 3.4 seconds */
402 			ticks = 100;		/* 1 seconds */
403 		}
404 	}
405 
406 	if (ticks == mibif_hc_update_interval)
407 		return;
408 
409 	if (hc_update_timer != NULL) {
410 		timer_stop(hc_update_timer);
411 		hc_update_timer = NULL;
412 	}
413 	update_hc_counters(NULL);
414 	if ((hc_update_timer = timer_start_repeat(ticks, ticks,
415 	    update_hc_counters, NULL, module)) == NULL) {
416 		syslog(LOG_ERR, "timer_start(%u): %m", ticks);
417 		return;
418 	}
419 	mibif_hc_update_interval = ticks;
420 }
421 
422 /**
423  * Restart the idle poll timer.
424  */
425 void
426 mibif_restart_mibII_poll_timer(void)
427 {
428 	if (mibII_poll_timer != NULL)
429 		timer_stop(mibII_poll_timer);
430 
431 	if ((mibII_poll_timer = timer_start_repeat(mibII_poll_ticks * 10,
432 	    mibII_poll_ticks * 10, mibII_idle, NULL, module)) == NULL)
433 		syslog(LOG_ERR, "timer_start(%u): %m", mibII_poll_ticks);
434 }
435 
436 /*
437  * Fetch new MIB data.
438  */
439 int
440 mib_fetch_ifmib(struct mibif *ifp)
441 {
442 	static int kmib[2] = { -1, 0 }; /* for sysctl net.ifdescr_maxlen */
443 
444 	int name[6];
445 	size_t kmiblen = nitems(kmib);
446 	size_t len;
447 	void *newmib;
448 	struct ifmibdata oldmib = ifp->mib;
449 	struct ifreq irr;
450 	u_int alias_maxlen = MIBIF_ALIAS_SIZE_MAX;
451 
452 	if (fetch_generic_mib(ifp, &oldmib) == -1)
453 		return (-1);
454 
455 	/*
456 	 * Quoting RFC2863, 3.1.15: "... LinkUp and linkDown traps are
457 	 * generated just after ifOperStatus leaves, or just before it
458 	 * enters, the down state, respectively;"
459 	 */
460 	if (ifp->trap_enable && ifp->mib.ifmd_data.ifi_link_state !=
461 	    oldmib.ifmd_data.ifi_link_state &&
462 	    (ifp->mib.ifmd_data.ifi_link_state == LINK_STATE_DOWN ||
463 	    oldmib.ifmd_data.ifi_link_state == LINK_STATE_DOWN))
464 		link_trap(ifp, ifp->mib.ifmd_data.ifi_link_state ==
465 		    LINK_STATE_UP ? 1 : 0);
466 
467 	ifp->flags &= ~(MIBIF_HIGHSPEED | MIBIF_VERYHIGHSPEED);
468 	if (ifp->mib.ifmd_data.ifi_baudrate > 20000000) {
469 		ifp->flags |= MIBIF_HIGHSPEED;
470 		if (ifp->mib.ifmd_data.ifi_baudrate > 650000000)
471 			ifp->flags |= MIBIF_VERYHIGHSPEED;
472 	}
473 	if (ifp->mib.ifmd_data.ifi_baudrate > mibif_maxspeed) {
474 		mibif_maxspeed = ifp->mib.ifmd_data.ifi_baudrate;
475 		mibif_reset_hc_timer();
476 	}
477 
478 	/*
479 	 * linkspecific MIB
480 	 */
481 	name[0] = CTL_NET;
482 	name[1] = PF_LINK;
483 	name[2] = NETLINK_GENERIC;
484 	name[3] = IFMIB_IFDATA;
485 	name[4] = ifp->sysindex;
486 	name[5] = IFDATA_LINKSPECIFIC;
487 	if (sysctl(name, nitems(name), NULL, &len, NULL, 0) == -1) {
488 		syslog(LOG_WARNING, "sysctl linkmib estimate (%s): %m",
489 		    ifp->name);
490 		if (ifp->specmib != NULL) {
491 			ifp->specmib = NULL;
492 			ifp->specmiblen = 0;
493 		}
494 		goto out;
495 	}
496 	if (len == 0) {
497 		if (ifp->specmib != NULL) {
498 			ifp->specmib = NULL;
499 			ifp->specmiblen = 0;
500 		}
501 		goto out;
502 	}
503 
504 	if (ifp->specmiblen != len) {
505 		if ((newmib = realloc(ifp->specmib, len)) == NULL) {
506 			ifp->specmib = NULL;
507 			ifp->specmiblen = 0;
508 			goto out;
509 		}
510 		ifp->specmib = newmib;
511 		ifp->specmiblen = len;
512 	}
513 	if (sysctl(name, nitems(name), ifp->specmib, &len, NULL, 0) == -1) {
514 		syslog(LOG_WARNING, "sysctl linkmib (%s): %m", ifp->name);
515 		if (ifp->specmib != NULL) {
516 			ifp->specmib = NULL;
517 			ifp->specmiblen = 0;
518 		}
519 	}
520 
521   out:
522 	/*
523 	 * Find sysctl mib for net.ifdescr_maxlen (one time).
524 	 * kmib[0] == -1 at first call to mib_fetch_ifmib().
525 	 * Then kmib[0] > 0 if we found sysctl mib for net.ifdescr_maxlen.
526 	 * Else, kmib[0] == 0 (unexpected error from a kernel).
527 	 */
528 	if (kmib[0] < 0 &&
529 	    sysctlnametomib("net.ifdescr_maxlen", kmib, &kmiblen) < 0) {
530 		kmib[0] = 0;
531 		syslog(LOG_WARNING, "sysctlnametomib net.ifdescr_maxlen: %m");
532 	}
533 
534 	/*
535 	 * Fetch net.ifdescr_maxlen value every time to catch up with changes.
536 	 */
537 	len = sizeof(alias_maxlen);
538 	if (kmib[0] > 0 && sysctl(kmib, 2, &alias_maxlen, &len, NULL, 0) < 0) {
539 		/* unexpected error from the kernel, use default value */
540 		alias_maxlen = MIBIF_ALIAS_SIZE_MAX;
541 		syslog(LOG_WARNING, "sysctl net.ifdescr_maxlen: %m");
542 	}
543 
544 	/*
545 	 * Kernel limit might be decreased after interfaces got
546 	 * their descriptions assigned. Try to obtain them anyway.
547 	 */
548 	if (alias_maxlen == 0)
549 		alias_maxlen = MIBIF_ALIAS_SIZE_MAX;
550 
551 	/*
552 	 * Allocate maximum memory for a buffer and later reallocate
553 	 * to free extra memory.
554 	 */
555 	if ((ifp->alias = malloc(alias_maxlen)) == NULL) {
556 		syslog(LOG_WARNING, "malloc(%d) failed: %m", (int)alias_maxlen);
557 		goto fin;
558 	}
559 
560 	strlcpy(irr.ifr_name, ifp->name, sizeof(irr.ifr_name));
561 	irr.ifr_buffer.buffer = ifp->alias;
562 	irr.ifr_buffer.length = alias_maxlen;
563 	if (ioctl(mib_netsock, SIOCGIFDESCR, &irr) == -1) {
564 		free(ifp->alias);
565 		ifp->alias = NULL;
566 		if (errno != ENOMSG)
567 			syslog(LOG_WARNING, "SIOCGIFDESCR (%s): %m", ifp->name);
568 	} else if (irr.ifr_buffer.buffer == NULL) {
569 		free(ifp->alias);
570 		ifp->alias = NULL;
571 		syslog(LOG_WARNING, "SIOCGIFDESCR (%s): too long (%zu)",
572 		    ifp->name, irr.ifr_buffer.length);
573 	} else {
574 		ifp->alias_size = strnlen(ifp->alias, alias_maxlen) + 1;
575 
576 		if (ifp->alias_size > MIBIF_ALIAS_SIZE)
577 		    ifp->alias_size = MIBIF_ALIAS_SIZE;
578 
579 		if (ifp->alias_size < alias_maxlen)
580 			ifp->alias = realloc(ifp->alias, ifp->alias_size);
581 	}
582 
583   fin:
584 	ifp->mibtick = get_ticks();
585 	return (0);
586 }
587 
588 /* find first/next address for a given interface */
589 struct mibifa *
590 mib_first_ififa(const struct mibif *ifp)
591 {
592 	struct mibifa *ifa;
593 
594 	TAILQ_FOREACH(ifa, &mibifa_list, link)
595 		if (ifp->index == ifa->ifindex)
596 			return (ifa);
597 	return (NULL);
598 }
599 
600 struct mibifa *
601 mib_next_ififa(struct mibifa *ifa0)
602 {
603 	struct mibifa *ifa;
604 
605 	ifa = ifa0;
606 	while ((ifa = TAILQ_NEXT(ifa, link)) != NULL)
607 		if (ifa->ifindex == ifa0->ifindex)
608 			return (ifa);
609 	return (NULL);
610 }
611 
612 /*
613  * Allocate a new IFA
614  */
615 static struct mibifa *
616 alloc_ifa(u_int ifindex, struct in_addr addr)
617 {
618 	struct mibifa *ifa;
619 	uint32_t ha;
620 
621 	if ((ifa = malloc(sizeof(struct mibifa))) == NULL) {
622 		syslog(LOG_ERR, "ifa: %m");
623 		return (NULL);
624 	}
625 	ifa->inaddr = addr;
626 	ifa->ifindex = ifindex;
627 
628 	ha = ntohl(ifa->inaddr.s_addr);
629 	ifa->index.len = 4;
630 	ifa->index.subs[0] = (ha >> 24) & 0xff;
631 	ifa->index.subs[1] = (ha >> 16) & 0xff;
632 	ifa->index.subs[2] = (ha >>  8) & 0xff;
633 	ifa->index.subs[3] = (ha >>  0) & 0xff;
634 
635 	ifa->flags = 0;
636 	ifa->inbcast.s_addr = 0;
637 	ifa->inmask.s_addr = 0xffffffff;
638 
639 	INSERT_OBJECT_OID(ifa, &mibifa_list);
640 
641 	return (ifa);
642 }
643 
644 /*
645  * Delete an interface address
646  */
647 static void
648 destroy_ifa(struct mibifa *ifa)
649 {
650 	TAILQ_REMOVE(&mibifa_list, ifa, link);
651 	free(ifa);
652 }
653 
654 
655 /*
656  * Helper routine to extract the sockaddr structures from a routing
657  * socket message.
658  */
659 void
660 mib_extract_addrs(int addrs, u_char *info, struct sockaddr **out)
661 {
662 	u_int i;
663 
664 	for (i = 0; i < RTAX_MAX; i++) {
665 		if ((addrs & (1 << i)) != 0) {
666 			*out = (struct sockaddr *)(void *)info;
667 			info += roundup((*out)->sa_len, sizeof(long));
668 		} else
669 			*out = NULL;
670 		out++;
671 	}
672 }
673 
674 /*
675  * save the phys address of an interface. Handle receive address entries here.
676  */
677 static void
678 get_physaddr(struct mibif *ifp, struct sockaddr_dl *sdl, u_char *ptr)
679 {
680 	u_char *np;
681 	struct mibrcvaddr *rcv;
682 
683 	if (sdl->sdl_alen == 0) {
684 		/* no address */
685 		if (ifp->physaddrlen != 0) {
686 			if ((rcv = mib_find_rcvaddr(ifp->index, ifp->physaddr,
687 			    ifp->physaddrlen)) != NULL)
688 				mib_rcvaddr_delete(rcv);
689 			free(ifp->physaddr);
690 			ifp->physaddr = NULL;
691 			ifp->physaddrlen = 0;
692 		}
693 		return;
694 	}
695 
696 	if (ifp->physaddrlen != sdl->sdl_alen) {
697 		/* length changed */
698 		if (ifp->physaddrlen) {
699 			/* delete olf receive address */
700 			if ((rcv = mib_find_rcvaddr(ifp->index, ifp->physaddr,
701 			    ifp->physaddrlen)) != NULL)
702 				mib_rcvaddr_delete(rcv);
703 		}
704 		if ((np = realloc(ifp->physaddr, sdl->sdl_alen)) == NULL) {
705 			free(ifp->physaddr);
706 			ifp->physaddr = NULL;
707 			ifp->physaddrlen = 0;
708 			return;
709 		}
710 		ifp->physaddr = np;
711 		ifp->physaddrlen = sdl->sdl_alen;
712 
713 	} else if (memcmp(ifp->physaddr, ptr, ifp->physaddrlen) == 0) {
714 		/* no change */
715 		return;
716 
717 	} else {
718 		/* address changed */
719 
720 		/* delete olf receive address */
721 		if ((rcv = mib_find_rcvaddr(ifp->index, ifp->physaddr,
722 		    ifp->physaddrlen)) != NULL)
723 			mib_rcvaddr_delete(rcv);
724 	}
725 
726 	memcpy(ifp->physaddr, ptr, ifp->physaddrlen);
727 
728 	/* make new receive address */
729 	if ((rcv = mib_rcvaddr_create(ifp, ifp->physaddr, ifp->physaddrlen)) != NULL)
730 		rcv->flags |= MIBRCVADDR_HW;
731 }
732 
733 /*
734  * Free an interface
735  */
736 static void
737 mibif_free(struct mibif *ifp)
738 {
739 	struct mibif *ifp1;
740 	struct mibindexmap *map;
741 	struct mibifa *ifa, *ifa1;
742 	struct mibrcvaddr *rcv, *rcv1;
743 	struct mibarp *at, *at1;
744 
745 	if (ifp->xnotify != NULL)
746 		(*ifp->xnotify)(ifp, MIBIF_NOTIFY_DESTROY, ifp->xnotify_data);
747 
748 	(void)mib_ifstack_delete(ifp, NULL);
749 	(void)mib_ifstack_delete(NULL, ifp);
750 
751 	TAILQ_REMOVE(&mibif_list, ifp, link);
752 
753 	/* if this was the fastest interface - recompute this */
754 	if (ifp->mib.ifmd_data.ifi_baudrate == mibif_maxspeed) {
755 		mibif_maxspeed = ifp->mib.ifmd_data.ifi_baudrate;
756 		TAILQ_FOREACH(ifp1, &mibif_list, link)
757 			if (ifp1->mib.ifmd_data.ifi_baudrate > mibif_maxspeed)
758 				mibif_maxspeed =
759 				    ifp1->mib.ifmd_data.ifi_baudrate;
760 		mibif_reset_hc_timer();
761 	}
762 
763 	if (ifp->alias != NULL) {
764 		free(ifp->alias);
765 		ifp->alias = NULL;
766 	}
767 	free(ifp->private);
768 	ifp->private = NULL;
769 	free(ifp->physaddr);
770 	ifp->physaddr = NULL;
771 	free(ifp->specmib);
772 	ifp->specmib = NULL;
773 
774 	STAILQ_FOREACH(map, &mibindexmap_list, link)
775 		if (map->mibif == ifp) {
776 			map->mibif = NULL;
777 			break;
778 		}
779 
780 	/* purge interface addresses */
781 	ifa = TAILQ_FIRST(&mibifa_list);
782 	while (ifa != NULL) {
783 		ifa1 = TAILQ_NEXT(ifa, link);
784 		if (ifa->ifindex == ifp->index)
785 			destroy_ifa(ifa);
786 		ifa = ifa1;
787 	}
788 
789 	/* purge receive addresses */
790 	rcv = TAILQ_FIRST(&mibrcvaddr_list);
791 	while (rcv != NULL) {
792 		rcv1 = TAILQ_NEXT(rcv, link);
793 		if (rcv->ifindex == ifp->index)
794 			mib_rcvaddr_delete(rcv);
795 		rcv = rcv1;
796 	}
797 
798 	/* purge ARP entries */
799 	at = TAILQ_FIRST(&mibarp_list);
800 	while (at != NULL) {
801 		at1 = TAILQ_NEXT(at, link);
802 		if (at->index.subs[0] == ifp->index)
803 			mib_arp_delete(at);
804 		at = at1;
805 	}
806 
807 	free(ifp);
808 	ifp = NULL;
809 	mib_if_number--;
810 	mib_iftable_last_change = this_tick;
811 }
812 
813 /*
814  * Create a new interface
815  */
816 static struct mibif *
817 mibif_create(u_int sysindex, const char *name)
818 {
819 	struct mibif *ifp;
820 	struct mibindexmap *map;
821 
822 	if ((ifp = malloc(sizeof(*ifp))) == NULL) {
823 		syslog(LOG_WARNING, "%s: %m", __func__);
824 		return (NULL);
825 	}
826 	memset(ifp, 0, sizeof(*ifp));
827 	if ((ifp->private = malloc(sizeof(struct mibif_private))) == NULL) {
828 		syslog(LOG_WARNING, "%s: %m", __func__);
829 		free(ifp);
830 		return (NULL);
831 	}
832 	memset(ifp->private, 0, sizeof(struct mibif_private));
833 
834 	ifp->sysindex = sysindex;
835 	strlcpy(ifp->name, name, sizeof(ifp->name));
836 	strlcpy(ifp->descr, name, sizeof(ifp->descr));
837 	ifp->spec_oid = oid_zeroDotZero;
838 
839 	map = NULL;
840 	if (!mib_if_is_dyn(ifp->name)) {
841 		/* non-dynamic. look whether we know the interface */
842 		STAILQ_FOREACH(map, &mibindexmap_list, link)
843 			if (strcmp(map->name, ifp->name) == 0) {
844 				ifp->index = map->ifindex;
845 				map->mibif = ifp;
846 				break;
847 			}
848 		/* assume it has a connector if it is not dynamic */
849 		ifp->has_connector = 1;
850 		ifp->trap_enable = 1;
851 	}
852 	if (map == NULL) {
853 		/* new interface - get new index */
854 		if (next_if_index > 0x7fffffff)
855 			errx(1, "ifindex wrap");
856 
857 		if ((map = malloc(sizeof(*map))) == NULL) {
858 			syslog(LOG_ERR, "ifmap: %m");
859 			free(ifp);
860 			return (NULL);
861 		}
862 		map->ifindex = next_if_index++;
863 		map->sysindex = ifp->sysindex;
864 		strcpy(map->name, ifp->name);
865 		map->mibif = ifp;
866 		STAILQ_INSERT_TAIL(&mibindexmap_list, map, link);
867 	} else {
868 		/* re-instantiate. Introduce a counter discontinuity */
869 		ifp->counter_disc = get_ticks();
870 	}
871 	ifp->index = map->ifindex;
872 	ifp->mib.ifmd_data.ifi_link_state = LINK_STATE_UNKNOWN;
873 
874 	INSERT_OBJECT_INT(ifp, &mibif_list);
875 	mib_if_number++;
876 	mib_iftable_last_change = this_tick;
877 
878 	/* instantiate default ifStack entries */
879 	(void)mib_ifstack_create(ifp, NULL);
880 	(void)mib_ifstack_create(NULL, ifp);
881 
882 	return (ifp);
883 }
884 
885 /*
886  * Inform all interested parties about a new interface
887  */
888 static void
889 notify_newif(struct mibif *ifp)
890 {
891 	struct newifreg *reg;
892 
893 	TAILQ_FOREACH(reg, &newifreg_list, link)
894 		if ((*reg->func)(ifp))
895 			return;
896 }
897 
898 /*
899  * This is called for new interfaces after we have fetched the interface
900  * MIB. If this is a broadcast interface try to guess the broadcast address
901  * depending on the interface type.
902  */
903 static void
904 check_llbcast(struct mibif *ifp)
905 {
906 	static u_char ether_bcast[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
907 	struct mibrcvaddr *rcv;
908 
909 	if (!(ifp->mib.ifmd_flags & IFF_BROADCAST))
910 		return;
911 
912 	switch (ifp->mib.ifmd_data.ifi_type) {
913 
914 	  case IFT_ETHER:
915 	  case IFT_FDDI:
916 	  case IFT_ISO88025:
917 	  case IFT_L2VLAN:
918 		if (mib_find_rcvaddr(ifp->index, ether_bcast, 6) == NULL &&
919 		    (rcv = mib_rcvaddr_create(ifp, ether_bcast, 6)) != NULL)
920 			rcv->flags |= MIBRCVADDR_BCAST;
921 		break;
922 	}
923 }
924 
925 
926 /*
927  * Retrieve the current interface list from the system.
928  */
929 void
930 mib_refresh_iflist(void)
931 {
932 	struct mibif *ifp, *ifp1;
933 	size_t len;
934 	u_short idx;
935 	int name[6];
936 	int count;
937 	struct ifmibdata mib;
938 
939 	TAILQ_FOREACH(ifp, &mibif_list, link)
940 		ifp->flags &= ~MIBIF_FOUND;
941 
942 	len = sizeof(count);
943 	if (sysctlbyname("net.link.generic.system.ifcount", &count, &len,
944 	    NULL, 0) == -1) {
945 		syslog(LOG_ERR, "ifcount: %m");
946 		return;
947 	}
948 	name[0] = CTL_NET;
949 	name[1] = PF_LINK;
950 	name[2] = NETLINK_GENERIC;
951 	name[3] = IFMIB_IFDATA;
952 	name[5] = IFDATA_GENERAL;
953 	for (idx = 1; idx <= count; idx++) {
954 		name[4] = idx;
955 		len = sizeof(mib);
956 		if (sysctl(name, nitems(name), &mib, &len, NULL, 0) == -1) {
957 			if (errno == ENOENT)
958 				continue;
959 			syslog(LOG_ERR, "ifmib(%u): %m", idx);
960 			return;
961 		}
962 		if ((ifp = mib_find_if_sys(idx)) != NULL) {
963 			ifp->flags |= MIBIF_FOUND;
964 			continue;
965 		}
966 		/* Unknown interface - create */
967 		if ((ifp = mibif_create(idx, mib.ifmd_name)) != NULL) {
968 			ifp->flags |= MIBIF_FOUND;
969 			(void)mib_fetch_ifmib(ifp);
970 			check_llbcast(ifp);
971 			notify_newif(ifp);
972 		}
973 	}
974 
975 	/*
976 	 * Purge interfaces that disappeared
977 	 */
978 	ifp = TAILQ_FIRST(&mibif_list);
979 	while (ifp != NULL) {
980 		ifp1 = TAILQ_NEXT(ifp, link);
981 		if (!(ifp->flags & MIBIF_FOUND))
982 			mibif_free(ifp);
983 		ifp = ifp1;
984 	}
985 }
986 
987 /*
988  * Find an interface address
989  */
990 struct mibifa *
991 mib_find_ifa(struct in_addr addr)
992 {
993 	struct mibifa *ifa;
994 
995 	TAILQ_FOREACH(ifa, &mibifa_list, link)
996 		if (ifa->inaddr.s_addr == addr.s_addr)
997 			return (ifa);
998 	return (NULL);
999 }
1000 
1001 /*
1002  * Process a new ARP entry
1003  */
1004 static void
1005 process_arp(const struct rt_msghdr *rtm, const struct sockaddr_dl *sdl,
1006     const struct sockaddr_in *sa)
1007 {
1008 	struct mibif *ifp;
1009 	struct mibarp *at;
1010 
1011 	/* IP arp table entry */
1012 	if (sdl->sdl_alen == 0)
1013 		return;
1014 	if ((ifp = mib_find_if_sys(sdl->sdl_index)) == NULL)
1015 		return;
1016 	/* have a valid entry */
1017 	if ((at = mib_find_arp(ifp, sa->sin_addr)) == NULL &&
1018 	    (at = mib_arp_create(ifp, sa->sin_addr,
1019 	    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) == NULL)
1020 		return;
1021 
1022 	if (rtm->rtm_rmx.rmx_expire == 0)
1023 		at->flags |= MIBARP_PERM;
1024 	else
1025 		at->flags &= ~MIBARP_PERM;
1026 	at->flags |= MIBARP_FOUND;
1027 }
1028 
1029 /*
1030  * Handle a routing socket message.
1031  */
1032 static void
1033 handle_rtmsg(struct rt_msghdr *rtm)
1034 {
1035 	struct sockaddr *addrs[RTAX_MAX];
1036 	struct if_msghdr *ifm;
1037 	struct ifa_msghdr ifam, *ifamp;
1038 	struct ifma_msghdr *ifmam;
1039 #ifdef RTM_IFANNOUNCE
1040 	struct if_announcemsghdr *ifan;
1041 #endif
1042 	struct mibif *ifp;
1043 	struct sockaddr_dl *sdl;
1044 	struct sockaddr_in *sa;
1045 	struct mibifa *ifa;
1046 	struct mibrcvaddr *rcv;
1047 	u_char *ptr;
1048 
1049 	if (rtm->rtm_version != RTM_VERSION) {
1050 		syslog(LOG_ERR, "Bogus RTM version %u", rtm->rtm_version);
1051 		return;
1052 	}
1053 
1054 	switch (rtm->rtm_type) {
1055 
1056 	  case RTM_NEWADDR:
1057 		ifamp = (struct ifa_msghdr *)rtm;
1058 		memcpy(&ifam, ifamp, sizeof(ifam));
1059 		mib_extract_addrs(ifam.ifam_addrs, (u_char *)(ifamp + 1), addrs);
1060 		if (addrs[RTAX_IFA] == NULL || addrs[RTAX_NETMASK] == NULL)
1061 			break;
1062 
1063 		sa = (struct sockaddr_in *)(void *)addrs[RTAX_IFA];
1064 		if ((ifa = mib_find_ifa(sa->sin_addr)) == NULL) {
1065 			/* unknown address */
1066 		    	if ((ifp = mib_find_if_sys(ifam.ifam_index)) == NULL) {
1067 				syslog(LOG_WARNING, "RTM_NEWADDR for unknown "
1068 				    "interface %u", ifam.ifam_index);
1069 				break;
1070 			}
1071 		     	if ((ifa = alloc_ifa(ifp->index, sa->sin_addr)) == NULL)
1072 				break;
1073 		}
1074 		sa = (struct sockaddr_in *)(void *)addrs[RTAX_NETMASK];
1075 		ifa->inmask = sa->sin_addr;
1076 
1077 		if (addrs[RTAX_BRD] != NULL) {
1078 			sa = (struct sockaddr_in *)(void *)addrs[RTAX_BRD];
1079 			ifa->inbcast = sa->sin_addr;
1080 		}
1081 		ifa->flags |= MIBIFA_FOUND;
1082 		break;
1083 
1084 	  case RTM_DELADDR:
1085 		ifamp = (struct ifa_msghdr *)rtm;
1086 		memcpy(&ifam, ifamp, sizeof(ifam));
1087 		mib_extract_addrs(ifam.ifam_addrs, (u_char *)(ifamp + 1), addrs);
1088 		if (addrs[RTAX_IFA] == NULL)
1089 			break;
1090 
1091 		sa = (struct sockaddr_in *)(void *)addrs[RTAX_IFA];
1092 		if ((ifa = mib_find_ifa(sa->sin_addr)) != NULL) {
1093 			ifa->flags |= MIBIFA_FOUND;
1094 			if (!(ifa->flags & MIBIFA_DESTROYED))
1095 				destroy_ifa(ifa);
1096 		}
1097 		break;
1098 
1099 	  case RTM_NEWMADDR:
1100 		ifmam = (struct ifma_msghdr *)rtm;
1101 		mib_extract_addrs(ifmam->ifmam_addrs, (u_char *)(ifmam + 1), addrs);
1102 		if (addrs[RTAX_IFA] == NULL ||
1103 		    addrs[RTAX_IFA]->sa_family != AF_LINK)
1104 			break;
1105 		sdl = (struct sockaddr_dl *)(void *)addrs[RTAX_IFA];
1106 		if ((rcv = mib_find_rcvaddr(sdl->sdl_index,
1107 		    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) == NULL) {
1108 			/* unknown address */
1109 		    	if ((ifp = mib_find_if_sys(sdl->sdl_index)) == NULL) {
1110 				syslog(LOG_WARNING, "RTM_NEWMADDR for unknown "
1111 				    "interface %u", sdl->sdl_index);
1112 				break;
1113 			}
1114 		     	if ((rcv = mib_rcvaddr_create(ifp,
1115 			    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) == NULL)
1116 				break;
1117 			rcv->flags |= MIBRCVADDR_VOLATILE;
1118 		}
1119 		rcv->flags |= MIBRCVADDR_FOUND;
1120 		break;
1121 
1122 	  case RTM_DELMADDR:
1123 		ifmam = (struct ifma_msghdr *)rtm;
1124 		mib_extract_addrs(ifmam->ifmam_addrs, (u_char *)(ifmam + 1), addrs);
1125 		if (addrs[RTAX_IFA] == NULL ||
1126 		    addrs[RTAX_IFA]->sa_family != AF_LINK)
1127 			break;
1128 		sdl = (struct sockaddr_dl *)(void *)addrs[RTAX_IFA];
1129 		if ((rcv = mib_find_rcvaddr(sdl->sdl_index,
1130 		    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) != NULL)
1131 			mib_rcvaddr_delete(rcv);
1132 		break;
1133 
1134 	  case RTM_IFINFO:
1135 		ifm = (struct if_msghdr *)(void *)rtm;
1136 		mib_extract_addrs(ifm->ifm_addrs, (u_char *)(ifm + 1), addrs);
1137 		if ((ifp = mib_find_if_sys(ifm->ifm_index)) == NULL)
1138 			break;
1139 		if (addrs[RTAX_IFP] != NULL &&
1140 		    addrs[RTAX_IFP]->sa_family == AF_LINK) {
1141 			sdl = (struct sockaddr_dl *)(void *)addrs[RTAX_IFP];
1142 			ptr = sdl->sdl_data + sdl->sdl_nlen;
1143 			get_physaddr(ifp, sdl, ptr);
1144 		}
1145 		(void)mib_fetch_ifmib(ifp);
1146 		break;
1147 
1148 #ifdef RTM_IFANNOUNCE
1149 	  case RTM_IFANNOUNCE:
1150 		ifan = (struct if_announcemsghdr *)rtm;
1151 		ifp = mib_find_if_sys(ifan->ifan_index);
1152 
1153 		switch (ifan->ifan_what) {
1154 
1155 		  case IFAN_ARRIVAL:
1156 			if (ifp == NULL && (ifp = mibif_create(ifan->ifan_index,
1157 			    ifan->ifan_name)) != NULL) {
1158 				(void)mib_fetch_ifmib(ifp);
1159 				check_llbcast(ifp);
1160 				notify_newif(ifp);
1161 			}
1162 			break;
1163 
1164 		  case IFAN_DEPARTURE:
1165 			if (ifp != NULL)
1166 				mibif_free(ifp);
1167 			break;
1168 		}
1169 		break;
1170 #endif
1171 	  case RTM_GET:
1172 	  case RTM_ADD:
1173 		mib_extract_addrs(rtm->rtm_addrs, (u_char *)(rtm + 1), addrs);
1174 		if (rtm->rtm_flags & RTF_LLINFO) {
1175 			if (addrs[RTAX_DST] == NULL ||
1176 			    addrs[RTAX_GATEWAY] == NULL ||
1177 			    addrs[RTAX_DST]->sa_family != AF_INET ||
1178 			    addrs[RTAX_GATEWAY]->sa_family != AF_LINK)
1179 				break;
1180 			process_arp(rtm,
1181 			    (struct sockaddr_dl *)(void *)addrs[RTAX_GATEWAY],
1182 			    (struct sockaddr_in *)(void *)addrs[RTAX_DST]);
1183 		} else {
1184 			if (rtm->rtm_errno == 0 && (rtm->rtm_flags & RTF_UP))
1185 				mib_sroute_process(rtm, addrs[RTAX_GATEWAY],
1186 				    addrs[RTAX_DST], addrs[RTAX_NETMASK]);
1187 		}
1188 		break;
1189 
1190 	  case RTM_DELETE:
1191 		mib_extract_addrs(rtm->rtm_addrs, (u_char *)(rtm + 1), addrs);
1192 
1193 		if (rtm->rtm_errno == 0 && (rtm->rtm_flags & RTF_UP))
1194 			mib_sroute_process(rtm, addrs[RTAX_GATEWAY],
1195 			    addrs[RTAX_DST], addrs[RTAX_NETMASK]);
1196 		break;
1197 	}
1198 }
1199 
1200 /*
1201  * send a routing message
1202  */
1203 void
1204 mib_send_rtmsg(struct rt_msghdr *rtm, struct sockaddr *gw,
1205     struct sockaddr *dst, struct sockaddr *mask)
1206 {
1207 	size_t len;
1208 	struct rt_msghdr *msg;
1209 	char *cp;
1210 	ssize_t sent;
1211 
1212 	len = sizeof(*rtm) + SA_SIZE(gw) + SA_SIZE(dst) + SA_SIZE(mask);
1213 	if ((msg = malloc(len)) == NULL) {
1214 		syslog(LOG_ERR, "%s: %m", __func__);
1215 		return;
1216 	}
1217 	cp = (char *)(msg + 1);
1218 
1219 	memset(msg, 0, sizeof(*msg));
1220 	msg->rtm_flags = 0;
1221 	msg->rtm_version = RTM_VERSION;
1222 	msg->rtm_addrs = RTA_DST | RTA_GATEWAY;
1223 
1224 	memcpy(cp, dst, SA_SIZE(dst));
1225 	cp += SA_SIZE(dst);
1226 	memcpy(cp, gw, SA_SIZE(gw));
1227 	cp += SA_SIZE(gw);
1228 	if (mask != NULL) {
1229 		memcpy(cp, mask, SA_SIZE(mask));
1230 		cp += SA_SIZE(mask);
1231 		msg->rtm_addrs |= RTA_NETMASK;
1232 	}
1233 	msg->rtm_msglen = cp - (char *)msg;
1234 	msg->rtm_type = RTM_GET;
1235 	if ((sent = write(route, msg, msg->rtm_msglen)) == -1) {
1236 		syslog(LOG_ERR, "%s: write: %m", __func__);
1237 		free(msg);
1238 		return;
1239 	}
1240 	if (sent != msg->rtm_msglen) {
1241 		syslog(LOG_ERR, "%s: short write", __func__);
1242 		free(msg);
1243 		return;
1244 	}
1245 	free(msg);
1246 }
1247 
1248 /*
1249  * Fetch the routing table via sysctl
1250  */
1251 u_char *
1252 mib_fetch_rtab(int af, int info, int arg, size_t *lenp)
1253 {
1254 	int name[6];
1255 	u_char *buf, *newbuf;
1256 
1257 	name[0] = CTL_NET;
1258 	name[1] = PF_ROUTE;
1259 	name[2] = 0;
1260 	name[3] = af;
1261 	name[4] = info;
1262 	name[5] = arg;
1263 
1264 	*lenp = 0;
1265 
1266 	/* initial estimate */
1267 	if (sysctl(name, nitems(name), NULL, lenp, NULL, 0) == -1) {
1268 		syslog(LOG_ERR, "sysctl estimate (%d,%d,%d,%d,%d,%d): %m",
1269 		    name[0], name[1], name[2], name[3], name[4], name[5]);
1270 		return (NULL);
1271 	}
1272 	if (*lenp == 0)
1273 		return (NULL);
1274 
1275 	buf = NULL;
1276 	for (;;) {
1277 		if ((newbuf = realloc(buf, *lenp)) == NULL) {
1278 			syslog(LOG_ERR, "sysctl buffer: %m");
1279 			free(buf);
1280 			return (NULL);
1281 		}
1282 		buf = newbuf;
1283 
1284 		if (sysctl(name, nitems(name), buf, lenp, NULL, 0) == 0)
1285 			break;
1286 
1287 		if (errno != ENOMEM) {
1288 			syslog(LOG_ERR, "sysctl get: %m");
1289 			free(buf);
1290 			return (NULL);
1291 		}
1292 		*lenp += *lenp / 8 + 1;
1293 	}
1294 
1295 	return (buf);
1296 }
1297 
1298 /*
1299  * Update the following info: interface, interface addresses, interface
1300  * receive addresses, arp-table.
1301  * This does not change the interface list itself.
1302  */
1303 static void
1304 update_ifa_info(void)
1305 {
1306 	u_char *buf, *next;
1307 	struct rt_msghdr *rtm;
1308 	struct mibifa *ifa, *ifa1;
1309 	struct mibrcvaddr *rcv, *rcv1;
1310 	size_t needed;
1311 	static const int infos[][3] = {
1312 		{ 0, NET_RT_IFLIST, 0 },
1313 #ifdef NET_RT_IFMALIST
1314 		{ AF_LINK, NET_RT_IFMALIST, 0 },
1315 #endif
1316 	};
1317 	u_int i;
1318 
1319 	TAILQ_FOREACH(ifa, &mibifa_list, link)
1320 		ifa->flags &= ~MIBIFA_FOUND;
1321 	TAILQ_FOREACH(rcv, &mibrcvaddr_list, link)
1322 		rcv->flags &= ~MIBRCVADDR_FOUND;
1323 
1324 	for (i = 0; i < sizeof(infos) / sizeof(infos[0]); i++) {
1325 		if ((buf = mib_fetch_rtab(infos[i][0], infos[i][1], infos[i][2],
1326 		   &needed)) == NULL)
1327 			continue;
1328 
1329 		next = buf;
1330 		while (next < buf + needed) {
1331 			rtm = (struct rt_msghdr *)(void *)next;
1332 			next += rtm->rtm_msglen;
1333 			handle_rtmsg(rtm);
1334 		}
1335 		free(buf);
1336 	}
1337 
1338 	/*
1339 	 * Purge the address list of unused entries. These may happen for
1340 	 * interface aliases that are on the same subnet. We don't receive
1341 	 * routing socket messages for them.
1342 	 */
1343 	ifa = TAILQ_FIRST(&mibifa_list);
1344 	while (ifa != NULL) {
1345 		ifa1 = TAILQ_NEXT(ifa, link);
1346 		if (!(ifa->flags & MIBIFA_FOUND))
1347 			destroy_ifa(ifa);
1348 		ifa = ifa1;
1349 	}
1350 
1351 	rcv = TAILQ_FIRST(&mibrcvaddr_list);
1352 	while (rcv != NULL) {
1353 		rcv1 = TAILQ_NEXT(rcv, link);
1354 		if (!(rcv->flags & (MIBRCVADDR_FOUND | MIBRCVADDR_BCAST |
1355 		    MIBRCVADDR_HW)))
1356 			mib_rcvaddr_delete(rcv);
1357 		rcv = rcv1;
1358 	}
1359 }
1360 
1361 /*
1362  * Update arp table
1363  */
1364 void
1365 mib_arp_update(void)
1366 {
1367 	struct mibarp *at, *at1;
1368 	size_t needed;
1369 	u_char *buf, *next;
1370 	struct rt_msghdr *rtm;
1371 
1372 	if (in_update_arp)
1373 		return;		/* Aaargh */
1374 	in_update_arp = 1;
1375 
1376 	TAILQ_FOREACH(at, &mibarp_list, link)
1377 		at->flags &= ~MIBARP_FOUND;
1378 
1379 	if ((buf = mib_fetch_rtab(AF_INET, NET_RT_FLAGS, 0, &needed)) == NULL) {
1380 		in_update_arp = 0;
1381 		return;
1382 	}
1383 
1384 	next = buf;
1385 	while (next < buf + needed) {
1386 		rtm = (struct rt_msghdr *)(void *)next;
1387 		next += rtm->rtm_msglen;
1388 		handle_rtmsg(rtm);
1389 	}
1390 	free(buf);
1391 
1392 	at = TAILQ_FIRST(&mibarp_list);
1393 	while (at != NULL) {
1394 		at1 = TAILQ_NEXT(at, link);
1395 		if (!(at->flags & MIBARP_FOUND))
1396 			mib_arp_delete(at);
1397 		at = at1;
1398 	}
1399 	mibarpticks = get_ticks();
1400 	in_update_arp = 0;
1401 }
1402 
1403 
1404 /*
1405  * Input on the routing socket.
1406  */
1407 static void
1408 route_input(int fd, void *udata __unused)
1409 {
1410 	u_char	buf[1024 * 16];
1411 	ssize_t n;
1412 	struct rt_msghdr *rtm;
1413 
1414 	if ((n = read(fd, buf, sizeof(buf))) == -1)
1415 		err(1, "read(rt_socket)");
1416 
1417 	if (n == 0)
1418 		errx(1, "EOF on rt_socket");
1419 
1420 	rtm = (struct rt_msghdr *)(void *)buf;
1421 	if ((size_t)n != rtm->rtm_msglen)
1422 		errx(1, "n=%zu, rtm_msglen=%u", (size_t)n, rtm->rtm_msglen);
1423 
1424 	handle_rtmsg(rtm);
1425 }
1426 
1427 /*
1428  * execute and SIOCAIFADDR
1429  */
1430 static int
1431 siocaifaddr(char *ifname, struct in_addr addr, struct in_addr mask,
1432     struct in_addr bcast)
1433 {
1434 	struct ifaliasreq addreq;
1435 	struct sockaddr_in *sa;
1436 
1437 	memset(&addreq, 0, sizeof(addreq));
1438 	strlcpy(addreq.ifra_name, ifname, sizeof(addreq.ifra_name));
1439 
1440 	sa = (struct sockaddr_in *)(void *)&addreq.ifra_addr;
1441 	sa->sin_family = AF_INET;
1442 	sa->sin_len = sizeof(*sa);
1443 	sa->sin_addr = addr;
1444 
1445 	sa = (struct sockaddr_in *)(void *)&addreq.ifra_mask;
1446 	sa->sin_family = AF_INET;
1447 	sa->sin_len = sizeof(*sa);
1448 	sa->sin_addr = mask;
1449 
1450 	sa = (struct sockaddr_in *)(void *)&addreq.ifra_broadaddr;
1451 	sa->sin_family = AF_INET;
1452 	sa->sin_len = sizeof(*sa);
1453 	sa->sin_addr = bcast;
1454 
1455 	return (ioctl(mib_netsock, SIOCAIFADDR, &addreq));
1456 }
1457 
1458 /*
1459  * Exececute a SIOCDIFADDR
1460  */
1461 static int
1462 siocdifaddr(const char *ifname, struct in_addr addr)
1463 {
1464 	struct ifreq delreq;
1465 	struct sockaddr_in *sa;
1466 
1467 	memset(&delreq, 0, sizeof(delreq));
1468 	strlcpy(delreq.ifr_name, ifname, sizeof(delreq.ifr_name));
1469 	sa = (struct sockaddr_in *)(void *)&delreq.ifr_addr;
1470 	sa->sin_family = AF_INET;
1471 	sa->sin_len = sizeof(*sa);
1472 	sa->sin_addr = addr;
1473 
1474 	return (ioctl(mib_netsock, SIOCDIFADDR, &delreq));
1475 }
1476 
1477 /*
1478  * Verify an interface address without fetching the entire list
1479  */
1480 static int
1481 verify_ifa(const char *name, struct mibifa *ifa)
1482 {
1483 	struct ifreq req;
1484 	struct sockaddr_in *sa;
1485 
1486 	memset(&req, 0, sizeof(req));
1487 	strlcpy(req.ifr_name, name, sizeof(req.ifr_name));
1488 	sa = (struct sockaddr_in *)(void *)&req.ifr_addr;
1489 	sa->sin_family = AF_INET;
1490 	sa->sin_len = sizeof(*sa);
1491 	sa->sin_addr = ifa->inaddr;
1492 
1493 	if (ioctl(mib_netsock, SIOCGIFADDR, &req) == -1)
1494 		return (-1);
1495 	if (ifa->inaddr.s_addr != sa->sin_addr.s_addr) {
1496 		syslog(LOG_ERR, "%s: address mismatch", __func__);
1497 		return (-1);
1498 	}
1499 
1500 	if (ioctl(mib_netsock, SIOCGIFNETMASK, &req) == -1)
1501 		return (-1);
1502 	if (ifa->inmask.s_addr != sa->sin_addr.s_addr) {
1503 		syslog(LOG_ERR, "%s: netmask mismatch", __func__);
1504 		return (-1);
1505 	}
1506 	return (0);
1507 }
1508 
1509 /*
1510  * Restore a deleted interface address. Don't wait for the routing socket
1511  * to update us.
1512  */
1513 void
1514 mib_undestroy_ifa(struct mibifa *ifa)
1515 {
1516 	struct mibif *ifp;
1517 
1518 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL)
1519 		/* keep it destroyed */
1520 		return;
1521 
1522 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast))
1523 		/* keep it destroyed */
1524 		return;
1525 
1526 	ifa->flags &= ~MIBIFA_DESTROYED;
1527 }
1528 
1529 /*
1530  * Destroy an interface address
1531  */
1532 int
1533 mib_destroy_ifa(struct mibifa *ifa)
1534 {
1535 	struct mibif *ifp;
1536 
1537 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1538 		/* ups. */
1539 		mib_iflist_bad = 1;
1540 		return (-1);
1541 	}
1542 	if (siocdifaddr(ifp->name, ifa->inaddr)) {
1543 		/* ups. */
1544 		syslog(LOG_ERR, "SIOCDIFADDR: %m");
1545 		mib_iflist_bad = 1;
1546 		return (-1);
1547 	}
1548 	ifa->flags |= MIBIFA_DESTROYED;
1549 	return (0);
1550 }
1551 
1552 /*
1553  * Rollback the modification of an address. Don't bother to wait for
1554  * the routing socket.
1555  */
1556 void
1557 mib_unmodify_ifa(struct mibifa *ifa)
1558 {
1559 	struct mibif *ifp;
1560 
1561 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1562 		/* ups. */
1563 		mib_iflist_bad = 1;
1564 		return;
1565 	}
1566 
1567 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast)) {
1568 		/* ups. */
1569 		mib_iflist_bad = 1;
1570 		return;
1571 	}
1572 }
1573 
1574 /*
1575  * Modify an IFA.
1576  */
1577 int
1578 mib_modify_ifa(struct mibifa *ifa)
1579 {
1580 	struct mibif *ifp;
1581 
1582 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1583 		/* ups. */
1584 		mib_iflist_bad = 1;
1585 		return (-1);
1586 	}
1587 
1588 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast)) {
1589 		/* ups. */
1590 		mib_iflist_bad = 1;
1591 		return (-1);
1592 	}
1593 
1594 	if (verify_ifa(ifp->name, ifa)) {
1595 		/* ups. */
1596 		mib_iflist_bad = 1;
1597 		return (-1);
1598 	}
1599 
1600 	return (0);
1601 }
1602 
1603 /*
1604  * Destroy a freshly created interface address. Don't bother to wait for
1605  * the routing socket.
1606  */
1607 void
1608 mib_uncreate_ifa(struct mibifa *ifa)
1609 {
1610 	struct mibif *ifp;
1611 
1612 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1613 		/* ups. */
1614 		mib_iflist_bad = 1;
1615 		return;
1616 	}
1617 	if (siocdifaddr(ifp->name, ifa->inaddr)) {
1618 		/* ups. */
1619 		mib_iflist_bad = 1;
1620 		return;
1621 	}
1622 
1623 	destroy_ifa(ifa);
1624 }
1625 
1626 /*
1627  * Create a new ifa and verify it
1628  */
1629 struct mibifa *
1630 mib_create_ifa(u_int ifindex, struct in_addr addr, struct in_addr mask,
1631     struct in_addr bcast)
1632 {
1633 	struct mibif *ifp;
1634 	struct mibifa *ifa;
1635 
1636 	if ((ifp = mib_find_if(ifindex)) == NULL)
1637 		return (NULL);
1638 	if ((ifa = alloc_ifa(ifindex, addr)) == NULL)
1639 		return (NULL);
1640 	ifa->inmask = mask;
1641 	ifa->inbcast = bcast;
1642 
1643 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast)) {
1644 		syslog(LOG_ERR, "%s: %m", __func__);
1645 		destroy_ifa(ifa);
1646 		return (NULL);
1647 	}
1648 	if (verify_ifa(ifp->name, ifa)) {
1649 		destroy_ifa(ifa);
1650 		return (NULL);
1651 	}
1652 	return (ifa);
1653 }
1654 
1655 /*
1656  * Get all cloning interfaces and make them dynamic.
1657  * Hah! Whe should probably do this on a periodic basis (XXX).
1658  */
1659 static void
1660 get_cloners(void)
1661 {
1662 	struct if_clonereq req;
1663 	char *buf, *cp;
1664 	int i;
1665 
1666 	memset(&req, 0, sizeof(req));
1667 	if (ioctl(mib_netsock, SIOCIFGCLONERS, &req) == -1) {
1668 		syslog(LOG_ERR, "get cloners: %m");
1669 		return;
1670 	}
1671 	if ((buf = malloc(req.ifcr_total * IFNAMSIZ)) == NULL) {
1672 		syslog(LOG_ERR, "%m");
1673 		return;
1674 	}
1675 	req.ifcr_count = req.ifcr_total;
1676 	req.ifcr_buffer = buf;
1677 	if (ioctl(mib_netsock, SIOCIFGCLONERS, &req) == -1) {
1678 		syslog(LOG_ERR, "get cloners: %m");
1679 		free(buf);
1680 		return;
1681 	}
1682 	for (cp = buf, i = 0; i < req.ifcr_total; i++, cp += IFNAMSIZ)
1683 		mib_if_set_dyn(cp);
1684 	free(buf);
1685 }
1686 
1687 /*
1688  * Idle function
1689  */
1690 static void
1691 mibII_idle(void *arg __unused)
1692 {
1693 	struct mibifa *ifa;
1694 
1695 	if (mib_iflist_bad) {
1696 		TAILQ_FOREACH(ifa, &mibifa_list, link)
1697 			ifa->flags &= ~MIBIFA_DESTROYED;
1698 
1699 		/* assume, that all cloning interfaces are dynamic */
1700 		get_cloners();
1701 
1702 		mib_refresh_iflist();
1703 		update_ifa_info();
1704 		mib_arp_update();
1705 		mib_iflist_bad = 0;
1706 	}
1707 
1708 	mib_arp_update();
1709 }
1710 
1711 
1712 /*
1713  * Start the module
1714  */
1715 static void
1716 mibII_start(void)
1717 {
1718 	if ((route_fd = fd_select(route, route_input, NULL, module)) == NULL) {
1719 		syslog(LOG_ERR, "fd_select(route): %m");
1720 		return;
1721 	}
1722 	mib_refresh_iflist();
1723 	update_ifa_info();
1724 	mib_arp_update();
1725 	(void)mib_fetch_route();
1726 	mib_iftable_last_change = 0;
1727 	mib_ifstack_last_change = 0;
1728 
1729 	ifmib_reg = or_register(&oid_ifMIB,
1730 	    "The MIB module to describe generic objects for network interface"
1731 	    " sub-layers.", module);
1732 
1733 	ipmib_reg = or_register(&oid_ipMIB,
1734 	   "The MIB module for managing IP and ICMP implementations, but "
1735 	   "excluding their management of IP routes.", module);
1736 
1737 	tcpmib_reg = or_register(&oid_tcpMIB,
1738 	   "The MIB module for managing TCP implementations.", module);
1739 
1740 	udpmib_reg = or_register(&oid_udpMIB,
1741 	   "The MIB module for managing UDP implementations.", module);
1742 
1743 	ipForward_reg = or_register(&oid_ipForward,
1744 	   "The MIB module for the display of CIDR multipath IP Routes.",
1745 	   module);
1746 
1747 	mibII_poll_timer = NULL;
1748 	mibII_poll_ticks = MIBII_POLL_TICKS;
1749 	mibif_restart_mibII_poll_timer();
1750 }
1751 
1752 /*
1753  * Initialize the module
1754  */
1755 static int
1756 mibII_init(struct lmodule *mod, int argc __unused, char *argv[] __unused)
1757 {
1758 	size_t len;
1759 
1760 	module = mod;
1761 
1762 	len = sizeof(clockinfo);
1763 	if (sysctlbyname("kern.clockrate", &clockinfo, &len, NULL, 0) == -1) {
1764 		syslog(LOG_ERR, "kern.clockrate: %m");
1765 		return (-1);
1766 	}
1767 	if (len != sizeof(clockinfo)) {
1768 		syslog(LOG_ERR, "kern.clockrate: wrong size");
1769 		return (-1);
1770 	}
1771 
1772 	if ((route = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC)) == -1) {
1773 		syslog(LOG_ERR, "PF_ROUTE: %m");
1774 		return (-1);
1775 	}
1776 
1777 	if ((mib_netsock = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
1778 		syslog(LOG_ERR, "PF_INET: %m");
1779 		(void)close(route);
1780 		return (-1);
1781 	}
1782 	(void)shutdown(mib_netsock, SHUT_RDWR);
1783 
1784 	/* assume, that all cloning interfaces are dynamic */
1785 	get_cloners();
1786 
1787 	return (0);
1788 }
1789 
1790 static int
1791 mibII_fini(void)
1792 {
1793 	if (mibII_poll_timer != NULL ) {
1794 		timer_stop(mibII_poll_timer);
1795 		mibII_poll_timer = NULL;
1796 	}
1797 
1798 	if (route_fd != NULL)
1799 		fd_deselect(route_fd);
1800 	if (route != -1)
1801 		(void)close(route);
1802 	if (mib_netsock != -1)
1803 		(void)close(mib_netsock);
1804 	/* XXX free memory */
1805 
1806 	or_unregister(ipForward_reg);
1807 	or_unregister(udpmib_reg);
1808 	or_unregister(tcpmib_reg);
1809 	or_unregister(ipmib_reg);
1810 	or_unregister(ifmib_reg);
1811 
1812 	return (0);
1813 }
1814 
1815 static void
1816 mibII_loading(const struct lmodule *mod, int loaded)
1817 {
1818 	struct mibif *ifp;
1819 
1820 	if (loaded == 1)
1821 		return;
1822 
1823 	TAILQ_FOREACH(ifp, &mibif_list, link)
1824 		if (ifp->xnotify_mod == mod) {
1825 			ifp->xnotify_mod = NULL;
1826 			ifp->xnotify_data = NULL;
1827 			ifp->xnotify = NULL;
1828 		}
1829 
1830 	mib_unregister_newif(mod);
1831 }
1832 
1833 extern const struct snmp_module config;
1834 const struct snmp_module config = {
1835 	"This module implements the interface and ip groups.",
1836 	mibII_init,
1837 	mibII_fini,
1838 	NULL,		/* idle */
1839 	NULL,		/* dump */
1840 	NULL,		/* config */
1841 	mibII_start,
1842 	NULL,
1843 	mibII_ctree,
1844 	mibII_CTREE_SIZE,
1845 	mibII_loading
1846 };
1847 
1848 /*
1849  * Should have a list of these attached to each interface.
1850  */
1851 void *
1852 mibif_notify(struct mibif *ifp, const struct lmodule *mod,
1853     mibif_notify_f func, void *data)
1854 {
1855 	ifp->xnotify = func;
1856 	ifp->xnotify_data = data;
1857 	ifp->xnotify_mod = mod;
1858 
1859 	return (ifp);
1860 }
1861 
1862 void
1863 mibif_unnotify(void *arg)
1864 {
1865 	struct mibif *ifp = arg;
1866 
1867 	ifp->xnotify = NULL;
1868 	ifp->xnotify_data = NULL;
1869 	ifp->xnotify_mod = NULL;
1870 }
1871