1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * This module exports the functions:
4  *
5  *     'int set_selection_user(struct tiocl_selection __user *,
6  *			       struct tty_struct *)'
7  *     'int set_selection_kernel(struct tiocl_selection *, struct tty_struct *)'
8  *     'void clear_selection(void)'
9  *     'int paste_selection(struct tty_struct *)'
10  *     'int sel_loadlut(u32 __user *)'
11  *
12  * Now that /dev/vcs exists, most of this can disappear again.
13  */
14 
15 #include <linux/module.h>
16 #include <linux/tty.h>
17 #include <linux/sched.h>
18 #include <linux/mm.h>
19 #include <linux/mutex.h>
20 #include <linux/slab.h>
21 #include <linux/types.h>
22 
23 #include <linux/uaccess.h>
24 
25 #include <linux/kbd_kern.h>
26 #include <linux/vt_kern.h>
27 #include <linux/consolemap.h>
28 #include <linux/selection.h>
29 #include <linux/tiocl.h>
30 #include <linux/console.h>
31 #include <linux/tty_flip.h>
32 
33 #include <linux/sched/signal.h>
34 
35 /* Don't take this from <ctype.h>: 011-015 on the screen aren't spaces */
36 #define is_space_on_vt(c)	((c) == ' ')
37 
38 /* FIXME: all this needs locking */
39 static struct vc_selection {
40 	struct mutex lock;
41 	struct vc_data *cons;			/* must not be deallocated */
42 	char *buffer;
43 	unsigned int buf_len;
44 	volatile int start;			/* cleared by clear_selection */
45 	int end;
46 } vc_sel = {
47 	.lock = __MUTEX_INITIALIZER(vc_sel.lock),
48 	.start = -1,
49 };
50 
51 /* clear_selection, highlight and highlight_pointer can be called
52    from interrupt (via scrollback/front) */
53 
54 /* set reverse video on characters s-e of console with selection. */
highlight(const int s,const int e)55 static inline void highlight(const int s, const int e)
56 {
57 	invert_screen(vc_sel.cons, s, e-s+2, true);
58 }
59 
60 /* use complementary color to show the pointer */
highlight_pointer(const int where)61 static inline void highlight_pointer(const int where)
62 {
63 	complement_pos(vc_sel.cons, where);
64 }
65 
66 static u32
sel_pos(int n,bool unicode)67 sel_pos(int n, bool unicode)
68 {
69 	if (unicode)
70 		return screen_glyph_unicode(vc_sel.cons, n / 2);
71 	return inverse_translate(vc_sel.cons, screen_glyph(vc_sel.cons, n),
72 			false);
73 }
74 
75 /**
76  * clear_selection - remove current selection
77  *
78  * Remove the current selection highlight, if any from the console holding the
79  * selection.
80  *
81  * Locking: The caller must hold the console lock.
82  */
clear_selection(void)83 void clear_selection(void)
84 {
85 	highlight_pointer(-1); /* hide the pointer */
86 	if (vc_sel.start != -1) {
87 		highlight(vc_sel.start, vc_sel.end);
88 		vc_sel.start = -1;
89 	}
90 }
91 EXPORT_SYMBOL_GPL(clear_selection);
92 
vc_is_sel(const struct vc_data * vc)93 bool vc_is_sel(const struct vc_data *vc)
94 {
95 	return vc == vc_sel.cons;
96 }
97 
98 /*
99  * User settable table: what characters are to be considered alphabetic?
100  * 128 bits. Locked by the console lock.
101  */
102 static u32 inwordLut[]={
103   0x00000000, /* control chars     */
104   0x03FFE000, /* digits and "-./"  */
105   0x87FFFFFE, /* uppercase and '_' */
106   0x07FFFFFE, /* lowercase         */
107 };
108 
inword(const u32 c)109 static inline int inword(const u32 c)
110 {
111 	return c > 0x7f || (( inwordLut[c>>5] >> (c & 0x1F) ) & 1);
112 }
113 
114 /**
115  * sel_loadlut() - load the LUT table
116  * @lut: user table
117  *
118  * Load the LUT table from user space. Make a temporary copy so a partial
119  * update doesn't make a mess.
120  *
121  * Locking: The console lock is acquired.
122  */
sel_loadlut(u32 __user * lut)123 int sel_loadlut(u32 __user *lut)
124 {
125 	u32 tmplut[ARRAY_SIZE(inwordLut)];
126 
127 	if (copy_from_user(tmplut, lut, sizeof(inwordLut)))
128 		return -EFAULT;
129 
130 	console_lock();
131 	memcpy(inwordLut, tmplut, sizeof(inwordLut));
132 	console_unlock();
133 
134 	return 0;
135 }
136 
137 /* does screen address p correspond to character at LH/RH edge of screen? */
atedge(const int p,int size_row)138 static inline int atedge(const int p, int size_row)
139 {
140 	return (!(p % size_row)	|| !((p + 2) % size_row));
141 }
142 
143 /* stores the char in UTF8 and returns the number of bytes used (1-4) */
store_utf8(u32 c,char * p)144 static int store_utf8(u32 c, char *p)
145 {
146 	if (c < 0x80) {
147 		/*  0******* */
148 		p[0] = c;
149 		return 1;
150 	} else if (c < 0x800) {
151 		/* 110***** 10****** */
152 		p[0] = 0xc0 | (c >> 6);
153 		p[1] = 0x80 | (c & 0x3f);
154 		return 2;
155 	} else if (c < 0x10000) {
156 		/* 1110**** 10****** 10****** */
157 		p[0] = 0xe0 | (c >> 12);
158 		p[1] = 0x80 | ((c >> 6) & 0x3f);
159 		p[2] = 0x80 | (c & 0x3f);
160 		return 3;
161 	} else if (c < 0x110000) {
162 		/* 11110*** 10****** 10****** 10****** */
163 		p[0] = 0xf0 | (c >> 18);
164 		p[1] = 0x80 | ((c >> 12) & 0x3f);
165 		p[2] = 0x80 | ((c >> 6) & 0x3f);
166 		p[3] = 0x80 | (c & 0x3f);
167 		return 4;
168 	} else {
169 		/* outside Unicode, replace with U+FFFD */
170 		p[0] = 0xef;
171 		p[1] = 0xbf;
172 		p[2] = 0xbd;
173 		return 3;
174 	}
175 }
176 
177 /**
178  * set_selection_user - set the current selection.
179  * @sel: user selection info
180  * @tty: the console tty
181  *
182  * Invoked by the ioctl handle for the vt layer.
183  *
184  * Locking: The entire selection process is managed under the console_lock.
185  * It's a lot under the lock but its hardly a performance path.
186  */
set_selection_user(const struct tiocl_selection __user * sel,struct tty_struct * tty)187 int set_selection_user(const struct tiocl_selection __user *sel,
188 		       struct tty_struct *tty)
189 {
190 	struct tiocl_selection v;
191 
192 	if (copy_from_user(&v, sel, sizeof(*sel)))
193 		return -EFAULT;
194 
195 	return set_selection_kernel(&v, tty);
196 }
197 
vc_selection_store_chars(struct vc_data * vc,bool unicode)198 static int vc_selection_store_chars(struct vc_data *vc, bool unicode)
199 {
200 	char *bp, *obp;
201 	unsigned int i;
202 
203 	/* Allocate a new buffer before freeing the old one ... */
204 	/* chars can take up to 4 bytes with unicode */
205 	bp = kmalloc_array((vc_sel.end - vc_sel.start) / 2 + 1, unicode ? 4 : 1,
206 			   GFP_KERNEL | __GFP_NOWARN);
207 	if (!bp) {
208 		printk(KERN_WARNING "selection: kmalloc() failed\n");
209 		clear_selection();
210 		return -ENOMEM;
211 	}
212 	kfree(vc_sel.buffer);
213 	vc_sel.buffer = bp;
214 
215 	obp = bp;
216 	for (i = vc_sel.start; i <= vc_sel.end; i += 2) {
217 		u32 c = sel_pos(i, unicode);
218 		if (unicode)
219 			bp += store_utf8(c, bp);
220 		else
221 			*bp++ = c;
222 		if (!is_space_on_vt(c))
223 			obp = bp;
224 		if (!((i + 2) % vc->vc_size_row)) {
225 			/* strip trailing blanks from line and add newline,
226 			   unless non-space at end of line. */
227 			if (obp != bp) {
228 				bp = obp;
229 				*bp++ = '\r';
230 			}
231 			obp = bp;
232 		}
233 	}
234 	vc_sel.buf_len = bp - vc_sel.buffer;
235 
236 	return 0;
237 }
238 
vc_do_selection(struct vc_data * vc,unsigned short mode,int ps,int pe)239 static int vc_do_selection(struct vc_data *vc, unsigned short mode, int ps,
240 		int pe)
241 {
242 	int new_sel_start, new_sel_end, spc;
243 	bool unicode = vt_do_kdgkbmode(fg_console) == K_UNICODE;
244 
245 	switch (mode) {
246 	case TIOCL_SELCHAR:	/* character-by-character selection */
247 		new_sel_start = ps;
248 		new_sel_end = pe;
249 		break;
250 	case TIOCL_SELWORD:	/* word-by-word selection */
251 		spc = is_space_on_vt(sel_pos(ps, unicode));
252 		for (new_sel_start = ps; ; ps -= 2) {
253 			if ((spc && !is_space_on_vt(sel_pos(ps, unicode))) ||
254 			    (!spc && !inword(sel_pos(ps, unicode))))
255 				break;
256 			new_sel_start = ps;
257 			if (!(ps % vc->vc_size_row))
258 				break;
259 		}
260 
261 		spc = is_space_on_vt(sel_pos(pe, unicode));
262 		for (new_sel_end = pe; ; pe += 2) {
263 			if ((spc && !is_space_on_vt(sel_pos(pe, unicode))) ||
264 			    (!spc && !inword(sel_pos(pe, unicode))))
265 				break;
266 			new_sel_end = pe;
267 			if (!((pe + 2) % vc->vc_size_row))
268 				break;
269 		}
270 		break;
271 	case TIOCL_SELLINE:	/* line-by-line selection */
272 		new_sel_start = rounddown(ps, vc->vc_size_row);
273 		new_sel_end = rounddown(pe, vc->vc_size_row) +
274 			vc->vc_size_row - 2;
275 		break;
276 	case TIOCL_SELPOINTER:
277 		highlight_pointer(pe);
278 		return 0;
279 	default:
280 		return -EINVAL;
281 	}
282 
283 	/* remove the pointer */
284 	highlight_pointer(-1);
285 
286 	/* select to end of line if on trailing space */
287 	if (new_sel_end > new_sel_start &&
288 		!atedge(new_sel_end, vc->vc_size_row) &&
289 		is_space_on_vt(sel_pos(new_sel_end, unicode))) {
290 		for (pe = new_sel_end + 2; ; pe += 2)
291 			if (!is_space_on_vt(sel_pos(pe, unicode)) ||
292 			    atedge(pe, vc->vc_size_row))
293 				break;
294 		if (is_space_on_vt(sel_pos(pe, unicode)))
295 			new_sel_end = pe;
296 	}
297 	if (vc_sel.start == -1)	/* no current selection */
298 		highlight(new_sel_start, new_sel_end);
299 	else if (new_sel_start == vc_sel.start)
300 	{
301 		if (new_sel_end == vc_sel.end)	/* no action required */
302 			return 0;
303 		else if (new_sel_end > vc_sel.end)	/* extend to right */
304 			highlight(vc_sel.end + 2, new_sel_end);
305 		else				/* contract from right */
306 			highlight(new_sel_end + 2, vc_sel.end);
307 	}
308 	else if (new_sel_end == vc_sel.end)
309 	{
310 		if (new_sel_start < vc_sel.start) /* extend to left */
311 			highlight(new_sel_start, vc_sel.start - 2);
312 		else				/* contract from left */
313 			highlight(vc_sel.start, new_sel_start - 2);
314 	}
315 	else	/* some other case; start selection from scratch */
316 	{
317 		clear_selection();
318 		highlight(new_sel_start, new_sel_end);
319 	}
320 	vc_sel.start = new_sel_start;
321 	vc_sel.end = new_sel_end;
322 
323 	return vc_selection_store_chars(vc, unicode);
324 }
325 
vc_selection(struct vc_data * vc,struct tiocl_selection * v,struct tty_struct * tty)326 static int vc_selection(struct vc_data *vc, struct tiocl_selection *v,
327 		struct tty_struct *tty)
328 {
329 	int ps, pe;
330 
331 	poke_blanked_console();
332 
333 	if (v->sel_mode == TIOCL_SELCLEAR) {
334 		/* useful for screendump without selection highlights */
335 		clear_selection();
336 		return 0;
337 	}
338 
339 	v->xs = min_t(u16, v->xs - 1, vc->vc_cols - 1);
340 	v->ys = min_t(u16, v->ys - 1, vc->vc_rows - 1);
341 	v->xe = min_t(u16, v->xe - 1, vc->vc_cols - 1);
342 	v->ye = min_t(u16, v->ye - 1, vc->vc_rows - 1);
343 
344 	if (mouse_reporting() && (v->sel_mode & TIOCL_SELMOUSEREPORT)) {
345 		mouse_report(tty, v->sel_mode & TIOCL_SELBUTTONMASK, v->xs,
346 			     v->ys);
347 		return 0;
348 	}
349 
350 	ps = v->ys * vc->vc_size_row + (v->xs << 1);
351 	pe = v->ye * vc->vc_size_row + (v->xe << 1);
352 	if (ps > pe)	/* make vc_sel.start <= vc_sel.end */
353 		swap(ps, pe);
354 
355 	if (vc_sel.cons != vc) {
356 		clear_selection();
357 		vc_sel.cons = vc;
358 	}
359 
360 	return vc_do_selection(vc, v->sel_mode, ps, pe);
361 }
362 
set_selection_kernel(struct tiocl_selection * v,struct tty_struct * tty)363 int set_selection_kernel(struct tiocl_selection *v, struct tty_struct *tty)
364 {
365 	int ret;
366 
367 	mutex_lock(&vc_sel.lock);
368 	console_lock();
369 	ret = vc_selection(vc_cons[fg_console].d, v, tty);
370 	console_unlock();
371 	mutex_unlock(&vc_sel.lock);
372 
373 	return ret;
374 }
375 EXPORT_SYMBOL_GPL(set_selection_kernel);
376 
377 /* Insert the contents of the selection buffer into the
378  * queue of the tty associated with the current console.
379  * Invoked by ioctl().
380  *
381  * Locking: called without locks. Calls the ldisc wrongly with
382  * unsafe methods,
383  */
paste_selection(struct tty_struct * tty)384 int paste_selection(struct tty_struct *tty)
385 {
386 	struct vc_data *vc = tty->driver_data;
387 	int	pasted = 0;
388 	size_t count;
389 	struct  tty_ldisc *ld;
390 	DECLARE_WAITQUEUE(wait, current);
391 	int ret = 0;
392 
393 	console_lock();
394 	poke_blanked_console();
395 	console_unlock();
396 
397 	ld = tty_ldisc_ref_wait(tty);
398 	if (!ld)
399 		return -EIO;	/* ldisc was hung up */
400 	tty_buffer_lock_exclusive(&vc->port);
401 
402 	add_wait_queue(&vc->paste_wait, &wait);
403 	mutex_lock(&vc_sel.lock);
404 	while (vc_sel.buffer && vc_sel.buf_len > pasted) {
405 		set_current_state(TASK_INTERRUPTIBLE);
406 		if (signal_pending(current)) {
407 			ret = -EINTR;
408 			break;
409 		}
410 		if (tty_throttled(tty)) {
411 			mutex_unlock(&vc_sel.lock);
412 			schedule();
413 			mutex_lock(&vc_sel.lock);
414 			continue;
415 		}
416 		__set_current_state(TASK_RUNNING);
417 		count = vc_sel.buf_len - pasted;
418 		count = tty_ldisc_receive_buf(ld, vc_sel.buffer + pasted, NULL,
419 					      count);
420 		pasted += count;
421 	}
422 	mutex_unlock(&vc_sel.lock);
423 	remove_wait_queue(&vc->paste_wait, &wait);
424 	__set_current_state(TASK_RUNNING);
425 
426 	tty_buffer_unlock_exclusive(&vc->port);
427 	tty_ldisc_deref(ld);
428 	return ret;
429 }
430 EXPORT_SYMBOL_GPL(paste_selection);
431