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