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