if_tun.c revision 205222
1/*	$NetBSD: if_tun.c,v 1.14 1994/06/29 06:36:25 cgd Exp $	*/
2
3/*-
4 * Copyright (c) 1988, Julian Onions <jpo@cs.nott.ac.uk>
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: head/sys/net/if_tun.c 205222 2010-03-16 17:59:12Z qingli $
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 */
69struct 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 */
109static struct mtx tunmtx;
110static MALLOC_DEFINE(M_TUN, TUNNAME, "Tunnel Interface");
111static int tundebug = 0;
112static int tundclone = 1;
113static struct clonedevs *tunclones;
114static TAILQ_HEAD(,tun_softc)	tunhead = TAILQ_HEAD_INITIALIZER(tunhead);
115SYSCTL_INT(_debug, OID_AUTO, if_tun_debug, CTLFLAG_RW, &tundebug, 0, "");
116
117SYSCTL_DECL(_net_link);
118SYSCTL_NODE(_net_link, OID_AUTO, tun, CTLFLAG_RW, 0,
119    "IP tunnel software network interface.");
120SYSCTL_INT(_net_link_tun, OID_AUTO, devfs_cloning, CTLFLAG_RW, &tundclone, 0,
121    "Enable legacy devfs interface creation.");
122
123TUNABLE_INT("net.link.tun.devfs_cloning", &tundclone);
124
125static void	tunclone(void *arg, struct ucred *cred, char *name,
126		    int namelen, struct cdev **dev);
127static void	tuncreate(const char *name, struct cdev *dev);
128static int	tunifioctl(struct ifnet *, u_long, caddr_t);
129static int	tuninit(struct ifnet *);
130static int	tunmodevent(module_t, int, void *);
131static int	tunoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
132		    struct route *ro);
133static void	tunstart(struct ifnet *);
134
135static int	tun_clone_create(struct if_clone *, int, caddr_t);
136static void	tun_clone_destroy(struct ifnet *);
137
138IFC_SIMPLE_DECLARE(tun, 0);
139
140static d_open_t		tunopen;
141static d_close_t	tunclose;
142static d_read_t		tunread;
143static d_write_t	tunwrite;
144static d_ioctl_t	tunioctl;
145static d_poll_t		tunpoll;
146static d_kqfilter_t	tunkqfilter;
147
148static int		tunkqread(struct knote *, long);
149static int		tunkqwrite(struct knote *, long);
150static void		tunkqdetach(struct knote *);
151
152static struct filterops tun_read_filterops = {
153	.f_isfd =	1,
154	.f_attach =	NULL,
155	.f_detach =	tunkqdetach,
156	.f_event =	tunkqread,
157};
158
159static struct filterops tun_write_filterops = {
160	.f_isfd =	1,
161	.f_attach =	NULL,
162	.f_detach =	tunkqdetach,
163	.f_event =	tunkqwrite,
164};
165
166static struct cdevsw tun_cdevsw = {
167	.d_version =	D_VERSION,
168	.d_flags =	D_PSEUDO | D_NEEDGIANT | 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
179static int
180tun_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
197static void
198tunclone(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
244static void
245tun_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
269static void
270tun_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
280static int
281tunmodevent(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
317static moduledata_t tun_mod = {
318	"if_tun",
319	tunmodevent,
320	0
321};
322
323DECLARE_MODULE(if_tun, tun_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
324
325static void
326tunstart(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	if (tp->tun_flags & TUN_ASYNC && tp->tun_sigio) {
348		mtx_unlock(&tp->tun_mtx);
349		pgsigio(&tp->tun_sigio, SIGIO, 0);
350	} else
351		mtx_unlock(&tp->tun_mtx);
352	selwakeuppri(&tp->tun_rsel, PZERO + 1);
353	KNOTE_UNLOCKED(&tp->tun_rsel.si_note, 0);
354}
355
356/* XXX: should return an error code so it can fail. */
357static void
358tuncreate(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, NULL);
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
399static int
400tunopen(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	mtx_unlock(&tp->tun_mtx);
430	ifp = TUN2IFP(tp);
431	if_link_state_change(ifp, LINK_STATE_UP);
432	TUNDEBUG(ifp, "open\n");
433
434	return (0);
435}
436
437/*
438 * tunclose - close the device - mark i/f down & delete
439 * routing info
440 */
441static	int
442tunclose(struct cdev *dev, int foo, int bar, struct thread *td)
443{
444	struct tun_softc *tp;
445	struct ifnet *ifp;
446	int s;
447
448	tp = dev->si_drv1;
449	ifp = TUN2IFP(tp);
450
451	mtx_lock(&tp->tun_mtx);
452	tp->tun_flags &= ~TUN_OPEN;
453	tp->tun_pid = 0;
454	mtx_unlock(&tp->tun_mtx);
455
456	/*
457	 * junk all pending output
458	 */
459	CURVNET_SET(ifp->if_vnet);
460	s = splimp();
461	IFQ_PURGE(&ifp->if_snd);
462	splx(s);
463
464	if (ifp->if_flags & IFF_UP) {
465		s = splimp();
466		if_down(ifp);
467		splx(s);
468	}
469
470	/* Delete all addresses and routes which reference this interface. */
471	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
472		struct ifaddr *ifa;
473
474		s = splimp();
475		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
476			/* deal w/IPv4 PtP destination; unlocked read */
477			if (ifa->ifa_addr->sa_family == AF_INET) {
478				rtinit(ifa, (int)RTM_DELETE,
479				    tp->tun_flags & TUN_DSTADDR ? RTF_HOST : 0);
480			} else {
481				rtinit(ifa, (int)RTM_DELETE, 0);
482			}
483		}
484		if_purgeaddrs(ifp);
485		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
486		splx(s);
487	}
488	if_link_state_change(ifp, LINK_STATE_DOWN);
489	CURVNET_RESTORE();
490
491	mtx_lock(&tp->tun_mtx);
492	funsetown(&tp->tun_sigio);
493	selwakeuppri(&tp->tun_rsel, PZERO + 1);
494	KNOTE_UNLOCKED(&tp->tun_rsel.si_note, 0);
495	TUNDEBUG (ifp, "closed\n");
496
497	cv_broadcast(&tp->tun_cv);
498	mtx_unlock(&tp->tun_mtx);
499	return (0);
500}
501
502static int
503tuninit(struct ifnet *ifp)
504{
505#ifdef INET
506	struct tun_softc *tp = ifp->if_softc;
507	struct ifaddr *ifa;
508#endif
509	int error = 0;
510
511	TUNDEBUG(ifp, "tuninit\n");
512
513	ifp->if_flags |= IFF_UP;
514	ifp->if_drv_flags |= IFF_DRV_RUNNING;
515	getmicrotime(&ifp->if_lastchange);
516
517#ifdef INET
518	if_addr_rlock(ifp);
519	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
520		if (ifa->ifa_addr->sa_family == AF_INET) {
521			struct sockaddr_in *si;
522
523			si = (struct sockaddr_in *)ifa->ifa_addr;
524			mtx_lock(&tp->tun_mtx);
525			if (si->sin_addr.s_addr)
526				tp->tun_flags |= TUN_IASET;
527
528			si = (struct sockaddr_in *)ifa->ifa_dstaddr;
529			if (si && si->sin_addr.s_addr)
530				tp->tun_flags |= TUN_DSTADDR;
531			mtx_unlock(&tp->tun_mtx);
532		}
533	}
534	if_addr_runlock(ifp);
535#endif
536	return (error);
537}
538
539/*
540 * Process an ioctl request.
541 */
542static int
543tunifioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
544{
545	struct ifreq *ifr = (struct ifreq *)data;
546	struct tun_softc *tp = ifp->if_softc;
547	struct ifstat *ifs;
548	int		error = 0, s;
549
550	s = splimp();
551	switch(cmd) {
552	case SIOCGIFSTATUS:
553		ifs = (struct ifstat *)data;
554		mtx_lock(&tp->tun_mtx);
555		if (tp->tun_pid)
556			sprintf(ifs->ascii + strlen(ifs->ascii),
557			    "\tOpened by PID %d\n", tp->tun_pid);
558		mtx_unlock(&tp->tun_mtx);
559		break;
560	case SIOCSIFADDR:
561		error = tuninit(ifp);
562		TUNDEBUG(ifp, "address set, error=%d\n", error);
563		break;
564	case SIOCSIFDSTADDR:
565		error = tuninit(ifp);
566		TUNDEBUG(ifp, "destination address set, error=%d\n", error);
567		break;
568	case SIOCSIFMTU:
569		ifp->if_mtu = ifr->ifr_mtu;
570		TUNDEBUG(ifp, "mtu set\n");
571		break;
572	case SIOCSIFFLAGS:
573	case SIOCADDMULTI:
574	case SIOCDELMULTI:
575		break;
576	default:
577		error = EINVAL;
578	}
579	splx(s);
580	return (error);
581}
582
583/*
584 * tunoutput - queue packets from higher level ready to put out.
585 */
586static int
587tunoutput(
588	struct ifnet *ifp,
589	struct mbuf *m0,
590	struct sockaddr *dst,
591	struct route *ro)
592{
593	struct tun_softc *tp = ifp->if_softc;
594	u_short cached_tun_flags;
595	int error;
596	u_int32_t af;
597
598	TUNDEBUG (ifp, "tunoutput\n");
599
600#ifdef MAC
601	error = mac_ifnet_check_transmit(ifp, m0);
602	if (error) {
603		m_freem(m0);
604		return (error);
605	}
606#endif
607
608	/* Could be unlocked read? */
609	mtx_lock(&tp->tun_mtx);
610	cached_tun_flags = tp->tun_flags;
611	mtx_unlock(&tp->tun_mtx);
612	if ((cached_tun_flags & TUN_READY) != TUN_READY) {
613		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
614		m_freem (m0);
615		return (EHOSTDOWN);
616	}
617
618	if ((ifp->if_flags & IFF_UP) != IFF_UP) {
619		m_freem (m0);
620		return (EHOSTDOWN);
621	}
622
623	/* BPF writes need to be handled specially. */
624	if (dst->sa_family == AF_UNSPEC) {
625		bcopy(dst->sa_data, &af, sizeof(af));
626		dst->sa_family = af;
627	}
628
629	if (bpf_peers_present(ifp->if_bpf)) {
630		af = dst->sa_family;
631		bpf_mtap2(ifp->if_bpf, &af, sizeof(af), m0);
632	}
633
634	/* prepend sockaddr? this may abort if the mbuf allocation fails */
635	if (cached_tun_flags & TUN_LMODE) {
636		/* allocate space for sockaddr */
637		M_PREPEND(m0, dst->sa_len, M_DONTWAIT);
638
639		/* if allocation failed drop packet */
640		if (m0 == NULL) {
641			ifp->if_iqdrops++;
642			ifp->if_oerrors++;
643			return (ENOBUFS);
644		} else {
645			bcopy(dst, m0->m_data, dst->sa_len);
646		}
647	}
648
649	if (cached_tun_flags & TUN_IFHEAD) {
650		/* Prepend the address family */
651		M_PREPEND(m0, 4, M_DONTWAIT);
652
653		/* if allocation failed drop packet */
654		if (m0 == NULL) {
655			ifp->if_iqdrops++;
656			ifp->if_oerrors++;
657			return (ENOBUFS);
658		} else
659			*(u_int32_t *)m0->m_data = htonl(dst->sa_family);
660	} else {
661#ifdef INET
662		if (dst->sa_family != AF_INET)
663#endif
664		{
665			m_freem(m0);
666			return (EAFNOSUPPORT);
667		}
668	}
669
670	error = (ifp->if_transmit)(ifp, m0);
671	if (error) {
672		ifp->if_collisions++;
673		return (ENOBUFS);
674	}
675	ifp->if_opackets++;
676	return (0);
677}
678
679/*
680 * the cdevsw interface is now pretty minimal.
681 */
682static	int
683tunioctl(struct cdev *dev, u_long cmd, caddr_t data, int flag, struct thread *td)
684{
685	int		s;
686	int		error;
687	struct tun_softc *tp = dev->si_drv1;
688	struct tuninfo *tunp;
689
690	switch (cmd) {
691	case TUNSIFINFO:
692		tunp = (struct tuninfo *)data;
693		if (tunp->mtu < IF_MINMTU)
694			return (EINVAL);
695		if (TUN2IFP(tp)->if_mtu != tunp->mtu) {
696			error = priv_check(td, PRIV_NET_SETIFMTU);
697			if (error)
698				return (error);
699		}
700		TUN2IFP(tp)->if_mtu = tunp->mtu;
701		TUN2IFP(tp)->if_type = tunp->type;
702		TUN2IFP(tp)->if_baudrate = tunp->baudrate;
703		break;
704	case TUNGIFINFO:
705		tunp = (struct tuninfo *)data;
706		tunp->mtu = TUN2IFP(tp)->if_mtu;
707		tunp->type = TUN2IFP(tp)->if_type;
708		tunp->baudrate = TUN2IFP(tp)->if_baudrate;
709		break;
710	case TUNSDEBUG:
711		tundebug = *(int *)data;
712		break;
713	case TUNGDEBUG:
714		*(int *)data = tundebug;
715		break;
716	case TUNSLMODE:
717		mtx_lock(&tp->tun_mtx);
718		if (*(int *)data) {
719			tp->tun_flags |= TUN_LMODE;
720			tp->tun_flags &= ~TUN_IFHEAD;
721		} else
722			tp->tun_flags &= ~TUN_LMODE;
723		mtx_unlock(&tp->tun_mtx);
724		break;
725	case TUNSIFHEAD:
726		mtx_lock(&tp->tun_mtx);
727		if (*(int *)data) {
728			tp->tun_flags |= TUN_IFHEAD;
729			tp->tun_flags &= ~TUN_LMODE;
730		} else
731			tp->tun_flags &= ~TUN_IFHEAD;
732		mtx_unlock(&tp->tun_mtx);
733		break;
734	case TUNGIFHEAD:
735		/* Could be unlocked read? */
736		mtx_lock(&tp->tun_mtx);
737		*(int *)data = (tp->tun_flags & TUN_IFHEAD) ? 1 : 0;
738		mtx_unlock(&tp->tun_mtx);
739		break;
740	case TUNSIFMODE:
741		/* deny this if UP */
742		if (TUN2IFP(tp)->if_flags & IFF_UP)
743			return(EBUSY);
744
745		switch (*(int *)data & ~IFF_MULTICAST) {
746		case IFF_POINTOPOINT:
747		case IFF_BROADCAST:
748			TUN2IFP(tp)->if_flags &=
749			    ~(IFF_BROADCAST|IFF_POINTOPOINT|IFF_MULTICAST);
750			TUN2IFP(tp)->if_flags |= *(int *)data;
751			break;
752		default:
753			return(EINVAL);
754		}
755		break;
756	case TUNSIFPID:
757		mtx_lock(&tp->tun_mtx);
758		tp->tun_pid = curthread->td_proc->p_pid;
759		mtx_unlock(&tp->tun_mtx);
760		break;
761	case FIONBIO:
762		break;
763	case FIOASYNC:
764		mtx_lock(&tp->tun_mtx);
765		if (*(int *)data)
766			tp->tun_flags |= TUN_ASYNC;
767		else
768			tp->tun_flags &= ~TUN_ASYNC;
769		mtx_unlock(&tp->tun_mtx);
770		break;
771	case FIONREAD:
772		s = splimp();
773		if (!IFQ_IS_EMPTY(&TUN2IFP(tp)->if_snd)) {
774			struct mbuf *mb;
775			IFQ_LOCK(&TUN2IFP(tp)->if_snd);
776			IFQ_POLL_NOLOCK(&TUN2IFP(tp)->if_snd, mb);
777			for( *(int *)data = 0; mb != 0; mb = mb->m_next)
778				*(int *)data += mb->m_len;
779			IFQ_UNLOCK(&TUN2IFP(tp)->if_snd);
780		} else
781			*(int *)data = 0;
782		splx(s);
783		break;
784	case FIOSETOWN:
785		return (fsetown(*(int *)data, &tp->tun_sigio));
786
787	case FIOGETOWN:
788		*(int *)data = fgetown(&tp->tun_sigio);
789		return (0);
790
791	/* This is deprecated, FIOSETOWN should be used instead. */
792	case TIOCSPGRP:
793		return (fsetown(-(*(int *)data), &tp->tun_sigio));
794
795	/* This is deprecated, FIOGETOWN should be used instead. */
796	case TIOCGPGRP:
797		*(int *)data = -fgetown(&tp->tun_sigio);
798		return (0);
799
800	default:
801		return (ENOTTY);
802	}
803	return (0);
804}
805
806/*
807 * The cdevsw read interface - reads a packet at a time, or at
808 * least as much of a packet as can be read.
809 */
810static	int
811tunread(struct cdev *dev, struct uio *uio, int flag)
812{
813	struct tun_softc *tp = dev->si_drv1;
814	struct ifnet	*ifp = TUN2IFP(tp);
815	struct mbuf	*m;
816	int		error=0, len, s;
817
818	TUNDEBUG (ifp, "read\n");
819	mtx_lock(&tp->tun_mtx);
820	if ((tp->tun_flags & TUN_READY) != TUN_READY) {
821		mtx_unlock(&tp->tun_mtx);
822		TUNDEBUG (ifp, "not ready 0%o\n", tp->tun_flags);
823		return (EHOSTDOWN);
824	}
825
826	tp->tun_flags &= ~TUN_RWAIT;
827	mtx_unlock(&tp->tun_mtx);
828
829	s = splimp();
830	do {
831		IFQ_DEQUEUE(&ifp->if_snd, m);
832		if (m == NULL) {
833			if (flag & O_NONBLOCK) {
834				splx(s);
835				return (EWOULDBLOCK);
836			}
837			mtx_lock(&tp->tun_mtx);
838			tp->tun_flags |= TUN_RWAIT;
839			mtx_unlock(&tp->tun_mtx);
840			if ((error = tsleep(tp, PCATCH | (PZERO + 1),
841					"tunread", 0)) != 0) {
842				splx(s);
843				return (error);
844			}
845		}
846	} while (m == NULL);
847	splx(s);
848
849	while (m && uio->uio_resid > 0 && error == 0) {
850		len = min(uio->uio_resid, m->m_len);
851		if (len != 0)
852			error = uiomove(mtod(m, void *), len, uio);
853		m = m_free(m);
854	}
855
856	if (m) {
857		TUNDEBUG(ifp, "Dropping mbuf\n");
858		m_freem(m);
859	}
860	return (error);
861}
862
863/*
864 * the cdevsw write interface - an atomic write is a packet - or else!
865 */
866static	int
867tunwrite(struct cdev *dev, struct uio *uio, int flag)
868{
869	struct tun_softc *tp = dev->si_drv1;
870	struct ifnet	*ifp = TUN2IFP(tp);
871	struct mbuf	*m;
872	int		error = 0;
873	uint32_t	family;
874	int 		isr;
875
876	TUNDEBUG(ifp, "tunwrite\n");
877
878	if ((ifp->if_flags & IFF_UP) != IFF_UP)
879		/* ignore silently */
880		return (0);
881
882	if (uio->uio_resid == 0)
883		return (0);
884
885	if (uio->uio_resid < 0 || uio->uio_resid > TUNMRU) {
886		TUNDEBUG(ifp, "len=%zd!\n", uio->uio_resid);
887		return (EIO);
888	}
889
890	if ((m = m_uiotombuf(uio, M_DONTWAIT, 0, 0, M_PKTHDR)) == NULL) {
891		ifp->if_ierrors++;
892		return (error);
893	}
894
895	m->m_pkthdr.rcvif = ifp;
896#ifdef MAC
897	mac_ifnet_create_mbuf(ifp, m);
898#endif
899
900	/* Could be unlocked read? */
901	mtx_lock(&tp->tun_mtx);
902	if (tp->tun_flags & TUN_IFHEAD) {
903		mtx_unlock(&tp->tun_mtx);
904		if (m->m_len < sizeof(family) &&
905		    (m = m_pullup(m, sizeof(family))) == NULL)
906			return (ENOBUFS);
907		family = ntohl(*mtod(m, u_int32_t *));
908		m_adj(m, sizeof(family));
909	} else {
910		mtx_unlock(&tp->tun_mtx);
911		family = AF_INET;
912	}
913
914	BPF_MTAP2(ifp, &family, sizeof(family), m);
915
916	switch (family) {
917#ifdef INET
918	case AF_INET:
919		isr = NETISR_IP;
920		break;
921#endif
922#ifdef INET6
923	case AF_INET6:
924		isr = NETISR_IPV6;
925		break;
926#endif
927#ifdef IPX
928	case AF_IPX:
929		isr = NETISR_IPX;
930		break;
931#endif
932#ifdef NETATALK
933	case AF_APPLETALK:
934		isr = NETISR_ATALK2;
935		break;
936#endif
937	default:
938		m_freem(m);
939		return (EAFNOSUPPORT);
940	}
941	/* First chunk of an mbuf contains good junk */
942	if (harvest.point_to_point)
943		random_harvest(m, 16, 3, 0, RANDOM_NET);
944	ifp->if_ibytes += m->m_pkthdr.len;
945	ifp->if_ipackets++;
946	CURVNET_SET(ifp->if_vnet);
947	netisr_dispatch(isr, m);
948	CURVNET_RESTORE();
949	return (0);
950}
951
952/*
953 * tunpoll - the poll interface, this is only useful on reads
954 * really. The write detect always returns true, write never blocks
955 * anyway, it either accepts the packet or drops it.
956 */
957static	int
958tunpoll(struct cdev *dev, int events, struct thread *td)
959{
960	int		s;
961	struct tun_softc *tp = dev->si_drv1;
962	struct ifnet	*ifp = TUN2IFP(tp);
963	int		revents = 0;
964	struct mbuf	*m;
965
966	s = splimp();
967	TUNDEBUG(ifp, "tunpoll\n");
968
969	if (events & (POLLIN | POLLRDNORM)) {
970		IFQ_LOCK(&ifp->if_snd);
971		IFQ_POLL_NOLOCK(&ifp->if_snd, m);
972		if (m != NULL) {
973			TUNDEBUG(ifp, "tunpoll q=%d\n", ifp->if_snd.ifq_len);
974			revents |= events & (POLLIN | POLLRDNORM);
975		} else {
976			TUNDEBUG(ifp, "tunpoll waiting\n");
977			selrecord(td, &tp->tun_rsel);
978		}
979		IFQ_UNLOCK(&ifp->if_snd);
980	}
981	if (events & (POLLOUT | POLLWRNORM))
982		revents |= events & (POLLOUT | POLLWRNORM);
983
984	splx(s);
985	return (revents);
986}
987
988/*
989 * tunkqfilter - support for the kevent() system call.
990 */
991static int
992tunkqfilter(struct cdev *dev, struct knote *kn)
993{
994	int			s;
995	struct tun_softc	*tp = dev->si_drv1;
996	struct ifnet	*ifp = TUN2IFP(tp);
997
998	s = splimp();
999	switch(kn->kn_filter) {
1000	case EVFILT_READ:
1001		TUNDEBUG(ifp, "%s kqfilter: EVFILT_READ, minor = %#x\n",
1002		    ifp->if_xname, dev2unit(dev));
1003		kn->kn_fop = &tun_read_filterops;
1004		break;
1005
1006	case EVFILT_WRITE:
1007		TUNDEBUG(ifp, "%s kqfilter: EVFILT_WRITE, minor = %#x\n",
1008		    ifp->if_xname, dev2unit(dev));
1009		kn->kn_fop = &tun_write_filterops;
1010		break;
1011
1012	default:
1013		TUNDEBUG(ifp, "%s kqfilter: invalid filter, minor = %#x\n",
1014		    ifp->if_xname, dev2unit(dev));
1015		splx(s);
1016		return(EINVAL);
1017	}
1018	splx(s);
1019
1020	kn->kn_hook = (caddr_t) dev;
1021	knlist_add(&tp->tun_rsel.si_note, kn, 0);
1022
1023	return (0);
1024}
1025
1026/*
1027 * Return true of there is data in the interface queue.
1028 */
1029static int
1030tunkqread(struct knote *kn, long hint)
1031{
1032	int			ret, s;
1033	struct cdev		*dev = (struct cdev *)(kn->kn_hook);
1034	struct tun_softc	*tp = dev->si_drv1;
1035	struct ifnet	*ifp = TUN2IFP(tp);
1036
1037	s = splimp();
1038	if ((kn->kn_data = ifp->if_snd.ifq_len) > 0) {
1039		TUNDEBUG(ifp,
1040		    "%s have data in the queue.  Len = %d, minor = %#x\n",
1041		    ifp->if_xname, ifp->if_snd.ifq_len, dev2unit(dev));
1042		ret = 1;
1043	} else {
1044		TUNDEBUG(ifp,
1045		    "%s waiting for data, minor = %#x\n", ifp->if_xname,
1046		    dev2unit(dev));
1047		ret = 0;
1048	}
1049	splx(s);
1050
1051	return (ret);
1052}
1053
1054/*
1055 * Always can write, always return MTU in kn->data.
1056 */
1057static int
1058tunkqwrite(struct knote *kn, long hint)
1059{
1060	int			s;
1061	struct tun_softc	*tp = ((struct cdev *)kn->kn_hook)->si_drv1;
1062	struct ifnet	*ifp = TUN2IFP(tp);
1063
1064	s = splimp();
1065	kn->kn_data = ifp->if_mtu;
1066	splx(s);
1067
1068	return (1);
1069}
1070
1071static void
1072tunkqdetach(struct knote *kn)
1073{
1074	struct tun_softc	*tp = ((struct cdev *)kn->kn_hook)->si_drv1;
1075
1076	knlist_remove(&tp->tun_rsel.si_note, kn, 0);
1077}
1078