xref: /freebsd/sys/kern/tty_inq.c (revision aa339f1d5df9e38f36a34eb522355c4eebcae6c4)
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/param.h>
33 #include <sys/kernel.h>
34 #include <sys/lock.h>
35 #include <sys/queue.h>
36 #include <sys/sysctl.h>
37 #include <sys/systm.h>
38 #include <sys/tty.h>
39 #include <sys/uio.h>
40 
41 #include <vm/uma.h>
42 
43 /*
44  * TTY input queue buffering.
45  *
46  * Unlike the output queue, the input queue has more features that are
47  * needed to properly implement various features offered by the TTY
48  * interface:
49  *
50  * - Data can be removed from the tail of the queue, which is used to
51  *   implement backspace.
52  * - Once in a while, input has to be `canonicalized'. When ICANON is
53  *   turned on, this will be done after a CR has been inserted.
54  *   Otherwise, it should be done after any character has been inserted.
55  * - The input queue can store one bit per byte, called the quoting bit.
56  *   This bit is used by TTYDISC to make backspace work on quoted
57  *   characters.
58  *
59  * In most cases, there is probably less input than output, so unlike
60  * the outq, we'll stick to 128 byte blocks here.
61  */
62 
63 static int ttyinq_flush_secure = 1;
64 SYSCTL_INT(_kern, OID_AUTO, tty_inq_flush_secure, CTLFLAG_RW,
65 	&ttyinq_flush_secure, 0, "Zero buffers while flushing");
66 
67 #define TTYINQ_QUOTESIZE	(TTYINQ_DATASIZE / BMSIZE)
68 #define BMSIZE			32
69 #define GETBIT(tib,boff) \
70 	((tib)->tib_quotes[(boff) / BMSIZE] & (1 << ((boff) % BMSIZE)))
71 #define SETBIT(tib,boff) \
72 	((tib)->tib_quotes[(boff) / BMSIZE] |= (1 << ((boff) % BMSIZE)))
73 #define CLRBIT(tib,boff) \
74 	((tib)->tib_quotes[(boff) / BMSIZE] &= ~(1 << ((boff) % BMSIZE)))
75 
76 struct ttyinq_block {
77 	struct ttyinq_block	*tib_prev;
78 	struct ttyinq_block	*tib_next;
79 	uint32_t		tib_quotes[TTYINQ_QUOTESIZE];
80 	char			tib_data[TTYINQ_DATASIZE];
81 };
82 
83 static uma_zone_t ttyinq_zone;
84 
85 #define	TTYINQ_INSERT_TAIL(ti, tib) do {				\
86 	if (ti->ti_end == 0) {						\
87 		tib->tib_prev = NULL;					\
88 		tib->tib_next = ti->ti_firstblock;			\
89 		ti->ti_firstblock = tib;				\
90 	} else {							\
91 		tib->tib_prev = ti->ti_lastblock;			\
92 		tib->tib_next = ti->ti_lastblock->tib_next;		\
93 		ti->ti_lastblock->tib_next = tib;			\
94 	}								\
95 	if (tib->tib_next != NULL)					\
96 		tib->tib_next->tib_prev = tib;				\
97 	ti->ti_nblocks++;						\
98 } while (0)
99 
100 #define	TTYINQ_REMOVE_HEAD(ti) do {					\
101 	ti->ti_firstblock = ti->ti_firstblock->tib_next;		\
102 	if (ti->ti_firstblock != NULL)					\
103 		ti->ti_firstblock->tib_prev = NULL;			\
104 	ti->ti_nblocks--;						\
105 } while (0)
106 
107 #define	TTYINQ_RECYCLE(ti, tib) do {					\
108 	if (ti->ti_quota <= ti->ti_nblocks)				\
109 		uma_zfree(ttyinq_zone, tib);				\
110 	else								\
111 		TTYINQ_INSERT_TAIL(ti, tib);				\
112 } while (0)
113 
114 int
115 ttyinq_setsize(struct ttyinq *ti, struct tty *tp, size_t size)
116 {
117 	struct ttyinq_block *tib;
118 
119 	ti->ti_quota = howmany(size, TTYINQ_DATASIZE);
120 
121 	while (ti->ti_quota > ti->ti_nblocks) {
122 		/*
123 		 * List is getting bigger.
124 		 * Add new blocks to the tail of the list.
125 		 *
126 		 * We must unlock the TTY temporarily, because we need
127 		 * to allocate memory. This won't be a problem, because
128 		 * in the worst case, another thread ends up here, which
129 		 * may cause us to allocate too many blocks, but this
130 		 * will be caught by the loop below.
131 		 */
132 		tty_unlock(tp);
133 		tib = uma_zalloc(ttyinq_zone, M_WAITOK);
134 		tty_lock(tp);
135 
136 		if (tty_gone(tp)) {
137 			uma_zfree(ttyinq_zone, tib);
138 			return (ENXIO);
139 		}
140 
141 		TTYINQ_INSERT_TAIL(ti, tib);
142 	}
143 	return (0);
144 }
145 
146 void
147 ttyinq_free(struct ttyinq *ti)
148 {
149 	struct ttyinq_block *tib;
150 
151 	ttyinq_flush(ti);
152 	ti->ti_quota = 0;
153 
154 	while ((tib = ti->ti_firstblock) != NULL) {
155 		TTYINQ_REMOVE_HEAD(ti);
156 		uma_zfree(ttyinq_zone, tib);
157 	}
158 
159 	MPASS(ti->ti_nblocks == 0);
160 }
161 
162 int
163 ttyinq_read_uio(struct ttyinq *ti, struct tty *tp, struct uio *uio,
164     size_t rlen, size_t flen)
165 {
166 
167 	MPASS(rlen <= uio->uio_resid);
168 
169 	while (rlen > 0) {
170 		int error;
171 		struct ttyinq_block *tib;
172 		size_t cbegin, cend, clen;
173 
174 		/* See if there still is data. */
175 		if (ti->ti_begin == ti->ti_linestart)
176 			return (0);
177 		tib = ti->ti_firstblock;
178 		if (tib == NULL)
179 			return (0);
180 
181 		/*
182 		 * The end address should be the lowest of these three:
183 		 * - The write pointer
184 		 * - The blocksize - we can't read beyond the block
185 		 * - The end address if we could perform the full read
186 		 */
187 		cbegin = ti->ti_begin;
188 		cend = MIN(MIN(ti->ti_linestart, ti->ti_begin + rlen),
189 		    TTYINQ_DATASIZE);
190 		clen = cend - cbegin;
191 		MPASS(clen >= flen);
192 		rlen -= clen;
193 
194 		/*
195 		 * We can prevent buffering in some cases:
196 		 * - We need to read the block until the end.
197 		 * - We don't need to read the block until the end, but
198 		 *   there is no data beyond it, which allows us to move
199 		 *   the write pointer to a new block.
200 		 */
201 		if (cend == TTYINQ_DATASIZE || cend == ti->ti_end) {
202 			/*
203 			 * Fast path: zero copy. Remove the first block,
204 			 * so we can unlock the TTY temporarily.
205 			 */
206 			TTYINQ_REMOVE_HEAD(ti);
207 			ti->ti_begin = 0;
208 
209 			/*
210 			 * Because we remove the first block, we must
211 			 * fix up the block offsets.
212 			 */
213 #define CORRECT_BLOCK(t) do {			\
214 	if (t <= TTYINQ_DATASIZE)		\
215 		t = 0;				\
216 	else					\
217 		t -= TTYINQ_DATASIZE;		\
218 } while (0)
219 			CORRECT_BLOCK(ti->ti_linestart);
220 			CORRECT_BLOCK(ti->ti_reprint);
221 			CORRECT_BLOCK(ti->ti_end);
222 #undef CORRECT_BLOCK
223 
224 			/*
225 			 * Temporary unlock and copy the data to
226 			 * userspace. We may need to flush trailing
227 			 * bytes, like EOF characters.
228 			 */
229 			tty_unlock(tp);
230 			error = uiomove(tib->tib_data + cbegin,
231 			    clen - flen, uio);
232 			tty_lock(tp);
233 
234 			/* Block can now be readded to the list. */
235 			TTYINQ_RECYCLE(ti, tib);
236 		} else {
237 			char ob[TTYINQ_DATASIZE - 1];
238 
239 			/*
240 			 * Slow path: store data in a temporary buffer.
241 			 */
242 			memcpy(ob, tib->tib_data + cbegin, clen - flen);
243 			ti->ti_begin += clen;
244 			MPASS(ti->ti_begin < TTYINQ_DATASIZE);
245 
246 			/* Temporary unlock and copy the data to userspace. */
247 			tty_unlock(tp);
248 			error = uiomove(ob, clen - flen, uio);
249 			tty_lock(tp);
250 		}
251 
252 		if (error != 0)
253 			return (error);
254 		if (tty_gone(tp))
255 			return (ENXIO);
256 	}
257 
258 	return (0);
259 }
260 
261 static __inline void
262 ttyinq_set_quotes(struct ttyinq_block *tib, size_t offset,
263     size_t length, int value)
264 {
265 
266 	if (value) {
267 		/* Set the bits. */
268 		for (; length > 0; length--, offset++)
269 			SETBIT(tib, offset);
270 	} else {
271 		/* Unset the bits. */
272 		for (; length > 0; length--, offset++)
273 			CLRBIT(tib, offset);
274 	}
275 }
276 
277 size_t
278 ttyinq_write(struct ttyinq *ti, const void *buf, size_t nbytes, int quote)
279 {
280 	const char *cbuf = buf;
281 	struct ttyinq_block *tib;
282 	unsigned int boff;
283 	size_t l;
284 
285 	while (nbytes > 0) {
286 		boff = ti->ti_end % TTYINQ_DATASIZE;
287 
288 		if (ti->ti_end == 0) {
289 			/* First time we're being used or drained. */
290 			MPASS(ti->ti_begin == 0);
291 			tib = ti->ti_firstblock;
292 			if (tib == NULL) {
293 				/* Queue has no blocks. */
294 				break;
295 			}
296 			ti->ti_lastblock = tib;
297 		} else if (boff == 0) {
298 			/* We reached the end of this block on last write. */
299 			tib = ti->ti_lastblock->tib_next;
300 			if (tib == NULL) {
301 				/* We've reached the watermark. */
302 				break;
303 			}
304 			ti->ti_lastblock = tib;
305 		} else {
306 			tib = ti->ti_lastblock;
307 		}
308 
309 		/* Don't copy more than was requested. */
310 		l = MIN(nbytes, TTYINQ_DATASIZE - boff);
311 		MPASS(l > 0);
312 		memcpy(tib->tib_data + boff, cbuf, l);
313 
314 		/* Set the quoting bits for the proper region. */
315 		ttyinq_set_quotes(tib, boff, l, quote);
316 
317 		cbuf += l;
318 		nbytes -= l;
319 		ti->ti_end += l;
320 	}
321 
322 	return (cbuf - (const char *)buf);
323 }
324 
325 int
326 ttyinq_write_nofrag(struct ttyinq *ti, const void *buf, size_t nbytes, int quote)
327 {
328 	size_t ret __unused;
329 
330 	if (ttyinq_bytesleft(ti) < nbytes)
331 		return (-1);
332 
333 	/* We should always be able to write it back. */
334 	ret = ttyinq_write(ti, buf, nbytes, quote);
335 	MPASS(ret == nbytes);
336 
337 	return (0);
338 }
339 
340 void
341 ttyinq_canonicalize(struct ttyinq *ti)
342 {
343 
344 	ti->ti_linestart = ti->ti_reprint = ti->ti_end;
345 	ti->ti_startblock = ti->ti_reprintblock = ti->ti_lastblock;
346 }
347 
348 size_t
349 ttyinq_findchar(struct ttyinq *ti, const char *breakc, size_t maxlen,
350     char *lastc)
351 {
352 	struct ttyinq_block *tib = ti->ti_firstblock;
353 	unsigned int boff = ti->ti_begin;
354 	unsigned int bend = MIN(MIN(TTYINQ_DATASIZE, ti->ti_linestart),
355 	    ti->ti_begin + maxlen);
356 
357 	MPASS(maxlen > 0);
358 
359 	if (tib == NULL)
360 		return (0);
361 
362 	while (boff < bend) {
363 		if (strchr(breakc, tib->tib_data[boff]) && !GETBIT(tib, boff)) {
364 			*lastc = tib->tib_data[boff];
365 			return (boff - ti->ti_begin + 1);
366 		}
367 		boff++;
368 	}
369 
370 	/* Not found - just process the entire block. */
371 	return (bend - ti->ti_begin);
372 }
373 
374 void
375 ttyinq_flush(struct ttyinq *ti)
376 {
377 	struct ttyinq_block *tib;
378 
379 	ti->ti_begin = 0;
380 	ti->ti_linestart = 0;
381 	ti->ti_reprint = 0;
382 	ti->ti_end = 0;
383 
384 	/* Zero all data in the input queue to get rid of passwords. */
385 	if (ttyinq_flush_secure) {
386 		for (tib = ti->ti_firstblock; tib != NULL; tib = tib->tib_next)
387 			bzero(&tib->tib_data, sizeof tib->tib_data);
388 	}
389 }
390 
391 int
392 ttyinq_peekchar(struct ttyinq *ti, char *c, int *quote)
393 {
394 	unsigned int boff;
395 	struct ttyinq_block *tib = ti->ti_lastblock;
396 
397 	if (ti->ti_linestart == ti->ti_end)
398 		return (-1);
399 
400 	MPASS(ti->ti_end > 0);
401 	boff = (ti->ti_end - 1) % TTYINQ_DATASIZE;
402 
403 	*c = tib->tib_data[boff];
404 	*quote = GETBIT(tib, boff);
405 
406 	return (0);
407 }
408 
409 void
410 ttyinq_unputchar(struct ttyinq *ti)
411 {
412 
413 	MPASS(ti->ti_linestart < ti->ti_end);
414 
415 	if (--ti->ti_end % TTYINQ_DATASIZE == 0) {
416 		/* Roll back to the previous block. */
417 		ti->ti_lastblock = ti->ti_lastblock->tib_prev;
418 		/*
419 		 * This can only fail if we are unputchar()'ing the
420 		 * first character in the queue.
421 		 */
422 		MPASS((ti->ti_lastblock == NULL) == (ti->ti_end == 0));
423 	}
424 }
425 
426 void
427 ttyinq_reprintpos_set(struct ttyinq *ti)
428 {
429 
430 	ti->ti_reprint = ti->ti_end;
431 	ti->ti_reprintblock = ti->ti_lastblock;
432 }
433 
434 void
435 ttyinq_reprintpos_reset(struct ttyinq *ti)
436 {
437 
438 	ti->ti_reprint = ti->ti_linestart;
439 	ti->ti_reprintblock = ti->ti_startblock;
440 }
441 
442 static void
443 ttyinq_line_iterate(struct ttyinq *ti,
444     ttyinq_line_iterator_t *iterator, void *data,
445     unsigned int offset, struct ttyinq_block *tib)
446 {
447 	unsigned int boff;
448 
449 	/* Use the proper block when we're at the queue head. */
450 	if (offset == 0)
451 		tib = ti->ti_firstblock;
452 
453 	/* Iterate all characters and call the iterator function. */
454 	for (; offset < ti->ti_end; offset++) {
455 		boff = offset % TTYINQ_DATASIZE;
456 		MPASS(tib != NULL);
457 
458 		/* Call back the iterator function. */
459 		iterator(data, tib->tib_data[boff], GETBIT(tib, boff));
460 
461 		/* Last byte iterated - go to the next block. */
462 		if (boff == TTYINQ_DATASIZE - 1)
463 			tib = tib->tib_next;
464 	}
465 }
466 
467 void
468 ttyinq_line_iterate_from_linestart(struct ttyinq *ti,
469     ttyinq_line_iterator_t *iterator, void *data)
470 {
471 
472 	ttyinq_line_iterate(ti, iterator, data,
473 	    ti->ti_linestart, ti->ti_startblock);
474 }
475 
476 void
477 ttyinq_line_iterate_from_reprintpos(struct ttyinq *ti,
478     ttyinq_line_iterator_t *iterator, void *data)
479 {
480 
481 	ttyinq_line_iterate(ti, iterator, data,
482 	    ti->ti_reprint, ti->ti_reprintblock);
483 }
484 
485 static void
486 ttyinq_startup(void *dummy)
487 {
488 
489 	ttyinq_zone = uma_zcreate("ttyinq", sizeof(struct ttyinq_block),
490 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
491 }
492 
493 SYSINIT(ttyinq, SI_SUB_DRIVERS, SI_ORDER_FIRST, ttyinq_startup, NULL);
494