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