xref: /freebsd-12.1/sys/net/if_tun.c (revision dfd2f2d4)
1 /*	$NetBSD: if_tun.c,v 1.14 1994/06/29 06:36:25 cgd Exp $	*/
2 
3 /*-
4  * Copyright (c) 1988, Julian Onions <[email protected]>
5  * Nottingham University 1987.
6  *
7  * This source may be freely distributed, however I would be interested
8  * in any changes that are made.
9  *
10  * This driver takes packets off the IP i/f and hands them up to a
11  * user process to have its wicked way with. This driver has it's
12  * roots in a similar driver written by Phil Cockcroft (formerly) at
13  * UCL. This driver is based much more on read/write/poll mode of
14  * operation though.
15  *
16  * $FreeBSD$
17  */
18 
19 #include "opt_atalk.h"
20 #include "opt_inet.h"
21 #include "opt_inet6.h"
22 #include "opt_ipx.h"
23 
24 #include <sys/param.h>
25 #include <sys/priv.h>
26 #include <sys/proc.h>
27 #include <sys/systm.h>
28 #include <sys/jail.h>
29 #include <sys/mbuf.h>
30 #include <sys/module.h>
31 #include <sys/socket.h>
32 #include <sys/fcntl.h>
33 #include <sys/filio.h>
34 #include <sys/sockio.h>
35 #include <sys/ttycom.h>
36 #include <sys/poll.h>
37 #include <sys/selinfo.h>
38 #include <sys/signalvar.h>
39 #include <sys/filedesc.h>
40 #include <sys/kernel.h>
41 #include <sys/sysctl.h>
42 #include <sys/conf.h>
43 #include <sys/uio.h>
44 #include <sys/malloc.h>
45 #include <sys/random.h>
46 
47 #include <net/if.h>
48 #include <net/if_clone.h>
49 #include <net/if_types.h>
50 #include <net/netisr.h>
51 #include <net/route.h>
52 #include <net/vnet.h>
53 #ifdef INET
54 #include <netinet/in.h>
55 #endif
56 #include <net/bpf.h>
57 #include <net/if_tun.h>
58 
59 #include <sys/queue.h>
60 #include <sys/condvar.h>
61 
62 #include <security/mac/mac_framework.h>
63 
64 /*
65  * tun_list is protected by global tunmtx.  Other mutable fields are
66  * protected by tun->tun_mtx, or by their owning subsystem.  tun_dev is
67  * static for the duration of a tunnel interface.
68  */
69 struct tun_softc {
70 	TAILQ_ENTRY(tun_softc)	tun_list;
71 	struct cdev *tun_dev;
72 	u_short	tun_flags;		/* misc flags */
73 #define	TUN_OPEN	0x0001
74 #define	TUN_INITED	0x0002
75 #define	TUN_RCOLL	0x0004
76 #define	TUN_IASET	0x0008
77 #define	TUN_DSTADDR	0x0010
78 #define	TUN_LMODE	0x0020
79 #define	TUN_RWAIT	0x0040
80 #define	TUN_ASYNC	0x0080
81 #define	TUN_IFHEAD	0x0100
82 
83 #define TUN_READY       (TUN_OPEN | TUN_INITED)
84 
85 	/*
86 	 * XXXRW: tun_pid is used to exclusively lock /dev/tun.  Is this
87 	 * actually needed?  Can we just return EBUSY if already open?
88 	 * Problem is that this involved inherent races when a tun device
89 	 * is handed off from one process to another, as opposed to just
90 	 * being slightly stale informationally.
91 	 */
92 	pid_t	tun_pid;		/* owning pid */
93 	struct	ifnet *tun_ifp;		/* the interface */
94 	struct  sigio *tun_sigio;	/* information for async I/O */
95 	struct	selinfo	tun_rsel;	/* read select */
96 	struct mtx	tun_mtx;	/* protect mutable softc fields */
97 	struct cv	tun_cv;		/* protect against ref'd dev destroy */
98 };
99 #define TUN2IFP(sc)	((sc)->tun_ifp)
100 
101 #define TUNDEBUG	if (tundebug) if_printf
102 #define	TUNNAME		"tun"
103 
104 /*
105  * All mutable global variables in if_tun are locked using tunmtx, with
106  * the exception of tundebug, which is used unlocked, and tunclones,
107  * which is static after setup.
108  */
109 static struct mtx tunmtx;
110 static MALLOC_DEFINE(M_TUN, TUNNAME, "Tunnel Interface");
111 static int tundebug = 0;
112 static int tundclone = 1;
113 static struct clonedevs *tunclones;
114 static TAILQ_HEAD(,tun_softc)	tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
115 SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
116 
117 SYSCTL_DECL(_net_link);
118 SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
119     "IP tunnel software network interface.");
120 SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RW, &tundclone, 0,
121     "Enable legacy devfs interface creation.");
122 
123 TUNABLE_INT("net.link.tun.devfs_cloning", &tundclone);
124 
125 static void	tunclone(void *arg, struct ucred *cred, char *name,
126 		    int namelen, struct cdev **dev);
127 static void	tuncreate(const char *name, struct cdev *dev);
128 static int	tunifioctl(struct ifnet *, u_long, caddr_t);
129 static int	tuninit(struct ifnet *);
130 static int	tunmodevent(module_t, int, void *);
131 static int	tunoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
132 		    struct route *ro);
133 static void	tunstart(struct ifnet *);
134 
135 static int	tun_clone_create(struct if_clone *, int, caddr_t);
136 static void	tun_clone_destroy(struct ifnet *);
137 
138 IFC_SIMPLE_DECLARE(tun, 0);
139 
140 static d_open_t		tunopen;
141 static d_close_t	tunclose;
142 static d_read_t		tunread;
143 static d_write_t	tunwrite;
144 static d_ioctl_t	tunioctl;
145 static d_poll_t		tunpoll;
146 static d_kqfilter_t	tunkqfilter;
147 
148 static int		tunkqread(struct knote *, long);
149 static int		tunkqwrite(struct knote *, long);
150 static void		tunkqdetach(struct knote *);
151 
152 static struct filterops tun_read_filterops = {
153 	.f_isfd =	1,
154 	.f_attach =	NULL,
155 	.f_detach =	tunkqdetach,
156 	.f_event =	tunkqread,
157 };
158 
159 static struct filterops tun_write_filterops = {
160 	.f_isfd =	1,
161 	.f_attach =	NULL,
162 	.f_detach =	tunkqdetach,
163 	.f_event =	tunkqwrite,
164 };
165 
166 static struct cdevsw tun_cdevsw = {
167 	.d_version =	D_VERSION,
168 	.d_flags =	D_PSEUDO | D_NEEDMINOR,
169 	.d_open =	tunopen,
170 	.d_close =	tunclose,
171 	.d_read =	tunread,
172 	.d_write =	tunwrite,
173 	.d_ioctl =	tunioctl,
174 	.d_poll =	tunpoll,
175 	.d_kqfilter =	tunkqfilter,
176 	.d_name =	TUNNAME,
177 };
178 
179 static int
180 tun_clone_create(struct if_clone *ifc, int unit, caddr_t params)
181 {
182 	struct cdev *dev;
183 	int i;
184 
185 	/* find any existing device, or allocate new unit number */
186 	i = clone_create(&tunclones, &tun_cdevsw, &unit, &dev, 0);
187 	if (i) {
188 		/* No preexisting struct cdev *, create one */
189 		dev = make_dev(&tun_cdevsw, unit,
190 		    UID_UUCP, GID_DIALER, 0600, "%s%d", ifc->ifc_name, unit);
191 	}
192 	tuncreate(ifc->ifc_name, dev);
193 
194 	return (0);
195 }
196 
197 static void
198 tunclone(void *arg, struct ucred *cred, char *name, int namelen,
199     struct cdev **dev)
200 {
201 	char devname[SPECNAMELEN + 1];
202 	int u, i, append_unit;
203 
204 	if (*dev != NULL)
205 		return;
206 
207 	/*
208 	 * If tun cloning is enabled, only the superuser can create an
209 	 * interface.
210 	 */
211 	if (!tundclone || priv_check_cred(cred, PRIV_NET_IFCREATE, 0) != 0)
212 		return;
213 
214 	if (strcmp(name, TUNNAME) == 0) {
215 		u = -1;
216 	} else if (dev_stdclone(name, NULL, TUNNAME, &u) != 1)
217 		return;	/* Don't recognise the name */
218 	if (u != -1 && u > IF_MAXUNIT)
219 		return;	/* Unit number too high */
220 
221 	if (u == -1)
222 		append_unit = 1;
223 	else
224 		append_unit = 0;
225 
226 	CURVNET_SET(CRED_TO_VNET(cred));
227 	/* find any existing device, or allocate new unit number */
228 	i = clone_create(&tunclones, &tun_cdevsw, &u, dev, 0);
229 	if (i) {
230 		if (append_unit) {
231 			namelen = snprintf(devname, sizeof(devname), "%s%d", name,
232 			    u);
233 			name = devname;
234 		}
235 		/* No preexisting struct cdev *, create one */
236 		*dev = make_dev_credf(MAKEDEV_REF, &tun_cdevsw, u, cred,
237 		    UID_UUCP, GID_DIALER, 0600, "%s", name);
238 	}
239 
240 	if_clone_create(name, namelen, NULL);
241 	CURVNET_RESTORE();
242 }
243 
244 static void
245 tun_destroy(struct tun_softc *tp)
246 {
247 	struct cdev *dev;
248 
249 	/* Unlocked read. */
250 	mtx_lock(&tp->tun_mtx);
251 	if ((tp->tun_flags & TUN_OPEN) != 0)
252 		cv_wait_unlock(&tp->tun_cv, &tp->tun_mtx);
253 	else
254 		mtx_unlock(&tp->tun_mtx);
255 
256 	CURVNET_SET(TUN2IFP(tp)->if_vnet);
257 	dev = tp->tun_dev;
258 	bpfdetach(TUN2IFP(tp));
259 	if_detach(TUN2IFP(tp));
260 	if_free(TUN2IFP(tp));
261 	destroy_dev(dev);
262 	knlist_destroy(&tp->tun_rsel.si_note);
263 	mtx_destroy(&tp->tun_mtx);
264 	cv_destroy(&tp->tun_cv);
265 	free(tp, M_TUN);
266 	CURVNET_RESTORE();
267 }
268 
269 static void
270 tun_clone_destroy(struct ifnet *ifp)
271 {
272 	struct tun_softc *tp = ifp->if_softc;
273 
274 	mtx_lock(&tunmtx);
275 	TAILQ_REMOVE(&tunhead, tp, tun_list);
276 	mtx_unlock(&tunmtx);
277 	tun_destroy(tp);
278 }
279 
280 static int
281 tunmodevent(module_t mod, int type, void *data)
282 {
283 	static eventhandler_tag tag;
284 	struct tun_softc *tp;
285 
286 	switch (type) {
287 	case MOD_LOAD:
288 		mtx_init(&tunmtx, "tunmtx", NULL, MTX_DEF);
289 		clone_setup(&tunclones);
290 		tag = EVENTHANDLER_REGISTER(dev_clone, tunclone, 0, 1000);
291 		if (tag == NULL)
292 			return (ENOMEM);
293 		if_clone_attach(&tun_cloner);
294 		break;
295 	case MOD_UNLOAD:
296 		if_clone_detach(&tun_cloner);
297 		EVENTHANDLER_DEREGISTER(dev_clone, tag);
298 		drain_dev_clone_events();
299 
300 		mtx_lock(&tunmtx);
301 		while ((tp = TAILQ_FIRST(&tunhead)) != NULL) {
302 			TAILQ_REMOVE(&tunhead, tp, tun_list);
303 			mtx_unlock(&tunmtx);
304 			tun_destroy(tp);
305 			mtx_lock(&tunmtx);
306 		}
307 		mtx_unlock(&tunmtx);
308 		clone_cleanup(&tunclones);
309 		mtx_destroy(&tunmtx);
310 		break;
311 	default:
312 		return EOPNOTSUPP;
313 	}
314 	return 0;
315 }
316 
317 static moduledata_t tun_mod = {
318 	"if_tun",
319 	tunmodevent,
320 	0
321 };
322 
323 DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
324 
325 static void
326 tunstart(struct ifnet *ifp)
327 {
328 	struct tun_softc *tp = ifp->if_softc;
329 	struct mbuf *m;
330 
331 	TUNDEBUG(ifp,"%s starting\n", ifp->if_xname);
332 	if (ALTQ_IS_ENABLED(&ifp->if_snd)) {
333 		IFQ_LOCK(&ifp->if_snd);
334 		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
335 		if (m == NULL) {
336 			IFQ_UNLOCK(&ifp->if_snd);
337 			return;
338 		}
339 		IFQ_UNLOCK(&ifp->if_snd);
340 	}
341 
342 	mtx_lock(&tp->tun_mtx);
343 	if (tp->tun_flags & TUN_RWAIT) {
344 		tp->tun_flags &= ~TUN_RWAIT;
345 		wakeup(tp);
346 	}
347 	selwakeuppri(&tp->tun_rsel, PZERO + 1);
348 	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
349 	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
350 		mtx_unlock(&tp->tun_mtx);
351 		pgsigio(&tp->tun_sigio, SIGIO, 0);
352 	} else
353 		mtx_unlock(&tp->tun_mtx);
354 }
355 
356 /* XXX: should return an error code so it can fail. */
357 static void
358 tuncreate(const char *name, struct cdev *dev)
359 {
360 	struct tun_softc *sc;
361 	struct ifnet *ifp;
362 
363 	dev->si_flags &= ~SI_CHEAPCLONE;
364 
365 	sc = malloc(sizeof(*sc), M_TUN, M_WAITOK | M_ZERO);
366 	mtx_init(&sc->tun_mtx, "tun_mtx", NULL, MTX_DEF);
367 	cv_init(&sc->tun_cv, "tun_condvar");
368 	sc->tun_flags = TUN_INITED;
369 	sc->tun_dev = dev;
370 	mtx_lock(&tunmtx);
371 	TAILQ_INSERT_TAIL(&tunhead, sc, tun_list);
372 	mtx_unlock(&tunmtx);
373 
374 	ifp = sc->tun_ifp = if_alloc(IFT_PPP);
375 	if (ifp == NULL)
376 		panic("%s%d: failed to if_alloc() interface.\n",
377 		    name, dev2unit(dev));
378 	if_initname(ifp, name, dev2unit(dev));
379 	ifp->if_mtu = TUNMTU;
380 	ifp->if_ioctl = tunifioctl;
381 	ifp->if_output = tunoutput;
382 	ifp->if_start = tunstart;
383 	ifp->if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
384 	ifp->if_softc = sc;
385 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
386 	ifp->if_snd.ifq_drv_maxlen = 0;
387 	IFQ_SET_READY(&ifp->if_snd);
388 	knlist_init_mtx(&sc->tun_rsel.si_note, &sc->tun_mtx);
389 	ifp->if_capabilities |= IFCAP_LINKSTATE;
390 	ifp->if_capenable |= IFCAP_LINKSTATE;
391 
392 	if_attach(ifp);
393 	bpfattach(ifp, DLT_NULL, sizeof(u_int32_t));
394 	dev->si_drv1 = sc;
395 	TUNDEBUG(ifp, "interface %s is created, minor = %#x\n",
396 	    ifp->if_xname, dev2unit(dev));
397 }
398 
399 static int
400 tunopen(struct cdev *dev, int flag, int mode, struct thread *td)
401 {
402 	struct ifnet	*ifp;
403 	struct tun_softc *tp;
404 
405 	/*
406 	 * XXXRW: Non-atomic test and set of dev->si_drv1 requires
407 	 * synchronization.
408 	 */
409 	tp = dev->si_drv1;
410 	if (!tp) {
411 		tuncreate(TUNNAME, dev);
412 		tp = dev->si_drv1;
413 	}
414 
415 	/*
416 	 * XXXRW: This use of tun_pid is subject to error due to the
417 	 * fact that a reference to the tunnel can live beyond the
418 	 * death of the process that created it.  Can we replace this
419 	 * with a simple busy flag?
420 	 */
421 	mtx_lock(&tp->tun_mtx);
422 	if (tp->tun_pid != 0 && tp->tun_pid != td->td_proc->p_pid) {
423 		mtx_unlock(&tp->tun_mtx);
424 		return (EBUSY);
425 	}
426 	tp->tun_pid = td->td_proc->p_pid;
427 
428 	tp->tun_flags |= TUN_OPEN;
429 	ifp = TUN2IFP(tp);
430 	if_link_state_change(ifp, LINK_STATE_UP);
431 	TUNDEBUG(ifp, "open\n");
432 	mtx_unlock(&tp->tun_mtx);
433 
434 	return (0);
435 }
436 
437 /*
438  * tunclose - close the device - mark i/f down & delete
439  * routing info
440  */
441 static	int
442 tunclose(struct cdev *dev, int foo, int bar, struct thread *td)
443 {
444 	struct tun_softc *tp;
445 	struct ifnet *ifp;
446 
447 	tp = dev->si_drv1;
448 	ifp = TUN2IFP(tp);
449 
450 	mtx_lock(&tp->tun_mtx);
451 	tp->tun_flags &= ~TUN_OPEN;
452 	tp->tun_pid = 0;
453 
454 	/*
455 	 * junk all pending output
456 	 */
457 	CURVNET_SET(ifp->if_vnet);
458 	IFQ_PURGE(&ifp->if_snd);
459 
460 	if (ifp->if_flags & IFF_UP) {
461 		mtx_unlock(&tp->tun_mtx);
462 		if_down(ifp);
463 		mtx_lock(&tp->tun_mtx);
464 	}
465 
466 	/* Delete all addresses and routes which reference this interface. */
467 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
468 		struct ifaddr *ifa;
469 
470 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
471 		mtx_unlock(&tp->tun_mtx);
472 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
473 			/* deal w/IPv4 PtP destination; unlocked read */
474 			if (ifa->ifa_addr->sa_family == AF_INET) {
475 				rtinit(ifa, (int)RTM_DELETE,
476 				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
477 			} else {
478 				rtinit(ifa, (int)RTM_DELETE, 0);
479 			}
480 		}
481 		if_purgeaddrs(ifp);
482 		mtx_lock(&tp->tun_mtx);
483 	}
484 	if_link_state_change(ifp, LINK_STATE_DOWN);
485 	CURVNET_RESTORE();
486 
487 	funsetown(&tp->tun_sigio);
488 	selwakeuppri(&tp->tun_rsel, PZERO + 1);
489 	KNOTE_LOCKED(&tp->tun_rsel.si_note, 0);
490 	TUNDEBUG (ifp, "closed\n");
491 
492 	cv_broadcast(&tp->tun_cv);
493 	mtx_unlock(&tp->tun_mtx);
494 	return (0);
495 }
496 
497 static int
498 tuninit(struct ifnet *ifp)
499 {
500 	struct tun_softc *tp = ifp->if_softc;
501 #ifdef INET
502 	struct ifaddr *ifa;
503 #endif
504 	int error = 0;
505 
506 	TUNDEBUG(ifp, "tuninit\n");
507 
508 	mtx_lock(&tp->tun_mtx);
509 	ifp->if_flags |= IFF_UP;
510 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
511 	getmicrotime(&ifp->if_lastchange);
512 
513 #ifdef INET
514 	if_addr_rlock(ifp);
515 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
516 		if (ifa->ifa_addr->sa_family == AF_INET) {
517 			struct sockaddr_in *si;
518 
519 			si = (struct sockaddr_in *)ifa->ifa_addr;
520 			if (si->sin_addr.s_addr)
521 				tp->tun_flags |= TUN_IASET;
522 
523 			si = (struct sockaddr_in *)ifa->ifa_dstaddr;
524 			if (si && si->sin_addr.s_addr)
525 				tp->tun_flags |= TUN_DSTADDR;
526 		}
527 	}
528 	if_addr_runlock(ifp);
529 #endif
530 	mtx_unlock(&tp->tun_mtx);
531 	return (error);
532 }
533 
534 /*
535  * Process an ioctl request.
536  */
537 static int
538 tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
539 {
540 	struct ifreq *ifr = (struct ifreq *)data;
541 	struct tun_softc *tp = ifp->if_softc;
542 	struct ifstat *ifs;
543 	int		error = 0;
544 
545 	switch(cmd) {
546 	case SIOCGIFSTATUS:
547 		ifs = (struct ifstat *)data;
548 		mtx_lock(&tp->tun_mtx);
549 		if (tp->tun_pid)
550 			sprintf(ifs->ascii + strlen(ifs->ascii),
551 			    "\tOpened by PID %d\n", tp->tun_pid);
552 		mtx_unlock(&tp->tun_mtx);
553 		break;
554 	case SIOCSIFADDR:
555 		error = tuninit(ifp);
556 		TUNDEBUG(ifp, "address set, error=%d\n", error);
557 		break;
558 	case SIOCSIFDSTADDR:
559 		error = tuninit(ifp);
560 		TUNDEBUG(ifp, "destination address set, error=%d\n", error);
561 		break;
562 	case SIOCSIFMTU:
563 		ifp->if_mtu = ifr->ifr_mtu;
564 		TUNDEBUG(ifp, "mtu set\n");
565 		break;
566 	case SIOCSIFFLAGS:
567 	case SIOCADDMULTI:
568 	case SIOCDELMULTI:
569 		break;
570 	default:
571 		error = EINVAL;
572 	}
573 	return (error);
574 }
575 
576 /*
577  * tunoutput - queue packets from higher level ready to put out.
578  */
579 static int
580 tunoutput(
581 	struct ifnet *ifp,
582 	struct mbuf *m0,
583 	struct sockaddr *dst,
584 	struct route *ro)
585 {
586 	struct tun_softc *tp = ifp->if_softc;
587 	u_short cached_tun_flags;
588 	int error;
589 	u_int32_t af;
590 
591 	TUNDEBUG (ifp, "tunoutput\n");
592 
593 #ifdef MAC
594 	error = mac_ifnet_check_transmit(ifp, m0);
595 	if (error) {
596 		m_freem(m0);
597 		return (error);
598 	}
599 #endif
600 
601 	/* Could be unlocked read? */
602 	mtx_lock(&tp->tun_mtx);
603 	cached_tun_flags = tp->tun_flags;
604 	mtx_unlock(&tp->tun_mtx);
605 	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
606 		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
607 		m_freem (m0);
608 		return (EHOSTDOWN);
609 	}
610 
611 	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
612 		m_freem (m0);
613 		return (EHOSTDOWN);
614 	}
615 
616 	/* BPF writes need to be handled specially. */
617 	if (dst->sa_family == AF_UNSPEC) {
618 		bcopy(dst->sa_data, &af, sizeof(af));
619 		dst->sa_family = af;
620 	}
621 
622 	if (bpf_peers_present(ifp->if_bpf)) {
623 		af = dst->sa_family;
624 		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
625 	}
626 
627 	/* prepend sockaddr? this may abort if the mbuf allocation fails */
628 	if (cached_tun_flags & TUN_LMODE) {
629 		/* allocate space for sockaddr */
630 		M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
631 
632 		/* if allocation failed drop packet */
633 		if (m0 == NULL) {
634 			ifp->if_iqdrops++;
635 			ifp->if_oerrors++;
636 			return (ENOBUFS);
637 		} else {
638 			bcopy(dst, m0->m_data, dst->sa_len);
639 		}
640 	}
641 
642 	if (cached_tun_flags & TUN_IFHEAD) {
643 		/* Prepend the address family */
644 		M_PREPEND(m0, 4, M_DONTWAIT);
645 
646 		/* if allocation failed drop packet */
647 		if (m0 == NULL) {
648 			ifp->if_iqdrops++;
649 			ifp->if_oerrors++;
650 			return (ENOBUFS);
651 		} else
652 			*(u_int32_t *)m0->m_data = htonl(dst->sa_family);
653 	} else {
654 #ifdef INET
655 		if (dst->sa_family != AF_INET)
656 #endif
657 		{
658 			m_freem(m0);
659 			return (EAFNOSUPPORT);
660 		}
661 	}
662 
663 	error = (ifp->if_transmit)(ifp, m0);
664 	if (error) {
665 		ifp->if_collisions++;
666 		return (ENOBUFS);
667 	}
668 	ifp->if_opackets++;
669 	return (0);
670 }
671 
672 /*
673  * the cdevsw interface is now pretty minimal.
674  */
675 static	int
676 tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
677 {
678 	int		error;
679 	struct tun_softc *tp = dev->si_drv1;
680 	struct tuninfo *tunp;
681 
682 	switch (cmd) {
683 	case TUNSIFINFO:
684 		tunp = (struct tuninfo *)data;
685 		if (tunp->mtu < IF_MINMTU)
686 			return (EINVAL);
687 		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
688 			error = priv_check(td, PRIV_NET_SETIFMTU);
689 			if (error)
690 				return (error);
691 		}
692 		mtx_lock(&tp->tun_mtx);
693 		TUN2IFP(tp)->if_mtu = tunp->mtu;
694 		TUN2IFP(tp)->if_type = tunp->type;
695 		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
696 		mtx_unlock(&tp->tun_mtx);
697 		break;
698 	case TUNGIFINFO:
699 		tunp = (struct tuninfo *)data;
700 		mtx_lock(&tp->tun_mtx);
701 		tunp->mtu = TUN2IFP(tp)->if_mtu;
702 		tunp->type = TUN2IFP(tp)->if_type;
703 		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
704 		mtx_unlock(&tp->tun_mtx);
705 		break;
706 	case TUNSDEBUG:
707 		tundebug = *(int *)data;
708 		break;
709 	case TUNGDEBUG:
710 		*(int *)data = tundebug;
711 		break;
712 	case TUNSLMODE:
713 		mtx_lock(&tp->tun_mtx);
714 		if (*(int *)data) {
715 			tp->tun_flags |= TUN_LMODE;
716 			tp->tun_flags &= ~TUN_IFHEAD;
717 		} else
718 			tp->tun_flags &= ~TUN_LMODE;
719 		mtx_unlock(&tp->tun_mtx);
720 		break;
721 	case TUNSIFHEAD:
722 		mtx_lock(&tp->tun_mtx);
723 		if (*(int *)data) {
724 			tp->tun_flags |= TUN_IFHEAD;
725 			tp->tun_flags &= ~TUN_LMODE;
726 		} else
727 			tp->tun_flags &= ~TUN_IFHEAD;
728 		mtx_unlock(&tp->tun_mtx);
729 		break;
730 	case TUNGIFHEAD:
731 		mtx_lock(&tp->tun_mtx);
732 		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
733 		mtx_unlock(&tp->tun_mtx);
734 		break;
735 	case TUNSIFMODE:
736 		/* deny this if UP */
737 		if (TUN2IFP(tp)->if_flags & IFF_UP)
738 			return(EBUSY);
739 
740 		switch (*(int *)data & ~IFF_MULTICAST) {
741 		case IFF_POINTOPOINT:
742 		case IFF_BROADCAST:
743 			mtx_lock(&tp->tun_mtx);
744 			TUN2IFP(tp)->if_flags &=
745 			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
746 			TUN2IFP(tp)->if_flags |= *(int *)data;
747 			mtx_unlock(&tp->tun_mtx);
748 			break;
749 		default:
750 			return(EINVAL);
751 		}
752 		break;
753 	case TUNSIFPID:
754 		mtx_lock(&tp->tun_mtx);
755 		tp->tun_pid = curthread->td_proc->p_pid;
756 		mtx_unlock(&tp->tun_mtx);
757 		break;
758 	case FIONBIO:
759 		break;
760 	case FIOASYNC:
761 		mtx_lock(&tp->tun_mtx);
762 		if (*(int *)data)
763 			tp->tun_flags |= TUN_ASYNC;
764 		else
765 			tp->tun_flags &= ~TUN_ASYNC;
766 		mtx_unlock(&tp->tun_mtx);
767 		break;
768 	case FIONREAD:
769 		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
770 			struct mbuf *mb;
771 			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
772 			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
773 			for (*(int *)data = 0; mb != NULL; mb = mb->m_next)
774 				*(int *)data += mb->m_len;
775 			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
776 		} else
777 			*(int *)data = 0;
778 		break;
779 	case FIOSETOWN:
780 		return (fsetown(*(int *)data, &tp->tun_sigio));
781 
782 	case FIOGETOWN:
783 		*(int *)data = fgetown(&tp->tun_sigio);
784 		return (0);
785 
786 	/* This is deprecated, FIOSETOWN should be used instead. */
787 	case TIOCSPGRP:
788 		return (fsetown(-(*(int *)data), &tp->tun_sigio));
789 
790 	/* This is deprecated, FIOGETOWN should be used instead. */
791 	case TIOCGPGRP:
792 		*(int *)data = -fgetown(&tp->tun_sigio);
793 		return (0);
794 
795 	default:
796 		return (ENOTTY);
797 	}
798 	return (0);
799 }
800 
801 /*
802  * The cdevsw read interface - reads a packet at a time, or at
803  * least as much of a packet as can be read.
804  */
805 static	int
806 tunread(struct cdev *dev, struct uio *uio, int flag)
807 {
808 	struct tun_softc *tp = dev->si_drv1;
809 	struct ifnet	*ifp = TUN2IFP(tp);
810 	struct mbuf	*m;
811 	int		error=0, len;
812 
813 	TUNDEBUG (ifp, "read\n");
814 	mtx_lock(&tp->tun_mtx);
815 	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
816 		mtx_unlock(&tp->tun_mtx);
817 		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
818 		return (EHOSTDOWN);
819 	}
820 
821 	tp->tun_flags &= ~TUN_RWAIT;
822 
823 	do {
824 		IFQ_DEQUEUE(&ifp->if_snd, m);
825 		if (m == NULL) {
826 			if (flag & O_NONBLOCK) {
827 				mtx_unlock(&tp->tun_mtx);
828 				return (EWOULDBLOCK);
829 			}
830 			tp->tun_flags |= TUN_RWAIT;
831 			error = mtx_sleep(tp, &tp->tun_mtx, PCATCH | (PZERO + 1),
832 			    "tunread", 0);
833 			if (error != 0) {
834 				mtx_unlock(&tp->tun_mtx);
835 				return (error);
836 			}
837 		}
838 	} while (m == NULL);
839 	mtx_unlock(&tp->tun_mtx);
840 
841 	while (m && uio->uio_resid > 0 && error == 0) {
842 		len = min(uio->uio_resid, m->m_len);
843 		if (len != 0)
844 			error = uiomove(mtod(m, void *), len, uio);
845 		m = m_free(m);
846 	}
847 
848 	if (m) {
849 		TUNDEBUG(ifp, "Dropping mbuf\n");
850 		m_freem(m);
851 	}
852 	return (error);
853 }
854 
855 /*
856  * the cdevsw write interface - an atomic write is a packet - or else!
857  */
858 static	int
859 tunwrite(struct cdev *dev, struct uio *uio, int flag)
860 {
861 	struct tun_softc *tp = dev->si_drv1;
862 	struct ifnet	*ifp = TUN2IFP(tp);
863 	struct mbuf	*m;
864 	int		error = 0;
865 	uint32_t	family;
866 	int 		isr;
867 
868 	TUNDEBUG(ifp, "tunwrite\n");
869 
870 	if ((ifp->if_flags & IFF_UP) != IFF_UP)
871 		/* ignore silently */
872 		return (0);
873 
874 	if (uio->uio_resid == 0)
875 		return (0);
876 
877 	if (uio->uio_resid < 0 || uio->uio_resid > TUNMRU) {
878 		TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
879 		return (EIO);
880 	}
881 
882 	if ((m = m_uiotombuf(uio, M_DONTWAIT, 0, 0, M_PKTHDR)) == NULL) {
883 		ifp->if_ierrors++;
884 		return (error);
885 	}
886 
887 	m->m_pkthdr.rcvif = ifp;
888 #ifdef MAC
889 	mac_ifnet_create_mbuf(ifp, m);
890 #endif
891 
892 	/* Could be unlocked read? */
893 	mtx_lock(&tp->tun_mtx);
894 	if (tp->tun_flags & TUN_IFHEAD) {
895 		mtx_unlock(&tp->tun_mtx);
896 		if (m->m_len < sizeof(family) &&
897 		    (m = m_pullup(m, sizeof(family))) == NULL)
898 			return (ENOBUFS);
899 		family = ntohl(*mtod(m, u_int32_t *));
900 		m_adj(m, sizeof(family));
901 	} else {
902 		mtx_unlock(&tp->tun_mtx);
903 		family = AF_INET;
904 	}
905 
906 	BPF_MTAP2(ifp, &family, sizeof(family), m);
907 
908 	switch (family) {
909 #ifdef INET
910 	case AF_INET:
911 		isr = NETISR_IP;
912 		break;
913 #endif
914 #ifdef INET6
915 	case AF_INET6:
916 		isr = NETISR_IPV6;
917 		break;
918 #endif
919 #ifdef IPX
920 	case AF_IPX:
921 		isr = NETISR_IPX;
922 		break;
923 #endif
924 #ifdef NETATALK
925 	case AF_APPLETALK:
926 		isr = NETISR_ATALK2;
927 		break;
928 #endif
929 	default:
930 		m_freem(m);
931 		return (EAFNOSUPPORT);
932 	}
933 	/* First chunk of an mbuf contains good junk */
934 	if (harvest.point_to_point)
935 		random_harvest(m, 16, 3, 0, RANDOM_NET);
936 	ifp->if_ibytes += m->m_pkthdr.len;
937 	ifp->if_ipackets++;
938 	CURVNET_SET(ifp->if_vnet);
939 	netisr_dispatch(isr, m);
940 	CURVNET_RESTORE();
941 	return (0);
942 }
943 
944 /*
945  * tunpoll - the poll interface, this is only useful on reads
946  * really. The write detect always returns true, write never blocks
947  * anyway, it either accepts the packet or drops it.
948  */
949 static	int
950 tunpoll(struct cdev *dev, int events, struct thread *td)
951 {
952 	struct tun_softc *tp = dev->si_drv1;
953 	struct ifnet	*ifp = TUN2IFP(tp);
954 	int		revents = 0;
955 	struct mbuf	*m;
956 
957 	TUNDEBUG(ifp, "tunpoll\n");
958 
959 	if (events & (POLLIN | POLLRDNORM)) {
960 		IFQ_LOCK(&ifp->if_snd);
961 		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
962 		if (m != NULL) {
963 			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
964 			revents |= events & (POLLIN | POLLRDNORM);
965 		} else {
966 			TUNDEBUG(ifp, "tunpoll waiting\n");
967 			selrecord(td, &tp->tun_rsel);
968 		}
969 		IFQ_UNLOCK(&ifp->if_snd);
970 	}
971 	if (events & (POLLOUT | POLLWRNORM))
972 		revents |= events & (POLLOUT | POLLWRNORM);
973 
974 	return (revents);
975 }
976 
977 /*
978  * tunkqfilter - support for the kevent() system call.
979  */
980 static int
981 tunkqfilter(struct cdev *dev, struct knote *kn)
982 {
983 	struct tun_softc	*tp = dev->si_drv1;
984 	struct ifnet	*ifp = TUN2IFP(tp);
985 
986 	switch(kn->kn_filter) {
987 	case EVFILT_READ:
988 		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
989 		    ifp->if_xname, dev2unit(dev));
990 		kn->kn_fop = &tun_read_filterops;
991 		break;
992 
993 	case EVFILT_WRITE:
994 		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
995 		    ifp->if_xname, dev2unit(dev));
996 		kn->kn_fop = &tun_write_filterops;
997 		break;
998 
999 	default:
1000 		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1001 		    ifp->if_xname, dev2unit(dev));
1002 		return(EINVAL);
1003 	}
1004 
1005 	kn->kn_hook = tp;
1006 	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1007 
1008 	return (0);
1009 }
1010 
1011 /*
1012  * Return true of there is data in the interface queue.
1013  */
1014 static int
1015 tunkqread(struct knote *kn, long hint)
1016 {
1017 	int			ret;
1018 	struct tun_softc	*tp = kn->kn_hook;
1019 	struct cdev		*dev = tp->tun_dev;
1020 	struct ifnet	*ifp = TUN2IFP(tp);
1021 
1022 	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1023 		TUNDEBUG(ifp,
1024 		    "%s have data in the queue.  Len = %d, minor = %#x\n",
1025 		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1026 		ret = 1;
1027 	} else {
1028 		TUNDEBUG(ifp,
1029 		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
1030 		    dev2unit(dev));
1031 		ret = 0;
1032 	}
1033 
1034 	return (ret);
1035 }
1036 
1037 /*
1038  * Always can write, always return MTU in kn->data.
1039  */
1040 static int
1041 tunkqwrite(struct knote *kn, long hint)
1042 {
1043 	struct tun_softc	*tp = kn->kn_hook;
1044 	struct ifnet	*ifp = TUN2IFP(tp);
1045 
1046 	kn->kn_data = ifp->if_mtu;
1047 
1048 	return (1);
1049 }
1050 
1051 static void
1052 tunkqdetach(struct knote *kn)
1053 {
1054 	struct tun_softc	*tp = kn->kn_hook;
1055 
1056 	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1057 }
1058