xref: /freebsd/contrib/bsnmp/snmp_mibII/mibII.c (revision 409a390c3341fb4f162cd7de1fd595a323ebbfd8)
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 	strcpy(d->name, 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 	strncpy(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, 6, &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 * 10, ticks * 10,
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 	int name[6];
443 	size_t len;
444 	void *newmib;
445 	struct ifmibdata oldmib = ifp->mib;
446 
447 	if (fetch_generic_mib(ifp, &oldmib) == -1)
448 		return (-1);
449 
450 	/*
451 	 * Quoting RFC2863, 3.1.15: "... LinkUp and linkDown traps are
452 	 * generated just after ifOperStatus leaves, or just before it
453 	 * enters, the down state, respectively;"
454 	 */
455 	if (ifp->trap_enable && ifp->mib.ifmd_data.ifi_link_state !=
456 	    oldmib.ifmd_data.ifi_link_state &&
457 	    (ifp->mib.ifmd_data.ifi_link_state == LINK_STATE_DOWN ||
458 	    oldmib.ifmd_data.ifi_link_state == LINK_STATE_DOWN))
459 		link_trap(ifp, ifp->mib.ifmd_data.ifi_link_state ==
460 		    LINK_STATE_UP ? 1 : 0);
461 
462 	ifp->flags &= ~(MIBIF_HIGHSPEED | MIBIF_VERYHIGHSPEED);
463 	if (ifp->mib.ifmd_data.ifi_baudrate > 20000000) {
464 		ifp->flags |= MIBIF_HIGHSPEED;
465 		if (ifp->mib.ifmd_data.ifi_baudrate > 650000000)
466 			ifp->flags |= MIBIF_VERYHIGHSPEED;
467 	}
468 	if (ifp->mib.ifmd_data.ifi_baudrate > mibif_maxspeed) {
469 		mibif_maxspeed = ifp->mib.ifmd_data.ifi_baudrate;
470 		mibif_reset_hc_timer();
471 	}
472 
473 	/*
474 	 * linkspecific MIB
475 	 */
476 	name[0] = CTL_NET;
477 	name[1] = PF_LINK;
478 	name[2] = NETLINK_GENERIC;
479 	name[3] = IFMIB_IFDATA;
480 	name[4] = ifp->sysindex;
481 	name[5] = IFDATA_LINKSPECIFIC;
482 	if (sysctl(name, 6, NULL, &len, NULL, 0) == -1) {
483 		syslog(LOG_WARNING, "sysctl linkmib estimate (%s): %m",
484 		    ifp->name);
485 		if (ifp->specmib != NULL) {
486 			ifp->specmib = NULL;
487 			ifp->specmiblen = 0;
488 		}
489 		goto out;
490 	}
491 	if (len == 0) {
492 		if (ifp->specmib != NULL) {
493 			ifp->specmib = NULL;
494 			ifp->specmiblen = 0;
495 		}
496 		goto out;
497 	}
498 
499 	if (ifp->specmiblen != len) {
500 		if ((newmib = realloc(ifp->specmib, len)) == NULL) {
501 			ifp->specmib = NULL;
502 			ifp->specmiblen = 0;
503 			goto out;
504 		}
505 		ifp->specmib = newmib;
506 		ifp->specmiblen = len;
507 	}
508 	if (sysctl(name, 6, ifp->specmib, &len, NULL, 0) == -1) {
509 		syslog(LOG_WARNING, "sysctl linkmib (%s): %m", ifp->name);
510 		if (ifp->specmib != NULL) {
511 			ifp->specmib = NULL;
512 			ifp->specmiblen = 0;
513 		}
514 	}
515 
516   out:
517 	ifp->mibtick = get_ticks();
518 	return (0);
519 }
520 
521 /* find first/next address for a given interface */
522 struct mibifa *
523 mib_first_ififa(const struct mibif *ifp)
524 {
525 	struct mibifa *ifa;
526 
527 	TAILQ_FOREACH(ifa, &mibifa_list, link)
528 		if (ifp->index == ifa->ifindex)
529 			return (ifa);
530 	return (NULL);
531 }
532 
533 struct mibifa *
534 mib_next_ififa(struct mibifa *ifa0)
535 {
536 	struct mibifa *ifa;
537 
538 	ifa = ifa0;
539 	while ((ifa = TAILQ_NEXT(ifa, link)) != NULL)
540 		if (ifa->ifindex == ifa0->ifindex)
541 			return (ifa);
542 	return (NULL);
543 }
544 
545 /*
546  * Allocate a new IFA
547  */
548 static struct mibifa *
549 alloc_ifa(u_int ifindex, struct in_addr addr)
550 {
551 	struct mibifa *ifa;
552 	uint32_t ha;
553 
554 	if ((ifa = malloc(sizeof(struct mibifa))) == NULL) {
555 		syslog(LOG_ERR, "ifa: %m");
556 		return (NULL);
557 	}
558 	ifa->inaddr = addr;
559 	ifa->ifindex = ifindex;
560 
561 	ha = ntohl(ifa->inaddr.s_addr);
562 	ifa->index.len = 4;
563 	ifa->index.subs[0] = (ha >> 24) & 0xff;
564 	ifa->index.subs[1] = (ha >> 16) & 0xff;
565 	ifa->index.subs[2] = (ha >>  8) & 0xff;
566 	ifa->index.subs[3] = (ha >>  0) & 0xff;
567 
568 	ifa->flags = 0;
569 	ifa->inbcast.s_addr = 0;
570 	ifa->inmask.s_addr = 0xffffffff;
571 
572 	INSERT_OBJECT_OID(ifa, &mibifa_list);
573 
574 	return (ifa);
575 }
576 
577 /*
578  * Delete an interface address
579  */
580 static void
581 destroy_ifa(struct mibifa *ifa)
582 {
583 	TAILQ_REMOVE(&mibifa_list, ifa, link);
584 	free(ifa);
585 }
586 
587 
588 /*
589  * Helper routine to extract the sockaddr structures from a routing
590  * socket message.
591  */
592 void
593 mib_extract_addrs(int addrs, u_char *info, struct sockaddr **out)
594 {
595 	u_int i;
596 
597 	for (i = 0; i < RTAX_MAX; i++) {
598 		if ((addrs & (1 << i)) != 0) {
599 			*out = (struct sockaddr *)(void *)info;
600 			info += roundup((*out)->sa_len, sizeof(long));
601 		} else
602 			*out = NULL;
603 		out++;
604 	}
605 }
606 
607 /*
608  * save the phys address of an interface. Handle receive address entries here.
609  */
610 static void
611 get_physaddr(struct mibif *ifp, struct sockaddr_dl *sdl, u_char *ptr)
612 {
613 	u_char *np;
614 	struct mibrcvaddr *rcv;
615 
616 	if (sdl->sdl_alen == 0) {
617 		/* no address */
618 		if (ifp->physaddrlen != 0) {
619 			if ((rcv = mib_find_rcvaddr(ifp->index, ifp->physaddr,
620 			    ifp->physaddrlen)) != NULL)
621 				mib_rcvaddr_delete(rcv);
622 			free(ifp->physaddr);
623 			ifp->physaddr = NULL;
624 			ifp->physaddrlen = 0;
625 		}
626 		return;
627 	}
628 
629 	if (ifp->physaddrlen != sdl->sdl_alen) {
630 		/* length changed */
631 		if (ifp->physaddrlen) {
632 			/* delete olf receive address */
633 			if ((rcv = mib_find_rcvaddr(ifp->index, ifp->physaddr,
634 			    ifp->physaddrlen)) != NULL)
635 				mib_rcvaddr_delete(rcv);
636 		}
637 		if ((np = realloc(ifp->physaddr, sdl->sdl_alen)) == NULL) {
638 			free(ifp->physaddr);
639 			ifp->physaddr = NULL;
640 			ifp->physaddrlen = 0;
641 			return;
642 		}
643 		ifp->physaddr = np;
644 		ifp->physaddrlen = sdl->sdl_alen;
645 
646 	} else if (memcmp(ifp->physaddr, ptr, ifp->physaddrlen) == 0) {
647 		/* no change */
648 		return;
649 
650 	} else {
651 		/* address changed */
652 
653 		/* delete olf receive address */
654 		if ((rcv = mib_find_rcvaddr(ifp->index, ifp->physaddr,
655 		    ifp->physaddrlen)) != NULL)
656 			mib_rcvaddr_delete(rcv);
657 	}
658 
659 	memcpy(ifp->physaddr, ptr, ifp->physaddrlen);
660 
661 	/* make new receive address */
662 	if ((rcv = mib_rcvaddr_create(ifp, ifp->physaddr, ifp->physaddrlen)) != NULL)
663 		rcv->flags |= MIBRCVADDR_HW;
664 }
665 
666 /*
667  * Free an interface
668  */
669 static void
670 mibif_free(struct mibif *ifp)
671 {
672 	struct mibif *ifp1;
673 	struct mibindexmap *map;
674 	struct mibifa *ifa, *ifa1;
675 	struct mibrcvaddr *rcv, *rcv1;
676 	struct mibarp *at, *at1;
677 
678 	if (ifp->xnotify != NULL)
679 		(*ifp->xnotify)(ifp, MIBIF_NOTIFY_DESTROY, ifp->xnotify_data);
680 
681 	(void)mib_ifstack_delete(ifp, NULL);
682 	(void)mib_ifstack_delete(NULL, ifp);
683 
684 	TAILQ_REMOVE(&mibif_list, ifp, link);
685 
686 	/* if this was the fastest interface - recompute this */
687 	if (ifp->mib.ifmd_data.ifi_baudrate == mibif_maxspeed) {
688 		mibif_maxspeed = ifp->mib.ifmd_data.ifi_baudrate;
689 		TAILQ_FOREACH(ifp1, &mibif_list, link)
690 			if (ifp1->mib.ifmd_data.ifi_baudrate > mibif_maxspeed)
691 				mibif_maxspeed =
692 				    ifp1->mib.ifmd_data.ifi_baudrate;
693 		mibif_reset_hc_timer();
694 	}
695 
696 	free(ifp->private);
697 	if (ifp->physaddr != NULL)
698 		free(ifp->physaddr);
699 	if (ifp->specmib != NULL)
700 		free(ifp->specmib);
701 
702 	STAILQ_FOREACH(map, &mibindexmap_list, link)
703 		if (map->mibif == ifp) {
704 			map->mibif = NULL;
705 			break;
706 		}
707 
708 	/* purge interface addresses */
709 	ifa = TAILQ_FIRST(&mibifa_list);
710 	while (ifa != NULL) {
711 		ifa1 = TAILQ_NEXT(ifa, link);
712 		if (ifa->ifindex == ifp->index)
713 			destroy_ifa(ifa);
714 		ifa = ifa1;
715 	}
716 
717 	/* purge receive addresses */
718 	rcv = TAILQ_FIRST(&mibrcvaddr_list);
719 	while (rcv != NULL) {
720 		rcv1 = TAILQ_NEXT(rcv, link);
721 		if (rcv->ifindex == ifp->index)
722 			mib_rcvaddr_delete(rcv);
723 		rcv = rcv1;
724 	}
725 
726 	/* purge ARP entries */
727 	at = TAILQ_FIRST(&mibarp_list);
728 	while (at != NULL) {
729 		at1 = TAILQ_NEXT(at, link);
730 		if (at->index.subs[0] == ifp->index)
731 			mib_arp_delete(at);
732 		at = at1;
733 	}
734 
735 
736 	free(ifp);
737 	mib_if_number--;
738 	mib_iftable_last_change = this_tick;
739 }
740 
741 /*
742  * Create a new interface
743  */
744 static struct mibif *
745 mibif_create(u_int sysindex, const char *name)
746 {
747 	struct mibif *ifp;
748 	struct mibindexmap *map;
749 
750 	if ((ifp = malloc(sizeof(*ifp))) == NULL) {
751 		syslog(LOG_WARNING, "%s: %m", __func__);
752 		return (NULL);
753 	}
754 	memset(ifp, 0, sizeof(*ifp));
755 	if ((ifp->private = malloc(sizeof(struct mibif_private))) == NULL) {
756 		syslog(LOG_WARNING, "%s: %m", __func__);
757 		free(ifp);
758 		return (NULL);
759 	}
760 	memset(ifp->private, 0, sizeof(struct mibif_private));
761 
762 	ifp->sysindex = sysindex;
763 	strcpy(ifp->name, name);
764 	strcpy(ifp->descr, name);
765 	ifp->spec_oid = oid_zeroDotZero;
766 
767 	map = NULL;
768 	if (!mib_if_is_dyn(ifp->name)) {
769 		/* non-dynamic. look whether we know the interface */
770 		STAILQ_FOREACH(map, &mibindexmap_list, link)
771 			if (strcmp(map->name, ifp->name) == 0) {
772 				ifp->index = map->ifindex;
773 				map->mibif = ifp;
774 				break;
775 			}
776 		/* assume it has a connector if it is not dynamic */
777 		ifp->has_connector = 1;
778 		ifp->trap_enable = 1;
779 	}
780 	if (map == NULL) {
781 		/* new interface - get new index */
782 		if (next_if_index > 0x7fffffff)
783 			errx(1, "ifindex wrap");
784 
785 		if ((map = malloc(sizeof(*map))) == NULL) {
786 			syslog(LOG_ERR, "ifmap: %m");
787 			free(ifp);
788 			return (NULL);
789 		}
790 		map->ifindex = next_if_index++;
791 		map->sysindex = ifp->sysindex;
792 		strcpy(map->name, ifp->name);
793 		map->mibif = ifp;
794 		STAILQ_INSERT_TAIL(&mibindexmap_list, map, link);
795 	} else {
796 		/* re-instantiate. Introduce a counter discontinuity */
797 		ifp->counter_disc = get_ticks();
798 	}
799 	ifp->index = map->ifindex;
800 	ifp->mib.ifmd_data.ifi_link_state = LINK_STATE_UNKNOWN;
801 
802 	INSERT_OBJECT_INT(ifp, &mibif_list);
803 	mib_if_number++;
804 	mib_iftable_last_change = this_tick;
805 
806 	/* instantiate default ifStack entries */
807 	(void)mib_ifstack_create(ifp, NULL);
808 	(void)mib_ifstack_create(NULL, ifp);
809 
810 	return (ifp);
811 }
812 
813 /*
814  * Inform all interested parties about a new interface
815  */
816 static void
817 notify_newif(struct mibif *ifp)
818 {
819 	struct newifreg *reg;
820 
821 	TAILQ_FOREACH(reg, &newifreg_list, link)
822 		if ((*reg->func)(ifp))
823 			return;
824 }
825 
826 /*
827  * This is called for new interfaces after we have fetched the interface
828  * MIB. If this is a broadcast interface try to guess the broadcast address
829  * depending on the interface type.
830  */
831 static void
832 check_llbcast(struct mibif *ifp)
833 {
834 	static u_char ether_bcast[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
835 	static u_char arcnet_bcast = 0;
836 	struct mibrcvaddr *rcv;
837 
838 	if (!(ifp->mib.ifmd_flags & IFF_BROADCAST))
839 		return;
840 
841 	switch (ifp->mib.ifmd_data.ifi_type) {
842 
843 	  case IFT_ETHER:
844 	  case IFT_FDDI:
845 	  case IFT_ISO88025:
846 		if (mib_find_rcvaddr(ifp->index, ether_bcast, 6) == NULL &&
847 		    (rcv = mib_rcvaddr_create(ifp, ether_bcast, 6)) != NULL)
848 			rcv->flags |= MIBRCVADDR_BCAST;
849 		break;
850 
851 	  case IFT_ARCNET:
852 		if (mib_find_rcvaddr(ifp->index, &arcnet_bcast, 1) == NULL &&
853 		    (rcv = mib_rcvaddr_create(ifp, &arcnet_bcast, 1)) != NULL)
854 			rcv->flags |= MIBRCVADDR_BCAST;
855 		break;
856 	}
857 }
858 
859 
860 /*
861  * Retrieve the current interface list from the system.
862  */
863 void
864 mib_refresh_iflist(void)
865 {
866 	struct mibif *ifp, *ifp1;
867 	size_t len;
868 	u_short idx;
869 	int name[6];
870 	int count;
871 	struct ifmibdata mib;
872 
873 	TAILQ_FOREACH(ifp, &mibif_list, link)
874 		ifp->flags &= ~MIBIF_FOUND;
875 
876 	len = sizeof(count);
877 	if (sysctlbyname("net.link.generic.system.ifcount", &count, &len,
878 	    NULL, 0) == -1) {
879 		syslog(LOG_ERR, "ifcount: %m");
880 		return;
881 	}
882 	name[0] = CTL_NET;
883 	name[1] = PF_LINK;
884 	name[2] = NETLINK_GENERIC;
885 	name[3] = IFMIB_IFDATA;
886 	name[5] = IFDATA_GENERAL;
887 	for (idx = 1; idx <= count; idx++) {
888 		name[4] = idx;
889 		len = sizeof(mib);
890 		if (sysctl(name, 6, &mib, &len, NULL, 0) == -1) {
891 			if (errno == ENOENT)
892 				continue;
893 			syslog(LOG_ERR, "ifmib(%u): %m", idx);
894 			return;
895 		}
896 		if ((ifp = mib_find_if_sys(idx)) != NULL) {
897 			ifp->flags |= MIBIF_FOUND;
898 			continue;
899 		}
900 		/* Unknown interface - create */
901 		if ((ifp = mibif_create(idx, mib.ifmd_name)) != NULL) {
902 			ifp->flags |= MIBIF_FOUND;
903 			(void)mib_fetch_ifmib(ifp);
904 			check_llbcast(ifp);
905 			notify_newif(ifp);
906 		}
907 	}
908 
909 	/*
910 	 * Purge interfaces that disappeared
911 	 */
912 	ifp = TAILQ_FIRST(&mibif_list);
913 	while (ifp != NULL) {
914 		ifp1 = TAILQ_NEXT(ifp, link);
915 		if (!(ifp->flags & MIBIF_FOUND))
916 			mibif_free(ifp);
917 		ifp = ifp1;
918 	}
919 }
920 
921 /*
922  * Find an interface address
923  */
924 struct mibifa *
925 mib_find_ifa(struct in_addr addr)
926 {
927 	struct mibifa *ifa;
928 
929 	TAILQ_FOREACH(ifa, &mibifa_list, link)
930 		if (ifa->inaddr.s_addr == addr.s_addr)
931 			return (ifa);
932 	return (NULL);
933 }
934 
935 /*
936  * Handle a routing socket message.
937  */
938 static void
939 handle_rtmsg(struct rt_msghdr *rtm)
940 {
941 	struct sockaddr *addrs[RTAX_MAX];
942 	struct if_msghdr *ifm;
943 	struct ifa_msghdr *ifam;
944 	struct ifma_msghdr *ifmam;
945 #ifdef RTM_IFANNOUNCE
946 	struct if_announcemsghdr *ifan;
947 #endif
948 	struct mibif *ifp;
949 	struct sockaddr_dl *sdl;
950 	struct sockaddr_in *sa;
951 	struct mibifa *ifa;
952 	struct mibrcvaddr *rcv;
953 	u_char *ptr;
954 
955 	if (rtm->rtm_version != RTM_VERSION) {
956 		syslog(LOG_ERR, "Bogus RTM version %u", rtm->rtm_version);
957 		return;
958 	}
959 
960 	switch (rtm->rtm_type) {
961 
962 	  case RTM_NEWADDR:
963 		ifam = (struct ifa_msghdr *)rtm;
964 		mib_extract_addrs(ifam->ifam_addrs, (u_char *)(ifam + 1), addrs);
965 		if (addrs[RTAX_IFA] == NULL || addrs[RTAX_NETMASK] == NULL)
966 			break;
967 
968 		sa = (struct sockaddr_in *)(void *)addrs[RTAX_IFA];
969 		if ((ifa = mib_find_ifa(sa->sin_addr)) == NULL) {
970 			/* unknown address */
971 		    	if ((ifp = mib_find_if_sys(ifam->ifam_index)) == NULL) {
972 				syslog(LOG_WARNING, "RTM_NEWADDR for unknown "
973 				    "interface %u", ifam->ifam_index);
974 				break;
975 			}
976 		     	if ((ifa = alloc_ifa(ifp->index, sa->sin_addr)) == NULL)
977 				break;
978 		}
979 		sa = (struct sockaddr_in *)(void *)addrs[RTAX_NETMASK];
980 		ifa->inmask = sa->sin_addr;
981 
982 		if (addrs[RTAX_BRD] != NULL) {
983 			sa = (struct sockaddr_in *)(void *)addrs[RTAX_BRD];
984 			ifa->inbcast = sa->sin_addr;
985 		}
986 		ifa->flags |= MIBIFA_FOUND;
987 		break;
988 
989 	  case RTM_DELADDR:
990 		ifam = (struct ifa_msghdr *)rtm;
991 		mib_extract_addrs(ifam->ifam_addrs, (u_char *)(ifam + 1), addrs);
992 		if (addrs[RTAX_IFA] == NULL)
993 			break;
994 
995 		sa = (struct sockaddr_in *)(void *)addrs[RTAX_IFA];
996 		if ((ifa = mib_find_ifa(sa->sin_addr)) != NULL) {
997 			ifa->flags |= MIBIFA_FOUND;
998 			if (!(ifa->flags & MIBIFA_DESTROYED))
999 				destroy_ifa(ifa);
1000 		}
1001 		break;
1002 
1003 	  case RTM_NEWMADDR:
1004 		ifmam = (struct ifma_msghdr *)rtm;
1005 		mib_extract_addrs(ifmam->ifmam_addrs, (u_char *)(ifmam + 1), addrs);
1006 		if (addrs[RTAX_IFA] == NULL ||
1007 		    addrs[RTAX_IFA]->sa_family != AF_LINK)
1008 			break;
1009 		sdl = (struct sockaddr_dl *)(void *)addrs[RTAX_IFA];
1010 		if ((rcv = mib_find_rcvaddr(sdl->sdl_index,
1011 		    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) == NULL) {
1012 			/* unknown address */
1013 		    	if ((ifp = mib_find_if_sys(sdl->sdl_index)) == NULL) {
1014 				syslog(LOG_WARNING, "RTM_NEWMADDR for unknown "
1015 				    "interface %u", sdl->sdl_index);
1016 				break;
1017 			}
1018 		     	if ((rcv = mib_rcvaddr_create(ifp,
1019 			    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) == NULL)
1020 				break;
1021 			rcv->flags |= MIBRCVADDR_VOLATILE;
1022 		}
1023 		rcv->flags |= MIBRCVADDR_FOUND;
1024 		break;
1025 
1026 	  case RTM_DELMADDR:
1027 		ifmam = (struct ifma_msghdr *)rtm;
1028 		mib_extract_addrs(ifmam->ifmam_addrs, (u_char *)(ifmam + 1), addrs);
1029 		if (addrs[RTAX_IFA] == NULL ||
1030 		    addrs[RTAX_IFA]->sa_family != AF_LINK)
1031 			break;
1032 		sdl = (struct sockaddr_dl *)(void *)addrs[RTAX_IFA];
1033 		if ((rcv = mib_find_rcvaddr(sdl->sdl_index,
1034 		    sdl->sdl_data + sdl->sdl_nlen, sdl->sdl_alen)) != NULL)
1035 			mib_rcvaddr_delete(rcv);
1036 		break;
1037 
1038 	  case RTM_IFINFO:
1039 		ifm = (struct if_msghdr *)(void *)rtm;
1040 		mib_extract_addrs(ifm->ifm_addrs, (u_char *)(ifm + 1), addrs);
1041 		if ((ifp = mib_find_if_sys(ifm->ifm_index)) == NULL)
1042 			break;
1043 		if (addrs[RTAX_IFP] != NULL &&
1044 		    addrs[RTAX_IFP]->sa_family == AF_LINK) {
1045 			sdl = (struct sockaddr_dl *)(void *)addrs[RTAX_IFP];
1046 			ptr = sdl->sdl_data + sdl->sdl_nlen;
1047 			get_physaddr(ifp, sdl, ptr);
1048 		}
1049 		(void)mib_fetch_ifmib(ifp);
1050 		break;
1051 
1052 #ifdef RTM_IFANNOUNCE
1053 	  case RTM_IFANNOUNCE:
1054 		ifan = (struct if_announcemsghdr *)rtm;
1055 		ifp = mib_find_if_sys(ifan->ifan_index);
1056 
1057 		switch (ifan->ifan_what) {
1058 
1059 		  case IFAN_ARRIVAL:
1060 			if (ifp == NULL && (ifp = mibif_create(ifan->ifan_index,
1061 			    ifan->ifan_name)) != NULL) {
1062 				(void)mib_fetch_ifmib(ifp);
1063 				check_llbcast(ifp);
1064 				notify_newif(ifp);
1065 			}
1066 			break;
1067 
1068 		  case IFAN_DEPARTURE:
1069 			if (ifp != NULL)
1070 				mibif_free(ifp);
1071 			break;
1072 		}
1073 		break;
1074 #endif
1075 	  case RTM_GET:
1076 	  case RTM_ADD:
1077 	  case RTM_DELETE:
1078 		mib_extract_addrs(rtm->rtm_addrs, (u_char *)(rtm + 1), addrs);
1079 
1080 		if (rtm->rtm_errno == 0 && (rtm->rtm_flags & RTF_UP))
1081 			mib_sroute_process(rtm, addrs[RTAX_GATEWAY],
1082 			    addrs[RTAX_DST], addrs[RTAX_NETMASK]);
1083 		break;
1084 	}
1085 }
1086 
1087 /*
1088  * send a routing message
1089  */
1090 void
1091 mib_send_rtmsg(struct rt_msghdr *rtm, struct sockaddr *gw,
1092     struct sockaddr *dst, struct sockaddr *mask)
1093 {
1094 	size_t len;
1095 	struct rt_msghdr *msg;
1096 	char *cp;
1097 	ssize_t sent;
1098 
1099 	len = sizeof(*rtm) + SA_SIZE(gw) + SA_SIZE(dst) + SA_SIZE(mask);
1100 	if ((msg = malloc(len)) == NULL) {
1101 		syslog(LOG_ERR, "%s: %m", __func__);
1102 		return;
1103 	}
1104 	cp = (char *)(msg + 1);
1105 
1106 	memset(msg, 0, sizeof(*msg));
1107 	msg->rtm_flags = 0;
1108 	msg->rtm_version = RTM_VERSION;
1109 	msg->rtm_addrs = RTA_DST | RTA_GATEWAY;
1110 
1111 	memcpy(cp, dst, SA_SIZE(dst));
1112 	cp += SA_SIZE(dst);
1113 	memcpy(cp, gw, SA_SIZE(gw));
1114 	cp += SA_SIZE(gw);
1115 	if (mask != NULL) {
1116 		memcpy(cp, mask, SA_SIZE(mask));
1117 		cp += SA_SIZE(mask);
1118 		msg->rtm_addrs |= RTA_NETMASK;
1119 	}
1120 	msg->rtm_msglen = cp - (char *)msg;
1121 	msg->rtm_type = RTM_GET;
1122 	if ((sent = write(route, msg, msg->rtm_msglen)) == -1) {
1123 		syslog(LOG_ERR, "%s: write: %m", __func__);
1124 		free(msg);
1125 		return;
1126 	}
1127 	if (sent != msg->rtm_msglen) {
1128 		syslog(LOG_ERR, "%s: short write", __func__);
1129 		free(msg);
1130 		return;
1131 	}
1132 	free(msg);
1133 }
1134 
1135 /*
1136  * Fetch the routing table via sysctl
1137  */
1138 u_char *
1139 mib_fetch_rtab(int af, int info, int arg, size_t *lenp)
1140 {
1141 	int name[6];
1142 	u_char *buf, *newbuf;
1143 
1144 	name[0] = CTL_NET;
1145 	name[1] = PF_ROUTE;
1146 	name[2] = 0;
1147 	name[3] = af;
1148 	name[4] = info;
1149 	name[5] = arg;
1150 
1151 	*lenp = 0;
1152 
1153 	/* initial estimate */
1154 	if (sysctl(name, 6, NULL, lenp, NULL, 0) == -1) {
1155 		syslog(LOG_ERR, "sysctl estimate (%d,%d,%d,%d,%d,%d): %m",
1156 		    name[0], name[1], name[2], name[3], name[4], name[5]);
1157 		return (NULL);
1158 	}
1159 	if (*lenp == 0)
1160 		return (NULL);
1161 
1162 	buf = NULL;
1163 	for (;;) {
1164 		if ((newbuf = realloc(buf, *lenp)) == NULL) {
1165 			syslog(LOG_ERR, "sysctl buffer: %m");
1166 			free(buf);
1167 			return (NULL);
1168 		}
1169 		buf = newbuf;
1170 
1171 		if (sysctl(name, 6, buf, lenp, NULL, 0) == 0)
1172 			break;
1173 
1174 		if (errno != ENOMEM) {
1175 			syslog(LOG_ERR, "sysctl get: %m");
1176 			free(buf);
1177 			return (NULL);
1178 		}
1179 		*lenp += *lenp / 8 + 1;
1180 	}
1181 
1182 	return (buf);
1183 }
1184 
1185 /*
1186  * Update the following info: interface, interface addresses, interface
1187  * receive addresses, arp-table.
1188  * This does not change the interface list itself.
1189  */
1190 static void
1191 update_ifa_info(void)
1192 {
1193 	u_char *buf, *next;
1194 	struct rt_msghdr *rtm;
1195 	struct mibifa *ifa, *ifa1;
1196 	struct mibrcvaddr *rcv, *rcv1;
1197 	size_t needed;
1198 	static const int infos[][3] = {
1199 		{ 0, NET_RT_IFLIST, 0 },
1200 #ifdef NET_RT_IFMALIST
1201 		{ AF_LINK, NET_RT_IFMALIST, 0 },
1202 #endif
1203 	};
1204 	u_int i;
1205 
1206 	TAILQ_FOREACH(ifa, &mibifa_list, link)
1207 		ifa->flags &= ~MIBIFA_FOUND;
1208 	TAILQ_FOREACH(rcv, &mibrcvaddr_list, link)
1209 		rcv->flags &= ~MIBRCVADDR_FOUND;
1210 
1211 	for (i = 0; i < sizeof(infos) / sizeof(infos[0]); i++) {
1212 		if ((buf = mib_fetch_rtab(infos[i][0], infos[i][1], infos[i][2],
1213 		   &needed)) == NULL)
1214 			continue;
1215 
1216 		next = buf;
1217 		while (next < buf + needed) {
1218 			rtm = (struct rt_msghdr *)(void *)next;
1219 			next += rtm->rtm_msglen;
1220 			handle_rtmsg(rtm);
1221 		}
1222 		free(buf);
1223 	}
1224 
1225 	/*
1226 	 * Purge the address list of unused entries. These may happen for
1227 	 * interface aliases that are on the same subnet. We don't receive
1228 	 * routing socket messages for them.
1229 	 */
1230 	ifa = TAILQ_FIRST(&mibifa_list);
1231 	while (ifa != NULL) {
1232 		ifa1 = TAILQ_NEXT(ifa, link);
1233 		if (!(ifa->flags & MIBIFA_FOUND))
1234 			destroy_ifa(ifa);
1235 		ifa = ifa1;
1236 	}
1237 
1238 	rcv = TAILQ_FIRST(&mibrcvaddr_list);
1239 	while (rcv != NULL) {
1240 		rcv1 = TAILQ_NEXT(rcv, link);
1241 		if (!(rcv->flags & (MIBRCVADDR_FOUND | MIBRCVADDR_BCAST |
1242 		    MIBRCVADDR_HW)))
1243 			mib_rcvaddr_delete(rcv);
1244 		rcv = rcv1;
1245 	}
1246 }
1247 
1248 /*
1249  * Update arp table
1250  *
1251 */
1252 void
1253 mib_arp_update(void)
1254 {
1255 	struct mibarp *at, *at1;
1256 	size_t needed;
1257 	u_char *buf, *next;
1258 	struct rt_msghdr *rtm;
1259 
1260 	if (in_update_arp)
1261 		return;		/* Aaargh */
1262 	in_update_arp = 1;
1263 
1264 	TAILQ_FOREACH(at, &mibarp_list, link)
1265 		at->flags &= ~MIBARP_FOUND;
1266 
1267 	if ((buf = mib_fetch_rtab(AF_INET, NET_RT_FLAGS, 0, &needed)) == NULL) {
1268 		in_update_arp = 0;
1269 		return;
1270 	}
1271 
1272 	next = buf;
1273 	while (next < buf + needed) {
1274 		rtm = (struct rt_msghdr *)(void *)next;
1275 		next += rtm->rtm_msglen;
1276 		handle_rtmsg(rtm);
1277 	}
1278 	free(buf);
1279 
1280 	at = TAILQ_FIRST(&mibarp_list);
1281 	while (at != NULL) {
1282 		at1 = TAILQ_NEXT(at, link);
1283 		if (!(at->flags & MIBARP_FOUND))
1284 			mib_arp_delete(at);
1285 		at = at1;
1286 	}
1287 	mibarpticks = get_ticks();
1288 	in_update_arp = 0;
1289 }
1290 
1291 
1292 /*
1293  * Intput on the routing socket.
1294  */
1295 static void
1296 route_input(int fd, void *udata __unused)
1297 {
1298 	u_char	buf[1024 * 16];
1299 	ssize_t n;
1300 	struct rt_msghdr *rtm;
1301 
1302 	if ((n = read(fd, buf, sizeof(buf))) == -1)
1303 		err(1, "read(rt_socket)");
1304 
1305 	if (n == 0)
1306 		errx(1, "EOF on rt_socket");
1307 
1308 	rtm = (struct rt_msghdr *)(void *)buf;
1309 	if ((size_t)n != rtm->rtm_msglen)
1310 		errx(1, "n=%zu, rtm_msglen=%u", (size_t)n, rtm->rtm_msglen);
1311 
1312 	handle_rtmsg(rtm);
1313 }
1314 
1315 /*
1316  * execute and SIOCAIFADDR
1317  */
1318 static int
1319 siocaifaddr(char *ifname, struct in_addr addr, struct in_addr mask,
1320     struct in_addr bcast)
1321 {
1322 	struct ifaliasreq addreq;
1323 	struct sockaddr_in *sa;
1324 
1325 	memset(&addreq, 0, sizeof(addreq));
1326 	strncpy(addreq.ifra_name, ifname, sizeof(addreq.ifra_name));
1327 
1328 	sa = (struct sockaddr_in *)(void *)&addreq.ifra_addr;
1329 	sa->sin_family = AF_INET;
1330 	sa->sin_len = sizeof(*sa);
1331 	sa->sin_addr = addr;
1332 
1333 	sa = (struct sockaddr_in *)(void *)&addreq.ifra_mask;
1334 	sa->sin_family = AF_INET;
1335 	sa->sin_len = sizeof(*sa);
1336 	sa->sin_addr = mask;
1337 
1338 	sa = (struct sockaddr_in *)(void *)&addreq.ifra_broadaddr;
1339 	sa->sin_family = AF_INET;
1340 	sa->sin_len = sizeof(*sa);
1341 	sa->sin_addr = bcast;
1342 
1343 	return (ioctl(mib_netsock, SIOCAIFADDR, &addreq));
1344 }
1345 
1346 /*
1347  * Exececute a SIOCDIFADDR
1348  */
1349 static int
1350 siocdifaddr(const char *ifname, struct in_addr addr)
1351 {
1352 	struct ifreq delreq;
1353 	struct sockaddr_in *sa;
1354 
1355 	memset(&delreq, 0, sizeof(delreq));
1356 	strncpy(delreq.ifr_name, ifname, sizeof(delreq.ifr_name));
1357 	sa = (struct sockaddr_in *)(void *)&delreq.ifr_addr;
1358 	sa->sin_family = AF_INET;
1359 	sa->sin_len = sizeof(*sa);
1360 	sa->sin_addr = addr;
1361 
1362 	return (ioctl(mib_netsock, SIOCDIFADDR, &delreq));
1363 }
1364 
1365 /*
1366  * Verify an interface address without fetching the entire list
1367  */
1368 static int
1369 verify_ifa(const char *name, struct mibifa *ifa)
1370 {
1371 	struct ifreq req;
1372 	struct sockaddr_in *sa;
1373 
1374 	memset(&req, 0, sizeof(req));
1375 	strncpy(req.ifr_name, name, sizeof(req.ifr_name));
1376 	sa = (struct sockaddr_in *)(void *)&req.ifr_addr;
1377 	sa->sin_family = AF_INET;
1378 	sa->sin_len = sizeof(*sa);
1379 	sa->sin_addr = ifa->inaddr;
1380 
1381 	if (ioctl(mib_netsock, SIOCGIFADDR, &req) == -1)
1382 		return (-1);
1383 	if (ifa->inaddr.s_addr != sa->sin_addr.s_addr) {
1384 		syslog(LOG_ERR, "%s: address mismatch", __func__);
1385 		return (-1);
1386 	}
1387 
1388 	if (ioctl(mib_netsock, SIOCGIFNETMASK, &req) == -1)
1389 		return (-1);
1390 	if (ifa->inmask.s_addr != sa->sin_addr.s_addr) {
1391 		syslog(LOG_ERR, "%s: netmask mismatch", __func__);
1392 		return (-1);
1393 	}
1394 	return (0);
1395 }
1396 
1397 /*
1398  * Restore a deleted interface address. Don't wait for the routing socket
1399  * to update us.
1400  */
1401 void
1402 mib_undestroy_ifa(struct mibifa *ifa)
1403 {
1404 	struct mibif *ifp;
1405 
1406 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL)
1407 		/* keep it destroyed */
1408 		return;
1409 
1410 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast))
1411 		/* keep it destroyed */
1412 		return;
1413 
1414 	ifa->flags &= ~MIBIFA_DESTROYED;
1415 }
1416 
1417 /*
1418  * Destroy an interface address
1419  */
1420 int
1421 mib_destroy_ifa(struct mibifa *ifa)
1422 {
1423 	struct mibif *ifp;
1424 
1425 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1426 		/* ups. */
1427 		mib_iflist_bad = 1;
1428 		return (-1);
1429 	}
1430 	if (siocdifaddr(ifp->name, ifa->inaddr)) {
1431 		/* ups. */
1432 		syslog(LOG_ERR, "SIOCDIFADDR: %m");
1433 		mib_iflist_bad = 1;
1434 		return (-1);
1435 	}
1436 	ifa->flags |= MIBIFA_DESTROYED;
1437 	return (0);
1438 }
1439 
1440 /*
1441  * Rollback the modification of an address. Don't bother to wait for
1442  * the routing socket.
1443  */
1444 void
1445 mib_unmodify_ifa(struct mibifa *ifa)
1446 {
1447 	struct mibif *ifp;
1448 
1449 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1450 		/* ups. */
1451 		mib_iflist_bad = 1;
1452 		return;
1453 	}
1454 
1455 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast)) {
1456 		/* ups. */
1457 		mib_iflist_bad = 1;
1458 		return;
1459 	}
1460 }
1461 
1462 /*
1463  * Modify an IFA.
1464  */
1465 int
1466 mib_modify_ifa(struct mibifa *ifa)
1467 {
1468 	struct mibif *ifp;
1469 
1470 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1471 		/* ups. */
1472 		mib_iflist_bad = 1;
1473 		return (-1);
1474 	}
1475 
1476 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast)) {
1477 		/* ups. */
1478 		mib_iflist_bad = 1;
1479 		return (-1);
1480 	}
1481 
1482 	if (verify_ifa(ifp->name, ifa)) {
1483 		/* ups. */
1484 		mib_iflist_bad = 1;
1485 		return (-1);
1486 	}
1487 
1488 	return (0);
1489 }
1490 
1491 /*
1492  * Destroy a freshly created interface address. Don't bother to wait for
1493  * the routing socket.
1494  */
1495 void
1496 mib_uncreate_ifa(struct mibifa *ifa)
1497 {
1498 	struct mibif *ifp;
1499 
1500 	if ((ifp = mib_find_if(ifa->ifindex)) == NULL) {
1501 		/* ups. */
1502 		mib_iflist_bad = 1;
1503 		return;
1504 	}
1505 	if (siocdifaddr(ifp->name, ifa->inaddr)) {
1506 		/* ups. */
1507 		mib_iflist_bad = 1;
1508 		return;
1509 	}
1510 
1511 	destroy_ifa(ifa);
1512 }
1513 
1514 /*
1515  * Create a new ifa and verify it
1516  */
1517 struct mibifa *
1518 mib_create_ifa(u_int ifindex, struct in_addr addr, struct in_addr mask,
1519     struct in_addr bcast)
1520 {
1521 	struct mibif *ifp;
1522 	struct mibifa *ifa;
1523 
1524 	if ((ifp = mib_find_if(ifindex)) == NULL)
1525 		return (NULL);
1526 	if ((ifa = alloc_ifa(ifindex, addr)) == NULL)
1527 		return (NULL);
1528 	ifa->inmask = mask;
1529 	ifa->inbcast = bcast;
1530 
1531 	if (siocaifaddr(ifp->name, ifa->inaddr, ifa->inmask, ifa->inbcast)) {
1532 		syslog(LOG_ERR, "%s: %m", __func__);
1533 		destroy_ifa(ifa);
1534 		return (NULL);
1535 	}
1536 	if (verify_ifa(ifp->name, ifa)) {
1537 		destroy_ifa(ifa);
1538 		return (NULL);
1539 	}
1540 	return (ifa);
1541 }
1542 
1543 /*
1544  * Get all cloning interfaces and make them dynamic.
1545  * Hah! Whe should probably do this on a periodic basis (XXX).
1546  */
1547 static void
1548 get_cloners(void)
1549 {
1550 	struct if_clonereq req;
1551 	char *buf, *cp;
1552 	int i;
1553 
1554 	memset(&req, 0, sizeof(req));
1555 	if (ioctl(mib_netsock, SIOCIFGCLONERS, &req) == -1) {
1556 		syslog(LOG_ERR, "get cloners: %m");
1557 		return;
1558 	}
1559 	if ((buf = malloc(req.ifcr_total * IFNAMSIZ)) == NULL) {
1560 		syslog(LOG_ERR, "%m");
1561 		return;
1562 	}
1563 	req.ifcr_count = req.ifcr_total;
1564 	req.ifcr_buffer = buf;
1565 	if (ioctl(mib_netsock, SIOCIFGCLONERS, &req) == -1) {
1566 		syslog(LOG_ERR, "get cloners: %m");
1567 		free(buf);
1568 		return;
1569 	}
1570 	for (cp = buf, i = 0; i < req.ifcr_total; i++, cp += IFNAMSIZ)
1571 		mib_if_set_dyn(cp);
1572 	free(buf);
1573 }
1574 
1575 /*
1576  * Idle function
1577  */
1578 static void
1579 mibII_idle(void *arg __unused)
1580 {
1581 	struct mibifa *ifa;
1582 
1583 	if (mib_iflist_bad) {
1584 		TAILQ_FOREACH(ifa, &mibifa_list, link)
1585 			ifa->flags &= ~MIBIFA_DESTROYED;
1586 
1587 		/* assume, that all cloning interfaces are dynamic */
1588 		get_cloners();
1589 
1590 		mib_refresh_iflist();
1591 		update_ifa_info();
1592 		mib_arp_update();
1593 		mib_iflist_bad = 0;
1594 	}
1595 
1596 	mib_arp_update();
1597 }
1598 
1599 
1600 /*
1601  * Start the module
1602  */
1603 static void
1604 mibII_start(void)
1605 {
1606 	if ((route_fd = fd_select(route, route_input, NULL, module)) == NULL) {
1607 		syslog(LOG_ERR, "fd_select(route): %m");
1608 		return;
1609 	}
1610 	mib_refresh_iflist();
1611 	update_ifa_info();
1612 	mib_arp_update();
1613 	(void)mib_fetch_route();
1614 	mib_iftable_last_change = 0;
1615 	mib_ifstack_last_change = 0;
1616 
1617 	ifmib_reg = or_register(&oid_ifMIB,
1618 	    "The MIB module to describe generic objects for network interface"
1619 	    " sub-layers.", module);
1620 
1621 	ipmib_reg = or_register(&oid_ipMIB,
1622 	   "The MIB module for managing IP and ICMP implementations, but "
1623 	   "excluding their management of IP routes.", module);
1624 
1625 	tcpmib_reg = or_register(&oid_tcpMIB,
1626 	   "The MIB module for managing TCP implementations.", module);
1627 
1628 	udpmib_reg = or_register(&oid_udpMIB,
1629 	   "The MIB module for managing UDP implementations.", module);
1630 
1631 	ipForward_reg = or_register(&oid_ipForward,
1632 	   "The MIB module for the display of CIDR multipath IP Routes.",
1633 	   module);
1634 
1635 	mibII_poll_timer = NULL;
1636 	mibII_poll_ticks = MIBII_POLL_TICKS;
1637 	mibif_restart_mibII_poll_timer();
1638 }
1639 
1640 /*
1641  * Initialize the module
1642  */
1643 static int
1644 mibII_init(struct lmodule *mod, int argc __unused, char *argv[] __unused)
1645 {
1646 	size_t len;
1647 
1648 	module = mod;
1649 
1650 	len = sizeof(clockinfo);
1651 	if (sysctlbyname("kern.clockrate", &clockinfo, &len, NULL, 0) == -1) {
1652 		syslog(LOG_ERR, "kern.clockrate: %m");
1653 		return (-1);
1654 	}
1655 	if (len != sizeof(clockinfo)) {
1656 		syslog(LOG_ERR, "kern.clockrate: wrong size");
1657 		return (-1);
1658 	}
1659 
1660 	if ((route = socket(PF_ROUTE, SOCK_RAW, AF_UNSPEC)) == -1) {
1661 		syslog(LOG_ERR, "PF_ROUTE: %m");
1662 		return (-1);
1663 	}
1664 
1665 	if ((mib_netsock = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {
1666 		syslog(LOG_ERR, "PF_INET: %m");
1667 		(void)close(route);
1668 		return (-1);
1669 	}
1670 	(void)shutdown(mib_netsock, SHUT_RDWR);
1671 
1672 	/* assume, that all cloning interfaces are dynamic */
1673 	get_cloners();
1674 
1675 	return (0);
1676 }
1677 
1678 static int
1679 mibII_fini(void)
1680 {
1681 	if (mibII_poll_timer != NULL ) {
1682 		timer_stop(mibII_poll_timer);
1683 		mibII_poll_timer = NULL;
1684 	}
1685 
1686 	if (route_fd != NULL)
1687 		fd_deselect(route_fd);
1688 	if (route != -1)
1689 		(void)close(route);
1690 	if (mib_netsock != -1)
1691 		(void)close(mib_netsock);
1692 	/* XXX free memory */
1693 
1694 	or_unregister(ipForward_reg);
1695 	or_unregister(udpmib_reg);
1696 	or_unregister(tcpmib_reg);
1697 	or_unregister(ipmib_reg);
1698 	or_unregister(ifmib_reg);
1699 
1700 	return (0);
1701 }
1702 
1703 static void
1704 mibII_loading(const struct lmodule *mod, int loaded)
1705 {
1706 	struct mibif *ifp;
1707 
1708 	if (loaded == 1)
1709 		return;
1710 
1711 	TAILQ_FOREACH(ifp, &mibif_list, link)
1712 		if (ifp->xnotify_mod == mod) {
1713 			ifp->xnotify_mod = NULL;
1714 			ifp->xnotify_data = NULL;
1715 			ifp->xnotify = NULL;
1716 		}
1717 
1718 	mib_unregister_newif(mod);
1719 }
1720 
1721 const struct snmp_module config = {
1722 	"This module implements the interface and ip groups.",
1723 	mibII_init,
1724 	mibII_fini,
1725 	NULL,		/* idle */
1726 	NULL,		/* dump */
1727 	NULL,		/* config */
1728 	mibII_start,
1729 	NULL,
1730 	mibII_ctree,
1731 	mibII_CTREE_SIZE,
1732 	mibII_loading
1733 };
1734 
1735 /*
1736  * Should have a list of these attached to each interface.
1737  */
1738 void *
1739 mibif_notify(struct mibif *ifp, const struct lmodule *mod,
1740     mibif_notify_f func, void *data)
1741 {
1742 	ifp->xnotify = func;
1743 	ifp->xnotify_data = data;
1744 	ifp->xnotify_mod = mod;
1745 
1746 	return (ifp);
1747 }
1748 
1749 void
1750 mibif_unnotify(void *arg)
1751 {
1752 	struct mibif *ifp = arg;
1753 
1754 	ifp->xnotify = NULL;
1755 	ifp->xnotify_data = NULL;
1756 	ifp->xnotify_mod = NULL;
1757 }
1758