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