xref: /freebsd/sys/kern/tty_pts.c (revision 6356dba0b403daa023dec24559ab1f8e602e4f14)
1 /*-
2  * Copyright (c) 2008 Ed Schouten <ed@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Portions of this software were developed under sponsorship from Snow
6  * B.V., the Netherlands.
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  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_tty.h"
34 
35 /* Add compatibility bits for FreeBSD. */
36 #define PTS_COMPAT
37 #ifdef DEV_PTY
38 /* Add /dev/ptyXX compat bits. */
39 #define PTS_EXTERNAL
40 #endif /* DEV_PTY */
41 /* Add bits to make Linux binaries work. */
42 #define PTS_LINUX
43 
44 #include <sys/param.h>
45 #include <sys/lock.h>
46 #include <sys/condvar.h>
47 #include <sys/conf.h>
48 #include <sys/fcntl.h>
49 #include <sys/file.h>
50 #include <sys/filedesc.h>
51 #include <sys/filio.h>
52 #include <sys/kernel.h>
53 #include <sys/malloc.h>
54 #include <sys/poll.h>
55 #include <sys/proc.h>
56 #include <sys/resourcevar.h>
57 #include <sys/serial.h>
58 #include <sys/stat.h>
59 #include <sys/syscall.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysent.h>
62 #include <sys/sysproto.h>
63 #include <sys/systm.h>
64 #include <sys/tty.h>
65 #include <sys/ttycom.h>
66 
67 #include <machine/stdarg.h>
68 
69 static struct unrhdr *pts_pool;
70 #define MAXPTSDEVS 999
71 
72 static MALLOC_DEFINE(M_PTS, "pts", "pseudo tty device");
73 
74 /*
75  * Per-PTS structure.
76  *
77  * List of locks
78  * (t)	locked by tty_lock()
79  * (c)	const until freeing
80  */
81 struct pts_softc {
82 	int		pts_unit;	/* (c) Device unit number. */
83 	unsigned int	pts_flags;	/* (t) Device flags. */
84 #define PTS_PKT		0x1	/* Packet mode. */
85 
86 	struct cv	pts_inwait;	/* (t) Blocking write() on master. */
87 	struct selinfo	pts_inpoll;	/* (t) Select queue for write(). */
88 	struct cv	pts_outwait;	/* (t) Blocking read() on master. */
89 	struct selinfo	pts_outpoll;	/* (t) Select queue for read(). */
90 
91 #ifdef PTS_EXTERNAL
92 	struct cdev	*pts_cdev;	/* (c) Master device node. */
93 #endif /* PTS_EXTERNAL */
94 
95 	struct uidinfo	*pts_uidinfo;	/* (c) Resource limit. */
96 };
97 
98 /*
99  * Controller-side file operations.
100  */
101 
102 static int
103 ptsdev_read(struct file *fp, struct uio *uio, struct ucred *active_cred,
104     int flags, struct thread *td)
105 {
106 	struct tty *tp = fp->f_data;
107 	struct pts_softc *psc = tty_softc(tp);
108 	int error, oresid;
109 
110 	if (uio->uio_resid == 0)
111 		return (0);
112 
113 	/*
114 	 * Implement packet mode. When packet mode is turned on, the
115 	 * first byte contains a bitmask of events that occured (start,
116 	 * stop, flush, window size, etc).
117 	 */
118 
119 	if (psc->pts_flags & PTS_PKT) {
120 		/* XXX: return proper bits. */
121 		error = ureadc(0, uio);
122 		if (error != 0)
123 			return (error);
124 		if (uio->uio_resid == 0)
125 			return (0);
126 	}
127 
128 	oresid = uio->uio_resid;
129 
130 	tty_lock(tp);
131 	for (;;) {
132 		error = ttydisc_getc_uio(tp, uio);
133 		/* We've got data (or an error). */
134 		if (error != 0 || uio->uio_resid != oresid)
135 			break;
136 
137 		/* Maybe the device isn't used anyway. */
138 		if (tty_opened(tp) == 0)
139 			break;
140 
141 		/* Wait for more data. */
142 		if (fp->f_flag & O_NONBLOCK) {
143 			error = EWOULDBLOCK;
144 			break;
145 		}
146 		error = cv_wait_sig(&psc->pts_outwait, tp->t_mtx);
147 		if (error != 0)
148 			break;
149 	}
150 	tty_unlock(tp);
151 
152 	return (error);
153 }
154 
155 static int
156 ptsdev_write(struct file *fp, struct uio *uio, struct ucred *active_cred,
157     int flags, struct thread *td)
158 {
159 	struct tty *tp = fp->f_data;
160 	struct pts_softc *psc = tty_softc(tp);
161 	char ib[256], *ibstart;
162 	size_t iblen, rintlen;
163 	int error = 0;
164 
165 	tty_lock(tp);
166 
167 	while (uio->uio_resid > 0) {
168 		/* Temporarily unlock to buffer new characters. */
169 		tty_unlock(tp);
170 		ibstart = ib;
171 		iblen = MIN(uio->uio_resid, sizeof ib);
172 		error = uiomove(ib, iblen, uio);
173 		tty_lock(tp);
174 		if (error != 0)
175 			goto done;
176 
177 		/*
178 		 * When possible, avoid the slow path. rint_bypass()
179 		 * copies all input to the input queue at once.
180 		 */
181 		while (iblen > 0) {
182 			if (ttydisc_can_bypass(tp)) {
183 				/* Store data at once. */
184 				rintlen = ttydisc_rint_bypass(tp,
185 				    ibstart, iblen);
186 				ibstart += rintlen;
187 				iblen -= rintlen;
188 
189 				if (iblen == 0) {
190 					/* All data written. */
191 					continue;
192 				}
193 			} else {
194 				error = ttydisc_rint(tp, *ibstart, 0);
195 				if (error == 0) {
196 					/* Character stored successfully. */
197 					ibstart++;
198 					iblen--;
199 					continue;
200 				}
201 			}
202 
203 			/* Maybe the device isn't used anyway. */
204 			if (tty_opened(tp) == 0) {
205 				error = EIO;
206 				goto done;
207 			}
208 
209 			/* Wait for more data. */
210 			if (fp->f_flag & O_NONBLOCK) {
211 				error = EWOULDBLOCK;
212 				goto done;
213 			}
214 
215 			/* Wake up users on the slave side. */
216 			ttydisc_rint_done(tp);
217 			error = cv_wait_sig(&psc->pts_inwait, tp->t_mtx);
218 			if (error != 0)
219 				goto done;
220 		}
221 	}
222 
223 done:	ttydisc_rint_done(tp);
224 	tty_unlock(tp);
225 	return (error);
226 }
227 
228 static int
229 ptsdev_ioctl(struct file *fp, u_long cmd, void *data,
230     struct ucred *active_cred, struct thread *td)
231 {
232 	struct tty *tp = fp->f_data;
233 	struct pts_softc *psc = tty_softc(tp);
234 	int error = 0, sig;
235 
236 	switch (cmd) {
237 	case FIONBIO:
238 		/* This device supports non-blocking operation. */
239 		return (0);
240 	case FIODGNAME: {
241 		struct fiodgname_arg *fgn;
242 		const char *p;
243 		int i;
244 
245 		/* Reverse device name lookups, for ptsname() and ttyname(). */
246 		fgn = data;
247 #ifdef PTS_EXTERNAL
248 		if (psc->pts_cdev != NULL)
249 			p = devtoname(psc->pts_cdev);
250 		else
251 #endif /* PTS_EXTERNAL */
252 			p = tty_devname(tp);
253 		i = strlen(p) + 1;
254 		if (i > fgn->len)
255 			return (EINVAL);
256 		return copyout(p, fgn->buf, i);
257 	}
258 
259 	/*
260 	 * We need to implement TIOCGPGRP and TIOCGSID here again. When
261 	 * called on the pseudo-terminal master, it should not check if
262 	 * the terminal is the foreground terminal of the calling
263 	 * process.
264 	 *
265 	 * TIOCGETA is also implemented here. Various Linux PTY routines
266 	 * often call isatty(), which is implemented by tcgetattr().
267 	 */
268 #ifdef PTS_LINUX
269 	case TIOCGETA:
270 		/* Obtain terminal flags through tcgetattr(). */
271 		tty_lock(tp);
272 		bcopy(&tp->t_termios, data, sizeof(struct termios));
273 		tty_unlock(tp);
274 		return (0);
275 #endif /* PTS_LINUX */
276 	case TIOCSETAF:
277 	case TIOCSETAW:
278 		/*
279 		 * We must make sure we turn tcsetattr() calls of TCSAFLUSH and
280 		 * TCSADRAIN into something different. If an application would
281 		 * call TCSAFLUSH or TCSADRAIN on the master descriptor, it may
282 		 * deadlock waiting for all data to be read.
283 		 */
284 		cmd = TIOCSETA;
285 		break;
286 #if defined(PTS_COMPAT) || defined(PTS_LINUX)
287 	case TIOCGPTN:
288 		/*
289 		 * Get the device unit number.
290 		 */
291 		if (psc->pts_unit < 0)
292 			return (ENOTTY);
293 		*(unsigned int *)data = psc->pts_unit;
294 		return (0);
295 #endif /* PTS_COMPAT || PTS_LINUX */
296 	case TIOCGPGRP:
297 		/* Get the foreground process group ID. */
298 		tty_lock(tp);
299 		if (tp->t_pgrp != NULL)
300 			*(int *)data = tp->t_pgrp->pg_id;
301 		else
302 			*(int *)data = NO_PID;
303 		tty_unlock(tp);
304 		return (0);
305 	case TIOCGSID:
306 		/* Get the session leader process ID. */
307 		tty_lock(tp);
308 		if (tp->t_session == NULL)
309 			error = ENOTTY;
310 		else
311 			*(int *)data = tp->t_session->s_sid;
312 		tty_unlock(tp);
313 		return (error);
314 	case TIOCPTMASTER:
315 		/* Yes, we are a pseudo-terminal master. */
316 		return (0);
317 	case TIOCSIG:
318 		/* Signal the foreground process group. */
319 		sig = *(int *)data;
320 		if (sig < 1 || sig >= NSIG)
321 			return (EINVAL);
322 
323 		tty_lock(tp);
324 		tty_signal_pgrp(tp, sig);
325 		tty_unlock(tp);
326 		return (0);
327 	case TIOCPKT:
328 		/* Enable/disable packet mode. */
329 		tty_lock(tp);
330 		if (*(int *)data)
331 			psc->pts_flags |= PTS_PKT;
332 		else
333 			psc->pts_flags &= ~PTS_PKT;
334 		tty_unlock(tp);
335 		return (0);
336 	}
337 
338 	/* Just redirect this ioctl to the slave device. */
339 	tty_lock(tp);
340 	error = tty_ioctl(tp, cmd, data, td);
341 	tty_unlock(tp);
342 
343 	return (error);
344 }
345 
346 static int
347 ptsdev_poll(struct file *fp, int events, struct ucred *active_cred,
348     struct thread *td)
349 {
350 	struct tty *tp = fp->f_data;
351 	struct pts_softc *psc = tty_softc(tp);
352 	int revents = 0;
353 
354 	tty_lock(tp);
355 
356 	if (tty_opened(tp) == 0) {
357 		/* Slave device is not opened. */
358 		tty_unlock(tp);
359 		return (events &
360 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
361 	}
362 
363 	if (events & (POLLIN|POLLRDNORM)) {
364 		/* See if we can getc something. */
365 		if (ttydisc_getc_poll(tp))
366 			revents |= events & (POLLIN|POLLRDNORM);
367 	}
368 	if (events & (POLLOUT|POLLWRNORM)) {
369 		/* See if we can rint something. */
370 		if (ttydisc_rint_poll(tp))
371 			revents |= events & (POLLOUT|POLLWRNORM);
372 	}
373 
374 	/*
375 	 * No need to check for POLLHUP here. This device cannot be used
376 	 * as a callout device, which means we always have a carrier,
377 	 * because the master is.
378 	 */
379 
380 	if (revents == 0) {
381 		/*
382 		 * This code might look misleading, but the naming of
383 		 * poll events on this side is the opposite of the slave
384 		 * device.
385 		 */
386 		if (events & (POLLIN|POLLRDNORM))
387 			selrecord(td, &psc->pts_outpoll);
388 		if (events & (POLLOUT|POLLWRNORM))
389 			selrecord(td, &psc->pts_inpoll);
390 	}
391 
392 	tty_unlock(tp);
393 
394 	return (revents);
395 }
396 
397 static int
398 ptsdev_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
399     struct thread *td)
400 {
401 	struct tty *tp = fp->f_data;
402 #ifdef PTS_EXTERNAL
403 	struct pts_softc *psc = tty_softc(tp);
404 #endif /* PTS_EXTERNAL */
405 
406 	/*
407 	 * According to POSIX, we must implement an fstat(). This also
408 	 * makes this implementation compatible with Linux binaries,
409 	 * because Linux calls fstat() on the pseudo-terminal master to
410 	 * obtain st_rdev.
411 	 *
412 	 * XXX: POSIX also mentions we must fill in st_dev, st_atime,
413 	 * st_ctime and st_mtime, but how?
414 	 */
415 
416 	bzero(sb, sizeof *sb);
417 #ifdef PTS_EXTERNAL
418 	if (psc->pts_cdev != NULL)
419 		sb->st_ino = sb->st_rdev = dev2udev(psc->pts_cdev);
420 	else
421 #endif /* PTS_EXTERNAL */
422 		sb->st_ino = sb->st_rdev = tty_udev(tp);
423 	sb->st_mode = S_IFCHR;
424 	sb->st_uid = tp->t_dev->si_cred->cr_ruid;
425 	sb->st_gid = GID_TTY;
426 
427 	return (0);
428 }
429 
430 static int
431 ptsdev_close(struct file *fp, struct thread *td)
432 {
433 	struct tty *tp = fp->f_data;
434 
435 	/* Deallocate TTY device. */
436 	tty_lock(tp);
437 	tty_rel_gone(tp);
438 
439 	return (0);
440 }
441 
442 static struct fileops ptsdev_ops = {
443 	.fo_read	= ptsdev_read,
444 	.fo_write	= ptsdev_write,
445 	.fo_ioctl	= ptsdev_ioctl,
446 	.fo_poll	= ptsdev_poll,
447 	.fo_stat	= ptsdev_stat,
448 	.fo_close	= ptsdev_close,
449 	.fo_flags	= DFLAG_PASSABLE,
450 };
451 
452 /*
453  * Driver-side hooks.
454  */
455 
456 static void
457 ptsdrv_outwakeup(struct tty *tp)
458 {
459 	struct pts_softc *psc = tty_softc(tp);
460 
461 	cv_broadcast(&psc->pts_outwait);
462 	selwakeup(&psc->pts_outpoll);
463 }
464 
465 static void
466 ptsdrv_inwakeup(struct tty *tp)
467 {
468 	struct pts_softc *psc = tty_softc(tp);
469 
470 	cv_broadcast(&psc->pts_inwait);
471 	selwakeup(&psc->pts_inpoll);
472 }
473 
474 static void
475 ptsdrv_close(struct tty *tp)
476 {
477 
478 	/* Wake up any blocked readers/writers. */
479 	ptsdrv_outwakeup(tp);
480 	ptsdrv_inwakeup(tp);
481 }
482 
483 static void
484 ptsdrv_free(void *softc)
485 {
486 	struct pts_softc *psc = softc;
487 
488 	/* Make device number available again. */
489 	if (psc->pts_unit >= 0)
490 		free_unr(pts_pool, psc->pts_unit);
491 
492 	chgptscnt(psc->pts_uidinfo, -1, 0);
493 	uifree(psc->pts_uidinfo);
494 
495 #ifdef PTS_EXTERNAL
496 	/* Destroy master device as well. */
497 	if (psc->pts_cdev != NULL)
498 		destroy_dev_sched(psc->pts_cdev);
499 #endif /* PTS_EXTERNAL */
500 
501 	free(psc, M_PTS);
502 }
503 
504 static struct ttydevsw pts_class = {
505 	.tsw_flags	= TF_NOPREFIX,
506 	.tsw_outwakeup	= ptsdrv_outwakeup,
507 	.tsw_inwakeup	= ptsdrv_inwakeup,
508 	.tsw_close	= ptsdrv_close,
509 	.tsw_free	= ptsdrv_free,
510 };
511 
512 static int
513 pts_alloc(int fflags, struct thread *td, struct file *fp)
514 {
515 	int unit, ok;
516 	struct tty *tp;
517 	struct pts_softc *psc;
518 	struct proc *p = td->td_proc;
519 	struct uidinfo *uid = td->td_ucred->cr_ruidinfo;
520 
521 	/* Resource limiting. */
522 	PROC_LOCK(p);
523 	ok = chgptscnt(uid, 1, lim_cur(p, RLIMIT_NPTS));
524 	PROC_UNLOCK(p);
525 	if (!ok)
526 		return (EAGAIN);
527 
528 	/* Try to allocate a new pts unit number. */
529 	unit = alloc_unr(pts_pool);
530 	if (unit < 0) {
531 		chgptscnt(uid, -1, 0);
532 		return (EAGAIN);
533 	}
534 
535 	/* Allocate TTY and softc. */
536 	psc = malloc(sizeof(struct pts_softc), M_PTS, M_WAITOK|M_ZERO);
537 	cv_init(&psc->pts_inwait, "pts inwait");
538 	cv_init(&psc->pts_outwait, "pts outwait");
539 
540 	psc->pts_unit = unit;
541 	psc->pts_uidinfo = uid;
542 	uihold(uid);
543 
544 	tp = tty_alloc(&pts_class, psc, NULL);
545 
546 	/* Expose the slave device as well. */
547 	tty_makedev(tp, td->td_ucred, "pts/%u", psc->pts_unit);
548 
549 	finit(fp, fflags, DTYPE_PTS, tp, &ptsdev_ops);
550 
551 	return (0);
552 }
553 
554 #ifdef PTS_EXTERNAL
555 int
556 pts_alloc_external(int fflags, struct thread *td, struct file *fp,
557     struct cdev *dev, const char *name)
558 {
559 	int ok;
560 	struct tty *tp;
561 	struct pts_softc *psc;
562 	struct proc *p = td->td_proc;
563 	struct uidinfo *uid = td->td_ucred->cr_ruidinfo;
564 
565 	/* Resource limiting. */
566 	PROC_LOCK(p);
567 	ok = chgptscnt(uid, 1, lim_cur(p, RLIMIT_NPTS));
568 	PROC_UNLOCK(p);
569 	if (!ok)
570 		return (EAGAIN);
571 
572 	/* Allocate TTY and softc. */
573 	psc = malloc(sizeof(struct pts_softc), M_PTS, M_WAITOK|M_ZERO);
574 	cv_init(&psc->pts_inwait, "pts inwait");
575 	cv_init(&psc->pts_outwait, "pts outwait");
576 
577 	psc->pts_unit = -1;
578 	psc->pts_cdev = dev;
579 	psc->pts_uidinfo = uid;
580 	uihold(uid);
581 
582 	tp = tty_alloc(&pts_class, psc, NULL);
583 
584 	/* Expose the slave device as well. */
585 	tty_makedev(tp, td->td_ucred, "%s", name);
586 
587 	finit(fp, fflags, DTYPE_PTS, tp, &ptsdev_ops);
588 
589 	return (0);
590 }
591 #endif /* PTS_EXTERNAL */
592 
593 int
594 posix_openpt(struct thread *td, struct posix_openpt_args *uap)
595 {
596 	int error, fd;
597 	struct file *fp;
598 
599 	/*
600 	 * POSIX states it's unspecified when other flags are passed. We
601 	 * don't allow this.
602 	 */
603 	if (uap->flags & ~(O_RDWR|O_NOCTTY))
604 		return (EINVAL);
605 
606 	error = falloc(td, &fp, &fd);
607 	if (error)
608 		return (error);
609 
610 	/* Allocate the actual pseudo-TTY. */
611 	error = pts_alloc(FFLAGS(uap->flags & O_ACCMODE), td, fp);
612 	if (error != 0) {
613 		fdclose(td->td_proc->p_fd, fp, fd, td);
614 		return (error);
615 	}
616 
617 	/* Pass it back to userspace. */
618 	td->td_retval[0] = fd;
619 	fdrop(fp, td);
620 
621 	return (0);
622 }
623 
624 #if defined(PTS_COMPAT) || defined(PTS_LINUX)
625 static int
626 ptmx_fdopen(struct cdev *dev, int fflags, struct thread *td, struct file *fp)
627 {
628 	int error;
629 
630 	error = pts_alloc(fflags & (FREAD|FWRITE), td, fp);
631 	if (error != 0)
632 		return (error);
633 
634 	return (0);
635 }
636 
637 static struct cdevsw ptmx_cdevsw = {
638 	.d_version	= D_VERSION,
639 	.d_fdopen	= ptmx_fdopen,
640 	.d_name		= "ptmx",
641 };
642 #endif /* PTS_COMPAT || PTS_LINUX */
643 
644 static void
645 pts_init(void *unused)
646 {
647 
648 	pts_pool = new_unrhdr(0, MAXPTSDEVS, NULL);
649 #if defined(PTS_COMPAT) || defined(PTS_LINUX)
650 	make_dev(&ptmx_cdevsw, 0, UID_ROOT, GID_WHEEL, 0666, "ptmx");
651 #endif /* PTS_COMPAT || PTS_LINUX */
652 }
653 
654 SYSINIT(pts, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, pts_init, NULL);
655