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