blob: bc131385f5362d08043b59a0280780e6260dbf43 [file] [log] [blame]
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +00001/* $OpenBSD: utf8.c,v 1.7 2017/05/31 09:15:42 deraadt Exp $ */
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +00002/*
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
Darren Tuckerdf820722016-06-06 11:36:13 +100023#include "includes.h"
24
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000025#include <sys/types.h>
Darren Tuckerf3f2cc82016-07-11 17:23:38 +100026#ifdef HAVE_LANGINFO_H
27# include <langinfo.h>
28#endif
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000029#include <limits.h>
Damien Millerdda78a02016-12-12 13:57:10 +110030#include <locale.h>
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000031#include <stdarg.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <string.h>
Darren Tuckerdf820722016-06-06 11:36:13 +100035#if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
36# include <vis.h>
37#endif
Darren Tuckerf3f2cc82016-07-11 17:23:38 +100038#ifdef HAVE_WCHAR_H
39# include <wchar.h>
40#endif
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000041
42#include "utf8.h"
43
44static int dangerous_locale(void);
schwarze@openbsd.orgcd9e1ea2016-05-30 12:57:21 +000045static int grow_dst(char **, size_t *, size_t, char **, size_t);
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000046static 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
58static int
59dangerous_locale(void) {
60 char *loc;
61
62 loc = nl_langinfo(CODESET);
djm@openbsd.org011c8ff2017-02-19 00:10:57 +000063 return strcmp(loc, "US-ASCII") != 0 && strcmp(loc, "UTF-8") != 0 &&
schwarze@openbsd.orgf8500b22017-04-17 14:31:23 +000064 strcmp(loc, "ANSI_X3.4-1968") != 0 && strcmp(loc, "646") != 0 &&
65 strcmp(loc, "") != 0;
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000066}
67
schwarze@openbsd.orgcd9e1ea2016-05-30 12:57:21 +000068static int
69grow_dst(char **dst, size_t *sz, size_t maxsz, char **dp, size_t need)
70{
71 char *tp;
72 size_t tsz;
73
74 if (*dp + need < *dst + *sz)
75 return 0;
76 tsz = *sz + 128;
77 if (tsz > maxsz)
78 tsz = maxsz;
deraadt@openbsd.org9e509d42017-05-31 09:15:42 +000079 if ((tp = recallocarray(*dst, *sz, tsz, 1)) == NULL)
schwarze@openbsd.orgcd9e1ea2016-05-30 12:57:21 +000080 return -1;
81 *dp = tp + (*dp - *dst);
82 *dst = tp;
83 *sz = tsz;
84 return 0;
85}
86
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +000087/*
88 * The following two functions limit the number of bytes written,
89 * including the terminating '\0', to sz. Unless wp is NULL,
90 * they limit the number of display columns occupied to *wp.
91 * Whichever is reached first terminates the output string.
92 * To stay close to the standard interfaces, they return the number of
93 * non-NUL bytes that would have been written if both were unlimited.
94 * If wp is NULL, newline, carriage return, and tab are allowed;
95 * otherwise, the actual number of columns occupied by what was
96 * written is returned in *wp.
97 */
98
99static int
100vasnmprintf(char **str, size_t maxsz, int *wp, const char *fmt, va_list ap)
101{
102 char *src; /* Source string returned from vasprintf. */
103 char *sp; /* Pointer into src. */
104 char *dst; /* Destination string to be returned. */
105 char *dp; /* Pointer into dst. */
106 char *tp; /* Temporary pointer for dst. */
107 size_t sz; /* Number of bytes allocated for dst. */
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000108 wchar_t wc; /* Wide character at sp. */
109 int len; /* Number of bytes in the character at sp. */
110 int ret; /* Number of bytes needed to format src. */
111 int width; /* Display width of the character wc. */
112 int total_width, max_width, print;
113
schwarze@openbsd.orgac284a32016-05-30 12:05:56 +0000114 src = NULL;
115 if ((ret = vasprintf(&src, fmt, ap)) <= 0)
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000116 goto fail;
117
schwarze@openbsd.orgcd9e1ea2016-05-30 12:57:21 +0000118 sz = strlen(src) + 1;
schwarze@openbsd.orgac284a32016-05-30 12:05:56 +0000119 if ((dst = malloc(sz)) == NULL) {
120 free(src);
jsg@openbsd.org3ec5fa42017-02-02 10:54:25 +0000121 ret = -1;
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000122 goto fail;
schwarze@openbsd.orgac284a32016-05-30 12:05:56 +0000123 }
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000124
125 if (maxsz > INT_MAX)
126 maxsz = INT_MAX;
127
128 sp = src;
129 dp = dst;
130 ret = 0;
131 print = 1;
132 total_width = 0;
133 max_width = wp == NULL ? INT_MAX : *wp;
134 while (*sp != '\0') {
135 if ((len = mbtowc(&wc, sp, MB_CUR_MAX)) == -1) {
136 (void)mbtowc(NULL, NULL, MB_CUR_MAX);
137 if (dangerous_locale()) {
138 ret = -1;
139 break;
140 }
141 len = 1;
142 width = -1;
143 } else if (wp == NULL &&
144 (wc == L'\n' || wc == L'\r' || wc == L'\t')) {
145 /*
146 * Don't use width uninitialized; the actual
147 * value doesn't matter because total_width
148 * is only returned for wp != NULL.
149 */
150 width = 0;
151 } else if ((width = wcwidth(wc)) == -1 &&
152 dangerous_locale()) {
153 ret = -1;
154 break;
155 }
156
157 /* Valid, printable character. */
158
159 if (width >= 0) {
160 if (print && (dp - dst >= (int)maxsz - len ||
161 total_width > max_width - width))
162 print = 0;
163 if (print) {
schwarze@openbsd.orgcd9e1ea2016-05-30 12:57:21 +0000164 if (grow_dst(&dst, &sz, maxsz,
165 &dp, len) == -1) {
166 ret = -1;
167 break;
168 }
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000169 total_width += width;
170 memcpy(dp, sp, len);
171 dp += len;
172 }
173 sp += len;
174 if (ret >= 0)
175 ret += len;
176 continue;
177 }
178
179 /* Escaping required. */
180
181 while (len > 0) {
182 if (print && (dp - dst >= (int)maxsz - 4 ||
183 total_width > max_width - 4))
184 print = 0;
185 if (print) {
schwarze@openbsd.orgcd9e1ea2016-05-30 12:57:21 +0000186 if (grow_dst(&dst, &sz, maxsz,
187 &dp, 4) == -1) {
188 ret = -1;
189 break;
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000190 }
191 tp = vis(dp, *sp, VIS_OCTAL | VIS_ALL, 0);
192 width = tp - dp;
193 total_width += width;
194 dp = tp;
195 } else
196 width = 4;
197 len--;
198 sp++;
199 if (ret >= 0)
200 ret += width;
201 }
202 if (len > 0)
203 break;
204 }
205 free(src);
206 *dp = '\0';
207 *str = dst;
208 if (wp != NULL)
209 *wp = total_width;
210
211 /*
212 * If the string was truncated by the width limit but
213 * would have fit into the size limit, the only sane way
214 * to report the problem is using the return value, such
215 * that the usual idiom "if (ret < 0 || ret >= sz) error"
216 * works as expected.
217 */
218
219 if (ret < (int)maxsz && !print)
220 ret = -1;
221 return ret;
222
223fail:
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000224 if (wp != NULL)
225 *wp = 0;
schwarze@openbsd.orgac284a32016-05-30 12:05:56 +0000226 if (ret == 0) {
227 *str = src;
228 return 0;
229 } else {
230 *str = NULL;
231 return -1;
232 }
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000233}
234
235int
236snmprintf(char *str, size_t sz, int *wp, const char *fmt, ...)
237{
238 va_list ap;
239 char *cp;
240 int ret;
241
242 va_start(ap, fmt);
243 ret = vasnmprintf(&cp, sz, wp, fmt, ap);
244 va_end(ap);
schwarze@openbsd.orgac284a32016-05-30 12:05:56 +0000245 if (cp != NULL) {
246 (void)strlcpy(str, cp, sz);
247 free(cp);
248 } else
249 *str = '\0';
schwarze@openbsd.org0e059cd2016-05-25 23:48:45 +0000250 return ret;
251}
252
253/*
254 * To stay close to the standard interfaces, the following functions
255 * return the number of non-NUL bytes written.
256 */
257
258int
259vfmprintf(FILE *stream, const char *fmt, va_list ap)
260{
261 char *str;
262 int ret;
263
264 if ((ret = vasnmprintf(&str, INT_MAX, NULL, fmt, ap)) < 0)
265 return -1;
266 if (fputs(str, stream) == EOF)
267 ret = -1;
268 free(str);
269 return ret;
270}
271
272int
273fmprintf(FILE *stream, const char *fmt, ...)
274{
275 va_list ap;
276 int ret;
277
278 va_start(ap, fmt);
279 ret = vfmprintf(stream, fmt, ap);
280 va_end(ap);
281 return ret;
282}
283
284int
285mprintf(const char *fmt, ...)
286{
287 va_list ap;
288 int ret;
289
290 va_start(ap, fmt);
291 ret = vfmprintf(stdout, fmt, ap);
292 va_end(ap);
293 return ret;
294}
Damien Millerdda78a02016-12-12 13:57:10 +1100295
296/*
297 * Set up libc for multibyte output in the user's chosen locale.
298 *
299 * XXX: we are known to have problems with Turkish (i/I confusion) so we
300 * deliberately fall back to the C locale for now. Longer term we should
301 * always prefer to select C.[encoding] if possible, but there's no
302 * standardisation in locales between systems, so we'll need to survey
303 * what's out there first.
304 */
305void
306msetlocale(void)
307{
308 const char *vars[] = { "LC_ALL", "LC_CTYPE", "LANG", NULL };
309 char *cp;
310 int i;
311
312 /*
313 * We can't yet cope with dotless/dotted I in Turkish locales,
314 * so fall back to the C locale for these.
315 */
316 for (i = 0; vars[i] != NULL; i++) {
317 if ((cp = getenv(vars[i])) == NULL)
318 continue;
319 if (strncasecmp(cp, "TR", 2) != 0)
320 break;
321 /*
322 * If we're in a UTF-8 locale then prefer to use
323 * the C.UTF-8 locale (or equivalent) if it exists.
324 */
325 if ((strcasestr(cp, "UTF-8") != NULL ||
326 strcasestr(cp, "UTF8") != NULL) &&
327 (setlocale(LC_CTYPE, "C.UTF-8") != NULL ||
328 setlocale(LC_CTYPE, "POSIX.UTF-8") != NULL))
329 return;
330 setlocale(LC_CTYPE, "C");
331 return;
332 }
333 /* We can handle this locale */
334 setlocale(LC_CTYPE, "");
335}