Merge commit 'origin/vendor/PAM_PASSWDQC'
[dragonfly.git] / sys / netgraph / tty / ng_tty.c
1
2 /*
3  * ng_tty.c
4  *
5  * Copyright (c) 1996-1999 Whistle Communications, Inc.
6  * All rights reserved.
7  * 
8  * Subject to the following obligations and disclaimer of warranty, use and
9  * redistribution of this software, in source or object code forms, with or
10  * without modifications are expressly permitted by Whistle Communications;
11  * provided, however, that:
12  * 1. Any and all reproductions of the source or object code must include the
13  *    copyright notice above and the following disclaimer of warranties; and
14  * 2. No rights are granted, in any manner or form, to use Whistle
15  *    Communications, Inc. trademarks, including the mark "WHISTLE
16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17  *    such appears in the above copyright notice or in the software.
18  * 
19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35  * OF SUCH DAMAGE.
36  *
37  * Author: Archie Cobbs <archie@freebsd.org>
38  *
39  * $FreeBSD: src/sys/netgraph/ng_tty.c,v 1.7.2.3 2002/02/13 00:43:12 dillon Exp $
40  * $DragonFly: src/sys/netgraph/tty/ng_tty.c,v 1.19 2008/01/06 16:55:52 swildner Exp $
41  * $Whistle: ng_tty.c,v 1.21 1999/11/01 09:24:52 julian Exp $
42  */
43
44 /*
45  * This file implements a terminal line discipline that is also a
46  * netgraph node. Installing this line discipline on a terminal device
47  * instantiates a new netgraph node of this type, which allows access
48  * to the device via the "hook" hook of the node.
49  *
50  * Once the line discipline is installed, you can find out the name
51  * of the corresponding netgraph node via a NGIOCGINFO ioctl().
52  *
53  * Incoming characters are delievered to the hook one at a time, each
54  * in its own mbuf. You may optionally define a ``hotchar,'' which causes
55  * incoming characters to be buffered up until either the hotchar is
56  * seen or the mbuf is full (MHLEN bytes). Then all buffered characters
57  * are immediately delivered.
58  *
59  * NOTE: This node operates at spltty().
60  */
61
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/kernel.h>
65 #include <sys/conf.h>
66 #include <sys/proc.h>
67 #include <sys/priv.h>
68 #include <sys/mbuf.h>
69 #include <sys/malloc.h>
70 #include <sys/fcntl.h>
71 #include <sys/tty.h>
72 #include <sys/ttycom.h>
73 #include <sys/syslog.h>
74 #include <sys/errno.h>
75 #include <sys/ioccom.h>
76 #include <sys/thread2.h>
77
78 #include <netgraph/ng_message.h>
79 #include <netgraph/netgraph.h>
80 #include "ng_tty.h"
81
82 /* Misc defs */
83 #define MAX_MBUFQ               3       /* Max number of queued mbufs */
84 #define NGT_HIWATER             400     /* High water mark on output */
85
86 /* Per-node private info */
87 struct ngt_sc {
88         struct  tty *tp;                /* Terminal device */
89         node_p  node;                   /* Netgraph node */
90         hook_p  hook;                   /* Netgraph hook */
91         struct  mbuf *m;                /* Incoming data buffer */
92         struct  mbuf *qhead, **qtail;   /* Queue of outgoing mbuf's */
93         short   qlen;                   /* Length of queue */
94         short   hotchar;                /* Hotchar, or -1 if none */
95         u_int   flags;                  /* Flags */
96         struct  callout ctimeout;       /* See man timeout(9) */
97 };
98 typedef struct ngt_sc *sc_p;
99
100 /* Flags */
101 #define FLG_TIMEOUT             0x0001  /* A timeout is pending */
102 #define FLG_DEBUG               0x0002
103
104 /* Debugging */
105 #ifdef INVARIANTS
106 #define QUEUECHECK(sc)                                                  \
107     do {                                                                \
108       struct mbuf       **mp;                                           \
109       int               k;                                              \
110                                                                         \
111       for (k = 0, mp = &sc->qhead;                                      \
112         k <= MAX_MBUFQ && *mp;                                          \
113         k++, mp = &(*mp)->m_nextpkt);                                   \
114       if (k != sc->qlen || k > MAX_MBUFQ || *mp || mp != sc->qtail)     \
115         panic("%s: queue", __func__);                           \
116     } while (0)
117 #else
118 #define QUEUECHECK(sc)  do {} while (0)
119 #endif
120
121 /* Line discipline methods */
122 static int      ngt_open(cdev_t dev, struct tty *tp);
123 static int      ngt_close(struct tty *tp, int flag);
124 static int      ngt_read(struct tty *tp, struct uio *uio, int flag);
125 static int      ngt_write(struct tty *tp, struct uio *uio, int flag);
126 static int      ngt_tioctl(struct tty *tp,
127                     u_long cmd, caddr_t data, int flag, struct ucred *cred);
128 static int      ngt_input(int c, struct tty *tp);
129 static int      ngt_start(struct tty *tp);
130
131 /* Netgraph methods */
132 static ng_constructor_t ngt_constructor;
133 static ng_rcvmsg_t      ngt_rcvmsg;
134 static ng_shutdown_t    ngt_shutdown;
135 static ng_newhook_t     ngt_newhook;
136 static ng_rcvdata_t     ngt_rcvdata;
137 static ng_disconnect_t  ngt_disconnect;
138 static int      ngt_mod_event(module_t mod, int event, void *data);
139
140 /* Other stuff */
141 static void     ngt_timeout(void *arg);
142
143 #define ERROUT(x)               do { error = (x); goto done; } while (0)
144
145 /* Line discipline descriptor */
146 static struct linesw ngt_disc = {
147         ngt_open,
148         ngt_close,
149         ngt_read,
150         ngt_write,
151         ngt_tioctl,
152         ngt_input,
153         ngt_start,
154         ttymodem,
155         NG_TTY_DFL_HOTCHAR      /* XXX can't change this in serial driver */
156 };
157
158 /* Netgraph node type descriptor */
159 static struct ng_type typestruct = {
160         NG_VERSION,
161         NG_TTY_NODE_TYPE,
162         ngt_mod_event,
163         ngt_constructor,
164         ngt_rcvmsg,
165         ngt_shutdown,
166         ngt_newhook,
167         NULL,
168         NULL,
169         ngt_rcvdata,
170         ngt_rcvdata,
171         ngt_disconnect,
172         NULL
173 };
174 NETGRAPH_INIT(tty, &typestruct);
175
176 static int ngt_unit;
177 static int ngt_nodeop_ok;       /* OK to create/remove node */
178 static int ngt_ldisc;
179
180 /******************************************************************
181                     LINE DISCIPLINE METHODS
182 ******************************************************************/
183
184 /*
185  * Set our line discipline on the tty.
186  * Called from device open routine or ttioctl() at >= splsofttty()
187  */
188 static int
189 ngt_open(cdev_t dev, struct tty *tp)
190 {
191         struct thread *td = curthread;  /* XXX */
192         char name[sizeof(NG_TTY_NODE_TYPE) + 8];
193         sc_p sc;
194         int error;
195
196         /* Super-user only */
197         if ((error = priv_check(td, PRIV_ROOT)))
198                 return (error);
199         crit_enter();
200
201         /* Already installed? */
202         if (tp->t_line == NETGRAPHDISC) {
203                 sc = (sc_p) tp->t_sc;
204                 if (sc != NULL && sc->tp == tp)
205                         goto done;
206         }
207
208         /* Initialize private struct */
209         MALLOC(sc, sc_p, sizeof(*sc), M_NETGRAPH, M_WAITOK | M_ZERO);
210         sc->tp = tp;
211         sc->hotchar = NG_TTY_DFL_HOTCHAR;
212         sc->qtail = &sc->qhead;
213         QUEUECHECK(sc);
214         callout_init(&sc->ctimeout);
215
216         /* Setup netgraph node */
217         ngt_nodeop_ok = 1;
218         error = ng_make_node_common(&typestruct, &sc->node);
219         ngt_nodeop_ok = 0;
220         if (error) {
221                 FREE(sc, M_NETGRAPH);
222                 goto done;
223         }
224         ksnprintf(name, sizeof(name), "%s%d", typestruct.name, ngt_unit++);
225
226         /* Set back pointers */
227         sc->node->private = sc;
228         tp->t_sc = (caddr_t) sc;
229
230         /* Assign node its name */
231         if ((error = ng_name_node(sc->node, name))) {
232                 log(LOG_ERR, "%s: node name exists?\n", name);
233                 ngt_nodeop_ok = 1;
234                 ng_rmnode(sc->node);
235                 ngt_nodeop_ok = 0;
236                 goto done;
237         }
238
239         /*
240          * Pre-allocate cblocks to the an appropriate amount.
241          * I'm not sure what is appropriate.
242          */
243         ttyflush(tp, FREAD | FWRITE);
244         clist_alloc_cblocks(&tp->t_canq, 0, 0);
245         clist_alloc_cblocks(&tp->t_rawq, 0, 0);
246         clist_alloc_cblocks(&tp->t_outq,
247             MLEN + NGT_HIWATER, MLEN + NGT_HIWATER);
248
249 done:
250         /* Done */
251         crit_exit();
252         return (error);
253 }
254
255 /*
256  * Line specific close routine, called from device close routine
257  * and from ttioctl at >= splsofttty(). This causes the node to
258  * be destroyed as well.
259  */
260 static int
261 ngt_close(struct tty *tp, int flag)
262 {
263         const sc_p sc = (sc_p) tp->t_sc;
264
265         crit_enter();
266         ttyflush(tp, FREAD | FWRITE);
267         clist_free_cblocks(&tp->t_outq);
268         tp->t_line = 0;
269         if (sc != NULL) {
270                 if (sc->flags & FLG_TIMEOUT) {
271                         callout_stop(&sc->ctimeout);
272                         sc->flags &= ~FLG_TIMEOUT;
273                 }
274                 ngt_nodeop_ok = 1;
275                 ng_rmnode(sc->node);
276                 ngt_nodeop_ok = 0;
277                 tp->t_sc = NULL;
278         }
279         crit_exit();
280         return (0);
281 }
282
283 /*
284  * Once the device has been turned into a node, we don't allow reading.
285  */
286 static int
287 ngt_read(struct tty *tp, struct uio *uio, int flag)
288 {
289         return (EIO);
290 }
291
292 /*
293  * Once the device has been turned into a node, we don't allow writing.
294  */
295 static int
296 ngt_write(struct tty *tp, struct uio *uio, int flag)
297 {
298         return (EIO);
299 }
300
301 /*
302  * We implement the NGIOCGINFO ioctl() defined in ng_message.h.
303  */
304 static int
305 ngt_tioctl(struct tty *tp, u_long cmd, caddr_t data, int flag, struct ucred *cred)
306 {
307         const sc_p sc = (sc_p) tp->t_sc;
308         int error = 0;
309
310         crit_enter();
311         switch (cmd) {
312         case NGIOCGINFO:
313             {
314                 struct nodeinfo *const ni = (struct nodeinfo *) data;
315                 const node_p node = sc->node;
316
317                 bzero(ni, sizeof(*ni));
318                 if (node->name)
319                         strncpy(ni->name, node->name, sizeof(ni->name) - 1);
320                 strncpy(ni->type, node->type->name, sizeof(ni->type) - 1);
321                 ni->id = (u_int32_t) node;
322                 ni->hooks = node->numhooks;
323                 break;
324             }
325         default:
326                 ERROUT(ENOIOCTL);
327         }
328 done:
329         crit_exit();
330         return (error);
331 }
332
333 /*
334  * Receive data coming from the device. We get one character at
335  * a time, which is kindof silly.
336  * Only guaranteed to be at splsofttty() or spltty().
337  */
338 static int
339 ngt_input(int c, struct tty *tp)
340 {
341         const sc_p sc = (sc_p) tp->t_sc;
342         const node_p node = sc->node;
343         struct mbuf *m;
344         int error = 0;
345
346         if (!sc || tp != sc->tp)
347                 return (0);
348         crit_enter();
349         if (!sc->hook)
350                 ERROUT(0);
351
352         /* Check for error conditions */
353         if ((tp->t_state & TS_CONNECTED) == 0) {
354                 if (sc->flags & FLG_DEBUG)
355                         log(LOG_DEBUG, "%s: no carrier\n", node->name);
356                 ERROUT(0);
357         }
358         if (c & TTY_ERRORMASK) {
359                 /* framing error or overrun on this char */
360                 if (sc->flags & FLG_DEBUG)
361                         log(LOG_DEBUG, "%s: line error %x\n",
362                             node->name, c & TTY_ERRORMASK);
363                 ERROUT(0);
364         }
365         c &= TTY_CHARMASK;
366
367         /* Get a new header mbuf if we need one */
368         if (!(m = sc->m)) {
369                 MGETHDR(m, MB_DONTWAIT, MT_DATA);
370                 if (!m) {
371                         if (sc->flags & FLG_DEBUG)
372                                 log(LOG_ERR,
373                                     "%s: can't get mbuf\n", node->name);
374                         ERROUT(ENOBUFS);
375                 }
376                 m->m_len = m->m_pkthdr.len = 0;
377                 m->m_pkthdr.rcvif = NULL;
378                 sc->m = m;
379         }
380
381         /* Add char to mbuf */
382         *mtod(m, u_char *) = c;
383         m->m_data++;
384         m->m_len++;
385         m->m_pkthdr.len++;
386
387         /* Ship off mbuf if it's time */
388         if (sc->hotchar == -1 || c == sc->hotchar || m->m_len >= MHLEN) {
389                 m->m_data = m->m_pktdat;
390                 error = ng_queue_data(sc->hook, m, NULL);
391                 sc->m = NULL;
392         }
393 done:
394         crit_exit();
395         return (error);
396 }
397
398 /*
399  * This is called when the device driver is ready for more output.
400  * Called from tty system at splsofttty() or spltty().
401  * Also call from ngt_rcv_data() when a new mbuf is available for output.
402  */
403 static int
404 ngt_start(struct tty *tp)
405 {
406         const sc_p sc = (sc_p) tp->t_sc;
407
408         crit_enter();
409         while (tp->t_outq.c_cc < NGT_HIWATER) { /* XXX 2.2 specific ? */
410                 struct mbuf *m = sc->qhead;
411
412                 /* Remove first mbuf from queue */
413                 if (!m)
414                         break;
415                 if ((sc->qhead = m->m_nextpkt) == NULL)
416                         sc->qtail = &sc->qhead;
417                 sc->qlen--;
418                 QUEUECHECK(sc);
419
420                 /* Send as much of it as possible */
421                 while (m) {
422                         int     sent;
423
424                         sent = m->m_len
425                             - b_to_q(mtod(m, u_char *), m->m_len, &tp->t_outq);
426                         m->m_data += sent;
427                         m->m_len -= sent;
428                         if (m->m_len > 0)
429                                 break;  /* device can't take no more */
430                         m = m_free(m);
431                 }
432
433                 /* Put remainder of mbuf chain (if any) back on queue */
434                 if (m) {
435                         m->m_nextpkt = sc->qhead;
436                         sc->qhead = m;
437                         if (sc->qtail == &sc->qhead)
438                                 sc->qtail = &m->m_nextpkt;
439                         sc->qlen++;
440                         QUEUECHECK(sc);
441                         break;
442                 }
443         }
444
445         /* Call output process whether or not there is any output. We are
446          * being called in lieu of ttstart and must do what it would. */
447         if (tp->t_oproc != NULL)
448                 (*tp->t_oproc) (tp);
449
450         /* This timeout is needed for operation on a pseudo-tty, because the
451          * pty code doesn't call pppstart after it has drained the t_outq. */
452         if (sc->qhead && (sc->flags & FLG_TIMEOUT) == 0) {
453                 callout_reset(&sc->ctimeout, 1, ngt_timeout, sc);
454                 sc->flags |= FLG_TIMEOUT;
455         }
456         crit_exit();
457         return (0);
458 }
459
460 /*
461  * We still have data to output to the device, so try sending more.
462  */
463 static void
464 ngt_timeout(void *arg)
465 {
466         const sc_p sc = (sc_p) arg;
467
468         crit_enter();
469         sc->flags &= ~FLG_TIMEOUT;
470         ngt_start(sc->tp);
471         crit_exit();
472 }
473
474 /******************************************************************
475                     NETGRAPH NODE METHODS
476 ******************************************************************/
477
478 /*
479  * Initialize a new node of this type.
480  *
481  * We only allow nodes to be created as a result of setting
482  * the line discipline on a tty, so always return an error if not.
483  */
484 static int
485 ngt_constructor(node_p *nodep)
486 {
487         if (!ngt_nodeop_ok)
488                 return (EOPNOTSUPP);
489         return (ng_make_node_common(&typestruct, nodep));
490 }
491
492 /*
493  * Add a new hook. There can only be one.
494  */
495 static int
496 ngt_newhook(node_p node, hook_p hook, const char *name)
497 {
498         const sc_p sc = node->private;
499         int error = 0;
500
501         if (strcmp(name, NG_TTY_HOOK))
502                 return (EINVAL);
503         crit_enter();
504         if (sc->hook)
505                 ERROUT(EISCONN);
506         sc->hook = hook;
507 done:
508         crit_exit();
509         return (error);
510 }
511
512 /*
513  * Disconnect the hook
514  */
515 static int
516 ngt_disconnect(hook_p hook)
517 {
518         const sc_p sc = hook->node->private;
519
520         crit_enter();
521         if (hook != sc->hook)
522                 panic(__func__);
523         sc->hook = NULL;
524         m_freem(sc->m);
525         sc->m = NULL;
526         crit_exit();
527         return (0);
528 }
529
530 /*
531  * Remove this node. The does the netgraph portion of the shutdown.
532  * This should only be called indirectly from ngt_close().
533  */
534 static int
535 ngt_shutdown(node_p node)
536 {
537         const sc_p sc = node->private;
538
539         if (!ngt_nodeop_ok)
540                 return (EOPNOTSUPP);
541         ng_unname(node);
542         ng_cutlinks(node);
543         node->private = NULL;
544         ng_unref(sc->node);
545         m_freem(sc->qhead);
546         m_freem(sc->m);
547         bzero(sc, sizeof(*sc));
548         FREE(sc, M_NETGRAPH);
549         return (0);
550 }
551
552 /*
553  * Receive incoming data from netgraph system. Put it on our
554  * output queue and start output if necessary.
555  */
556 static int
557 ngt_rcvdata(hook_p hook, struct mbuf *m, meta_p meta)
558 {
559         const sc_p sc = hook->node->private;
560         int error = 0;
561
562         if (hook != sc->hook)
563                 panic(__func__);
564         NG_FREE_META(meta);
565         crit_enter();
566         if (sc->qlen >= MAX_MBUFQ)
567                 ERROUT(ENOBUFS);
568         m->m_nextpkt = NULL;
569         *sc->qtail = m;
570         sc->qtail = &m->m_nextpkt;
571         sc->qlen++;
572         QUEUECHECK(sc);
573         m = NULL;
574         if (sc->qlen == 1)
575                 ngt_start(sc->tp);
576 done:
577         crit_exit();
578         if (m)
579                 m_freem(m);
580         return (error);
581 }
582
583 /*
584  * Receive control message
585  */
586 static int
587 ngt_rcvmsg(node_p node, struct ng_mesg *msg, const char *retaddr,
588            struct ng_mesg **rptr)
589 {
590         const sc_p sc = (sc_p) node->private;
591         struct ng_mesg *resp = NULL;
592         int error = 0;
593
594         switch (msg->header.typecookie) {
595         case NGM_TTY_COOKIE:
596                 switch (msg->header.cmd) {
597                 case NGM_TTY_SET_HOTCHAR:
598                     {
599                         int     hotchar;
600
601                         if (msg->header.arglen != sizeof(int))
602                                 ERROUT(EINVAL);
603                         hotchar = *((int *) msg->data);
604                         if (hotchar != (u_char) hotchar && hotchar != -1)
605                                 ERROUT(EINVAL);
606                         sc->hotchar = hotchar;  /* race condition is OK */
607                         break;
608                     }
609                 case NGM_TTY_GET_HOTCHAR:
610                         NG_MKRESPONSE(resp, msg, sizeof(int), M_NOWAIT);
611                         if (!resp)
612                                 ERROUT(ENOMEM);
613                         /* Race condition here is OK */
614                         *((int *) resp->data) = sc->hotchar;
615                         break;
616                 default:
617                         ERROUT(EINVAL);
618                 }
619                 break;
620         default:
621                 ERROUT(EINVAL);
622         }
623         if (rptr)
624                 *rptr = resp;
625         else if (resp)
626                 FREE(resp, M_NETGRAPH);
627
628 done:
629         FREE(msg, M_NETGRAPH);
630         return (error);
631 }
632
633 /******************************************************************
634                         INITIALIZATION
635 ******************************************************************/
636
637 /*
638  * Handle loading and unloading for this node type
639  */
640 static int
641 ngt_mod_event(module_t mod, int event, void *data)
642 {
643         /* struct ng_type *const type = data;*/
644         int error = 0;
645
646         switch (event) {
647         case MOD_LOAD:
648                 /* Register line discipline */
649                 crit_enter();
650                 if ((ngt_ldisc = ldisc_register(NETGRAPHDISC, &ngt_disc)) < 0) {
651                         crit_exit();
652                         log(LOG_ERR, "%s: can't register line discipline",
653                             __func__);
654                         return (EIO);
655                 }
656                 crit_exit();
657                 break;
658
659         case MOD_UNLOAD:
660
661                 /* Unregister line discipline */
662                 crit_enter();
663                 ldisc_deregister(ngt_ldisc);
664                 crit_exit();
665                 break;
666
667         default:
668                 error = EOPNOTSUPP;
669                 break;
670         }
671         return (error);
672 }
673