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