From cbf90d67a2abb3b14c4c7217854fa4c47a45c71b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Ekl=C3=B6f?= Date: Sun, 24 Jan 2021 11:32:45 +0100 Subject: [PATCH] search: filter out non-printable characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Don’t allow non-printable characters in the search input string. --- search.c | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/search.c b/search.c index 4d520ffc..5ccc278f 100644 --- a/search.c +++ b/search.c @@ -354,14 +354,28 @@ search_find_next(struct terminal *term) void search_add_chars(struct terminal *term, const char *src, size_t count) { + const char *_src = src; mbstate_t ps = {0}; - size_t wchars = mbsnrtowcs(NULL, &src, count, 0, &ps); + size_t wchars = mbsnrtowcs(NULL, &_src, count, 0, &ps); if (wchars == -1) { LOG_ERRNO("failed to convert %.*s to wchars", (int)count, src); return; } + _src = src; + ps = (mbstate_t){0}; + wchar_t wcs[wchars + 1]; + mbsnrtowcs(wcs, &_src, count, wchars, &ps); + + /* Strip non-printable characters */ + for (size_t i = 0, j = 0, orig_wchars = wchars; i < orig_wchars; i++) { + if (iswprint(wcs[i])) + wcs[j++] = wcs[i]; + else + wchars--; + } + if (!search_ensure_size(term, term->search.len + wchars)) return; @@ -371,9 +385,7 @@ search_add_chars(struct terminal *term, const char *src, size_t count) &term->search.buf[term->search.cursor], (term->search.len - term->search.cursor) * sizeof(wchar_t)); - memset(&ps, 0, sizeof(ps)); - mbsnrtowcs(&term->search.buf[term->search.cursor], &src, count, - wchars, &ps); + memcpy(&term->search.buf[term->search.cursor], wcs, wchars * sizeof(wchar_t)); term->search.len += wchars; term->search.cursor += wchars;