tty/teken: fix UTF8 sequence validation logic

This patch fixes UTF-8 sequence validation logic in
teken_utf8_bytes_to_codepoint() and fixes fallback behaviour in
ttydisc_rubchar() when an invalid UTF8 sequence is encountered. The code
previously used __bitcount() to extract sequence length information from
the leading byte. However, this assumption breaks for certain code
points that have additional bits set in the first half of the leading
byte (e.g. Cyrillic characters). This lead to incorrect behaviour when
deleting those characters using backspaces. The code now checks the
number of consecutive set bits in the leading byte starting from the
MSB, as per RFC 3629.

Reviewed by:	christos
MFC after:	2 weeks
Differential Revision:	https://reviews.freebsd.org/D42147

(cherry picked from commit 2fed1c579c52d63b72fc08ffcc652ba0183f9254)
This commit is contained in:
Bojan Novković 2023-10-13 08:14:36 +03:00 committed by Christos Margiolis
parent d25f8c1bdc
commit 72a8e373f2
2 changed files with 27 additions and 8 deletions

View file

@ -844,23 +844,25 @@ ttydisc_rubchar(struct tty *tp)
*/
ttyinq_write(&tp->t_inq, bytes,
UTF8_STACKBUF, 0);
ttyinq_unputchar(&tp->t_inq);
} else {
/* Find codepoint and width. */
codepoint =
teken_utf8_bytes_to_codepoint(bytes,
nb);
if (codepoint !=
TEKEN_UTF8_INVALID_CODEPOINT) {
cwidth = teken_wcwidth(
codepoint);
} else {
if (codepoint ==
TEKEN_UTF8_INVALID_CODEPOINT ||
(cwidth = teken_wcwidth(
codepoint)) == -1) {
/*
* Place all bytes back into the
* inq and fall back to
* default behaviour.
*/
cwidth = 1;
ttyinq_write(&tp->t_inq, bytes,
nb, 0);
ttyinq_unputchar(&tp->t_inq);
}
}
tp->t_column -= cwidth;

View file

@ -128,15 +128,32 @@ static inline teken_char_t
teken_utf8_bytes_to_codepoint(uint8_t bytes[4], int nbytes)
{
/* Check for malformed characters. */
if (__bitcount(bytes[0] & 0xf0) != nbytes)
/*
* Check for malformed characters by comparing 'nbytes'
* to the byte length of the character.
*
* The table in section 3 of RFC 3629 defines 4 different
* values indicating the length of a UTF-8 byte sequence.
*
* 0xxxxxxx -> 1 byte
* 110xxxxx -> 2 bytes
* 1110xxxx -> 3 bytes
* 11110xxx -> 4 bytes
*
* The length is determined by the higher-order bits in
* the leading octet (except in the first case, where an MSB
* of 0 means a byte length of 1). Here we flip the 4 upper
* bits and count the leading zeros using __builtin_clz()
* to determine the number of bytes.
*/
if (__builtin_clz(~(bytes[0] & 0xf0) << 24) != nbytes)
return (TEKEN_UTF8_INVALID_CODEPOINT);
switch (nbytes) {
case 1:
return (bytes[0] & 0x7f);
case 2:
return (bytes[0] & 0xf) << 6 | (bytes[1] & 0x3f);
return (bytes[0] & 0x1f) << 6 | (bytes[1] & 0x3f);
case 3:
return (bytes[0] & 0xf) << 12 | (bytes[1] & 0x3f) << 6 | (bytes[2] & 0x3f);
case 4: