Coverage Report

Created: 2026-12-01 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/hpn-ssh/utf8.c
Line
Count
Source
1
/* $OpenBSD: utf8.c,v 1.12 2026/10/30 03:40:56 djm 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
47
48
/*
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.
57
 */
58
59
static int
60
0
dangerous_locale(void) {
61
0
  char  *loc;
62
63
0
  loc = nl_langinfo(CODESET);
64
0
  return strcmp(loc, "UTF-8") != 0 &&
65
0
      strcmp(loc, "US-ASCII") != 0 &&   /* OpenBSD */
66
0
      strcmp(loc, "ANSI_X3.4-1968") != 0 && /* Linux */
67
0
      strcmp(loc, "ISO8859-1") != 0 &&   /* AIX */
68
0
      strcmp(loc, "646") != 0 &&     /* Solaris, NetBSD */
69
0
      strcmp(loc, "") != 0;     /* Solaris 6 */
70
0
}
71
72
static int
73
grow_dst(char **dst, size_t *sz, size_t maxsz, char **dp, size_t need)
74
0
{
75
0
  char  *tp;
76
0
  size_t   tsz;
77
78
0
  if (*dp + need < *dst + *sz)
79
0
    return 0;
80
  /*
81
   * Grow geometrically to avoid recallocarray repeatedly having to
82
   * copy its buffer as the allocation grows.
83
   * Note: maxsz is always <=INT_MAX so we can't overflow the size_t;
84
   */
85
0
  tsz = *sz + (*sz > 128 ? *sz : 128);
86
0
  if (tsz > maxsz)
87
0
    tsz = maxsz;
88
0
  if ((tp = recallocarray(*dst, *sz, tsz, 1)) == NULL)
89
0
    return -1;
90
0
  *dp = tp + (*dp - *dst);
91
0
  *dst = tp;
92
0
  *sz = tsz;
93
0
  return 0;
94
0
}
95
96
/*
97
 * The following two functions limit the number of bytes written,
98
 * including the terminating '\0', to sz.  Unless wp is NULL,
99
 * they limit the number of display columns occupied to *wp.
100
 * Whichever is reached first terminates the output string.
101
 * To stay close to the standard interfaces, they return the number of
102
 * non-NUL bytes that would have been written if both were unlimited.
103
 * If wp is NULL, newline, carriage return, and tab are allowed;
104
 * otherwise, the actual number of columns occupied by what was
105
 * written is returned in *wp.
106
 */
107
108
int
109
vasnmprintf(char **str, size_t maxsz, int *wp, const char *fmt, va_list ap)
110
0
{
111
0
  char  *src; /* Source string returned from vasprintf. */
112
0
  char  *sp;  /* Pointer into src. */
113
0
  char  *dst; /* Destination string to be returned. */
114
0
  char  *dp;  /* Pointer into dst. */
115
0
  char  *tp;  /* Temporary pointer for dst. */
116
0
  size_t   sz;  /* Number of bytes allocated for dst. */
117
0
  wchar_t  wc;  /* Wide character at sp. */
118
0
  int  len; /* Number of bytes in the character at sp. */
119
0
  int  ret; /* Number of bytes needed to format src. */
120
0
  int  width; /* Display width of the character wc. */
121
0
  int  total_width, max_width, print;
122
123
0
  src = NULL;
124
0
  if ((ret = vasprintf(&src, fmt, ap)) <= 0)
125
0
    goto fail;
126
127
0
  sz = strlen(src) + 1;
128
0
  if ((dst = malloc(sz)) == NULL) {
129
0
    free(src);
130
0
    ret = -1;
131
0
    goto fail;
132
0
  }
133
134
0
  if (maxsz > INT_MAX)
135
0
    maxsz = INT_MAX;
136
137
0
  sp = src;
138
0
  dp = dst;
139
0
  ret = 0;
140
0
  print = 1;
141
0
  total_width = 0;
142
0
  max_width = wp == NULL ? INT_MAX : *wp;
143
0
  while (*sp != '\0') {
144
0
    if ((len = mbtowc(&wc, sp, MB_CUR_MAX)) == -1) {
145
0
      (void)mbtowc(NULL, NULL, MB_CUR_MAX);
146
0
      if (dangerous_locale()) {
147
0
        ret = -1;
148
0
        break;
149
0
      }
150
0
      len = 1;
151
0
      width = -1;
152
0
    } else if (wp == NULL &&
153
0
        (wc == L'\n' || wc == L'\r' || wc == L'\t')) {
154
      /*
155
       * Don't use width uninitialized; the actual
156
       * value doesn't matter because total_width
157
       * is only returned for wp != NULL.
158
       */
159
0
      width = 0;
160
0
    } else if ((width = wcwidth(wc)) == -1 &&
161
0
        dangerous_locale()) {
162
0
      ret = -1;
163
0
      break;
164
0
    }
165
166
    /* Valid, printable character. */
167
168
0
    if (width >= 0) {
169
0
      if (print && (dp - dst >= (int)maxsz - len ||
170
0
          total_width > max_width - width))
171
0
        print = 0;
172
0
      if (print) {
173
0
        if (grow_dst(&dst, &sz, maxsz,
174
0
            &dp, len) == -1) {
175
0
          ret = -1;
176
0
          break;
177
0
        }
178
0
        total_width += width;
179
0
        memcpy(dp, sp, len);
180
0
        dp += len;
181
0
      }
182
0
      sp += len;
183
0
      if (ret >= 0)
184
0
        ret += len;
185
0
      continue;
186
0
    }
187
188
    /* Escaping required. */
189
190
0
    while (len > 0) {
191
0
      if (print && (dp - dst >= (int)maxsz - 4 ||
192
0
          total_width > max_width - 4))
193
0
        print = 0;
194
0
      if (print) {
195
0
        if (grow_dst(&dst, &sz, maxsz,
196
0
            &dp, 4) == -1) {
197
0
          ret = -1;
198
0
          break;
199
0
        }
200
0
        tp = vis(dp, *sp, VIS_OCTAL | VIS_ALL, 0);
201
0
        width = tp - dp;
202
0
        total_width += width;
203
0
        dp = tp;
204
0
      } else
205
0
        width = 4;
206
0
      len--;
207
0
      sp++;
208
0
      if (ret >= 0)
209
0
        ret += width;
210
0
    }
211
0
    if (len > 0)
212
0
      break;
213
0
  }
214
0
  free(src);
215
0
  *dp = '\0';
216
0
  *str = dst;
217
0
  if (wp != NULL)
218
0
    *wp = total_width;
219
220
  /*
221
   * If the string was truncated by the width limit but
222
   * would have fit into the size limit, the only sane way
223
   * to report the problem is using the return value, such
224
   * that the usual idiom "if (ret < 0 || ret >= sz) error"
225
   * works as expected.
226
   */
227
228
0
  if (ret < (int)maxsz && !print)
229
0
    ret = -1;
230
0
  return ret;
231
232
0
fail:
233
0
  if (wp != NULL)
234
0
    *wp = 0;
235
0
  if (ret == 0) {
236
0
    *str = src;
237
0
    return 0;
238
0
  } else {
239
0
    *str = NULL;
240
0
    return -1;
241
0
  }
242
0
}
243
244
int
245
snmprintf(char *str, size_t sz, int *wp, const char *fmt, ...)
246
0
{
247
0
  va_list  ap;
248
0
  char  *cp = NULL;
249
0
  int  ret;
250
251
0
  va_start(ap, fmt);
252
0
  ret = vasnmprintf(&cp, sz, wp, fmt, ap);
253
0
  va_end(ap);
254
0
  if (cp != NULL) {
255
0
    (void)strlcpy(str, cp, sz);
256
0
    free(cp);
257
0
  } else
258
0
    *str = '\0';
259
0
  return ret;
260
0
}
261
262
int
263
asmprintf(char **outp, size_t sz, int *wp, const char *fmt, ...)
264
0
{
265
0
  va_list  ap;
266
0
  int  ret;
267
268
0
  *outp = NULL;
269
0
  va_start(ap, fmt);
270
0
  ret = vasnmprintf(outp, sz, wp, fmt, ap);
271
0
  va_end(ap);
272
273
0
  return ret;
274
0
}
275
276
/*
277
 * To stay close to the standard interfaces, the following functions
278
 * return the number of non-NUL bytes written.
279
 */
280
281
int
282
vfmprintf(FILE *stream, const char *fmt, va_list ap)
283
0
{
284
0
  char  *str = NULL;
285
0
  int  ret;
286
287
0
  if ((ret = vasnmprintf(&str, INT_MAX, NULL, fmt, ap)) < 0) {
288
0
    free(str);
289
0
    return -1;
290
0
  }
291
0
  if (fputs(str, stream) == EOF)
292
0
    ret = -1;
293
0
  free(str);
294
0
  return ret;
295
0
}
296
297
int
298
fmprintf(FILE *stream, const char *fmt, ...)
299
0
{
300
0
  va_list  ap;
301
0
  int  ret;
302
303
0
  va_start(ap, fmt);
304
0
  ret = vfmprintf(stream, fmt, ap);
305
0
  va_end(ap);
306
0
  return ret;
307
0
}
308
309
int
310
mprintf(const char *fmt, ...)
311
0
{
312
0
  va_list  ap;
313
0
  int  ret;
314
315
0
  va_start(ap, fmt);
316
0
  ret = vfmprintf(stdout, fmt, ap);
317
0
  va_end(ap);
318
0
  return ret;
319
0
}
320
321
/*
322
 * Set up libc for multibyte output in the user's chosen locale.
323
 *
324
 * XXX: we are known to have problems with Turkic languages (i/I confusion) so
325
 *      we deliberately fall back to the C locale for now. Longer term we
326
 *      should always prefer to select C.[encoding] if possible, but there's
327
 *      no standardisation in locales between systems, so we'll need to survey
328
 *      what's out there first.
329
 * XXX: alternately runtime probe that toupper('i') != 'I' and vice-versa?
330
 */
331
void
332
msetlocale(void)
333
0
{
334
0
  const char *vars[] = { "LC_ALL", "LC_CTYPE", "LANG", NULL };
335
0
  char *cp;
336
0
  int i;
337
338
  /*
339
   * We can't yet cope with dotless/dotted I in Turkic locales,
340
   * so fall back to the C locale for these.
341
   */
342
0
  for (i = 0; vars[i] != NULL; i++) {
343
0
    if ((cp = getenv(vars[i])) == NULL)
344
0
      continue;
345
0
    if (strncasecmp(cp, "tr", 2) != 0 &&
346
0
        strncasecmp(cp, "crh", 3) != 0 &&
347
0
        strncasecmp(cp, "az", 2) != 0)
348
0
      break;
349
    /*
350
     * If we're in a UTF-8 locale then prefer to use
351
     * the C.UTF-8 locale (or equivalent) if it exists.
352
     */
353
0
    if ((strcasestr(cp, "UTF-8") != NULL ||
354
0
        strcasestr(cp, "UTF8") != NULL) &&
355
0
        (setlocale(LC_CTYPE, "C.UTF-8") != NULL ||
356
0
        setlocale(LC_CTYPE, "POSIX.UTF-8") != NULL))
357
0
      return;
358
0
    setlocale(LC_CTYPE, "C");
359
0
    return;
360
0
  }
361
  /* We can handle this locale */
362
0
  setlocale(LC_CTYPE, "");
363
0
}