xref: /openssh-portable/utf8.c (revision 3ec5fa4b)
1 /* $OpenBSD: utf8.c,v 1.4 2017/02/02 10:54:25 jsg Exp $ */
2 /*
3  * Copyright (c) 2016 Ingo Schwarze <schwarze@openbsd.org>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 /*
19  * Utility functions for multibyte-character handling,
20  * in particular to sanitize untrusted strings for terminal output.
21  */
22 
23 #include "includes.h"
24 
25 #include <sys/types.h>
26 #ifdef HAVE_LANGINFO_H
27 # include <langinfo.h>
28 #endif
29 #include <limits.h>
30 #include <locale.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
36 # include <vis.h>
37 #endif
38 #ifdef HAVE_WCHAR_H
39 # include <wchar.h>
40 #endif
41 
42 #include "utf8.h"
43 
44 static int	 dangerous_locale(void);
45 static int	 grow_dst(char **, size_t *, size_t, char **, size_t);
46 static int	 vasnmprintf(char **, size_t, int *, const char *, va_list);
47 
48 
49 /*
50  * For US-ASCII and UTF-8 encodings, we can safely recover from
51  * encoding errors and from non-printable characters.  For any
52  * other encodings, err to the side of caution and abort parsing:
53  * For state-dependent encodings, recovery is impossible.
54  * For arbitrary encodings, replacement of non-printable
55  * characters would be non-trivial and too fragile.
56  */
57 
58 static int
59 dangerous_locale(void) {
60 	char	*loc;
61 
62 	loc = nl_langinfo(CODESET);
63 	return strcmp(loc, "US-ASCII") && strcmp(loc, "UTF-8");
64 }
65 
66 static int
67 grow_dst(char **dst, size_t *sz, size_t maxsz, char **dp, size_t need)
68 {
69 	char	*tp;
70 	size_t	 tsz;
71 
72 	if (*dp + need < *dst + *sz)
73 		return 0;
74 	tsz = *sz + 128;
75 	if (tsz > maxsz)
76 		tsz = maxsz;
77 	if ((tp = realloc(*dst, tsz)) == NULL)
78 		return -1;
79 	*dp = tp + (*dp - *dst);
80 	*dst = tp;
81 	*sz = tsz;
82 	return 0;
83 }
84 
85 /*
86  * The following two functions limit the number of bytes written,
87  * including the terminating '\0', to sz.  Unless wp is NULL,
88  * they limit the number of display columns occupied to *wp.
89  * Whichever is reached first terminates the output string.
90  * To stay close to the standard interfaces, they return the number of
91  * non-NUL bytes that would have been written if both were unlimited.
92  * If wp is NULL, newline, carriage return, and tab are allowed;
93  * otherwise, the actual number of columns occupied by what was
94  * written is returned in *wp.
95  */
96 
97 static int
98 vasnmprintf(char **str, size_t maxsz, int *wp, const char *fmt, va_list ap)
99 {
100 	char	*src;	/* Source string returned from vasprintf. */
101 	char	*sp;	/* Pointer into src. */
102 	char	*dst;	/* Destination string to be returned. */
103 	char	*dp;	/* Pointer into dst. */
104 	char	*tp;	/* Temporary pointer for dst. */
105 	size_t	 sz;	/* Number of bytes allocated for dst. */
106 	wchar_t	 wc;	/* Wide character at sp. */
107 	int	 len;	/* Number of bytes in the character at sp. */
108 	int	 ret;	/* Number of bytes needed to format src. */
109 	int	 width;	/* Display width of the character wc. */
110 	int	 total_width, max_width, print;
111 
112 	src = NULL;
113 	if ((ret = vasprintf(&src, fmt, ap)) <= 0)
114 		goto fail;
115 
116 	sz = strlen(src) + 1;
117 	if ((dst = malloc(sz)) == NULL) {
118 		free(src);
119 		ret = -1;
120 		goto fail;
121 	}
122 
123 	if (maxsz > INT_MAX)
124 		maxsz = INT_MAX;
125 
126 	sp = src;
127 	dp = dst;
128 	ret = 0;
129 	print = 1;
130 	total_width = 0;
131 	max_width = wp == NULL ? INT_MAX : *wp;
132 	while (*sp != '\0') {
133 		if ((len = mbtowc(&wc, sp, MB_CUR_MAX)) == -1) {
134 			(void)mbtowc(NULL, NULL, MB_CUR_MAX);
135 			if (dangerous_locale()) {
136 				ret = -1;
137 				break;
138 			}
139 			len = 1;
140 			width = -1;
141 		} else if (wp == NULL &&
142 		    (wc == L'\n' || wc == L'\r' || wc == L'\t')) {
143 			/*
144 			 * Don't use width uninitialized; the actual
145 			 * value doesn't matter because total_width
146 			 * is only returned for wp != NULL.
147 			 */
148 			width = 0;
149 		} else if ((width = wcwidth(wc)) == -1 &&
150 		    dangerous_locale()) {
151 			ret = -1;
152 			break;
153 		}
154 
155 		/* Valid, printable character. */
156 
157 		if (width >= 0) {
158 			if (print && (dp - dst >= (int)maxsz - len ||
159 			    total_width > max_width - width))
160 				print = 0;
161 			if (print) {
162 				if (grow_dst(&dst, &sz, maxsz,
163 				    &dp, len) == -1) {
164 					ret = -1;
165 					break;
166 				}
167 				total_width += width;
168 				memcpy(dp, sp, len);
169 				dp += len;
170 			}
171 			sp += len;
172 			if (ret >= 0)
173 				ret += len;
174 			continue;
175 		}
176 
177 		/* Escaping required. */
178 
179 		while (len > 0) {
180 			if (print && (dp - dst >= (int)maxsz - 4 ||
181 			    total_width > max_width - 4))
182 				print = 0;
183 			if (print) {
184 				if (grow_dst(&dst, &sz, maxsz,
185 				    &dp, 4) == -1) {
186 					ret = -1;
187 					break;
188 				}
189 				tp = vis(dp, *sp, VIS_OCTAL | VIS_ALL, 0);
190 				width = tp - dp;
191 				total_width += width;
192 				dp = tp;
193 			} else
194 				width = 4;
195 			len--;
196 			sp++;
197 			if (ret >= 0)
198 				ret += width;
199 		}
200 		if (len > 0)
201 			break;
202 	}
203 	free(src);
204 	*dp = '\0';
205 	*str = dst;
206 	if (wp != NULL)
207 		*wp = total_width;
208 
209 	/*
210 	 * If the string was truncated by the width limit but
211 	 * would have fit into the size limit, the only sane way
212 	 * to report the problem is using the return value, such
213 	 * that the usual idiom "if (ret < 0 || ret >= sz) error"
214 	 * works as expected.
215 	 */
216 
217 	if (ret < (int)maxsz && !print)
218 		ret = -1;
219 	return ret;
220 
221 fail:
222 	if (wp != NULL)
223 		*wp = 0;
224 	if (ret == 0) {
225 		*str = src;
226 		return 0;
227 	} else {
228 		*str = NULL;
229 		return -1;
230 	}
231 }
232 
233 int
234 snmprintf(char *str, size_t sz, int *wp, const char *fmt, ...)
235 {
236 	va_list	 ap;
237 	char	*cp;
238 	int	 ret;
239 
240 	va_start(ap, fmt);
241 	ret = vasnmprintf(&cp, sz, wp, fmt, ap);
242 	va_end(ap);
243 	if (cp != NULL) {
244 		(void)strlcpy(str, cp, sz);
245 		free(cp);
246 	} else
247 		*str = '\0';
248 	return ret;
249 }
250 
251 /*
252  * To stay close to the standard interfaces, the following functions
253  * return the number of non-NUL bytes written.
254  */
255 
256 int
257 vfmprintf(FILE *stream, const char *fmt, va_list ap)
258 {
259 	char	*str;
260 	int	 ret;
261 
262 	if ((ret = vasnmprintf(&str, INT_MAX, NULL, fmt, ap)) < 0)
263 		return -1;
264 	if (fputs(str, stream) == EOF)
265 		ret = -1;
266 	free(str);
267 	return ret;
268 }
269 
270 int
271 fmprintf(FILE *stream, const char *fmt, ...)
272 {
273 	va_list	 ap;
274 	int	 ret;
275 
276 	va_start(ap, fmt);
277 	ret = vfmprintf(stream, fmt, ap);
278 	va_end(ap);
279 	return ret;
280 }
281 
282 int
283 mprintf(const char *fmt, ...)
284 {
285 	va_list	 ap;
286 	int	 ret;
287 
288 	va_start(ap, fmt);
289 	ret = vfmprintf(stdout, fmt, ap);
290 	va_end(ap);
291 	return ret;
292 }
293 
294 /*
295  * Set up libc for multibyte output in the user's chosen locale.
296  *
297  * XXX: we are known to have problems with Turkish (i/I confusion) so we
298  *      deliberately fall back to the C locale for now. Longer term we should
299  *      always prefer to select C.[encoding] if possible, but there's no
300  *      standardisation in locales between systems, so we'll need to survey
301  *      what's out there first.
302  */
303 void
304 msetlocale(void)
305 {
306 	const char *vars[] = { "LC_ALL", "LC_CTYPE", "LANG", NULL };
307 	char *cp;
308 	int i;
309 
310 	/*
311 	 * We can't yet cope with dotless/dotted I in Turkish locales,
312 	 * so fall back to the C locale for these.
313 	 */
314 	for (i = 0; vars[i] != NULL; i++) {
315 		if ((cp = getenv(vars[i])) == NULL)
316 			continue;
317 		if (strncasecmp(cp, "TR", 2) != 0)
318 			break;
319 		/*
320 		 * If we're in a UTF-8 locale then prefer to use
321 		 * the C.UTF-8 locale (or equivalent) if it exists.
322 		 */
323 		if ((strcasestr(cp, "UTF-8") != NULL ||
324 		    strcasestr(cp, "UTF8") != NULL) &&
325 		    (setlocale(LC_CTYPE, "C.UTF-8") != NULL ||
326 		    setlocale(LC_CTYPE, "POSIX.UTF-8") != NULL))
327 			return;
328 		setlocale(LC_CTYPE, "C");
329 		return;
330 	}
331 	/* We can handle this locale */
332 	setlocale(LC_CTYPE, "");
333 }
334