xref: /openbsd-src/sys/kern/tty_pty.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /*	$OpenBSD: tty_pty.c,v 1.112 2021/12/15 15:30:47 visa Exp $	*/
2 /*	$NetBSD: tty_pty.c,v 1.33.4.1 1996/06/02 09:08:11 mrg Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1989, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)tty_pty.c	8.4 (Berkeley) 2/20/95
33  */
34 
35 /*
36  * Pseudo-teletype Driver
37  * (Actually two drivers, requiring two entries in 'cdevsw')
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/namei.h>
43 #include <sys/mount.h>
44 #include <sys/ioctl.h>
45 #include <sys/proc.h>
46 #include <sys/tty.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/filedesc.h>
50 #include <sys/uio.h>
51 #include <sys/kernel.h>
52 #include <sys/malloc.h>
53 #include <sys/vnode.h>
54 #include <sys/signalvar.h>
55 #include <sys/conf.h>
56 #include <sys/stat.h>
57 #include <sys/sysctl.h>
58 #include <sys/poll.h>
59 #include <sys/pledge.h>
60 #include <sys/rwlock.h>
61 
62 #define BUFSIZ 100		/* Chunk size iomoved to/from user */
63 
64 /*
65  * pts == /dev/tty[p-zP-T][0-9a-zA-Z]
66  * ptc == /dev/pty[p-zP-T][0-9a-zA-Z]
67  */
68 
69 /* XXX this needs to come from somewhere sane, and work with MAKEDEV */
70 #define TTY_LETTERS "pqrstuvwxyzPQRST"
71 #define TTY_SUFFIX "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
72 
73 static int pts_major;
74 
75 struct	pt_softc {
76 	struct	tty *pt_tty;
77 	int	pt_flags;
78 	struct	selinfo pt_selr, pt_selw;
79 	u_char	pt_send;
80 	u_char	pt_ucntl;
81 	char	pty_pn[11];
82 	char	pty_sn[11];
83 };
84 
85 #define	NPTY_MIN		8	/* number of initial ptys */
86 #define NPTY_MAX		992	/* maximum number of ptys supported */
87 
88 static struct pt_softc **pt_softc = NULL;	/* pty array */
89 static int npty = 0;				/* size of pty array */
90 static int maxptys = NPTY_MAX;			/* maximum number of ptys */
91 /* for pty array */
92 struct rwlock pt_softc_lock = RWLOCK_INITIALIZER("ptarrlk");
93 
94 #define	PF_PKT		0x08		/* packet mode */
95 #define	PF_STOPPED	0x10		/* user told stopped */
96 #define	PF_REMOTE	0x20		/* remote and flow controlled input */
97 #define	PF_NOSTOP	0x40
98 #define PF_UCNTL	0x80		/* user control mode */
99 
100 void	ptyattach(int);
101 void	ptcwakeup(struct tty *, int);
102 struct tty *ptytty(dev_t);
103 void	ptsstart(struct tty *);
104 int	sysctl_pty(int *, u_int, void *, size_t *, void *, size_t);
105 
106 void	filt_ptcrdetach(struct knote *);
107 int	filt_ptcread(struct knote *, long);
108 void	filt_ptcwdetach(struct knote *);
109 int	filt_ptcwrite(struct knote *, long);
110 int	filt_ptcexcept(struct knote *, long);
111 
112 static struct pt_softc **ptyarralloc(int);
113 static int check_pty(int);
114 
115 static gid_t tty_gid = TTY_GID;
116 
117 void	ptydevname(int, struct pt_softc *);
118 dev_t	pty_getfree(void);
119 
120 void	ptmattach(int);
121 int	ptmopen(dev_t, int, int, struct proc *);
122 int	ptmclose(dev_t, int, int, struct proc *);
123 int	ptmioctl(dev_t, u_long, caddr_t, int, struct proc *p);
124 static int ptm_vn_open(struct nameidata *);
125 
126 void
127 ptydevname(int minor, struct pt_softc *pti)
128 {
129 	char buf[11] = "/dev/XtyXX";
130 	int i, j;
131 
132 	i = minor / (sizeof(TTY_SUFFIX) - 1);
133 	j = minor % (sizeof(TTY_SUFFIX) - 1);
134 	if (i >= sizeof(TTY_LETTERS) - 1) {
135 		pti->pty_pn[0] = '\0';
136 		pti->pty_sn[0] = '\0';
137 		return;
138 	}
139 	buf[5] = 'p';
140 	buf[8] = TTY_LETTERS[i];
141 	buf[9] = TTY_SUFFIX[j];
142 	memcpy(pti->pty_pn, buf, sizeof(buf));
143 	buf[5] = 't';
144 	memcpy(pti->pty_sn, buf, sizeof(buf));
145 }
146 
147 /*
148  * Allocate and zero array of nelem elements.
149  */
150 struct pt_softc **
151 ptyarralloc(int nelem)
152 {
153 	struct pt_softc **pt;
154 
155 	pt = mallocarray(nelem, sizeof(struct pt_softc *), M_DEVBUF,
156 	    M_WAITOK|M_ZERO);
157 	return pt;
158 }
159 
160 /*
161  * Check if the minor is correct and ensure necessary structures
162  * are properly allocated.
163  */
164 int
165 check_pty(int dev)
166 {
167 	struct pt_softc *pti;
168 	int minor = minor(dev);
169 
170 	rw_enter_write(&pt_softc_lock);
171 	if (minor >= npty) {
172 		struct pt_softc **newpt;
173 		int newnpty;
174 
175 		/* check if the requested pty can be granted */
176 		if (minor >= maxptys)
177 			goto limit_reached;
178 
179 		/* grow pty array by powers of two, up to maxptys */
180 		for (newnpty = npty; newnpty <= minor; newnpty *= 2)
181 			;
182 
183 		if (newnpty > maxptys)
184 			newnpty = maxptys;
185 		newpt = ptyarralloc(newnpty);
186 
187 		memcpy(newpt, pt_softc, npty * sizeof(struct pt_softc *));
188 		free(pt_softc, M_DEVBUF, npty * sizeof(struct pt_softc *));
189 		pt_softc = newpt;
190 		npty = newnpty;
191 	}
192 
193 	/*
194 	 * If the entry is not yet allocated, allocate one.
195 	 */
196 	if (!pt_softc[minor]) {
197 		pti = malloc(sizeof(struct pt_softc), M_DEVBUF,
198 		    M_WAITOK|M_ZERO);
199 		pti->pt_tty = ttymalloc(1000000);
200 		pti->pt_tty->t_dev = dev;
201 		ptydevname(minor, pti);
202 		pt_softc[minor] = pti;
203 	}
204 	rw_exit_write(&pt_softc_lock);
205 	return (0);
206 limit_reached:
207 	rw_exit_write(&pt_softc_lock);
208 	tablefull("pty");
209 	return (ENXIO);
210 }
211 
212 /*
213  * Establish n (or default if n is 1) ptys in the system.
214  */
215 void
216 ptyattach(int n)
217 {
218 	/* maybe should allow 0 => none? */
219 	if (n <= 1)
220 		n = NPTY_MIN;
221 	pt_softc = ptyarralloc(n);
222 	npty = n;
223 
224 	/*
225 	 * If we have pty, we need ptm too.
226 	 */
227 	ptmattach(1);
228 }
229 
230 int
231 ptsopen(dev_t dev, int flag, int devtype, struct proc *p)
232 {
233 	struct pt_softc *pti;
234 	struct tty *tp;
235 	int error;
236 
237 	if ((error = check_pty(dev)))
238 		return (error);
239 
240 	pti = pt_softc[minor(dev)];
241 	tp = pti->pt_tty;
242 	if ((tp->t_state & TS_ISOPEN) == 0) {
243 		tp->t_state |= TS_WOPEN;
244 		ttychars(tp);		/* Set up default chars */
245 		tp->t_iflag = TTYDEF_IFLAG;
246 		tp->t_oflag = TTYDEF_OFLAG;
247 		tp->t_lflag = TTYDEF_LFLAG;
248 		tp->t_cflag = TTYDEF_CFLAG;
249 		tp->t_ispeed = tp->t_ospeed = B115200;
250 		ttsetwater(tp);		/* would be done in xxparam() */
251 	} else if (tp->t_state & TS_XCLUDE && suser(p) != 0)
252 		return (EBUSY);
253 	if (tp->t_oproc)			/* Ctrlr still around. */
254 		tp->t_state |= TS_CARR_ON;
255 	while ((tp->t_state & TS_CARR_ON) == 0) {
256 		tp->t_state |= TS_WOPEN;
257 		if (flag & FNONBLOCK)
258 			break;
259 		error = ttysleep(tp, &tp->t_rawq, TTIPRI | PCATCH, ttopen);
260 		if (error)
261 			return (error);
262 	}
263 	error = (*linesw[tp->t_line].l_open)(dev, tp, p);
264 	ptcwakeup(tp, FREAD|FWRITE);
265 	return (error);
266 }
267 
268 int
269 ptsclose(dev_t dev, int flag, int mode, struct proc *p)
270 {
271 	struct pt_softc *pti = pt_softc[minor(dev)];
272 	struct tty *tp = pti->pt_tty;
273 	int error;
274 
275 	error = (*linesw[tp->t_line].l_close)(tp, flag, p);
276 	error |= ttyclose(tp);
277 	ptcwakeup(tp, FREAD|FWRITE);
278 	return (error);
279 }
280 
281 int
282 ptsread(dev_t dev, struct uio *uio, int flag)
283 {
284 	struct proc *p = curproc;
285 	struct process *pr = p->p_p;
286 	struct pt_softc *pti = pt_softc[minor(dev)];
287 	struct tty *tp = pti->pt_tty;
288 	int error = 0;
289 
290 again:
291 	if (pti->pt_flags & PF_REMOTE) {
292 		while (isbackground(pr, tp)) {
293 			if (sigismasked(p, SIGTTIN) ||
294 			    pr->ps_pgrp->pg_jobc == 0 ||
295 			    pr->ps_flags & PS_PPWAIT)
296 				return (EIO);
297 			pgsignal(pr->ps_pgrp, SIGTTIN, 1);
298 			error = ttysleep(tp, &lbolt, TTIPRI | PCATCH, ttybg);
299 			if (error)
300 				return (error);
301 		}
302 		if (tp->t_canq.c_cc == 0) {
303 			if (flag & IO_NDELAY)
304 				return (EWOULDBLOCK);
305 			error = ttysleep(tp, &tp->t_canq,
306 			    TTIPRI | PCATCH, ttyin);
307 			if (error)
308 				return (error);
309 			goto again;
310 		}
311 		while (tp->t_canq.c_cc > 1 && uio->uio_resid > 0)
312 			if (ureadc(getc(&tp->t_canq), uio) < 0) {
313 				error = EFAULT;
314 				break;
315 			}
316 		if (tp->t_canq.c_cc == 1)
317 			(void) getc(&tp->t_canq);
318 		if (tp->t_canq.c_cc)
319 			return (error);
320 	} else
321 		if (tp->t_oproc)
322 			error = (*linesw[tp->t_line].l_read)(tp, uio, flag);
323 	ptcwakeup(tp, FWRITE);
324 	return (error);
325 }
326 
327 /*
328  * Write to pseudo-tty.
329  * Wakeups of controlling tty will happen
330  * indirectly, when tty driver calls ptsstart.
331  */
332 int
333 ptswrite(dev_t dev, struct uio *uio, int flag)
334 {
335 	struct pt_softc *pti = pt_softc[minor(dev)];
336 	struct tty *tp = pti->pt_tty;
337 
338 	if (tp->t_oproc == NULL)
339 		return (EIO);
340 	return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
341 }
342 
343 /*
344  * Start output on pseudo-tty.
345  * Wake up process polling or sleeping for input from controlling tty.
346  */
347 void
348 ptsstart(struct tty *tp)
349 {
350 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
351 
352 	if (tp->t_state & TS_TTSTOP)
353 		return;
354 	if (pti->pt_flags & PF_STOPPED) {
355 		pti->pt_flags &= ~PF_STOPPED;
356 		pti->pt_send = TIOCPKT_START;
357 	}
358 	ptcwakeup(tp, FREAD);
359 }
360 
361 int
362 ptsstop(struct tty *tp, int flush)
363 {
364 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
365 	int flag;
366 
367 	/* note: FLUSHREAD and FLUSHWRITE already ok */
368 	if (flush == 0) {
369 		flush = TIOCPKT_STOP;
370 		pti->pt_flags |= PF_STOPPED;
371 	} else
372 		pti->pt_flags &= ~PF_STOPPED;
373 	pti->pt_send |= flush;
374 	/* change of perspective */
375 	flag = 0;
376 	if (flush & FREAD)
377 		flag |= FWRITE;
378 	if (flush & FWRITE)
379 		flag |= FREAD;
380 	ptcwakeup(tp, flag);
381 	return 0;
382 }
383 
384 void
385 ptcwakeup(struct tty *tp, int flag)
386 {
387 	struct pt_softc *pti = pt_softc[minor(tp->t_dev)];
388 
389 	if (flag & FREAD) {
390 		selwakeup(&pti->pt_selr);
391 		wakeup(&tp->t_outq.c_cf);
392 	}
393 	if (flag & FWRITE) {
394 		selwakeup(&pti->pt_selw);
395 		wakeup(&tp->t_rawq.c_cf);
396 	}
397 }
398 
399 int ptcopen(dev_t, int, int, struct proc *);
400 
401 int
402 ptcopen(dev_t dev, int flag, int devtype, struct proc *p)
403 {
404 	struct pt_softc *pti;
405 	struct tty *tp;
406 	int error;
407 
408 	if ((error = check_pty(dev)))
409 		return (error);
410 
411 	pti = pt_softc[minor(dev)];
412 	tp = pti->pt_tty;
413 	if (tp->t_oproc)
414 		return (EIO);
415 	tp->t_oproc = ptsstart;
416 	(void)(*linesw[tp->t_line].l_modem)(tp, 1);
417 	tp->t_lflag &= ~EXTPROC;
418 	pti->pt_flags = 0;
419 	pti->pt_send = 0;
420 	pti->pt_ucntl = 0;
421 	return (0);
422 }
423 
424 int
425 ptcclose(dev_t dev, int flag, int devtype, struct proc *p)
426 {
427 	struct pt_softc *pti = pt_softc[minor(dev)];
428 	struct tty *tp = pti->pt_tty;
429 
430 	(void)(*linesw[tp->t_line].l_modem)(tp, 0);
431 	tp->t_state &= ~TS_CARR_ON;
432 	tp->t_oproc = NULL;		/* mark closed */
433 	return (0);
434 }
435 
436 int
437 ptcread(dev_t dev, struct uio *uio, int flag)
438 {
439 	struct pt_softc *pti = pt_softc[minor(dev)];
440 	struct tty *tp = pti->pt_tty;
441 	char buf[BUFSIZ];
442 	int error = 0, cc, bufcc = 0;
443 
444 	/*
445 	 * We want to block until the slave
446 	 * is open, and there's something to read;
447 	 * but if we lost the slave or we're NBIO,
448 	 * then return the appropriate error instead.
449 	 */
450 	for (;;) {
451 		if (tp->t_state & TS_ISOPEN) {
452 			if (pti->pt_flags & PF_PKT && pti->pt_send) {
453 				error = ureadc((int)pti->pt_send, uio);
454 				if (error)
455 					return (error);
456 				if (pti->pt_send & TIOCPKT_IOCTL) {
457 					cc = MIN(uio->uio_resid,
458 						sizeof(tp->t_termios));
459 					error = uiomove(&tp->t_termios, cc, uio);
460 					if (error)
461 						return (error);
462 				}
463 				pti->pt_send = 0;
464 				return (0);
465 			}
466 			if (pti->pt_flags & PF_UCNTL && pti->pt_ucntl) {
467 				error = ureadc((int)pti->pt_ucntl, uio);
468 				if (error)
469 					return (error);
470 				pti->pt_ucntl = 0;
471 				return (0);
472 			}
473 			if (tp->t_outq.c_cc && (tp->t_state & TS_TTSTOP) == 0)
474 				break;
475 		}
476 		if ((tp->t_state & TS_CARR_ON) == 0)
477 			return (0);	/* EOF */
478 		if (flag & IO_NDELAY)
479 			return (EWOULDBLOCK);
480 		error = tsleep_nsec(&tp->t_outq.c_cf, TTIPRI | PCATCH, ttyin,
481 		    INFSLP);
482 		if (error)
483 			return (error);
484 	}
485 	if (pti->pt_flags & (PF_PKT|PF_UCNTL))
486 		error = ureadc(0, uio);
487 	while (uio->uio_resid > 0 && error == 0) {
488 		cc = MIN(uio->uio_resid, BUFSIZ);
489 		cc = q_to_b(&tp->t_outq, buf, cc);
490 		if (cc > bufcc)
491 			bufcc = cc;
492 		if (cc <= 0)
493 			break;
494 		error = uiomove(buf, cc, uio);
495 	}
496 	ttwakeupwr(tp);
497 	if (bufcc)
498 		explicit_bzero(buf, bufcc);
499 	return (error);
500 }
501 
502 
503 int
504 ptcwrite(dev_t dev, struct uio *uio, int flag)
505 {
506 	struct pt_softc *pti = pt_softc[minor(dev)];
507 	struct tty *tp = pti->pt_tty;
508 	u_char *cp = NULL;
509 	int cc = 0, bufcc = 0;
510 	u_char buf[BUFSIZ];
511 	size_t cnt = 0;
512 	int error = 0;
513 
514 again:
515 	if ((tp->t_state & TS_ISOPEN) == 0)
516 		goto block;
517 	if (pti->pt_flags & PF_REMOTE) {
518 		if (tp->t_canq.c_cc)
519 			goto block;
520 		while (uio->uio_resid > 0 && tp->t_canq.c_cc < TTYHOG(tp) - 1) {
521 			if (cc == 0) {
522 				cc = MIN(uio->uio_resid, BUFSIZ);
523 				cc = min(cc, TTYHOG(tp) - 1 - tp->t_canq.c_cc);
524 				if (cc > bufcc)
525 					bufcc = cc;
526 				cp = buf;
527 				error = uiomove(cp, cc, uio);
528 				if (error)
529 					goto done;
530 				/* check again for safety */
531 				if ((tp->t_state & TS_ISOPEN) == 0) {
532 					error = EIO;
533 					goto done;
534 				}
535 			}
536 			if (cc)
537 				(void) b_to_q((char *)cp, cc, &tp->t_canq);
538 			cc = 0;
539 		}
540 		(void) putc(0, &tp->t_canq);
541 		ttwakeup(tp);
542 		wakeup(&tp->t_canq);
543 		goto done;
544 	}
545 	do {
546 		if (cc == 0) {
547 			cc = MIN(uio->uio_resid, BUFSIZ);
548 			if (cc > bufcc)
549 				bufcc = cc;
550 			cp = buf;
551 			error = uiomove(cp, cc, uio);
552 			if (error)
553 				goto done;
554 			/* check again for safety */
555 			if ((tp->t_state & TS_ISOPEN) == 0) {
556 				error = EIO;
557 				goto done;
558 			}
559 		}
560 		bufcc = cc;
561 		while (cc > 0) {
562 			if ((tp->t_rawq.c_cc + tp->t_canq.c_cc) >= TTYHOG(tp) - 2 &&
563 			   (tp->t_canq.c_cc > 0 || !ISSET(tp->t_lflag, ICANON))) {
564 				wakeup(&tp->t_rawq);
565 				goto block;
566 			}
567 			if ((*linesw[tp->t_line].l_rint)(*cp++, tp) == 1 &&
568 			    tsleep(tp, TTIPRI | PCATCH, "ttyretype", 1) == EINTR)
569 				goto interrupt;
570 			cnt++;
571 			cc--;
572 		}
573 		cc = 0;
574 	} while (uio->uio_resid > 0);
575 	goto done;
576 block:
577 	/*
578 	 * Come here to wait for slave to open, for space
579 	 * in outq, or space in rawq.
580 	 */
581 	if ((tp->t_state & TS_CARR_ON) == 0) {
582 		error = EIO;
583 		goto done;
584 	}
585 	if (flag & IO_NDELAY) {
586 		/* adjust for data copied in but not written */
587 		uio->uio_resid += cc;
588 		if (cnt == 0)
589 			error = EWOULDBLOCK;
590 		goto done;
591 	}
592 	error = tsleep_nsec(&tp->t_rawq.c_cf, TTOPRI | PCATCH, ttyout, INFSLP);
593 	if (error == 0)
594 		goto again;
595 
596 interrupt:
597 	/* adjust for data copied in but not written */
598 	uio->uio_resid += cc;
599 done:
600 	if (bufcc)
601 		explicit_bzero(buf, bufcc);
602 	return (error);
603 }
604 
605 int
606 ptcpoll(dev_t dev, int events, struct proc *p)
607 {
608 	struct pt_softc *pti = pt_softc[minor(dev)];
609 	struct tty *tp = pti->pt_tty;
610 	int revents = 0, s;
611 
612 	if (!ISSET(tp->t_state, TS_ISOPEN) && ISSET(tp->t_state, TS_CARR_ON))
613 		goto notopen;
614 
615 	if (events & (POLLIN | POLLRDNORM)) {
616 		/*
617 		 * Need to protect access to t_outq
618 		 */
619 		s = spltty();
620 		if ((tp->t_outq.c_cc && !ISSET(tp->t_state, TS_TTSTOP)) ||
621 		    ((pti->pt_flags & PF_PKT) && pti->pt_send) ||
622 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
623 			revents |= events & (POLLIN | POLLRDNORM);
624 		splx(s);
625 	}
626 	/* NOTE: POLLHUP and POLLOUT/POLLWRNORM are mutually exclusive */
627 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
628 		revents |= POLLHUP;
629 	} else if (events & (POLLOUT | POLLWRNORM)) {
630 		if ((pti->pt_flags & PF_REMOTE) ?
631 		    (tp->t_canq.c_cc == 0) :
632 		    ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG(tp) - 2) ||
633 		    (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON))))
634 			revents |= events & (POLLOUT | POLLWRNORM);
635 	}
636 	if (events & (POLLPRI | POLLRDBAND)) {
637 		/* If in packet or user control mode, check for data. */
638 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
639 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
640 			revents |= events & (POLLPRI | POLLRDBAND);
641 	}
642 
643 	if (revents == 0) {
644 notopen:
645 		if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND))
646 			selrecord(p, &pti->pt_selr);
647 		if (events & (POLLOUT | POLLWRNORM))
648 			selrecord(p, &pti->pt_selw);
649 	}
650 
651 	return (revents);
652 }
653 
654 void
655 filt_ptcrdetach(struct knote *kn)
656 {
657 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
658 	int s;
659 
660 	s = spltty();
661 	klist_remove_locked(&pti->pt_selr.si_note, kn);
662 	splx(s);
663 }
664 
665 int
666 filt_ptcread(struct knote *kn, long hint)
667 {
668 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
669 	struct tty *tp;
670 	int active;
671 
672 	tp = pti->pt_tty;
673 	kn->kn_data = 0;
674 
675 	if (ISSET(tp->t_state, TS_ISOPEN)) {
676 		if (!ISSET(tp->t_state, TS_TTSTOP))
677 			kn->kn_data = tp->t_outq.c_cc;
678 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
679 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl))
680 			kn->kn_data++;
681 	}
682 	active = (kn->kn_data > 0);
683 
684 	if (!ISSET(tp->t_state, TS_CARR_ON)) {
685 		kn->kn_flags |= EV_EOF;
686 		if (kn->kn_flags & __EV_POLL)
687 			kn->kn_flags |= __EV_HUP;
688 		active = 1;
689 	} else {
690 		kn->kn_flags &= ~(EV_EOF | __EV_HUP);
691 	}
692 
693 	return (active);
694 }
695 
696 void
697 filt_ptcwdetach(struct knote *kn)
698 {
699 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
700 	int s;
701 
702 	s = spltty();
703 	klist_remove_locked(&pti->pt_selw.si_note, kn);
704 	splx(s);
705 }
706 
707 int
708 filt_ptcwrite(struct knote *kn, long hint)
709 {
710 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
711 	struct tty *tp;
712 	int active;
713 
714 	tp = pti->pt_tty;
715 	kn->kn_data = 0;
716 
717 	if (ISSET(tp->t_state, TS_ISOPEN)) {
718 		if (ISSET(pti->pt_flags, PF_REMOTE)) {
719 			if (tp->t_canq.c_cc == 0)
720 				kn->kn_data = tp->t_canq.c_cn;
721 		} else if ((tp->t_rawq.c_cc + tp->t_canq.c_cc < TTYHOG(tp)-2) ||
722 		    (tp->t_canq.c_cc == 0 && ISSET(tp->t_lflag, ICANON)))
723 			kn->kn_data = tp->t_canq.c_cn -
724 			    (tp->t_rawq.c_cc + tp->t_canq.c_cc);
725 	}
726 	active = (kn->kn_data > 0);
727 
728 	/* Write-side HUP condition is only for poll(2) and select(2). */
729 	if (kn->kn_flags & (__EV_POLL | __EV_SELECT)) {
730 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
731 			kn->kn_flags |= __EV_HUP;
732 			active = 1;
733 		} else {
734 			kn->kn_flags &= ~__EV_HUP;
735 		}
736 	}
737 
738 	return (active);
739 }
740 
741 int
742 filt_ptcexcept(struct knote *kn, long hint)
743 {
744 	struct pt_softc *pti = (struct pt_softc *)kn->kn_hook;
745 	struct tty *tp;
746 	int active = 0;
747 
748 	tp = pti->pt_tty;
749 
750 	if (kn->kn_sfflags & NOTE_OOB) {
751 		/* If in packet or user control mode, check for data. */
752 		if (((pti->pt_flags & PF_PKT) && pti->pt_send) ||
753 		    ((pti->pt_flags & PF_UCNTL) && pti->pt_ucntl)) {
754 			kn->kn_fflags |= NOTE_OOB;
755 			kn->kn_data = 1;
756 			active = 1;
757 		}
758 	}
759 
760 	if (kn->kn_flags & __EV_POLL) {
761 		if (!ISSET(tp->t_state, TS_CARR_ON)) {
762 			kn->kn_flags |= __EV_HUP;
763 			active = 1;
764 		} else {
765 			kn->kn_flags &= ~__EV_HUP;
766 		}
767 	}
768 
769 	return (active);
770 }
771 
772 const struct filterops ptcread_filtops = {
773 	.f_flags	= FILTEROP_ISFD,
774 	.f_attach	= NULL,
775 	.f_detach	= filt_ptcrdetach,
776 	.f_event	= filt_ptcread,
777 };
778 
779 const struct filterops ptcwrite_filtops = {
780 	.f_flags	= FILTEROP_ISFD,
781 	.f_attach	= NULL,
782 	.f_detach	= filt_ptcwdetach,
783 	.f_event	= filt_ptcwrite,
784 };
785 
786 const struct filterops ptcexcept_filtops = {
787 	.f_flags	= FILTEROP_ISFD,
788 	.f_attach	= NULL,
789 	.f_detach	= filt_ptcrdetach,
790 	.f_event	= filt_ptcexcept,
791 };
792 
793 int
794 ptckqfilter(dev_t dev, struct knote *kn)
795 {
796 	struct pt_softc *pti = pt_softc[minor(dev)];
797 	struct klist *klist;
798 	int s;
799 
800 	switch (kn->kn_filter) {
801 	case EVFILT_READ:
802 		klist = &pti->pt_selr.si_note;
803 		kn->kn_fop = &ptcread_filtops;
804 		break;
805 	case EVFILT_WRITE:
806 		klist = &pti->pt_selw.si_note;
807 		kn->kn_fop = &ptcwrite_filtops;
808 		break;
809 	case EVFILT_EXCEPT:
810 		klist = &pti->pt_selr.si_note;
811 		kn->kn_fop = &ptcexcept_filtops;
812 		break;
813 	default:
814 		return (EINVAL);
815 	}
816 
817 	kn->kn_hook = (caddr_t)pti;
818 
819 	s = spltty();
820 	klist_insert_locked(klist, kn);
821 	splx(s);
822 
823 	return (0);
824 }
825 
826 struct tty *
827 ptytty(dev_t dev)
828 {
829 	struct pt_softc *pti = pt_softc[minor(dev)];
830 	struct tty *tp = pti->pt_tty;
831 
832 	return (tp);
833 }
834 
835 int
836 ptyioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
837 {
838 	struct pt_softc *pti = pt_softc[minor(dev)];
839 	struct tty *tp = pti->pt_tty;
840 	u_char *cc = tp->t_cc;
841 	int stop, error;
842 
843 	/*
844 	 * IF CONTROLLER STTY THEN MUST FLUSH TO PREVENT A HANG.
845 	 * ttywflush(tp) will hang if there are characters in the outq.
846 	 */
847 	if (cmd == TIOCEXT) {
848 		/*
849 		 * When the EXTPROC bit is being toggled, we need
850 		 * to send an TIOCPKT_IOCTL if the packet driver
851 		 * is turned on.
852 		 */
853 		if (*(int *)data) {
854 			if (pti->pt_flags & PF_PKT) {
855 				pti->pt_send |= TIOCPKT_IOCTL;
856 				ptcwakeup(tp, FREAD);
857 			}
858 			tp->t_lflag |= EXTPROC;
859 		} else {
860 			if ((tp->t_lflag & EXTPROC) &&
861 			    (pti->pt_flags & PF_PKT)) {
862 				pti->pt_send |= TIOCPKT_IOCTL;
863 				ptcwakeup(tp, FREAD);
864 			}
865 			tp->t_lflag &= ~EXTPROC;
866 		}
867 		return(0);
868 	} else if (cdevsw[major(dev)].d_open == ptcopen)
869 		switch (cmd) {
870 
871 		case TIOCGPGRP:
872 			/*
873 			 * We avoid calling ttioctl on the controller since,
874 			 * in that case, tp must be the controlling terminal.
875 			 */
876 			*(int *)data = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
877 			return (0);
878 
879 		case TIOCPKT:
880 			if (*(int *)data) {
881 				if (pti->pt_flags & PF_UCNTL)
882 					return (EINVAL);
883 				pti->pt_flags |= PF_PKT;
884 			} else
885 				pti->pt_flags &= ~PF_PKT;
886 			return (0);
887 
888 		case TIOCUCNTL:
889 			if (*(int *)data) {
890 				if (pti->pt_flags & PF_PKT)
891 					return (EINVAL);
892 				pti->pt_flags |= PF_UCNTL;
893 			} else
894 				pti->pt_flags &= ~PF_UCNTL;
895 			return (0);
896 
897 		case TIOCREMOTE:
898 			if (*(int *)data)
899 				pti->pt_flags |= PF_REMOTE;
900 			else
901 				pti->pt_flags &= ~PF_REMOTE;
902 			ttyflush(tp, FREAD|FWRITE);
903 			return (0);
904 
905 		case TIOCSETD:
906 		case TIOCSETA:
907 		case TIOCSETAW:
908 		case TIOCSETAF:
909 			ndflush(&tp->t_outq, tp->t_outq.c_cc);
910 			break;
911 
912 		case TIOCSIG:
913 			if (*(unsigned int *)data >= NSIG ||
914 			    *(unsigned int *)data == 0)
915 				return(EINVAL);
916 			if ((tp->t_lflag & NOFLSH) == 0)
917 				ttyflush(tp, FREAD|FWRITE);
918 			pgsignal(tp->t_pgrp, *(unsigned int *)data, 1);
919 			if ((*(unsigned int *)data == SIGINFO) &&
920 			    ((tp->t_lflag & NOKERNINFO) == 0))
921 				ttyinfo(tp);
922 			return (0);
923 
924 		case FIONREAD:
925 			/*
926 			 * FIONREAD on the master side must return the amount
927 			 * in the output queue rather than the input.
928 			 */
929 			*(int *)data = tp->t_outq.c_cc;
930 			return (0);
931 		}
932 	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
933 	if (error < 0)
934 		 error = ttioctl(tp, cmd, data, flag, p);
935 	if (error < 0) {
936 		/*
937 		 * Translate TIOCSBRK/TIOCCBRK to user mode ioctls to
938 		 * let the master interpret BREAK conditions.
939 		 */
940 		switch (cmd) {
941 		case TIOCSBRK:
942 			cmd = UIOCCMD(TIOCUCNTL_SBRK);
943 			break;
944 		case TIOCCBRK:
945 			cmd = UIOCCMD(TIOCUCNTL_CBRK);
946 			break;
947 		default:
948 			break;
949 		}
950 		if (pti->pt_flags & PF_UCNTL &&
951 		    (cmd & ~0xff) == UIOCCMD(0)) {
952 			if (cmd & 0xff) {
953 				pti->pt_ucntl = (u_char)cmd;
954 				ptcwakeup(tp, FREAD);
955 			}
956 			return (0);
957 		}
958 		error = ENOTTY;
959 	}
960 	/*
961 	 * If external processing and packet mode send ioctl packet.
962 	 */
963 	if ((tp->t_lflag & EXTPROC) && (pti->pt_flags & PF_PKT)) {
964 		switch (cmd) {
965 		case TIOCSETA:
966 		case TIOCSETAW:
967 		case TIOCSETAF:
968 			pti->pt_send |= TIOCPKT_IOCTL;
969 			ptcwakeup(tp, FREAD);
970 		default:
971 			break;
972 		}
973 	}
974 	stop = (tp->t_iflag & IXON) && CCEQ(cc[VSTOP], CTRL('s')) &&
975 	    CCEQ(cc[VSTART], CTRL('q'));
976 	if (pti->pt_flags & PF_NOSTOP) {
977 		if (stop) {
978 			pti->pt_send &= ~TIOCPKT_NOSTOP;
979 			pti->pt_send |= TIOCPKT_DOSTOP;
980 			pti->pt_flags &= ~PF_NOSTOP;
981 			ptcwakeup(tp, FREAD);
982 		}
983 	} else {
984 		if (!stop) {
985 			pti->pt_send &= ~TIOCPKT_DOSTOP;
986 			pti->pt_send |= TIOCPKT_NOSTOP;
987 			pti->pt_flags |= PF_NOSTOP;
988 			ptcwakeup(tp, FREAD);
989 		}
990 	}
991 	return (error);
992 }
993 
994 /*
995  * Return pty-related information.
996  */
997 int
998 sysctl_pty(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
999     size_t newlen)
1000 {
1001 	if (namelen != 1)
1002 		return (ENOTDIR);
1003 
1004 	switch (name[0]) {
1005 	default:
1006 		return (EOPNOTSUPP);
1007 	}
1008 	/* NOTREACHED */
1009 }
1010 
1011 /*
1012  * Check if a pty is free to use.
1013  */
1014 static int
1015 pty_isfree_locked(int minor)
1016 {
1017 	struct pt_softc *pt = pt_softc[minor];
1018 
1019 	return (pt == NULL || pt->pt_tty == NULL ||
1020 	    pt->pt_tty->t_oproc == NULL);
1021 }
1022 
1023 static int
1024 pty_isfree(int minor)
1025 {
1026 	int isfree;
1027 
1028 	rw_enter_read(&pt_softc_lock);
1029 	isfree = pty_isfree_locked(minor);
1030 	rw_exit_read(&pt_softc_lock);
1031 	return(isfree);
1032 }
1033 
1034 dev_t
1035 pty_getfree(void)
1036 {
1037 	int i;
1038 
1039 	rw_enter_read(&pt_softc_lock);
1040 	for (i = 0; i < npty; i++) {
1041 		if (pty_isfree_locked(i))
1042 			break;
1043 	}
1044 	rw_exit_read(&pt_softc_lock);
1045 	return (makedev(pts_major, i));
1046 }
1047 
1048 /*
1049  * Hacked up version of vn_open. We _only_ handle ptys and only open
1050  * them with FREAD|FWRITE and never deal with creat or stuff like that.
1051  *
1052  * We need it because we have to fake up root credentials to open the pty.
1053  */
1054 static int
1055 ptm_vn_open(struct nameidata *ndp)
1056 {
1057 	struct proc *p = ndp->ni_cnd.cn_proc;
1058 	struct ucred *cred;
1059 	struct vattr vattr;
1060 	struct vnode *vp;
1061 	int error;
1062 
1063 	if ((error = namei(ndp)) != 0)
1064 		return (error);
1065 	vp = ndp->ni_vp;
1066 	if (vp->v_type != VCHR) {
1067 		error = EINVAL;
1068 		goto bad;
1069 	}
1070 
1071 	/*
1072 	 * Get us a fresh cred with root privileges.
1073 	 */
1074 	cred = crget();
1075 	error = VOP_OPEN(vp, FREAD|FWRITE, cred, p);
1076 	if (!error) {
1077 		/* update atime/mtime */
1078 		VATTR_NULL(&vattr);
1079 		getnanotime(&vattr.va_atime);
1080 		vattr.va_mtime = vattr.va_atime;
1081 		vattr.va_vaflags |= VA_UTIMES_NULL;
1082 		(void)VOP_SETATTR(vp, &vattr, p->p_ucred, p);
1083 	}
1084 	crfree(cred);
1085 
1086 	if (error)
1087 		goto bad;
1088 
1089 	vp->v_writecount++;
1090 
1091 	return (0);
1092 bad:
1093 	vput(vp);
1094 	return (error);
1095 }
1096 
1097 void
1098 ptmattach(int n)
1099 {
1100 	/* find the major and minor of the pty devices */
1101 	int i;
1102 
1103 	for (i = 0; i < nchrdev; i++)
1104 		if (cdevsw[i].d_open == ptsopen)
1105 			break;
1106 
1107 	if (i == nchrdev)
1108 		panic("ptmattach: Can't find pty slave in cdevsw");
1109 
1110 	pts_major = i;
1111 }
1112 
1113 int
1114 ptmopen(dev_t dev, int flag, int mode, struct proc *p)
1115 {
1116 	return(0);
1117 }
1118 
1119 
1120 int
1121 ptmclose(dev_t dev, int flag, int mode, struct proc *p)
1122 {
1123 	return (0);
1124 }
1125 
1126 int
1127 ptmioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
1128 {
1129 	dev_t newdev;
1130 	struct pt_softc * pti;
1131 	struct nameidata cnd, snd;
1132 	struct filedesc *fdp = p->p_fd;
1133 	struct file *cfp = NULL, *sfp = NULL;
1134 	int cindx, sindx, error;
1135 	uid_t uid;
1136 	gid_t gid;
1137 	struct vattr vattr;
1138 	struct ucred *cred;
1139 	struct ptmget *ptm = (struct ptmget *)data;
1140 
1141 	switch (cmd) {
1142 	case PTMGET:
1143 		fdplock(fdp);
1144 		/* Grab two filedescriptors. */
1145 		if ((error = falloc(p, &cfp, &cindx)) != 0) {
1146 			fdpunlock(fdp);
1147 			break;
1148 		}
1149 		if ((error = falloc(p, &sfp, &sindx)) != 0) {
1150 			fdremove(fdp, cindx);
1151 			fdpunlock(fdp);
1152 			closef(cfp, p);
1153 			break;
1154 		}
1155 		fdpunlock(fdp);
1156 
1157 retry:
1158 		/* Find and open a free master pty. */
1159 		newdev = pty_getfree();
1160 		if ((error = check_pty(newdev)))
1161 			goto bad;
1162 		pti = pt_softc[minor(newdev)];
1163 		NDINIT(&cnd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1164 		    pti->pty_pn, p);
1165 		cnd.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
1166 		if ((error = ptm_vn_open(&cnd)) != 0) {
1167 			/*
1168 			 * Check if the master open failed because we lost
1169 			 * the race to grab it.
1170 			 */
1171 			if (error == EIO && !pty_isfree(minor(newdev)))
1172 				goto retry;
1173 			goto bad;
1174 		}
1175 		cfp->f_flag = FREAD|FWRITE;
1176 		cfp->f_type = DTYPE_VNODE;
1177 		cfp->f_ops = &vnops;
1178 		cfp->f_data = (caddr_t) cnd.ni_vp;
1179 		VOP_UNLOCK(cnd.ni_vp);
1180 
1181 		/*
1182 		 * Open the slave.
1183 		 * namei -> setattr -> unlock -> revoke -> vrele ->
1184 		 * namei -> open -> unlock
1185 		 * Three stage rocket:
1186 		 * 1. Change the owner and permissions on the slave.
1187 		 * 2. Revoke all the users of the slave.
1188 		 * 3. open the slave.
1189 		 */
1190 		NDINIT(&snd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1191 		    pti->pty_sn, p);
1192 		snd.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
1193 		snd.ni_unveil = UNVEIL_READ | UNVEIL_WRITE;
1194 		if ((error = namei(&snd)) != 0)
1195 			goto bad;
1196 		if ((snd.ni_vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
1197 			gid = tty_gid;
1198 			/* get real uid */
1199 			uid = p->p_ucred->cr_ruid;
1200 
1201 			VATTR_NULL(&vattr);
1202 			vattr.va_uid = uid;
1203 			vattr.va_gid = gid;
1204 			vattr.va_mode = (S_IRUSR|S_IWUSR|S_IWGRP) & ALLPERMS;
1205 			/* Get a fake cred to pretend we're root. */
1206 			cred = crget();
1207 			error = VOP_SETATTR(snd.ni_vp, &vattr, cred, p);
1208 			crfree(cred);
1209 			if (error) {
1210 				vput(snd.ni_vp);
1211 				goto bad;
1212 			}
1213 		}
1214 		VOP_UNLOCK(snd.ni_vp);
1215 		if (snd.ni_vp->v_usecount > 1 ||
1216 		    (snd.ni_vp->v_flag & (VALIASED)))
1217 			VOP_REVOKE(snd.ni_vp, REVOKEALL);
1218 
1219 		/*
1220 		 * The vnode is useless after the revoke, we need to
1221 		 * namei again.
1222 		 */
1223 		vrele(snd.ni_vp);
1224 
1225 		NDINIT(&snd, LOOKUP, NOFOLLOW|LOCKLEAF, UIO_SYSSPACE,
1226 		    pti->pty_sn, p);
1227 		snd.ni_pledge = PLEDGE_RPATH | PLEDGE_WPATH;
1228 		snd.ni_unveil= UNVEIL_READ | UNVEIL_WRITE;
1229 		/* now open it */
1230 		if ((error = ptm_vn_open(&snd)) != 0)
1231 			goto bad;
1232 		sfp->f_flag = FREAD|FWRITE;
1233 		sfp->f_type = DTYPE_VNODE;
1234 		sfp->f_ops = &vnops;
1235 		sfp->f_data = (caddr_t) snd.ni_vp;
1236 		VOP_UNLOCK(snd.ni_vp);
1237 
1238 		/* now, put the indexen and names into struct ptmget */
1239 		ptm->cfd = cindx;
1240 		ptm->sfd = sindx;
1241 		memcpy(ptm->cn, pti->pty_pn, sizeof(pti->pty_pn));
1242 		memcpy(ptm->sn, pti->pty_sn, sizeof(pti->pty_sn));
1243 
1244 		/* insert files now that we've passed all errors */
1245 		fdplock(fdp);
1246 		fdinsert(fdp, cindx, 0, cfp);
1247 		fdinsert(fdp, sindx, 0, sfp);
1248 		fdpunlock(fdp);
1249 		FRELE(cfp, p);
1250 		FRELE(sfp, p);
1251 		break;
1252 	default:
1253 		error = EINVAL;
1254 		break;
1255 	}
1256 	return (error);
1257 bad:
1258 	fdplock(fdp);
1259 	fdremove(fdp, cindx);
1260 	fdremove(fdp, sindx);
1261 	fdpunlock(fdp);
1262 	closef(cfp, p);
1263 	closef(sfp, p);
1264 	return (error);
1265 }
1266