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