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