1 /* $OpenBSD: utf8.c,v 1.11 2020/05/01 06:28:52 djm Exp $ */
3 * Copyright (c) 2016 Ingo Schwarze <schwarze@openbsd.org>
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.
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.
19 * Utility functions for multibyte-character handling,
20 * in particular to sanitize untrusted strings for terminal output.
25 #include <sys/types.h>
26 #ifdef HAVE_LANGINFO_H
27 # include <langinfo.h>
35 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
44 static int dangerous_locale(void);
45 static int grow_dst(char **, size_t *, size_t, char **, size_t);
49 * For US-ASCII and UTF-8 encodings, we can safely recover from
50 * encoding errors and from non-printable characters. For any
51 * other encodings, err to the side of caution and abort parsing:
52 * For state-dependent encodings, recovery is impossible.
53 * For arbitrary encodings, replacement of non-printable
54 * characters would be non-trivial and too fragile.
55 * The comments indicate what nl_langinfo(CODESET)
56 * returns for US-ASCII on various operating systems.
60 dangerous_locale(void) {
63 loc
= nl_langinfo(CODESET
);
64 return strcmp(loc
, "UTF-8") != 0 &&
65 strcmp(loc
, "US-ASCII") != 0 && /* OpenBSD */
66 strcmp(loc
, "ANSI_X3.4-1968") != 0 && /* Linux */
67 strcmp(loc
, "ISO8859-1") != 0 && /* AIX */
68 strcmp(loc
, "646") != 0 && /* Solaris, NetBSD */
69 strcmp(loc
, "") != 0; /* Solaris 6 */
73 grow_dst(char **dst
, size_t *sz
, size_t maxsz
, char **dp
, size_t need
)
78 if (*dp
+ need
< *dst
+ *sz
)
83 if ((tp
= recallocarray(*dst
, *sz
, tsz
, 1)) == NULL
)
85 *dp
= tp
+ (*dp
- *dst
);
92 * The following two functions limit the number of bytes written,
93 * including the terminating '\0', to sz. Unless wp is NULL,
94 * they limit the number of display columns occupied to *wp.
95 * Whichever is reached first terminates the output string.
96 * To stay close to the standard interfaces, they return the number of
97 * non-NUL bytes that would have been written if both were unlimited.
98 * If wp is NULL, newline, carriage return, and tab are allowed;
99 * otherwise, the actual number of columns occupied by what was
100 * written is returned in *wp.
104 vasnmprintf(char **str
, size_t maxsz
, int *wp
, const char *fmt
, va_list ap
)
106 char *src
; /* Source string returned from vasprintf. */
107 char *sp
; /* Pointer into src. */
108 char *dst
; /* Destination string to be returned. */
109 char *dp
; /* Pointer into dst. */
110 char *tp
; /* Temporary pointer for dst. */
111 size_t sz
; /* Number of bytes allocated for dst. */
112 wchar_t wc
; /* Wide character at sp. */
113 int len
; /* Number of bytes in the character at sp. */
114 int ret
; /* Number of bytes needed to format src. */
115 int width
; /* Display width of the character wc. */
116 int total_width
, max_width
, print
;
119 if ((ret
= vasprintf(&src
, fmt
, ap
)) <= 0)
122 sz
= strlen(src
) + 1;
123 if ((dst
= malloc(sz
)) == NULL
) {
137 max_width
= wp
== NULL
? INT_MAX
: *wp
;
138 while (*sp
!= '\0') {
139 if ((len
= mbtowc(&wc
, sp
, MB_CUR_MAX
)) == -1) {
140 (void)mbtowc(NULL
, NULL
, MB_CUR_MAX
);
141 if (dangerous_locale()) {
147 } else if (wp
== NULL
&&
148 (wc
== L
'\n' || wc
== L
'\r' || wc
== L
'\t')) {
150 * Don't use width uninitialized; the actual
151 * value doesn't matter because total_width
152 * is only returned for wp != NULL.
155 } else if ((width
= wcwidth(wc
)) == -1 &&
156 dangerous_locale()) {
161 /* Valid, printable character. */
164 if (print
&& (dp
- dst
>= (int)maxsz
- len
||
165 total_width
> max_width
- width
))
168 if (grow_dst(&dst
, &sz
, maxsz
,
173 total_width
+= width
;
183 /* Escaping required. */
186 if (print
&& (dp
- dst
>= (int)maxsz
- 4 ||
187 total_width
> max_width
- 4))
190 if (grow_dst(&dst
, &sz
, maxsz
,
195 tp
= vis(dp
, *sp
, VIS_OCTAL
| VIS_ALL
, 0);
197 total_width
+= width
;
216 * If the string was truncated by the width limit but
217 * would have fit into the size limit, the only sane way
218 * to report the problem is using the return value, such
219 * that the usual idiom "if (ret < 0 || ret >= sz) error"
223 if (ret
< (int)maxsz
&& !print
)
240 snmprintf(char *str
, size_t sz
, int *wp
, const char *fmt
, ...)
247 ret
= vasnmprintf(&cp
, sz
, wp
, fmt
, ap
);
250 (void)strlcpy(str
, cp
, sz
);
258 asmprintf(char **outp
, size_t sz
, int *wp
, const char *fmt
, ...)
265 ret
= vasnmprintf(outp
, sz
, wp
, fmt
, ap
);
272 * To stay close to the standard interfaces, the following functions
273 * return the number of non-NUL bytes written.
277 vfmprintf(FILE *stream
, const char *fmt
, va_list ap
)
282 if ((ret
= vasnmprintf(&str
, INT_MAX
, NULL
, fmt
, ap
)) < 0) {
286 if (fputs(str
, stream
) == EOF
)
293 fmprintf(FILE *stream
, const char *fmt
, ...)
299 ret
= vfmprintf(stream
, fmt
, ap
);
305 mprintf(const char *fmt
, ...)
311 ret
= vfmprintf(stdout
, fmt
, ap
);
317 * Set up libc for multibyte output in the user's chosen locale.
319 * XXX: we are known to have problems with Turkish (i/I confusion) so we
320 * deliberately fall back to the C locale for now. Longer term we should
321 * always prefer to select C.[encoding] if possible, but there's no
322 * standardisation in locales between systems, so we'll need to survey
323 * what's out there first.
328 const char *vars
[] = { "LC_ALL", "LC_CTYPE", "LANG", NULL
};
333 * We can't yet cope with dotless/dotted I in Turkish locales,
334 * so fall back to the C locale for these.
336 for (i
= 0; vars
[i
] != NULL
; i
++) {
337 if ((cp
= getenv(vars
[i
])) == NULL
)
339 if (strncasecmp(cp
, "TR", 2) != 0)
342 * If we're in a UTF-8 locale then prefer to use
343 * the C.UTF-8 locale (or equivalent) if it exists.
345 if ((strcasestr(cp
, "UTF-8") != NULL
||
346 strcasestr(cp
, "UTF8") != NULL
) &&
347 (setlocale(LC_CTYPE
, "C.UTF-8") != NULL
||
348 setlocale(LC_CTYPE
, "POSIX.UTF-8") != NULL
))
350 setlocale(LC_CTYPE
, "C");
353 /* We can handle this locale */
354 setlocale(LC_CTYPE
, "");