1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Portions of this software were developed under sponsorship from Snow
8 * B.V., the Netherlands.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 #include <sys/cdefs.h>
33 #include "opt_capsicum.h"
34 #include "opt_printf.h"
35
36 #include <sys/param.h>
37 #include <sys/capsicum.h>
38 #include <sys/conf.h>
39 #include <sys/cons.h>
40 #include <sys/fcntl.h>
41 #include <sys/file.h>
42 #include <sys/filedesc.h>
43 #include <sys/filio.h>
44 #ifdef COMPAT_43TTY
45 #include <sys/ioctl_compat.h>
46 #endif /* COMPAT_43TTY */
47 #include <sys/jail.h>
48 #include <sys/kernel.h>
49 #include <sys/limits.h>
50 #include <sys/malloc.h>
51 #include <sys/mount.h>
52 #include <sys/poll.h>
53 #include <sys/priv.h>
54 #include <sys/proc.h>
55 #include <sys/serial.h>
56 #include <sys/signal.h>
57 #include <sys/stat.h>
58 #include <sys/stdarg.h>
59 #include <sys/sx.h>
60 #include <sys/sysctl.h>
61 #include <sys/systm.h>
62 #include <sys/tty.h>
63 #include <sys/ttycom.h>
64 #define TTYDEFCHARS
65 #include <sys/ttydefaults.h>
66 #undef TTYDEFCHARS
67 #include <sys/ucred.h>
68 #include <sys/vnode.h>
69 #define EXTERR_CATEGORY EXTERR_CAT_TTY
70 #include <sys/exterrvar.h>
71
72 #include <fs/devfs/devfs.h>
73
74 static MALLOC_DEFINE(M_TTY, "tty", "tty device");
75
76 static void tty_rel_free(struct tty *tp, bool inttydevclose);
77
78 static TAILQ_HEAD(, tty) tty_list = TAILQ_HEAD_INITIALIZER(tty_list);
79 static struct sx tty_list_sx;
80 SX_SYSINIT(tty_list, &tty_list_sx, "tty list");
81 static unsigned int tty_list_count = 0;
82
83 /* Character device of /dev/console. */
84 static struct cdev *dev_console;
85 static const char *dev_console_filename;
86
87 /*
88 * Flags that are supported and stored by this implementation.
89 */
90 #define TTYSUP_IFLAG (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|INLCR|\
91 IGNCR|ICRNL|IXON|IXOFF|IXANY|IMAXBEL|IUTF8)
92 #define TTYSUP_OFLAG (OPOST|ONLCR|TAB3|ONOEOT|OCRNL|ONOCR|ONLRET)
93 #define TTYSUP_LFLAG (ECHOKE|ECHOE|ECHOK|ECHO|ECHONL|ECHOPRT|\
94 ECHOCTL|ISIG|ICANON|ALTWERASE|IEXTEN|TOSTOP|\
95 FLUSHO|NOKERNINFO|NOFLSH)
96 #define TTYSUP_CFLAG (CIGNORE|CSIZE|CSTOPB|CREAD|PARENB|PARODD|\
97 HUPCL|CLOCAL|CCTS_OFLOW|CRTS_IFLOW|CDTR_IFLOW|\
98 CDSR_OFLOW|CCAR_OFLOW|CNO_RTSDTR)
99
100 #define TTY_CALLOUT(tp,d) (dev2unit(d) & TTYUNIT_CALLOUT)
101
102 static int tty_drainwait = 5 * 60;
103 SYSCTL_INT(_kern, OID_AUTO, tty_drainwait, CTLFLAG_RWTUN,
104 &tty_drainwait, 0, "Default output drain timeout in seconds");
105
106 static bool tty_tiocsti = true;
107 SYSCTL_BOOL(_security_bsd, OID_AUTO, allow_tiocsti, CTLFLAG_RWTUN,
108 &tty_tiocsti, 0, "Allow TIOCSTI ioctl");
109
110 /*
111 * Set TTY buffer sizes.
112 */
113
114 #define TTYBUF_MAX 65536
115
116 #ifdef PRINTF_BUFR_SIZE
117 #define TTY_PRBUF_SIZE PRINTF_BUFR_SIZE
118 #else
119 #define TTY_PRBUF_SIZE 256
120 #endif
121
122 /*
123 * Allocate buffer space if necessary, and set low watermarks, based on speed.
124 * Note that the ttyxxxq_setsize() functions may drop and then reacquire the tty
125 * lock during memory allocation. They will return ENXIO if the tty disappears
126 * while unlocked.
127 */
128 static int
tty_watermarks(struct tty * tp)129 tty_watermarks(struct tty *tp)
130 {
131 size_t bs = 0;
132 int error;
133
134 /* Provide an input buffer for 2 seconds of data. */
135 if (tp->t_termios.c_cflag & CREAD)
136 bs = MIN(tp->t_termios.c_ispeed / 5, TTYBUF_MAX);
137 error = ttyinq_setsize(&tp->t_inq, tp, bs);
138 if (error != 0)
139 return (error);
140
141 /* Set low watermark at 10% (when 90% is available). */
142 tp->t_inlow = (ttyinq_getallocatedsize(&tp->t_inq) * 9) / 10;
143
144 /* Provide an output buffer for 2 seconds of data. */
145 bs = MIN(tp->t_termios.c_ospeed / 5, TTYBUF_MAX);
146 error = ttyoutq_setsize(&tp->t_outq, tp, bs);
147 if (error != 0)
148 return (error);
149
150 /* Set low watermark at 10% (when 90% is available). */
151 tp->t_outlow = (ttyoutq_getallocatedsize(&tp->t_outq) * 9) / 10;
152
153 return (0);
154 }
155
156 static int
tty_drain(struct tty * tp,int leaving)157 tty_drain(struct tty *tp, int leaving)
158 {
159 sbintime_t timeout_at;
160 size_t bytes;
161 int error;
162
163 if (ttyhook_hashook(tp, getc_inject))
164 /* buffer is inaccessible */
165 return (0);
166
167 /*
168 * For close(), use the recent historic timeout of "1 second without
169 * making progress". For tcdrain(), use t_drainwait as the timeout,
170 * with zero meaning "no timeout" which gives POSIX behavior.
171 */
172 if (leaving)
173 timeout_at = getsbinuptime() + SBT_1S;
174 else if (tp->t_drainwait != 0)
175 timeout_at = getsbinuptime() + SBT_1S * tp->t_drainwait;
176 else
177 timeout_at = 0;
178
179 /*
180 * Poll the output buffer and the hardware for completion, at 10 Hz.
181 * Polling is required for devices which are not able to signal an
182 * interrupt when the transmitter becomes idle (most USB serial devs).
183 * The unusual structure of this loop ensures we check for busy one more
184 * time after tty_timedwait() returns EWOULDBLOCK, so that success has
185 * higher priority than timeout if the IO completed in the last 100mS.
186 */
187 error = 0;
188 bytes = ttyoutq_bytesused(&tp->t_outq);
189 for (;;) {
190 if (ttyoutq_bytesused(&tp->t_outq) == 0 && !ttydevsw_busy(tp))
191 return (0);
192 if (error != 0)
193 return (error);
194 ttydevsw_outwakeup(tp);
195 error = tty_timedwait(tp, &tp->t_outwait, hz / 10);
196 if (error != 0 && error != EWOULDBLOCK)
197 return (error);
198 else if (timeout_at == 0 || getsbinuptime() < timeout_at)
199 error = 0;
200 else if (leaving && ttyoutq_bytesused(&tp->t_outq) < bytes) {
201 /* In close, making progress, grant an extra second. */
202 error = 0;
203 timeout_at += SBT_1S;
204 bytes = ttyoutq_bytesused(&tp->t_outq);
205 }
206 }
207 }
208
209 /*
210 * Though ttydev_enter() and ttydev_leave() seem to be related, they
211 * don't have to be used together. ttydev_enter() is used by the cdev
212 * operations to prevent an actual operation from being processed when
213 * the TTY has been abandoned. ttydev_leave() is used by ttydev_open()
214 * and ttydev_close() to determine whether per-TTY data should be
215 * deallocated.
216 */
217
218 static __inline int
ttydev_enter(struct tty * tp)219 ttydev_enter(struct tty *tp)
220 {
221
222 tty_lock(tp);
223
224 if (tty_gone(tp) || !tty_opened(tp)) {
225 /* Device is already gone. */
226 tty_unlock(tp);
227 return (EXTERROR(ENXIO, "ttydev_enter: device is gone"));
228 }
229
230 return (0);
231 }
232
233 static void
ttydev_leave(struct tty * tp,bool inttydevclose)234 ttydev_leave(struct tty *tp, bool inttydevclose)
235 {
236
237 tty_assert_locked(tp);
238
239 if (tty_opened(tp) || tp->t_flags & TF_OPENCLOSE) {
240 /* Device is still opened somewhere. */
241 if (inttydevclose)
242 tp->t_flags &= ~TF_INDEVCLOSE;
243 tty_unlock(tp);
244 return;
245 }
246
247 tp->t_flags |= TF_OPENCLOSE;
248
249 /* Remove console TTY. */
250 constty_clear(tp);
251
252 /* Drain any output. */
253 if (!tty_gone(tp))
254 tty_drain(tp, 1);
255
256 ttydisc_close(tp);
257
258 /* Free i/o queues now since they might be large. */
259 ttyinq_free(&tp->t_inq);
260 tp->t_inlow = 0;
261 ttyoutq_free(&tp->t_outq);
262 tp->t_outlow = 0;
263
264 if (!tty_gone(tp))
265 ttydevsw_close(tp);
266
267 tp->t_flags &= ~TF_OPENCLOSE;
268 cv_broadcast(&tp->t_dcdwait);
269 tty_rel_free(tp, inttydevclose);
270 }
271
272 /*
273 * Operations that are exposed through the character device in /dev.
274 */
275 static int
ttydev_open(struct cdev * dev,int oflags,int devtype __unused,struct thread * td)276 ttydev_open(struct cdev *dev, int oflags, int devtype __unused,
277 struct thread *td)
278 {
279 struct tty *tp;
280 int error;
281
282 tp = dev->si_drv1;
283 error = 0;
284 tty_lock(tp);
285 if (tty_gone(tp)) {
286 /* Device is already gone. */
287 tty_unlock(tp);
288 return (EXTERROR(ENXIO, "ttydev_open: device is gone"));
289 }
290
291 /*
292 * Block when other processes are currently opening or closing
293 * the TTY.
294 */
295 while (tp->t_flags & TF_OPENCLOSE) {
296 error = tty_wait(tp, &tp->t_dcdwait);
297 if (error != 0) {
298 tty_unlock(tp);
299 return (error);
300 }
301 }
302 tp->t_flags |= TF_OPENCLOSE;
303
304 /*
305 * Make sure the "tty" and "cua" device cannot be opened at the
306 * same time. The console is a "tty" device.
307 */
308 if (TTY_CALLOUT(tp, dev)) {
309 if (tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) {
310 error = EBUSY;
311 goto done;
312 }
313 } else {
314 if (tp->t_flags & TF_OPENED_OUT) {
315 error = EBUSY;
316 goto done;
317 }
318 }
319
320 if (tp->t_flags & TF_EXCLUDE && priv_check(td, PRIV_TTY_EXCLUSIVE)) {
321 error = EBUSY;
322 goto done;
323 }
324
325 if (!tty_opened(tp)) {
326 /* Set proper termios flags. */
327 if (TTY_CALLOUT(tp, dev))
328 tp->t_termios = tp->t_termios_init_out;
329 else
330 tp->t_termios = tp->t_termios_init_in;
331 ttydevsw_param(tp, &tp->t_termios);
332 /* Prevent modem control on callout devices and /dev/console. */
333 if (TTY_CALLOUT(tp, dev) || dev == dev_console)
334 tp->t_termios.c_cflag |= CLOCAL;
335
336 if ((tp->t_termios.c_cflag & CNO_RTSDTR) == 0)
337 ttydevsw_modem(tp, SER_DTR|SER_RTS, 0);
338
339 error = ttydevsw_open(tp);
340 if (error != 0)
341 goto done;
342
343 ttydisc_open(tp);
344 error = tty_watermarks(tp);
345 if (error != 0)
346 goto done;
347 }
348
349 /* Wait for Carrier Detect. */
350 if ((oflags & O_NONBLOCK) == 0 &&
351 (tp->t_termios.c_cflag & CLOCAL) == 0) {
352 while ((ttydevsw_modem(tp, 0, 0) & SER_DCD) == 0) {
353 error = tty_wait(tp, &tp->t_dcdwait);
354 if (error != 0)
355 goto done;
356 }
357 }
358
359 if (dev == dev_console)
360 tp->t_flags |= TF_OPENED_CONS;
361 else if (TTY_CALLOUT(tp, dev))
362 tp->t_flags |= TF_OPENED_OUT;
363 else
364 tp->t_flags |= TF_OPENED_IN;
365 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
366 (tp->t_flags & TF_OPENED_OUT) == 0);
367
368 done: tp->t_flags &= ~TF_OPENCLOSE;
369 cv_broadcast(&tp->t_dcdwait);
370 ttydev_leave(tp, false);
371
372 return (error);
373 }
374
375 static int
ttydev_close(struct cdev * dev,int fflag,int devtype __unused,struct thread * td)376 ttydev_close(struct cdev *dev, int fflag, int devtype __unused,
377 struct thread *td)
378 {
379 struct tty *tp = dev->si_drv1;
380
381 tty_lock(tp);
382 if ((tp->t_flags & TF_INDEVCLOSE) != 0) {
383 tty_unlock(tp);
384 return (0);
385 }
386 tp->t_flags |= TF_INDEVCLOSE;
387
388 /*
389 * Don't actually close the device if it is being used as the
390 * console.
391 */
392 MPASS((tp->t_flags & (TF_OPENED_CONS | TF_OPENED_IN)) == 0 ||
393 (tp->t_flags & TF_OPENED_OUT) == 0);
394 if (dev == dev_console)
395 tp->t_flags &= ~TF_OPENED_CONS;
396 else
397 tp->t_flags &= ~(TF_OPENED_IN|TF_OPENED_OUT);
398
399 if (tp->t_flags & TF_OPENED) {
400 tp->t_flags &= ~TF_INDEVCLOSE;
401 tty_unlock(tp);
402 return (0);
403 }
404
405 /* If revoking, flush output now to avoid draining it later. */
406 if ((fflag & FREVOKE) != 0) {
407 tty_flush(tp, FWRITE);
408 knlist_delete(&tp->t_inpoll.si_note, td, 1);
409 knlist_delete(&tp->t_outpoll.si_note, td, 1);
410 }
411
412 tp->t_flags &= ~TF_EXCLUDE;
413
414 /* Properly wake up threads that are stuck - revoke(). */
415 tp->t_revokecnt++;
416 tty_wakeup(tp, FREAD|FWRITE);
417 cv_broadcast(&tp->t_bgwait);
418 cv_broadcast(&tp->t_dcdwait);
419
420 ttydev_leave(tp, true);
421
422 return (0);
423 }
424
425 static __inline int
tty_is_ctty(struct tty * tp,struct proc * p)426 tty_is_ctty(struct tty *tp, struct proc *p)
427 {
428
429 tty_assert_locked(tp);
430
431 return (p->p_session == tp->t_session && p->p_flag & P_CONTROLT);
432 }
433
434 int
tty_wait_background(struct tty * tp,struct thread * td,int sig)435 tty_wait_background(struct tty *tp, struct thread *td, int sig)
436 {
437 struct proc *p;
438 struct pgrp *pg;
439 ksiginfo_t ksi;
440 int error;
441
442 MPASS(sig == SIGTTIN || sig == SIGTTOU);
443 tty_assert_locked(tp);
444
445 p = td->td_proc;
446 for (;;) {
447 pg = p->p_pgrp;
448 PGRP_LOCK(pg);
449 PROC_LOCK(p);
450
451 /*
452 * pg may no longer be our process group.
453 * Re-check after locking.
454 */
455 if (p->p_pgrp != pg) {
456 PROC_UNLOCK(p);
457 PGRP_UNLOCK(pg);
458 continue;
459 }
460
461 /*
462 * The process should only sleep, when:
463 * - This terminal is the controlling terminal
464 * - Its process group is not the foreground process
465 * group
466 * - The parent process isn't waiting for the child to
467 * exit
468 * - the signal to send to the process isn't masked
469 */
470 if (!tty_is_ctty(tp, p) || p->p_pgrp == tp->t_pgrp) {
471 /* Allow the action to happen. */
472 PROC_UNLOCK(p);
473 PGRP_UNLOCK(pg);
474 return (0);
475 }
476
477 if (SIGISMEMBER(p->p_sigacts->ps_sigignore, sig) ||
478 SIGISMEMBER(td->td_sigmask, sig)) {
479 /* Only allow them in write()/ioctl(). */
480 PROC_UNLOCK(p);
481 PGRP_UNLOCK(pg);
482 return (sig == SIGTTOU ? 0 : EIO);
483 }
484
485 if ((p->p_flag & P_PPWAIT) != 0 ||
486 (pg->pg_flags & PGRP_ORPHANED) != 0) {
487 /* Don't allow the action to happen. */
488 PROC_UNLOCK(p);
489 PGRP_UNLOCK(pg);
490 return (EXTERROR(EIO, "cannot wait in background"));
491 }
492 PROC_UNLOCK(p);
493
494 /*
495 * Send the signal and sleep until we're the new
496 * foreground process group.
497 */
498 if (sig != 0) {
499 ksiginfo_init(&ksi);
500 ksi.ksi_code = SI_KERNEL;
501 ksi.ksi_signo = sig;
502 sig = 0;
503 }
504
505 pgsignal(pg, ksi.ksi_signo, 1, &ksi);
506 PGRP_UNLOCK(pg);
507
508 error = tty_wait(tp, &tp->t_bgwait);
509 if (error)
510 return (error);
511 }
512 }
513
514 static int
ttydev_read(struct cdev * dev,struct uio * uio,int ioflag)515 ttydev_read(struct cdev *dev, struct uio *uio, int ioflag)
516 {
517 struct tty *tp = dev->si_drv1;
518 int error;
519
520 error = ttydev_enter(tp);
521 if (error)
522 goto done;
523 error = ttydisc_read(tp, uio, ioflag);
524 tty_unlock(tp);
525
526 /*
527 * The read() call should not throw an error when the device is
528 * being destroyed. Silently convert it to an EOF.
529 */
530 done: if (error == ENXIO)
531 error = 0;
532 return (error);
533 }
534
535 static int
ttydev_write(struct cdev * dev,struct uio * uio,int ioflag)536 ttydev_write(struct cdev *dev, struct uio *uio, int ioflag)
537 {
538 struct tty *tp = dev->si_drv1;
539 int defer, error;
540
541 error = ttydev_enter(tp);
542 if (error)
543 return (error);
544
545 if (tp->t_termios.c_lflag & TOSTOP) {
546 error = tty_wait_background(tp, curthread, SIGTTOU);
547 if (error)
548 goto done;
549 }
550
551 if (ioflag & IO_NDELAY && tp->t_flags & TF_BUSY_OUT) {
552 /* Allow non-blocking writes to bypass serialization. */
553 error = ttydisc_write(tp, uio, ioflag);
554 } else {
555 /* Serialize write() calls. */
556 while (tp->t_flags & TF_BUSY_OUT) {
557 error = tty_wait(tp, &tp->t_outserwait);
558 if (error)
559 goto done;
560 }
561
562 tp->t_flags |= TF_BUSY_OUT;
563 defer = sigdeferstop(SIGDEFERSTOP_ERESTART);
564 error = ttydisc_write(tp, uio, ioflag);
565 sigallowstop(defer);
566 tp->t_flags &= ~TF_BUSY_OUT;
567 cv_signal(&tp->t_outserwait);
568 }
569
570 done: tty_unlock(tp);
571 return (error);
572 }
573
574 static int
ttydev_ioctl(struct cdev * dev,u_long cmd,caddr_t data,int fflag,struct thread * td)575 ttydev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
576 struct thread *td)
577 {
578 struct tty *tp = dev->si_drv1;
579 int error;
580
581 error = ttydev_enter(tp);
582 if (error)
583 return (error);
584
585 switch (cmd) {
586 case TIOCCBRK:
587 case TIOCCONS:
588 case TIOCDRAIN:
589 case TIOCEXCL:
590 case TIOCFLUSH:
591 case TIOCNXCL:
592 case TIOCSBRK:
593 case TIOCSCTTY:
594 case TIOCSETA:
595 case TIOCSETAF:
596 case TIOCSETAW:
597 case TIOCSPGRP:
598 case TIOCSTART:
599 case TIOCSTAT:
600 case TIOCSTI:
601 case TIOCSTOP:
602 case TIOCSWINSZ:
603 #if 0
604 case TIOCSDRAINWAIT:
605 case TIOCSETD:
606 #endif
607 #ifdef COMPAT_43TTY
608 case TIOCLBIC:
609 case TIOCLBIS:
610 case TIOCLSET:
611 case TIOCSETC:
612 case OTIOCSETD:
613 case TIOCSETN:
614 case TIOCSETP:
615 case TIOCSLTC:
616 #endif /* COMPAT_43TTY */
617 /*
618 * If the ioctl() causes the TTY to be modified, let it
619 * wait in the background.
620 */
621 error = tty_wait_background(tp, curthread, SIGTTOU);
622 if (error)
623 goto done;
624 }
625
626 if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
627 struct termios *old = &tp->t_termios;
628 struct termios *new = (struct termios *)data;
629 struct termios *lock = TTY_CALLOUT(tp, dev) ?
630 &tp->t_termios_lock_out : &tp->t_termios_lock_in;
631 int cc;
632
633 /*
634 * Lock state devices. Just overwrite the values of the
635 * commands that are currently in use.
636 */
637 new->c_iflag = (old->c_iflag & lock->c_iflag) |
638 (new->c_iflag & ~lock->c_iflag);
639 new->c_oflag = (old->c_oflag & lock->c_oflag) |
640 (new->c_oflag & ~lock->c_oflag);
641 new->c_cflag = (old->c_cflag & lock->c_cflag) |
642 (new->c_cflag & ~lock->c_cflag);
643 new->c_lflag = (old->c_lflag & lock->c_lflag) |
644 (new->c_lflag & ~lock->c_lflag);
645 for (cc = 0; cc < NCCS; ++cc)
646 if (lock->c_cc[cc])
647 new->c_cc[cc] = old->c_cc[cc];
648 if (lock->c_ispeed)
649 new->c_ispeed = old->c_ispeed;
650 if (lock->c_ospeed)
651 new->c_ospeed = old->c_ospeed;
652 }
653
654 error = tty_ioctl(tp, cmd, data, fflag, td);
655 done: tty_unlock(tp);
656
657 return (error);
658 }
659
660 static int
ttydev_poll(struct cdev * dev,int events,struct thread * td)661 ttydev_poll(struct cdev *dev, int events, struct thread *td)
662 {
663 struct tty *tp = dev->si_drv1;
664 int error, revents = 0;
665
666 error = ttydev_enter(tp);
667 if (error)
668 return ((events & (POLLIN|POLLRDNORM)) | POLLHUP);
669
670 if (events & (POLLIN|POLLRDNORM)) {
671 /* See if we can read something. */
672 if (ttydisc_read_poll(tp) > 0)
673 revents |= events & (POLLIN|POLLRDNORM);
674 }
675
676 if (tp->t_flags & TF_ZOMBIE) {
677 /* Hangup flag on zombie state. */
678 revents |= POLLHUP;
679 } else if (events & (POLLOUT|POLLWRNORM)) {
680 /* See if we can write something. */
681 if (ttydisc_write_poll(tp) > 0)
682 revents |= events & (POLLOUT|POLLWRNORM);
683 }
684
685 if (revents == 0) {
686 if (events & (POLLIN|POLLRDNORM))
687 selrecord(td, &tp->t_inpoll);
688 if (events & (POLLOUT|POLLWRNORM))
689 selrecord(td, &tp->t_outpoll);
690 }
691
692 tty_unlock(tp);
693
694 return (revents);
695 }
696
697 static int
ttydev_mmap(struct cdev * dev,vm_ooffset_t offset,vm_paddr_t * paddr,int nprot,vm_memattr_t * memattr)698 ttydev_mmap(struct cdev *dev, vm_ooffset_t offset, vm_paddr_t *paddr,
699 int nprot, vm_memattr_t *memattr)
700 {
701 struct tty *tp = dev->si_drv1;
702 int error;
703
704 /* Handle mmap() through the driver. */
705
706 error = ttydev_enter(tp);
707 if (error)
708 return (-1);
709 error = ttydevsw_mmap(tp, offset, paddr, nprot, memattr);
710 tty_unlock(tp);
711
712 return (error);
713 }
714
715 /*
716 * kqueue support.
717 */
718
719 static void
tty_kqops_read_detach(struct knote * kn)720 tty_kqops_read_detach(struct knote *kn)
721 {
722 struct tty *tp = kn->kn_hook;
723
724 knlist_remove(&tp->t_inpoll.si_note, kn, 0);
725 }
726
727 static int
tty_kqops_read_event(struct knote * kn,long hint __unused)728 tty_kqops_read_event(struct knote *kn, long hint __unused)
729 {
730 struct tty *tp = kn->kn_hook;
731
732 tty_assert_locked(tp);
733
734 if (tty_gone(tp) || tp->t_flags & TF_ZOMBIE) {
735 kn->kn_flags |= EV_EOF;
736 return (1);
737 } else {
738 kn->kn_data = ttydisc_read_poll(tp);
739 return (kn->kn_data > 0);
740 }
741 }
742
743 static void
tty_kqops_write_detach(struct knote * kn)744 tty_kqops_write_detach(struct knote *kn)
745 {
746 struct tty *tp = kn->kn_hook;
747
748 knlist_remove(&tp->t_outpoll.si_note, kn, 0);
749 }
750
751 static int
tty_kqops_write_event(struct knote * kn,long hint __unused)752 tty_kqops_write_event(struct knote *kn, long hint __unused)
753 {
754 struct tty *tp = kn->kn_hook;
755
756 tty_assert_locked(tp);
757
758 if (tty_gone(tp)) {
759 kn->kn_flags |= EV_EOF;
760 return (1);
761 } else {
762 kn->kn_data = ttydisc_write_poll(tp);
763 return (kn->kn_data > 0);
764 }
765 }
766
767 static const struct filterops tty_kqops_read = {
768 .f_isfd = 1,
769 .f_detach = tty_kqops_read_detach,
770 .f_event = tty_kqops_read_event,
771 .f_copy = knote_triv_copy,
772 };
773
774 static const struct filterops tty_kqops_write = {
775 .f_isfd = 1,
776 .f_detach = tty_kqops_write_detach,
777 .f_event = tty_kqops_write_event,
778 .f_copy = knote_triv_copy,
779 };
780
781 static int
ttydev_kqfilter(struct cdev * dev,struct knote * kn)782 ttydev_kqfilter(struct cdev *dev, struct knote *kn)
783 {
784 struct tty *tp = dev->si_drv1;
785 int error;
786
787 error = ttydev_enter(tp);
788 if (error)
789 return (error);
790
791 switch (kn->kn_filter) {
792 case EVFILT_READ:
793 kn->kn_hook = tp;
794 kn->kn_fop = &tty_kqops_read;
795 knlist_add(&tp->t_inpoll.si_note, kn, 1);
796 break;
797 case EVFILT_WRITE:
798 kn->kn_hook = tp;
799 kn->kn_fop = &tty_kqops_write;
800 knlist_add(&tp->t_outpoll.si_note, kn, 1);
801 break;
802 default:
803 error = EINVAL;
804 break;
805 }
806
807 tty_unlock(tp);
808 return (error);
809 }
810
811 static struct cdevsw ttydev_cdevsw = {
812 .d_version = D_VERSION,
813 .d_open = ttydev_open,
814 .d_close = ttydev_close,
815 .d_read = ttydev_read,
816 .d_write = ttydev_write,
817 .d_ioctl = ttydev_ioctl,
818 .d_kqfilter = ttydev_kqfilter,
819 .d_poll = ttydev_poll,
820 .d_mmap = ttydev_mmap,
821 .d_name = "ttydev",
822 .d_flags = D_TTY,
823 };
824
825 /*
826 * Init/lock-state devices
827 */
828
829 static int
ttyil_open(struct cdev * dev,int oflags __unused,int devtype __unused,struct thread * td)830 ttyil_open(struct cdev *dev, int oflags __unused, int devtype __unused,
831 struct thread *td)
832 {
833 struct tty *tp;
834 int error;
835
836 tp = dev->si_drv1;
837 error = 0;
838 tty_lock(tp);
839 if (tty_gone(tp))
840 error = ENODEV;
841 tty_unlock(tp);
842
843 return (error);
844 }
845
846 static int
ttyil_close(struct cdev * dev __unused,int flag __unused,int mode __unused,struct thread * td __unused)847 ttyil_close(struct cdev *dev __unused, int flag __unused, int mode __unused,
848 struct thread *td __unused)
849 {
850
851 return (0);
852 }
853
854 static int
ttyil_rdwr(struct cdev * dev __unused,struct uio * uio __unused,int ioflag __unused)855 ttyil_rdwr(struct cdev *dev __unused, struct uio *uio __unused,
856 int ioflag __unused)
857 {
858
859 return (ENODEV);
860 }
861
862 static int
ttyil_ioctl(struct cdev * dev,u_long cmd,caddr_t data,int fflag,struct thread * td)863 ttyil_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
864 struct thread *td)
865 {
866 struct tty *tp = dev->si_drv1;
867 int error;
868
869 tty_lock(tp);
870 if (tty_gone(tp)) {
871 error = (EXTERROR(ENODEV, "ttyil_ioctl: device is gone"));
872 goto done;
873 }
874
875 error = ttydevsw_cioctl(tp, dev2unit(dev), cmd, data, td);
876 if (error != ENOIOCTL)
877 goto done;
878 error = 0;
879
880 switch (cmd) {
881 case TIOCGETA:
882 /* Obtain terminal flags through tcgetattr(). */
883 *(struct termios*)data = *(struct termios*)dev->si_drv2;
884 break;
885 case TIOCSETA:
886 /* Set terminal flags through tcsetattr(). */
887 error = priv_check(td, PRIV_TTY_SETA);
888 if (error)
889 break;
890 *(struct termios*)dev->si_drv2 = *(struct termios*)data;
891 break;
892 case TIOCGETD:
893 *(int *)data = TTYDISC;
894 break;
895 case TIOCGWINSZ:
896 bzero(data, sizeof(struct winsize));
897 break;
898 default:
899 error = ENOTTY;
900 }
901
902 done: tty_unlock(tp);
903 return (error);
904 }
905
906 static struct cdevsw ttyil_cdevsw = {
907 .d_version = D_VERSION,
908 .d_open = ttyil_open,
909 .d_close = ttyil_close,
910 .d_read = ttyil_rdwr,
911 .d_write = ttyil_rdwr,
912 .d_ioctl = ttyil_ioctl,
913 .d_name = "ttyil",
914 .d_flags = D_TTY,
915 };
916
917 static void
tty_init_termios(struct tty * tp)918 tty_init_termios(struct tty *tp)
919 {
920 struct termios *t = &tp->t_termios_init_in;
921
922 t->c_cflag = TTYDEF_CFLAG;
923 t->c_iflag = TTYDEF_IFLAG;
924 t->c_lflag = TTYDEF_LFLAG;
925 t->c_oflag = TTYDEF_OFLAG;
926 t->c_ispeed = TTYDEF_SPEED;
927 t->c_ospeed = TTYDEF_SPEED;
928 memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars);
929
930 tp->t_termios_init_out = *t;
931 }
932
933 void
tty_init_console(struct tty * tp,speed_t s)934 tty_init_console(struct tty *tp, speed_t s)
935 {
936 struct termios *ti = &tp->t_termios_init_in;
937 struct termios *to = &tp->t_termios_init_out;
938
939 if (s != 0) {
940 ti->c_ispeed = ti->c_ospeed = s;
941 to->c_ispeed = to->c_ospeed = s;
942 }
943
944 ti->c_cflag |= CLOCAL;
945 to->c_cflag |= CLOCAL;
946 }
947
948 /*
949 * Standard device routine implementations, mostly meant for
950 * pseudo-terminal device drivers. When a driver creates a new terminal
951 * device class, missing routines are patched.
952 */
953
954 static int
ttydevsw_defopen(struct tty * tp __unused)955 ttydevsw_defopen(struct tty *tp __unused)
956 {
957
958 return (0);
959 }
960
961 static void
ttydevsw_defclose(struct tty * tp __unused)962 ttydevsw_defclose(struct tty *tp __unused)
963 {
964
965 }
966
967 static void
ttydevsw_defoutwakeup(struct tty * tp __unused)968 ttydevsw_defoutwakeup(struct tty *tp __unused)
969 {
970
971 panic("Terminal device has output, while not implemented");
972 }
973
974 static void
ttydevsw_definwakeup(struct tty * tp __unused)975 ttydevsw_definwakeup(struct tty *tp __unused)
976 {
977
978 }
979
980 static int
ttydevsw_defioctl(struct tty * tp __unused,u_long cmd __unused,caddr_t data __unused,struct thread * td __unused)981 ttydevsw_defioctl(struct tty *tp __unused, u_long cmd __unused,
982 caddr_t data __unused, struct thread *td __unused)
983 {
984
985 return (ENOIOCTL);
986 }
987
988 static int
ttydevsw_defcioctl(struct tty * tp __unused,int unit __unused,u_long cmd __unused,caddr_t data __unused,struct thread * td __unused)989 ttydevsw_defcioctl(struct tty *tp __unused, int unit __unused,
990 u_long cmd __unused, caddr_t data __unused, struct thread *td __unused)
991 {
992
993 return (ENOIOCTL);
994 }
995
996 static int
ttydevsw_defparam(struct tty * tp __unused,struct termios * t)997 ttydevsw_defparam(struct tty *tp __unused, struct termios *t)
998 {
999
1000 /*
1001 * Allow the baud rate to be adjusted for pseudo-devices, but at
1002 * least restrict it to 115200 to prevent excessive buffer
1003 * usage. Also disallow 0, to prevent foot shooting.
1004 */
1005 if (t->c_ispeed < B50)
1006 t->c_ispeed = B50;
1007 else if (t->c_ispeed > B115200)
1008 t->c_ispeed = B115200;
1009 if (t->c_ospeed < B50)
1010 t->c_ospeed = B50;
1011 else if (t->c_ospeed > B115200)
1012 t->c_ospeed = B115200;
1013 t->c_cflag |= CREAD;
1014
1015 return (0);
1016 }
1017
1018 static int
ttydevsw_defmodem(struct tty * tp __unused,int sigon __unused,int sigoff __unused)1019 ttydevsw_defmodem(struct tty *tp __unused, int sigon __unused,
1020 int sigoff __unused)
1021 {
1022
1023 /* Simulate a carrier to make the TTY layer happy. */
1024 return (SER_DCD);
1025 }
1026
1027 static int
ttydevsw_defmmap(struct tty * tp __unused,vm_ooffset_t offset __unused,vm_paddr_t * paddr __unused,int nprot __unused,vm_memattr_t * memattr __unused)1028 ttydevsw_defmmap(struct tty *tp __unused, vm_ooffset_t offset __unused,
1029 vm_paddr_t *paddr __unused, int nprot __unused,
1030 vm_memattr_t *memattr __unused)
1031 {
1032
1033 return (-1);
1034 }
1035
1036 static void
ttydevsw_defpktnotify(struct tty * tp __unused,char event __unused)1037 ttydevsw_defpktnotify(struct tty *tp __unused, char event __unused)
1038 {
1039
1040 }
1041
1042 static void
ttydevsw_deffree(void * softc __unused)1043 ttydevsw_deffree(void *softc __unused)
1044 {
1045
1046 panic("Terminal device freed without a free-handler");
1047 }
1048
1049 static bool
ttydevsw_defbusy(struct tty * tp __unused)1050 ttydevsw_defbusy(struct tty *tp __unused)
1051 {
1052
1053 return (false);
1054 }
1055
1056 /*
1057 * TTY allocation and deallocation. TTY devices can be deallocated when
1058 * the driver doesn't use it anymore, when the TTY isn't a session's
1059 * controlling TTY and when the device node isn't opened through devfs.
1060 */
1061
1062 struct tty *
tty_alloc(struct ttydevsw * tsw,void * sc)1063 tty_alloc(struct ttydevsw *tsw, void *sc)
1064 {
1065
1066 return (tty_alloc_mutex(tsw, sc, NULL));
1067 }
1068
1069 struct tty *
tty_alloc_mutex(struct ttydevsw * tsw,void * sc,struct mtx * mutex)1070 tty_alloc_mutex(struct ttydevsw *tsw, void *sc, struct mtx *mutex)
1071 {
1072 struct tty *tp;
1073
1074 /* Make sure the driver defines all routines. */
1075 #define PATCH_FUNC(x) do { \
1076 if (tsw->tsw_ ## x == NULL) \
1077 tsw->tsw_ ## x = ttydevsw_def ## x; \
1078 } while (0)
1079 PATCH_FUNC(open);
1080 PATCH_FUNC(close);
1081 PATCH_FUNC(outwakeup);
1082 PATCH_FUNC(inwakeup);
1083 PATCH_FUNC(ioctl);
1084 PATCH_FUNC(cioctl);
1085 PATCH_FUNC(param);
1086 PATCH_FUNC(modem);
1087 PATCH_FUNC(mmap);
1088 PATCH_FUNC(pktnotify);
1089 PATCH_FUNC(free);
1090 PATCH_FUNC(busy);
1091 #undef PATCH_FUNC
1092
1093 tp = malloc(sizeof(struct tty) + TTY_PRBUF_SIZE, M_TTY,
1094 M_WAITOK | M_ZERO);
1095 tp->t_prbufsz = TTY_PRBUF_SIZE;
1096 tp->t_devsw = tsw;
1097 tp->t_devswsoftc = sc;
1098 tp->t_flags = tsw->tsw_flags;
1099 tp->t_drainwait = tty_drainwait;
1100
1101 tty_init_termios(tp);
1102
1103 cv_init(&tp->t_inwait, "ttyin");
1104 cv_init(&tp->t_outwait, "ttyout");
1105 cv_init(&tp->t_outserwait, "ttyosr");
1106 cv_init(&tp->t_bgwait, "ttybg");
1107 cv_init(&tp->t_dcdwait, "ttydcd");
1108
1109 /* Allow drivers to use a custom mutex to lock the TTY. */
1110 if (mutex != NULL) {
1111 tp->t_mtx = mutex;
1112 } else {
1113 tp->t_mtx = &tp->t_mtxobj;
1114 mtx_init(&tp->t_mtxobj, "ttymtx", NULL, MTX_DEF);
1115 }
1116
1117 knlist_init_mtx(&tp->t_inpoll.si_note, tp->t_mtx);
1118 knlist_init_mtx(&tp->t_outpoll.si_note, tp->t_mtx);
1119
1120 return (tp);
1121 }
1122
1123 static void
tty_dealloc(void * arg)1124 tty_dealloc(void *arg)
1125 {
1126 struct tty *tp = arg;
1127
1128 /*
1129 * ttyydev_leave() usually frees the i/o queues earlier, but it is
1130 * not always called between queue allocation and here. The queues
1131 * may be allocated by ioctls on a pty control device without the
1132 * corresponding pty slave device ever being open, or after it is
1133 * closed.
1134 */
1135 ttyinq_free(&tp->t_inq);
1136 ttyoutq_free(&tp->t_outq);
1137 seldrain(&tp->t_inpoll);
1138 seldrain(&tp->t_outpoll);
1139 knlist_clear(&tp->t_inpoll.si_note, 0);
1140 knlist_clear(&tp->t_outpoll.si_note, 0);
1141 knlist_destroy(&tp->t_inpoll.si_note);
1142 knlist_destroy(&tp->t_outpoll.si_note);
1143
1144 cv_destroy(&tp->t_inwait);
1145 cv_destroy(&tp->t_outwait);
1146 cv_destroy(&tp->t_bgwait);
1147 cv_destroy(&tp->t_dcdwait);
1148 cv_destroy(&tp->t_outserwait);
1149
1150 if (tp->t_mtx == &tp->t_mtxobj)
1151 mtx_destroy(&tp->t_mtxobj);
1152 ttydevsw_free(tp);
1153 free(tp, M_TTY);
1154 }
1155
1156 static void
tty_rel_free(struct tty * tp,bool inttydevclose)1157 tty_rel_free(struct tty *tp, bool inttydevclose)
1158 {
1159 struct cdev *dev;
1160
1161 tty_assert_locked(tp);
1162
1163 #define TF_ACTIVITY (TF_GONE|TF_OPENED|TF_HOOK|TF_OPENCLOSE)
1164 if (tp->t_sessioncnt != 0 || (tp->t_flags & TF_ACTIVITY) != TF_GONE) {
1165 /* TTY is still in use. */
1166 if (inttydevclose)
1167 tp->t_flags &= ~TF_INDEVCLOSE;
1168 tty_unlock(tp);
1169 return;
1170 }
1171
1172 /* Stop asynchronous I/O. */
1173 funsetown(&tp->t_sigio);
1174
1175 /* TTY can be deallocated. */
1176 dev = tp->t_dev;
1177 tp->t_dev = NULL;
1178 if (inttydevclose)
1179 tp->t_flags &= ~TF_INDEVCLOSE;
1180 tty_unlock(tp);
1181
1182 if (dev != NULL) {
1183 sx_xlock(&tty_list_sx);
1184 TAILQ_REMOVE(&tty_list, tp, t_list);
1185 tty_list_count--;
1186 sx_xunlock(&tty_list_sx);
1187 destroy_dev_sched_cb(dev, tty_dealloc, tp);
1188 }
1189 }
1190
1191 void
tty_rel_pgrp(struct tty * tp,struct pgrp * pg)1192 tty_rel_pgrp(struct tty *tp, struct pgrp *pg)
1193 {
1194
1195 MPASS(tp->t_sessioncnt > 0);
1196 tty_assert_locked(tp);
1197
1198 if (tp->t_pgrp == pg)
1199 tp->t_pgrp = NULL;
1200
1201 tty_unlock(tp);
1202 }
1203
1204 void
tty_rel_sess(struct tty * tp,struct session * sess)1205 tty_rel_sess(struct tty *tp, struct session *sess)
1206 {
1207
1208 MPASS(tp->t_sessioncnt > 0);
1209
1210 /* Current session has left. */
1211 if (tp->t_session == sess) {
1212 tp->t_session = NULL;
1213 MPASS(tp->t_pgrp == NULL);
1214 }
1215 tp->t_sessioncnt--;
1216 tty_rel_free(tp, false);
1217 }
1218
1219 void
tty_rel_gone(struct tty * tp)1220 tty_rel_gone(struct tty *tp)
1221 {
1222
1223 tty_assert_locked(tp);
1224 MPASS(!tty_gone(tp));
1225
1226 /* Simulate carrier removal. */
1227 ttydisc_modem(tp, 0);
1228
1229 /* Wake up all blocked threads. */
1230 tty_wakeup(tp, FREAD|FWRITE);
1231 cv_broadcast(&tp->t_bgwait);
1232 cv_broadcast(&tp->t_dcdwait);
1233
1234 tp->t_flags |= TF_GONE;
1235 tty_rel_free(tp, false);
1236 }
1237
1238 static int
tty_drop_ctty(struct tty * tp,struct proc * p)1239 tty_drop_ctty(struct tty *tp, struct proc *p)
1240 {
1241 struct session *session;
1242 struct vnode *vp;
1243
1244 /*
1245 * This looks terrible, but it's generally safe as long as the tty
1246 * hasn't gone away while we had the lock dropped. All of our sanity
1247 * checking that this operation is OK happens after we've picked it back
1248 * up, so other state changes are generally not fatal and the potential
1249 * for this particular operation to happen out-of-order in a
1250 * multithreaded scenario is likely a non-issue.
1251 */
1252 tty_unlock(tp);
1253 sx_xlock(&proctree_lock);
1254 tty_lock(tp);
1255 if (tty_gone(tp)) {
1256 sx_xunlock(&proctree_lock);
1257 return (EXTERROR(ENODEV, "tty_drop_ctty: device is gone"));
1258 }
1259
1260 /*
1261 * If the session doesn't have a controlling TTY, or if we weren't
1262 * invoked on the controlling TTY, we'll return ENOTTY as we've
1263 * historically done.
1264 */
1265 session = p->p_session;
1266 if (session->s_ttyp == NULL || session->s_ttyp != tp) {
1267 sx_xunlock(&proctree_lock);
1268 return (EXTERROR(ENOTTY, "no controlling tty"));
1269 }
1270
1271 if (!SESS_LEADER(p)) {
1272 sx_xunlock(&proctree_lock);
1273 return (EXTERROR(EPERM, "not a session leader"));
1274 }
1275
1276 PROC_LOCK(p);
1277 SESS_LOCK(session);
1278 vp = session->s_ttyvp;
1279 session->s_ttyp = NULL;
1280 session->s_ttyvp = NULL;
1281 session->s_ttydp = NULL;
1282 SESS_UNLOCK(session);
1283
1284 if (tp->t_session == session) {
1285 tp->t_session = NULL;
1286 tp->t_pgrp = NULL;
1287 }
1288 tp->t_sessioncnt--;
1289 p->p_flag &= ~P_CONTROLT;
1290 PROC_UNLOCK(p);
1291 sx_xunlock(&proctree_lock);
1292
1293 /*
1294 * If we did have a vnode, release our reference. Ordinarily we manage
1295 * these at the devfs layer, but we can't necessarily know that we were
1296 * invoked on the vnode referenced in the session (i.e. the vnode we
1297 * hold a reference to). We explicitly don't check VBAD/VIRF_DOOMED here
1298 * to avoid a vnode leak -- in circumstances elsewhere where we'd hit a
1299 * VIRF_DOOMED vnode, release has been deferred until the controlling TTY
1300 * is either changed or released.
1301 */
1302 if (vp != NULL)
1303 devfs_ctty_unref(vp);
1304 return (0);
1305 }
1306
1307 /*
1308 * Exposing information about current TTY's through sysctl
1309 */
1310
1311 static void
tty_to_xtty(struct tty * tp,struct xtty * xt)1312 tty_to_xtty(struct tty *tp, struct xtty *xt)
1313 {
1314
1315 tty_assert_locked(tp);
1316
1317 memset(xt, 0, sizeof(*xt));
1318 xt->xt_size = sizeof(struct xtty);
1319 xt->xt_insize = ttyinq_getsize(&tp->t_inq);
1320 xt->xt_incc = ttyinq_bytescanonicalized(&tp->t_inq);
1321 xt->xt_inlc = ttyinq_bytesline(&tp->t_inq);
1322 xt->xt_inlow = tp->t_inlow;
1323 xt->xt_outsize = ttyoutq_getsize(&tp->t_outq);
1324 xt->xt_outcc = ttyoutq_bytesused(&tp->t_outq);
1325 xt->xt_outlow = tp->t_outlow;
1326 xt->xt_column = tp->t_column;
1327 xt->xt_pgid = tp->t_pgrp ? tp->t_pgrp->pg_id : 0;
1328 xt->xt_sid = tp->t_session ? tp->t_session->s_sid : 0;
1329 xt->xt_flags = tp->t_flags;
1330 xt->xt_dev = tp->t_dev ? dev2udev(tp->t_dev) : (uint32_t)NODEV;
1331 }
1332
1333 static int
sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)1334 sysctl_kern_ttys(SYSCTL_HANDLER_ARGS)
1335 {
1336 unsigned long lsize;
1337 struct thread *td = curthread;
1338 struct xtty *xtlist, *xt;
1339 struct tty *tp;
1340 struct proc *p;
1341 int error;
1342 bool cansee;
1343
1344 sx_slock(&tty_list_sx);
1345 lsize = tty_list_count * sizeof(struct xtty);
1346 if (lsize == 0) {
1347 sx_sunlock(&tty_list_sx);
1348 return (0);
1349 }
1350
1351 xtlist = xt = malloc(lsize, M_TTY, M_WAITOK);
1352
1353 TAILQ_FOREACH(tp, &tty_list, t_list) {
1354 tty_lock(tp);
1355 if (tp->t_session != NULL &&
1356 (p = atomic_load_ptr(&tp->t_session->s_leader)) != NULL) {
1357 PROC_LOCK(p);
1358 cansee = (p_cansee(td, p) == 0);
1359 PROC_UNLOCK(p);
1360 } else {
1361 cansee = !jailed(td->td_ucred);
1362 }
1363 if (cansee) {
1364 tty_to_xtty(tp, xt);
1365 xt++;
1366 }
1367 tty_unlock(tp);
1368 }
1369 sx_sunlock(&tty_list_sx);
1370
1371 lsize = (xt - xtlist) * sizeof(struct xtty);
1372 if (lsize > 0) {
1373 error = SYSCTL_OUT(req, xtlist, lsize);
1374 } else {
1375 error = 0;
1376 }
1377 free(xtlist, M_TTY);
1378 return (error);
1379 }
1380
1381 SYSCTL_PROC(_kern, OID_AUTO, ttys, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
1382 0, 0, sysctl_kern_ttys, "S,xtty", "List of TTYs");
1383
1384 /*
1385 * Device node creation. Device has been set up, now we can expose it to
1386 * the user.
1387 */
1388
1389 int
tty_makedevf(struct tty * tp,struct ucred * cred,int flags,const char * fmt,...)1390 tty_makedevf(struct tty *tp, struct ucred *cred, int flags,
1391 const char *fmt, ...)
1392 {
1393 va_list ap;
1394 struct make_dev_args args;
1395 struct cdev *dev, *init, *lock, *cua, *cinit, *clock;
1396 const char *prefix = "tty";
1397 char name[SPECNAMELEN - 3]; /* for "tty" and "cua". */
1398 uid_t uid;
1399 gid_t gid;
1400 mode_t mode;
1401 int error;
1402
1403 /* Remove "tty" prefix from devices like PTY's. */
1404 if (tp->t_flags & TF_NOPREFIX)
1405 prefix = "";
1406
1407 va_start(ap, fmt);
1408 vsnrprintf(name, sizeof name, 32, fmt, ap);
1409 va_end(ap);
1410
1411 if (cred == NULL) {
1412 /* System device. */
1413 uid = UID_ROOT;
1414 gid = GID_WHEEL;
1415 mode = S_IRUSR|S_IWUSR;
1416 } else {
1417 /* User device. */
1418 uid = cred->cr_ruid;
1419 gid = GID_TTY;
1420 mode = S_IRUSR|S_IWUSR|S_IWGRP;
1421 }
1422
1423 flags = flags & TTYMK_CLONING ? MAKEDEV_REF : 0;
1424 flags |= MAKEDEV_CHECKNAME;
1425
1426 /* Master call-in device. */
1427 make_dev_args_init(&args);
1428 args.mda_flags = flags;
1429 args.mda_devsw = &ttydev_cdevsw;
1430 args.mda_cr = cred;
1431 args.mda_uid = uid;
1432 args.mda_gid = gid;
1433 args.mda_mode = mode;
1434 args.mda_si_drv1 = tp;
1435 error = make_dev_s(&args, &dev, "%s%s", prefix, name);
1436 if (error != 0)
1437 return (error);
1438 tp->t_dev = dev;
1439
1440 init = lock = cua = cinit = clock = NULL;
1441
1442 /* Slave call-in devices. */
1443 if (tp->t_flags & TF_INITLOCK) {
1444 args.mda_devsw = &ttyil_cdevsw;
1445 args.mda_unit = TTYUNIT_INIT;
1446 args.mda_si_drv1 = tp;
1447 args.mda_si_drv2 = &tp->t_termios_init_in;
1448 error = make_dev_s(&args, &init, "%s%s.init", prefix, name);
1449 if (error != 0)
1450 goto fail;
1451 dev_depends(dev, init);
1452
1453 args.mda_unit = TTYUNIT_LOCK;
1454 args.mda_si_drv2 = &tp->t_termios_lock_in;
1455 error = make_dev_s(&args, &lock, "%s%s.lock", prefix, name);
1456 if (error != 0)
1457 goto fail;
1458 dev_depends(dev, lock);
1459 }
1460
1461 /* Call-out devices. */
1462 if (tp->t_flags & TF_CALLOUT) {
1463 make_dev_args_init(&args);
1464 args.mda_flags = flags;
1465 args.mda_devsw = &ttydev_cdevsw;
1466 args.mda_cr = cred;
1467 args.mda_uid = UID_UUCP;
1468 args.mda_gid = GID_DIALER;
1469 args.mda_mode = 0660;
1470 args.mda_unit = TTYUNIT_CALLOUT;
1471 args.mda_si_drv1 = tp;
1472 error = make_dev_s(&args, &cua, "cua%s", name);
1473 if (error != 0)
1474 goto fail;
1475 dev_depends(dev, cua);
1476
1477 /* Slave call-out devices. */
1478 if (tp->t_flags & TF_INITLOCK) {
1479 args.mda_devsw = &ttyil_cdevsw;
1480 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_INIT;
1481 args.mda_si_drv2 = &tp->t_termios_init_out;
1482 error = make_dev_s(&args, &cinit, "cua%s.init", name);
1483 if (error != 0)
1484 goto fail;
1485 dev_depends(dev, cinit);
1486
1487 args.mda_unit = TTYUNIT_CALLOUT | TTYUNIT_LOCK;
1488 args.mda_si_drv2 = &tp->t_termios_lock_out;
1489 error = make_dev_s(&args, &clock, "cua%s.lock", name);
1490 if (error != 0)
1491 goto fail;
1492 dev_depends(dev, clock);
1493 }
1494 }
1495
1496 sx_xlock(&tty_list_sx);
1497 TAILQ_INSERT_TAIL(&tty_list, tp, t_list);
1498 tty_list_count++;
1499 sx_xunlock(&tty_list_sx);
1500
1501 return (0);
1502
1503 fail:
1504 destroy_dev(dev);
1505 if (init)
1506 destroy_dev(init);
1507 if (lock)
1508 destroy_dev(lock);
1509 if (cinit)
1510 destroy_dev(cinit);
1511 if (clock)
1512 destroy_dev(clock);
1513
1514 return (error);
1515 }
1516
1517 /*
1518 * Signalling processes.
1519 */
1520
1521 void
tty_signal_sessleader(struct tty * tp,int sig)1522 tty_signal_sessleader(struct tty *tp, int sig)
1523 {
1524 struct proc *p;
1525 struct session *s;
1526
1527 tty_assert_locked(tp);
1528 MPASS(sig >= 1 && sig < NSIG);
1529
1530 /* Make signals start output again. */
1531 tp->t_flags &= ~TF_STOPPED;
1532 tp->t_termios.c_lflag &= ~FLUSHO;
1533
1534 /*
1535 * Load s_leader exactly once to avoid race where s_leader is
1536 * set to NULL by a concurrent invocation of killjobc() by the
1537 * session leader. Note that we are not holding t_session's
1538 * lock for the read.
1539 */
1540 if ((s = tp->t_session) != NULL &&
1541 (p = atomic_load_ptr(&s->s_leader)) != NULL) {
1542 PROC_LOCK(p);
1543 kern_psignal(p, sig);
1544 PROC_UNLOCK(p);
1545 }
1546 }
1547
1548 void
tty_signal_pgrp(struct tty * tp,int sig)1549 tty_signal_pgrp(struct tty *tp, int sig)
1550 {
1551 ksiginfo_t ksi;
1552
1553 tty_assert_locked(tp);
1554 MPASS(sig >= 1 && sig < NSIG);
1555
1556 /* Make signals start output again. */
1557 tp->t_flags &= ~TF_STOPPED;
1558 tp->t_termios.c_lflag &= ~FLUSHO;
1559
1560 if (sig == SIGINFO && !(tp->t_termios.c_lflag & NOKERNINFO))
1561 tty_info(tp);
1562 if (tp->t_pgrp != NULL) {
1563 ksiginfo_init(&ksi);
1564 ksi.ksi_signo = sig;
1565 ksi.ksi_code = SI_KERNEL;
1566 PGRP_LOCK(tp->t_pgrp);
1567 pgsignal(tp->t_pgrp, sig, 1, &ksi);
1568 PGRP_UNLOCK(tp->t_pgrp);
1569 }
1570 }
1571
1572 void
tty_wakeup(struct tty * tp,int flags)1573 tty_wakeup(struct tty *tp, int flags)
1574 {
1575
1576 if (tp->t_flags & TF_ASYNC && tp->t_sigio != NULL)
1577 pgsigio(&tp->t_sigio, SIGIO, (tp->t_session != NULL));
1578
1579 if (flags & FWRITE) {
1580 cv_broadcast(&tp->t_outwait);
1581 selwakeup(&tp->t_outpoll);
1582 KNOTE_LOCKED(&tp->t_outpoll.si_note, 0);
1583 }
1584 if (flags & FREAD) {
1585 cv_broadcast(&tp->t_inwait);
1586 selwakeup(&tp->t_inpoll);
1587 KNOTE_LOCKED(&tp->t_inpoll.si_note, 0);
1588 }
1589 }
1590
1591 int
tty_wait(struct tty * tp,struct cv * cv)1592 tty_wait(struct tty *tp, struct cv *cv)
1593 {
1594 int error;
1595 int revokecnt = tp->t_revokecnt;
1596
1597 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1598 MPASS(!tty_gone(tp));
1599
1600 error = cv_wait_sig(cv, tp->t_mtx);
1601
1602 /* Bail out when the device slipped away. */
1603 if (tty_gone(tp))
1604 return (EXTERROR(ENXIO, "tty_wait: device is gone"));
1605
1606 /* Restart the system call when we may have been revoked. */
1607 if (tp->t_revokecnt != revokecnt)
1608 return (ERESTART);
1609
1610 return (error);
1611 }
1612
1613 int
tty_timedwait(struct tty * tp,struct cv * cv,int hz)1614 tty_timedwait(struct tty *tp, struct cv *cv, int hz)
1615 {
1616 int error;
1617 int revokecnt = tp->t_revokecnt;
1618
1619 tty_lock_assert(tp, MA_OWNED|MA_NOTRECURSED);
1620 MPASS(!tty_gone(tp));
1621
1622 error = cv_timedwait_sig(cv, tp->t_mtx, hz);
1623
1624 /* Bail out when the device slipped away. */
1625 if (tty_gone(tp))
1626 return (EXTERROR(ENXIO, "tty_timedwait: device is gone"));
1627
1628 /* Restart the system call when we may have been revoked. */
1629 if (tp->t_revokecnt != revokecnt)
1630 return (ERESTART);
1631
1632 return (error);
1633 }
1634
1635 void
tty_flush(struct tty * tp,int flags)1636 tty_flush(struct tty *tp, int flags)
1637 {
1638
1639 if (flags & FWRITE) {
1640 tp->t_flags &= ~TF_HIWAT_OUT;
1641 ttyoutq_flush(&tp->t_outq);
1642 tty_wakeup(tp, FWRITE);
1643 if (!tty_gone(tp)) {
1644 ttydevsw_outwakeup(tp);
1645 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHWRITE);
1646 }
1647 }
1648 if (flags & FREAD) {
1649 tty_hiwat_in_unblock(tp);
1650 ttyinq_flush(&tp->t_inq);
1651 tty_wakeup(tp, FREAD);
1652 if (!tty_gone(tp)) {
1653 ttydevsw_inwakeup(tp);
1654 ttydevsw_pktnotify(tp, TIOCPKT_FLUSHREAD);
1655 }
1656 }
1657 }
1658
1659 void
tty_set_winsize(struct tty * tp,const struct winsize * wsz)1660 tty_set_winsize(struct tty *tp, const struct winsize *wsz)
1661 {
1662
1663 if (memcmp(&tp->t_winsize, wsz, sizeof(*wsz)) == 0)
1664 return;
1665 tp->t_winsize = *wsz;
1666 tty_signal_pgrp(tp, SIGWINCH);
1667 }
1668
1669 static int
tty_sti_check(struct tty * tp,int fflag,struct thread * td)1670 tty_sti_check(struct tty *tp, int fflag, struct thread *td)
1671 {
1672 /* Check for global disable. */
1673 if (!tty_tiocsti)
1674 return (EXTERROR(EPERM, "security.bsd.allow_tiocsti"));
1675
1676 /* Root can bypass all of our constraints. */
1677 if (priv_check(td, PRIV_TTY_STI) == 0)
1678 return (0);
1679
1680 /* Unprivileged users must have it opened for read. */
1681 if ((fflag & FREAD) == 0)
1682 return (EXTERROR(EPERM, "opened read-only"));
1683
1684 /* It must also be their controlling tty. */
1685 if (!tty_is_ctty(tp, td->td_proc))
1686 return (EXTERROR(EACCES, "not a controlling tty"));
1687
1688 return (0);
1689 }
1690
1691 static int
tty_generic_ioctl(struct tty * tp,u_long cmd,void * data,int fflag,struct thread * td)1692 tty_generic_ioctl(struct tty *tp, u_long cmd, void *data, int fflag,
1693 struct thread *td)
1694 {
1695 int error;
1696
1697 switch (cmd) {
1698 /*
1699 * Modem commands.
1700 * The SER_* and TIOCM_* flags are the same, but one bit
1701 * shifted. I don't know why.
1702 */
1703 case TIOCSDTR:
1704 ttydevsw_modem(tp, SER_DTR, 0);
1705 return (0);
1706 case TIOCCDTR:
1707 ttydevsw_modem(tp, 0, SER_DTR);
1708 return (0);
1709 case TIOCMSET: {
1710 int bits = *(int *)data;
1711 ttydevsw_modem(tp,
1712 (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1,
1713 ((~bits) & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1714 return (0);
1715 }
1716 case TIOCMBIS: {
1717 int bits = *(int *)data;
1718 ttydevsw_modem(tp, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1, 0);
1719 return (0);
1720 }
1721 case TIOCMBIC: {
1722 int bits = *(int *)data;
1723 ttydevsw_modem(tp, 0, (bits & (TIOCM_DTR | TIOCM_RTS)) >> 1);
1724 return (0);
1725 }
1726 case TIOCMGET:
1727 *(int *)data = TIOCM_LE + (ttydevsw_modem(tp, 0, 0) << 1);
1728 return (0);
1729
1730 case FIOASYNC:
1731 if (*(int *)data)
1732 tp->t_flags |= TF_ASYNC;
1733 else
1734 tp->t_flags &= ~TF_ASYNC;
1735 return (0);
1736 case FIONBIO:
1737 /* This device supports non-blocking operation. */
1738 return (0);
1739 case FIONREAD:
1740 *(int *)data = ttydisc_bytesavail(tp);
1741 return (0);
1742 case FIONWRITE:
1743 case TIOCOUTQ:
1744 *(int *)data = ttyoutq_bytesused(&tp->t_outq);
1745 return (0);
1746 case FIOSETOWN:
1747 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1748 /* Not allowed to set ownership. */
1749 return (ENOTTY);
1750
1751 /* Temporarily unlock the TTY to set ownership. */
1752 tty_unlock(tp);
1753 error = fsetown(*(int *)data, &tp->t_sigio);
1754 tty_lock(tp);
1755 return (error);
1756 case FIOGETOWN:
1757 if (tp->t_session != NULL && !tty_is_ctty(tp, td->td_proc))
1758 /* Not allowed to set ownership. */
1759 return (ENOTTY);
1760
1761 /* Get ownership. */
1762 *(int *)data = fgetown(&tp->t_sigio);
1763 return (0);
1764 case TIOCGETA:
1765 /* Obtain terminal flags through tcgetattr(). */
1766 *(struct termios*)data = tp->t_termios;
1767 return (0);
1768 case TIOCSETA:
1769 case TIOCSETAW:
1770 case TIOCSETAF: {
1771 struct termios *t = data;
1772 bool canonicalize = false;
1773
1774 /*
1775 * Who makes up these funny rules? According to POSIX,
1776 * input baud rate is set equal to the output baud rate
1777 * when zero.
1778 */
1779 if (t->c_ispeed == 0)
1780 t->c_ispeed = t->c_ospeed;
1781
1782 /* Discard any unsupported bits. */
1783 t->c_iflag &= TTYSUP_IFLAG;
1784 t->c_oflag &= TTYSUP_OFLAG;
1785 t->c_lflag &= TTYSUP_LFLAG;
1786 t->c_cflag &= TTYSUP_CFLAG;
1787
1788 /* Set terminal flags through tcsetattr(). */
1789 if (cmd == TIOCSETAW || cmd == TIOCSETAF) {
1790 error = tty_drain(tp, 0);
1791 if (error)
1792 return (error);
1793 if (cmd == TIOCSETAF)
1794 tty_flush(tp, FREAD);
1795 }
1796
1797 /*
1798 * Only call param() when the flags really change.
1799 */
1800 if ((t->c_cflag & CIGNORE) == 0 &&
1801 (tp->t_termios.c_cflag != t->c_cflag ||
1802 ((tp->t_termios.c_iflag ^ t->c_iflag) &
1803 (IXON|IXOFF|IXANY)) ||
1804 tp->t_termios.c_ispeed != t->c_ispeed ||
1805 tp->t_termios.c_ospeed != t->c_ospeed)) {
1806 error = ttydevsw_param(tp, t);
1807 if (error)
1808 return (error);
1809
1810 /* XXX: CLOCAL? */
1811
1812 tp->t_termios.c_cflag = t->c_cflag & ~CIGNORE;
1813 tp->t_termios.c_ispeed = t->c_ispeed;
1814 tp->t_termios.c_ospeed = t->c_ospeed;
1815
1816 /* Baud rate has changed - update watermarks. */
1817 error = tty_watermarks(tp);
1818 if (error)
1819 return (error);
1820 }
1821
1822 /*
1823 * We'll canonicalize any partial input if we're transitioning
1824 * ICANON one way or the other. If we're going from -ICANON ->
1825 * ICANON, then in the worst case scenario we're in the middle
1826 * of a line but both ttydisc_read() and FIONREAD will search
1827 * for one of our line terminals.
1828 */
1829 if ((t->c_lflag & ICANON) != (tp->t_termios.c_lflag & ICANON))
1830 canonicalize = true;
1831 else if (tp->t_termios.c_cc[VEOF] != t->c_cc[VEOF] ||
1832 tp->t_termios.c_cc[VEOL] != t->c_cc[VEOL])
1833 canonicalize = true;
1834
1835 /* Copy new non-device driver parameters. */
1836 tp->t_termios.c_iflag = t->c_iflag;
1837 tp->t_termios.c_oflag = t->c_oflag;
1838 tp->t_termios.c_lflag = t->c_lflag;
1839 memcpy(&tp->t_termios.c_cc, t->c_cc, sizeof t->c_cc);
1840
1841 ttydisc_optimize(tp);
1842
1843 if (canonicalize)
1844 ttydisc_canonicalize(tp);
1845 if ((t->c_lflag & ICANON) == 0) {
1846 /*
1847 * When in non-canonical mode, wake up all
1848 * readers. Any partial input has already been
1849 * canonicalized above if we were in canonical mode.
1850 * VMIN and VTIME could also be adjusted.
1851 */
1852 tty_wakeup(tp, FREAD);
1853 }
1854
1855 /*
1856 * For packet mode: notify the PTY consumer that VSTOP
1857 * and VSTART may have been changed.
1858 */
1859 if (tp->t_termios.c_iflag & IXON &&
1860 tp->t_termios.c_cc[VSTOP] == CTRL('S') &&
1861 tp->t_termios.c_cc[VSTART] == CTRL('Q'))
1862 ttydevsw_pktnotify(tp, TIOCPKT_DOSTOP);
1863 else
1864 ttydevsw_pktnotify(tp, TIOCPKT_NOSTOP);
1865 return (0);
1866 }
1867 case TIOCGETD:
1868 /* For compatibility - we only support TTYDISC. */
1869 *(int *)data = TTYDISC;
1870 return (0);
1871 case TIOCGPGRP:
1872 if (!tty_is_ctty(tp, td->td_proc))
1873 return (EXTERROR(ENOTTY, "not a controlling tty"));
1874
1875 if (tp->t_pgrp != NULL)
1876 *(int *)data = tp->t_pgrp->pg_id;
1877 else
1878 *(int *)data = NO_PID;
1879 return (0);
1880 case TIOCGSID:
1881 if (!tty_is_ctty(tp, td->td_proc))
1882 return (EXTERROR(ENOTTY, "not a controlling tty"));
1883
1884 MPASS(tp->t_session);
1885 *(int *)data = tp->t_session->s_sid;
1886 return (0);
1887 case TIOCNOTTY:
1888 return (tty_drop_ctty(tp, td->td_proc));
1889 case TIOCSCTTY: {
1890 struct proc *p = td->td_proc;
1891
1892 /* XXX: This looks awful. */
1893 tty_unlock(tp);
1894 sx_xlock(&proctree_lock);
1895 error = ttydev_enter(tp);
1896 if (error != 0) {
1897 sx_xunlock(&proctree_lock);
1898 tty_lock(tp);
1899 return (error);
1900 }
1901
1902 if (!SESS_LEADER(p)) {
1903 /* Only the session leader may do this. */
1904 sx_xunlock(&proctree_lock);
1905 return (EXTERROR(EPERM, "not a session leader"));
1906 }
1907
1908 if (tp->t_session != NULL && tp->t_session == p->p_session) {
1909 /* This is already our controlling TTY. */
1910 sx_xunlock(&proctree_lock);
1911 return (0);
1912 }
1913
1914 if (p->p_session->s_ttyp != NULL ||
1915 (tp->t_session != NULL && tp->t_session->s_ttyvp != NULL &&
1916 tp->t_session->s_ttyvp->v_type != VBAD)) {
1917 /*
1918 * There is already a relation between a TTY and
1919 * a session, or the caller is not the session
1920 * leader.
1921 *
1922 * Allow the TTY to be stolen when the vnode is
1923 * invalid, but the reference to the TTY is
1924 * still active. This allows immediate reuse of
1925 * TTYs of which the session leader has been
1926 * killed or the TTY revoked.
1927 */
1928 sx_xunlock(&proctree_lock);
1929 return (EXTERROR(EPERM, "session already has CTTY"));
1930 }
1931
1932 /* Connect the session to the TTY. */
1933 tp->t_session = p->p_session;
1934 tp->t_session->s_ttyp = tp;
1935 tp->t_sessioncnt++;
1936
1937 /* Assign foreground process group. */
1938 tp->t_pgrp = p->p_pgrp;
1939 PROC_LOCK(p);
1940 p->p_flag |= P_CONTROLT;
1941 PROC_UNLOCK(p);
1942
1943 sx_xunlock(&proctree_lock);
1944 return (0);
1945 }
1946 case TIOCSPGRP: {
1947 struct pgrp *pg;
1948
1949 /*
1950 * XXX: Temporarily unlock the TTY to locate the process
1951 * group. This code would be lot nicer if we would ever
1952 * decompose proctree_lock.
1953 */
1954 tty_unlock(tp);
1955 sx_slock(&proctree_lock);
1956 pg = pgfind(*(int *)data);
1957 if (pg != NULL)
1958 PGRP_UNLOCK(pg);
1959 if (pg == NULL || pg->pg_session != td->td_proc->p_session) {
1960 sx_sunlock(&proctree_lock);
1961 tty_lock(tp);
1962 return (EXTERROR(EPERM,
1963 "pgrp %jd belongs to other session %jd",
1964 pg != NULL ? pg->pg_id : -1,
1965 td->td_proc->p_session->s_sid));
1966 }
1967 error = ttydev_enter(tp);
1968 if (error != 0) {
1969 sx_sunlock(&proctree_lock);
1970 tty_lock(tp);
1971 return (error);
1972 }
1973
1974 /*
1975 * Determine if this TTY is the controlling TTY after
1976 * relocking the TTY.
1977 */
1978 if (!tty_is_ctty(tp, td->td_proc)) {
1979 sx_sunlock(&proctree_lock);
1980 return (EXTERROR(ENOTTY, "not a controlling tty"));
1981 }
1982 tp->t_pgrp = pg;
1983 sx_sunlock(&proctree_lock);
1984
1985 /* Wake up the background process groups. */
1986 cv_broadcast(&tp->t_bgwait);
1987 return (0);
1988 }
1989 case TIOCFLUSH: {
1990 int flags = *(int *)data;
1991
1992 if (flags == 0)
1993 flags = (FREAD|FWRITE);
1994 else
1995 flags &= (FREAD|FWRITE);
1996 tty_flush(tp, flags);
1997 return (0);
1998 }
1999 case TIOCDRAIN:
2000 /* Drain TTY output. */
2001 return tty_drain(tp, 0);
2002 case TIOCGDRAINWAIT:
2003 *(int *)data = tp->t_drainwait;
2004 return (0);
2005 case TIOCSDRAINWAIT:
2006 error = priv_check(td, PRIV_TTY_DRAINWAIT);
2007 if (error == 0)
2008 tp->t_drainwait = *(int *)data;
2009 return (error);
2010 case TIOCCONS:
2011 /* Set terminal as console TTY. */
2012 if (*(int *)data) {
2013 error = priv_check(td, PRIV_TTY_CONSOLE);
2014 if (error)
2015 return (error);
2016 error = constty_set(tp);
2017 } else {
2018 error = constty_clear(tp);
2019 }
2020 return (error);
2021 case TIOCGWINSZ:
2022 /* Obtain window size. */
2023 *(struct winsize*)data = tp->t_winsize;
2024 return (0);
2025 case TIOCSWINSZ:
2026 /* Set window size. */
2027 tty_set_winsize(tp, data);
2028 return (0);
2029 case TIOCEXCL:
2030 tp->t_flags |= TF_EXCLUDE;
2031 return (0);
2032 case TIOCNXCL:
2033 tp->t_flags &= ~TF_EXCLUDE;
2034 return (0);
2035 case TIOCSTOP:
2036 tp->t_flags |= TF_STOPPED;
2037 ttydevsw_pktnotify(tp, TIOCPKT_STOP);
2038 return (0);
2039 case TIOCSTART:
2040 tp->t_flags &= ~TF_STOPPED;
2041 tp->t_termios.c_lflag &= ~FLUSHO;
2042 ttydevsw_outwakeup(tp);
2043 ttydevsw_pktnotify(tp, TIOCPKT_START);
2044 return (0);
2045 case TIOCSTAT:
2046 tty_info(tp);
2047 return (0);
2048 case TIOCSTI:
2049 error = tty_sti_check(tp, fflag, td);
2050 if (error != 0)
2051 return (error);
2052 ttydisc_rint(tp, *(char *)data, 0);
2053 ttydisc_rint_done(tp);
2054 return (0);
2055 }
2056
2057 #ifdef COMPAT_43TTY
2058 return tty_ioctl_compat(tp, cmd, data, fflag, td);
2059 #else /* !COMPAT_43TTY */
2060 return (ENOIOCTL);
2061 #endif /* COMPAT_43TTY */
2062 }
2063
2064 int
tty_ioctl(struct tty * tp,u_long cmd,void * data,int fflag,struct thread * td)2065 tty_ioctl(struct tty *tp, u_long cmd, void *data, int fflag, struct thread *td)
2066 {
2067 int error;
2068
2069 tty_assert_locked(tp);
2070
2071 if (tty_gone(tp))
2072 return (EXTERROR(ENXIO, "tty_ioctl: device is gone"));
2073
2074 error = ttydevsw_ioctl(tp, cmd, data, td);
2075 if (error == ENOIOCTL)
2076 error = tty_generic_ioctl(tp, cmd, data, fflag, td);
2077
2078 return (error);
2079 }
2080
2081 dev_t
tty_udev(struct tty * tp)2082 tty_udev(struct tty *tp)
2083 {
2084
2085 if (tp->t_dev)
2086 return (dev2udev(tp->t_dev));
2087 else
2088 return (NODEV);
2089 }
2090
2091 int
tty_checkoutq(struct tty * tp)2092 tty_checkoutq(struct tty *tp)
2093 {
2094
2095 /* 256 bytes should be enough to print a log message. */
2096 return (ttyoutq_bytesleft(&tp->t_outq) >= 256);
2097 }
2098
2099 void
tty_hiwat_in_block(struct tty * tp)2100 tty_hiwat_in_block(struct tty *tp)
2101 {
2102
2103 if ((tp->t_flags & TF_HIWAT_IN) == 0 &&
2104 tp->t_termios.c_iflag & IXOFF &&
2105 tp->t_termios.c_cc[VSTOP] != _POSIX_VDISABLE) {
2106 /*
2107 * Input flow control. Only enter the high watermark when we
2108 * can successfully store the VSTOP character.
2109 */
2110 if (ttyoutq_write_nofrag(&tp->t_outq,
2111 &tp->t_termios.c_cc[VSTOP], 1) == 0)
2112 tp->t_flags |= TF_HIWAT_IN;
2113 } else {
2114 /* No input flow control. */
2115 tp->t_flags |= TF_HIWAT_IN;
2116 }
2117 }
2118
2119 void
tty_hiwat_in_unblock(struct tty * tp)2120 tty_hiwat_in_unblock(struct tty *tp)
2121 {
2122
2123 if (tp->t_flags & TF_HIWAT_IN &&
2124 tp->t_termios.c_iflag & IXOFF &&
2125 tp->t_termios.c_cc[VSTART] != _POSIX_VDISABLE) {
2126 /*
2127 * Input flow control. Only leave the high watermark when we
2128 * can successfully store the VSTART character.
2129 */
2130 if (ttyoutq_write_nofrag(&tp->t_outq,
2131 &tp->t_termios.c_cc[VSTART], 1) == 0)
2132 tp->t_flags &= ~TF_HIWAT_IN;
2133 } else {
2134 /* No input flow control. */
2135 tp->t_flags &= ~TF_HIWAT_IN;
2136 }
2137
2138 if (!tty_gone(tp))
2139 ttydevsw_inwakeup(tp);
2140 }
2141
2142 /*
2143 * TTY hooks interface.
2144 */
2145
2146 static int
ttyhook_defrint(struct tty * tp,char c,int flags)2147 ttyhook_defrint(struct tty *tp, char c, int flags)
2148 {
2149
2150 if (ttyhook_rint_bypass(tp, &c, 1) != 1)
2151 return (-1);
2152
2153 return (0);
2154 }
2155
2156 int
ttyhook_register(struct tty ** rtp,struct proc * p,int fd,struct ttyhook * th,void * softc)2157 ttyhook_register(struct tty **rtp, struct proc *p, int fd, struct ttyhook *th,
2158 void *softc)
2159 {
2160 struct tty *tp;
2161 struct file *fp;
2162 struct cdev *dev;
2163 struct cdevsw *cdp;
2164 struct filedesc *fdp;
2165 cap_rights_t rights;
2166 int error, ref;
2167
2168 /* Validate the file descriptor. */
2169 /*
2170 * XXX this code inspects a file descriptor from a different process,
2171 * but there is no dedicated routine to do it in fd code, making the
2172 * ordeal highly questionable.
2173 */
2174 fdp = p->p_fd;
2175 FILEDESC_SLOCK(fdp);
2176 error = fget_cap_noref(fdp, fd, cap_rights_init_one(&rights, CAP_TTYHOOK),
2177 &fp, NULL);
2178 if (error == 0 && !fhold(fp))
2179 error = EBADF;
2180 FILEDESC_SUNLOCK(fdp);
2181 if (error != 0)
2182 return (error);
2183 if (fp->f_ops == &badfileops) {
2184 error = EBADF;
2185 goto done1;
2186 }
2187
2188 /*
2189 * Make sure the vnode is bound to a character device.
2190 * Unlocked check for the vnode type is ok there, because we
2191 * only shall prevent calling devvn_refthread on the file that
2192 * never has been opened over a character device.
2193 */
2194 if (fp->f_type != DTYPE_VNODE || fp->f_vnode->v_type != VCHR) {
2195 error = EINVAL;
2196 goto done1;
2197 }
2198
2199 /* Make sure it is a TTY. */
2200 cdp = devvn_refthread(fp->f_vnode, &dev, &ref);
2201 if (cdp == NULL) {
2202 error = ENXIO;
2203 goto done1;
2204 }
2205 if (dev != fp->f_data) {
2206 error = ENXIO;
2207 goto done2;
2208 }
2209 if (cdp != &ttydev_cdevsw) {
2210 error = ENOTTY;
2211 goto done2;
2212 }
2213 tp = dev->si_drv1;
2214
2215 /* Try to attach the hook to the TTY. */
2216 error = EBUSY;
2217 tty_lock(tp);
2218 MPASS((tp->t_hook == NULL) == ((tp->t_flags & TF_HOOK) == 0));
2219 if (tp->t_flags & TF_HOOK)
2220 goto done3;
2221
2222 tp->t_flags |= TF_HOOK;
2223 tp->t_hook = th;
2224 tp->t_hooksoftc = softc;
2225 *rtp = tp;
2226 error = 0;
2227
2228 /* Maybe we can switch into bypass mode now. */
2229 ttydisc_optimize(tp);
2230
2231 /* Silently convert rint() calls to rint_bypass() when possible. */
2232 if (!ttyhook_hashook(tp, rint) && ttyhook_hashook(tp, rint_bypass))
2233 th->th_rint = ttyhook_defrint;
2234
2235 done3: tty_unlock(tp);
2236 done2: dev_relthread(dev, ref);
2237 done1: fdrop(fp, curthread);
2238 return (error);
2239 }
2240
2241 void
ttyhook_unregister(struct tty * tp)2242 ttyhook_unregister(struct tty *tp)
2243 {
2244
2245 tty_assert_locked(tp);
2246 MPASS(tp->t_flags & TF_HOOK);
2247
2248 /* Disconnect the hook. */
2249 tp->t_flags &= ~TF_HOOK;
2250 tp->t_hook = NULL;
2251
2252 /* Maybe we need to leave bypass mode. */
2253 ttydisc_optimize(tp);
2254
2255 /* Maybe deallocate the TTY as well. */
2256 tty_rel_free(tp, false);
2257 }
2258
2259 /*
2260 * /dev/console handling.
2261 */
2262
2263 static int
ttyconsdev_open(struct cdev * dev,int oflags,int devtype,struct thread * td)2264 ttyconsdev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
2265 {
2266 struct tty *tp;
2267
2268 /* System has no console device. */
2269 if (dev_console_filename == NULL)
2270 return (EXTERROR(ENXIO, "system has no console device"));
2271
2272 /* Look up corresponding TTY by device name. */
2273 sx_slock(&tty_list_sx);
2274 TAILQ_FOREACH(tp, &tty_list, t_list) {
2275 if (strcmp(dev_console_filename, tty_devname(tp)) == 0) {
2276 dev_console->si_drv1 = tp;
2277 break;
2278 }
2279 }
2280 sx_sunlock(&tty_list_sx);
2281
2282 /* System console has no TTY associated. */
2283 if (dev_console->si_drv1 == NULL)
2284 return (EXTERROR(ENXIO, "system console has no TTY attached"));
2285
2286 return (ttydev_open(dev, oflags, devtype, td));
2287 }
2288
2289 static int
ttyconsdev_write(struct cdev * dev,struct uio * uio,int ioflag)2290 ttyconsdev_write(struct cdev *dev, struct uio *uio, int ioflag)
2291 {
2292
2293 log_console(uio);
2294
2295 return (ttydev_write(dev, uio, ioflag));
2296 }
2297
2298 /*
2299 * /dev/console is a little different than normal TTY's. When opened,
2300 * it determines which TTY to use. When data gets written to it, it
2301 * will be logged in the kernel message buffer.
2302 */
2303 static struct cdevsw ttyconsdev_cdevsw = {
2304 .d_version = D_VERSION,
2305 .d_open = ttyconsdev_open,
2306 .d_close = ttydev_close,
2307 .d_read = ttydev_read,
2308 .d_write = ttyconsdev_write,
2309 .d_ioctl = ttydev_ioctl,
2310 .d_kqfilter = ttydev_kqfilter,
2311 .d_poll = ttydev_poll,
2312 .d_mmap = ttydev_mmap,
2313 .d_name = "ttyconsdev",
2314 .d_flags = D_TTY,
2315 };
2316
2317 static void
ttyconsdev_init(void * unused __unused)2318 ttyconsdev_init(void *unused __unused)
2319 {
2320
2321 dev_console = make_dev_credf(MAKEDEV_ETERNAL, &ttyconsdev_cdevsw, 0,
2322 NULL, UID_ROOT, GID_WHEEL, 0600, "console");
2323 }
2324
2325 SYSINIT(tty, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyconsdev_init, NULL);
2326
2327 void
ttyconsdev_select(const char * name)2328 ttyconsdev_select(const char *name)
2329 {
2330
2331 dev_console_filename = name;
2332 }
2333
2334 /*
2335 * Debugging routines.
2336 */
2337
2338 #include "opt_ddb.h"
2339 #ifdef DDB
2340 #include <ddb/ddb.h>
2341 #include <ddb/db_sym.h>
2342
2343 static const struct {
2344 int flag;
2345 char val;
2346 } ttystates[] = {
2347 #if 0
2348 { TF_NOPREFIX, 'N' },
2349 #endif
2350 { TF_INITLOCK, 'I' },
2351 { TF_CALLOUT, 'C' },
2352
2353 /* Keep these together -> 'Oi' and 'Oo'. */
2354 { TF_OPENED, 'O' },
2355 { TF_OPENED_IN, 'i' },
2356 { TF_OPENED_OUT, 'o' },
2357 { TF_OPENED_CONS, 'c' },
2358
2359 { TF_GONE, 'G' },
2360 { TF_OPENCLOSE, 'B' },
2361 { TF_ASYNC, 'Y' },
2362 { TF_LITERAL, 'L' },
2363
2364 /* Keep these together -> 'Hi' and 'Ho'. */
2365 { TF_HIWAT, 'H' },
2366 { TF_HIWAT_IN, 'i' },
2367 { TF_HIWAT_OUT, 'o' },
2368
2369 { TF_STOPPED, 'S' },
2370 { TF_EXCLUDE, 'X' },
2371 { TF_BYPASS, 'l' },
2372 { TF_ZOMBIE, 'Z' },
2373 { TF_HOOK, 's' },
2374
2375 /* Keep these together -> 'bi' and 'bo'. */
2376 { TF_BUSY, 'b' },
2377 { TF_BUSY_IN, 'i' },
2378 { TF_BUSY_OUT, 'o' },
2379
2380 { 0, '\0'},
2381 };
2382
2383 #define TTY_FLAG_BITS \
2384 "\20\1NOPREFIX\2INITLOCK\3CALLOUT\4OPENED_IN" \
2385 "\5OPENED_OUT\6OPENED_CONS\7GONE\10OPENCLOSE" \
2386 "\11ASYNC\12LITERAL\13HIWAT_IN\14HIWAT_OUT" \
2387 "\15STOPPED\16EXCLUDE\17BYPASS\20ZOMBIE" \
2388 "\21HOOK\22BUSY_IN\23BUSY_OUT"
2389
2390 #define DB_PRINTSYM(name, addr) \
2391 db_printf("%s " #name ": ", sep); \
2392 db_printsym((db_addr_t) addr, DB_STGY_ANY); \
2393 db_printf("\n");
2394
2395 static void
_db_show_devsw(const char * sep,const struct ttydevsw * tsw)2396 _db_show_devsw(const char *sep, const struct ttydevsw *tsw)
2397 {
2398
2399 db_printf("%sdevsw: ", sep);
2400 db_printsym((db_addr_t)tsw, DB_STGY_ANY);
2401 db_printf(" (%p)\n", tsw);
2402 DB_PRINTSYM(open, tsw->tsw_open);
2403 DB_PRINTSYM(close, tsw->tsw_close);
2404 DB_PRINTSYM(outwakeup, tsw->tsw_outwakeup);
2405 DB_PRINTSYM(inwakeup, tsw->tsw_inwakeup);
2406 DB_PRINTSYM(ioctl, tsw->tsw_ioctl);
2407 DB_PRINTSYM(param, tsw->tsw_param);
2408 DB_PRINTSYM(modem, tsw->tsw_modem);
2409 DB_PRINTSYM(mmap, tsw->tsw_mmap);
2410 DB_PRINTSYM(pktnotify, tsw->tsw_pktnotify);
2411 DB_PRINTSYM(free, tsw->tsw_free);
2412 }
2413
2414 static void
_db_show_hooks(const char * sep,const struct ttyhook * th)2415 _db_show_hooks(const char *sep, const struct ttyhook *th)
2416 {
2417
2418 db_printf("%shook: ", sep);
2419 db_printsym((db_addr_t)th, DB_STGY_ANY);
2420 db_printf(" (%p)\n", th);
2421 if (th == NULL)
2422 return;
2423 DB_PRINTSYM(rint, th->th_rint);
2424 DB_PRINTSYM(rint_bypass, th->th_rint_bypass);
2425 DB_PRINTSYM(rint_done, th->th_rint_done);
2426 DB_PRINTSYM(rint_poll, th->th_rint_poll);
2427 DB_PRINTSYM(getc_inject, th->th_getc_inject);
2428 DB_PRINTSYM(getc_capture, th->th_getc_capture);
2429 DB_PRINTSYM(getc_poll, th->th_getc_poll);
2430 DB_PRINTSYM(close, th->th_close);
2431 }
2432
2433 static void
_db_show_termios(const char * name,const struct termios * t)2434 _db_show_termios(const char *name, const struct termios *t)
2435 {
2436
2437 db_printf("%s: iflag 0x%x oflag 0x%x cflag 0x%x "
2438 "lflag 0x%x ispeed %u ospeed %u\n", name,
2439 t->c_iflag, t->c_oflag, t->c_cflag, t->c_lflag,
2440 t->c_ispeed, t->c_ospeed);
2441 }
2442
2443 /* DDB command to show TTY statistics. */
DB_SHOW_COMMAND(tty,db_show_tty)2444 DB_SHOW_COMMAND(tty, db_show_tty)
2445 {
2446 struct tty *tp;
2447
2448 if (!have_addr) {
2449 db_printf("usage: show tty <addr>\n");
2450 return;
2451 }
2452 tp = (struct tty *)addr;
2453
2454 db_printf("%p: %s\n", tp, tty_devname(tp));
2455 db_printf("\tmtx: %p\n", tp->t_mtx);
2456 db_printf("\tflags: 0x%b\n", tp->t_flags, TTY_FLAG_BITS);
2457 db_printf("\trevokecnt: %u\n", tp->t_revokecnt);
2458
2459 /* Buffering mechanisms. */
2460 db_printf("\tinq: %p begin %u linestart %u reprint %u end %u "
2461 "nblocks %u quota %u\n", &tp->t_inq, tp->t_inq.ti_begin,
2462 tp->t_inq.ti_linestart, tp->t_inq.ti_reprint, tp->t_inq.ti_end,
2463 tp->t_inq.ti_nblocks, tp->t_inq.ti_quota);
2464 db_printf("\toutq: %p begin %u end %u nblocks %u quota %u\n",
2465 &tp->t_outq, tp->t_outq.to_begin, tp->t_outq.to_end,
2466 tp->t_outq.to_nblocks, tp->t_outq.to_quota);
2467 db_printf("\tinlow: %zu\n", tp->t_inlow);
2468 db_printf("\toutlow: %zu\n", tp->t_outlow);
2469 _db_show_termios("\ttermios", &tp->t_termios);
2470 db_printf("\twinsize: row %u col %u xpixel %u ypixel %u\n",
2471 tp->t_winsize.ws_row, tp->t_winsize.ws_col,
2472 tp->t_winsize.ws_xpixel, tp->t_winsize.ws_ypixel);
2473 db_printf("\tcolumn: %u\n", tp->t_column);
2474 db_printf("\twritepos: %u\n", tp->t_writepos);
2475 db_printf("\tcompatflags: 0x%x\n", tp->t_compatflags);
2476
2477 /* Init/lock-state devices. */
2478 _db_show_termios("\ttermios_init_in", &tp->t_termios_init_in);
2479 _db_show_termios("\ttermios_init_out", &tp->t_termios_init_out);
2480 _db_show_termios("\ttermios_lock_in", &tp->t_termios_lock_in);
2481 _db_show_termios("\ttermios_lock_out", &tp->t_termios_lock_out);
2482
2483 /* Hooks */
2484 _db_show_devsw("\t", tp->t_devsw);
2485 _db_show_hooks("\t", tp->t_hook);
2486
2487 /* Process info. */
2488 db_printf("\tpgrp: %p gid %d\n", tp->t_pgrp,
2489 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2490 db_printf("\tsession: %p", tp->t_session);
2491 if (tp->t_session != NULL)
2492 db_printf(" count %u leader %p tty %p sid %d login %s",
2493 tp->t_session->s_count, tp->t_session->s_leader,
2494 tp->t_session->s_ttyp, tp->t_session->s_sid,
2495 tp->t_session->s_login);
2496 db_printf("\n");
2497 db_printf("\tsessioncnt: %u\n", tp->t_sessioncnt);
2498 db_printf("\tdevswsoftc: %p\n", tp->t_devswsoftc);
2499 db_printf("\thooksoftc: %p\n", tp->t_hooksoftc);
2500 db_printf("\tdev: %p\n", tp->t_dev);
2501 }
2502
2503 /* DDB command to list TTYs. */
DB_SHOW_ALL_COMMAND(ttys,db_show_all_ttys)2504 DB_SHOW_ALL_COMMAND(ttys, db_show_all_ttys)
2505 {
2506 struct tty *tp;
2507 size_t isiz, osiz;
2508 int i, j;
2509
2510 /* Make the output look like `pstat -t'. */
2511 db_printf("PTR ");
2512 #if defined(__LP64__)
2513 db_printf(" ");
2514 #endif
2515 db_printf(" LINE INQ CAN LIN LOW OUTQ USE LOW "
2516 "COL SESS PGID STATE\n");
2517
2518 TAILQ_FOREACH(tp, &tty_list, t_list) {
2519 isiz = tp->t_inq.ti_nblocks * TTYINQ_DATASIZE;
2520 osiz = tp->t_outq.to_nblocks * TTYOUTQ_DATASIZE;
2521
2522 db_printf("%p %10s %5zu %4u %4u %4zu %5zu %4u %4zu %5u %5d "
2523 "%5d ", tp, tty_devname(tp), isiz,
2524 tp->t_inq.ti_linestart - tp->t_inq.ti_begin,
2525 tp->t_inq.ti_end - tp->t_inq.ti_linestart,
2526 isiz - tp->t_inlow, osiz,
2527 tp->t_outq.to_end - tp->t_outq.to_begin,
2528 osiz - tp->t_outlow, MIN(tp->t_column, 99999),
2529 tp->t_session ? tp->t_session->s_sid : 0,
2530 tp->t_pgrp ? tp->t_pgrp->pg_id : 0);
2531
2532 /* Flag bits. */
2533 for (i = j = 0; ttystates[i].flag; i++)
2534 if (tp->t_flags & ttystates[i].flag) {
2535 db_printf("%c", ttystates[i].val);
2536 j++;
2537 }
2538 if (j == 0)
2539 db_printf("-");
2540 db_printf("\n");
2541 }
2542 }
2543 #endif /* DDB */
2544