Coverage Report

Created: 2025-06-13 06:36

/src/util-linux/lib/mbsalign.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * SPDX-License-Identifier: LGPL-2.1-or-later
3
 *
4
 * Align/Truncate a string in a given screen width
5
 * Copyright (C) 2009-2010 Free Software Foundation, Inc.
6
 *
7
 * This program is free software: you can redistribute it and/or modify it
8
 * under the terms of the GNU Lesser General Public License as published by the
9
 * Free Software Foundation, either version 2.1 of the License, or (at your
10
 * option) any later version.
11
 *
12
 * Written by Pádraig Brady.
13
 */
14
#include <stdlib.h>
15
#include <string.h>
16
#include <stdio.h>
17
#include <stdbool.h>
18
#include <limits.h>
19
#include <ctype.h>
20
21
#include "c.h"
22
#include "mbsalign.h"
23
#include "strutils.h"
24
#include "widechar.h"
25
26
/*
27
 * Counts number of cells in multibyte string. All control and
28
 * non-printable chars are ignored.
29
 *
30
 * Returns: number of cells.
31
 */
32
size_t mbs_nwidth(const char *buf, size_t bufsz)
33
0
{
34
0
  const char *p = buf, *last = buf;
35
0
  size_t width = 0;
36
37
0
#ifdef HAVE_WIDECHAR
38
0
  mbstate_t st;
39
0
  memset(&st, 0, sizeof(st));
40
0
#endif
41
0
  if (p && *p && bufsz)
42
0
    last = p + (bufsz - 1);
43
44
0
  while (p && *p && p <= last) {
45
0
    if (iscntrl((unsigned char) *p)) {
46
0
      p++;
47
48
      /* try detect "\e[x;ym" and skip on success */
49
0
      if (*p && *p == '[') {
50
0
        const char *e = p;
51
0
        while (*e && e < last && *e != 'm')
52
0
          e++;
53
0
        if (*e == 'm')
54
0
          p = e + 1;
55
0
      }
56
0
      continue;
57
0
    }
58
0
#ifdef HAVE_WIDECHAR
59
0
    wchar_t wc;
60
0
    size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
61
62
0
    if (len == 0)
63
0
      break;
64
0
    if (len > 0 && iswprint(wc)) {
65
0
      int x = wcwidth(wc);
66
0
      if (x > 0)
67
0
        width += x;
68
0
    } else if (len == (size_t) -1 || len == (size_t) -2)
69
0
      len = 1;
70
0
    p += len;
71
#else
72
    if (isprint((unsigned char) *p))
73
      width++;
74
    p++;
75
#endif
76
0
  }
77
78
0
  return width;
79
0
}
80
81
size_t mbs_width(const char *s)
82
0
{
83
0
  if (!s || !*s)
84
0
    return 0;
85
0
  return mbs_nwidth(s, strlen(s));
86
0
}
87
88
/*
89
 * Counts number of cells in multibyte string. For all control and
90
 * non-printable chars is the result width enlarged to store \x?? hex
91
 * sequence. See mbs_safe_encode().
92
 *
93
 * Returns: number of cells, @sz returns number of bytes.
94
 */
95
size_t mbs_safe_nwidth(const char *buf, size_t bufsz, size_t *sz)
96
0
{
97
0
  const char *p = buf, *last = buf;
98
0
  size_t width = 0, bytes = 0;
99
100
0
#ifdef HAVE_WIDECHAR
101
0
  mbstate_t st;
102
0
  memset(&st, 0, sizeof(st));
103
0
#endif
104
0
  if (p && *p && bufsz)
105
0
    last = p + (bufsz - 1);
106
107
0
  while (p && *p && p <= last) {
108
0
    if ((p < last && *p == '\\' && *(p + 1) == 'x')
109
0
        || iscntrl((unsigned char) *p)) {
110
0
      width += 4, bytes += 4;   /* *p encoded to \x?? */
111
0
      p++;
112
0
    }
113
0
#ifdef HAVE_WIDECHAR
114
0
    else {
115
0
      wchar_t wc;
116
0
      size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
117
118
0
      if (len == 0)
119
0
        break;
120
121
0
      if (len == (size_t) -1 || len == (size_t) -2) {
122
0
        len = 1;
123
0
        if (isprint((unsigned char) *p))
124
0
          width += 1, bytes += 1;
125
0
        else
126
0
          width += 4, bytes += 4;
127
128
0
      } else if (!iswprint(wc)) {
129
0
        width += len * 4; /* hex encode whole sequence */
130
0
        bytes += len * 4;
131
0
      } else {
132
0
        width += wcwidth(wc); /* number of cells */
133
0
        bytes += len;   /* number of bytes */
134
0
      }
135
0
      p += len;
136
0
    }
137
#else
138
    else if (!isprint((unsigned char) *p)) {
139
      width += 4, bytes += 4;   /* *p encoded to \x?? */
140
      p++;
141
    } else {
142
      width++, bytes++;
143
      p++;
144
    }
145
#endif
146
0
  }
147
148
0
  if (sz)
149
0
    *sz = bytes;
150
0
  return width;
151
0
}
152
153
size_t mbs_safe_width(const char *s)
154
0
{
155
0
  if (!s || !*s)
156
0
    return 0;
157
0
  return mbs_safe_nwidth(s, strlen(s), NULL);
158
0
}
159
160
/*
161
 * Copy @s to @buf and replace control and non-printable chars with
162
 * \x?? hex sequence. The @width returns number of cells. The @safechars
163
 * are not encoded.
164
 *
165
 * The @buf has to be big enough to store mbs_safe_encode_size(strlen(s)))
166
 * bytes.
167
 */
168
char *mbs_safe_encode_to_buffer(const char *s, size_t *width, char *buf, const char *safechars)
169
0
{
170
0
  const char *p = s;
171
0
  char *r;
172
0
  size_t sz = s ? strlen(s) : 0;
173
174
0
#ifdef HAVE_WIDECHAR
175
0
  mbstate_t st;
176
0
  memset(&st, 0, sizeof(st));
177
0
#endif
178
0
  if (!sz || !buf)
179
0
    return NULL;
180
181
0
  r = buf;
182
0
  *width = 0;
183
184
0
  while (p && *p) {
185
0
    if (safechars && strchr(safechars, *p)) {
186
0
      *r++ = *p++;
187
0
      continue;
188
0
    }
189
190
0
    if ((*p == '\\' && *(p + 1) == 'x')
191
0
        || iscntrl((unsigned char) *p)) {
192
0
      sprintf(r, "\\x%02x", (unsigned char) *p);
193
0
      r += 4;
194
0
      *width += 4;
195
0
      p++;
196
0
    }
197
0
#ifdef HAVE_WIDECHAR
198
0
    else {
199
0
      wchar_t wc;
200
0
      size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
201
202
0
      if (len == 0)
203
0
        break;   /* end of string */
204
205
0
      if (len == (size_t) -1 || len == (size_t) -2) {
206
0
        len = 1;
207
        /*
208
         * Not valid multibyte sequence -- maybe it's
209
         * printable char according to the current locales.
210
         */
211
0
        if (!isprint((unsigned char) *p)) {
212
0
          sprintf(r, "\\x%02x", (unsigned char) *p);
213
0
          r += 4;
214
0
          *width += 4;
215
0
        } else {
216
0
          (*width)++;
217
0
          *r++ = *p;
218
0
        }
219
0
      } else if (!iswprint(wc)) {
220
0
        size_t i;
221
0
        for (i = 0; i < len; i++) {
222
0
          sprintf(r, "\\x%02x", (unsigned char) p[i]);
223
0
          r += 4;
224
0
          *width += 4;
225
0
        }
226
0
      } else {
227
0
        memcpy(r, p, len);
228
0
        r += len;
229
0
        *width += wcwidth(wc);
230
0
      }
231
0
      p += len;
232
0
    }
233
#else
234
    else if (!isprint((unsigned char) *p)) {
235
      sprintf(r, "\\x%02x", (unsigned char) *p);
236
      p++;
237
      r += 4;
238
      *width += 4;
239
    } else {
240
      *r++ = *p++;
241
      (*width)++;
242
    }
243
#endif
244
0
  }
245
246
0
  *r = '\0';
247
0
  return buf;
248
0
}
249
250
/*
251
 * Copy @s to @buf and replace broken sequences to \x?? hex sequence. The
252
 * @width returns number of cells. The @safechars are not encoded.
253
 *
254
 * The @buf has to be big enough to store mbs_safe_encode_size(strlen(s)))
255
 * bytes.
256
 */
257
char *mbs_invalid_encode_to_buffer(const char *s, size_t *width, char *buf)
258
0
{
259
0
  const char *p = s;
260
0
  char *r;
261
0
  size_t sz = s ? strlen(s) : 0;
262
263
0
#ifdef HAVE_WIDECHAR
264
0
  mbstate_t st;
265
0
  memset(&st, 0, sizeof(st));
266
0
#endif
267
0
  if (!sz || !buf)
268
0
    return NULL;
269
270
0
  r = buf;
271
0
  *width = 0;
272
273
0
  while (p && *p) {
274
0
#ifdef HAVE_WIDECHAR
275
0
    wchar_t wc;
276
0
    size_t len = mbrtowc(&wc, p, MB_CUR_MAX, &st);
277
#else
278
    size_t len = 1;
279
#endif
280
281
0
    if (len == 0)
282
0
      break;   /* end of string */
283
284
0
    if (len == (size_t) -1 || len == (size_t) -2) {
285
0
      len = 1;
286
      /*
287
       * Not valid multibyte sequence -- maybe it's
288
       * printable char according to the current locales.
289
       */
290
0
      if (!isprint((unsigned char) *p)) {
291
0
        sprintf(r, "\\x%02x", (unsigned char) *p);
292
0
        r += 4;
293
0
        *width += 4;
294
0
      } else {
295
0
        (*width)++;
296
0
        *r++ = *p;
297
0
      }
298
0
    } else if (*p == '\\' && *(p + 1) == 'x') {
299
0
      sprintf(r, "\\x%02x", (unsigned char) *p);
300
0
      r += 4;
301
0
      *width += 4;
302
0
    } else {
303
0
      r = mempcpy(r, p, len);
304
0
      *width += wcwidth(wc);
305
0
    }
306
0
    p += len;
307
0
  }
308
309
0
  *r = '\0';
310
0
  return buf;
311
0
}
312
313
/*
314
 * Guess size
315
 */
316
size_t mbs_safe_encode_size(size_t bytes)
317
0
{
318
0
  return (bytes * 4) + 1;
319
0
}
320
321
/*
322
 * Count size of the original string in bytes (count \x?? as one byte)
323
 */
324
size_t mbs_safe_decode_size(const char *p)
325
0
{
326
0
  size_t bytes = 0;
327
328
0
  while (p && *p) {
329
0
    if (*p == '\\' && *(p + 1) == 'x' &&
330
0
        isxdigit(*(p + 2)) && isxdigit(*(p + 3)))
331
0
      p += 4;
332
0
    else
333
0
      p++;
334
0
    bytes++;
335
0
  }
336
0
  return bytes;
337
0
}
338
339
/*
340
 * Returns allocated string where all control and non-printable chars are
341
 * replaced with \x?? hex sequence.
342
 */
343
char *mbs_safe_encode(const char *s, size_t *width)
344
0
{
345
0
  size_t sz = s ? strlen(s) : 0;
346
0
  char *buf, *ret = NULL;
347
348
0
  if (!sz)
349
0
    return NULL;
350
0
  buf = malloc(mbs_safe_encode_size(sz));
351
0
  if (buf)
352
0
    ret = mbs_safe_encode_to_buffer(s, width, buf, NULL);
353
0
  if (!ret)
354
0
    free(buf);
355
0
  return ret;
356
0
}
357
358
/*
359
 * Returns allocated string where all broken widechars chars are
360
 * replaced with \x?? hex sequence.
361
 */
362
char *mbs_invalid_encode(const char *s, size_t *width)
363
0
{
364
0
  size_t sz = s ? strlen(s) : 0;
365
0
  char *buf, *ret = NULL;
366
367
0
  if (!sz)
368
0
    return NULL;
369
0
  buf = malloc(mbs_safe_encode_size(sz));
370
0
  if (buf)
371
0
    ret = mbs_invalid_encode_to_buffer(s, width, buf);
372
0
  if (!ret)
373
0
    free(buf);
374
0
  return ret;
375
0
}
376
377
#ifdef HAVE_WIDECHAR
378
379
static bool
380
wc_ensure_printable (wchar_t *wchars)
381
0
{
382
0
  bool replaced = false;
383
0
  wchar_t *wc = wchars;
384
0
  while (*wc)
385
0
    {
386
0
      if (!iswprint ((wint_t) *wc))
387
0
        {
388
0
          *wc = 0xFFFD; /* L'\uFFFD' (replacement char) */
389
0
          replaced = true;
390
0
        }
391
0
      wc++;
392
0
    }
393
0
  return replaced;
394
0
}
395
396
/* Truncate wchar string to width cells.
397
 * Returns number of cells used.  */
398
399
static size_t
400
wc_truncate (wchar_t *wc, size_t width)
401
0
{
402
0
  size_t cells = 0;
403
0
  int next_cells = 0;
404
405
0
  while (*wc)
406
0
    {
407
0
      next_cells = wcwidth (*wc);
408
0
      if (next_cells == -1) /* non printable */
409
0
        {
410
0
          *wc = 0xFFFD; /* L'\uFFFD' (replacement char) */
411
0
          next_cells = 1;
412
0
        }
413
0
      if (cells + next_cells > width)
414
0
        break;
415
416
0
      cells += next_cells;
417
0
      wc++;
418
0
    }
419
0
  *wc = L'\0';
420
0
  return cells;
421
0
}
422
423
static int
424
rpl_wcswidth (const wchar_t *s, size_t n)
425
0
{
426
0
  int ret = 0;
427
428
0
  while (n-- > 0 && *s != L'\0')
429
0
    {
430
0
      int nwidth = wcwidth (*s++);
431
0
      if (nwidth == -1)             /* non printable */
432
0
        return -1;
433
0
      if (ret > (INT_MAX - nwidth)) /* overflow */
434
0
        return -1;
435
0
      ret += nwidth;
436
0
    }
437
438
0
  return ret;
439
0
}
440
#endif /* HAVE_WIDECHAR */
441
442
/* Truncate multi-byte string to @width and returns number of
443
 * bytes of the new string @str, and in @width returns number
444
 * of cells.
445
 */
446
size_t
447
mbs_truncate(char *str, size_t *width)
448
0
{
449
0
  ssize_t bytes = strlen(str);
450
0
#ifdef HAVE_WIDECHAR
451
0
  ssize_t sz = mbstowcs(NULL, str, 0);
452
0
  wchar_t *wcs = NULL;
453
454
0
  if (sz == (ssize_t) -1)
455
0
    goto done;
456
457
0
  wcs = calloc(1, (sz + 1) * sizeof(wchar_t));
458
0
  if (!wcs)
459
0
    goto done;
460
461
0
  if (!mbstowcs(wcs, str, sz))
462
0
    goto done;
463
0
  *width = wc_truncate(wcs, *width);
464
0
  bytes = wcstombs(str, wcs, bytes);
465
0
done:
466
0
  free(wcs);
467
#else
468
  if (bytes >= 0 && *width < (size_t) bytes)
469
    bytes = *width;
470
#endif
471
0
  if (bytes >= 0)
472
0
    str[bytes] = '\0';
473
0
  return bytes;
474
0
}
475
476
/* Write N_SPACES space characters to DEST while ensuring
477
   nothing is written beyond DEST_END. A terminating NUL
478
   is always added to DEST.
479
   A pointer to the terminating NUL is returned.  */
480
481
static char*
482
mbs_align_pad (char *dest, const char* dest_end, size_t n_spaces, int padchar)
483
0
{
484
0
  for (/* nothing */; n_spaces && (dest < dest_end); n_spaces--)
485
0
    *dest++ = padchar;
486
0
  *dest = '\0';
487
0
  return dest;
488
0
}
489
490
size_t
491
mbsalign (const char *src, char *dest, size_t dest_size,
492
          size_t *width, mbs_align_t align, int flags)
493
0
{
494
0
  return mbsalign_with_padding(src, dest, dest_size, width, align, flags, ' ');
495
0
}
496
497
/* Align a string, SRC, in a field of *WIDTH columns, handling multi-byte
498
   characters; write the result into the DEST_SIZE-byte buffer, DEST.
499
   ALIGNMENT specifies whether to left- or right-justify or to center.
500
   If SRC requires more than *WIDTH columns, truncate it to fit.
501
   When centering, the number of trailing spaces may be one less than the
502
   number of leading spaces. The FLAGS parameter is unused at present.
503
   Return the length in bytes required for the final result, not counting
504
   the trailing NUL.  A return value of DEST_SIZE or larger means there
505
   wasn't enough space.  DEST will be NUL terminated in any case.
506
   Return (size_t) -1 upon error (invalid multi-byte sequence in SRC,
507
   or malloc failure), unless MBA_UNIBYTE_FALLBACK is specified.
508
   Update *WIDTH to indicate how many columns were used before padding.  */
509
510
size_t
511
mbsalign_with_padding (const char *src, char *dest, size_t dest_size,
512
                 size_t *width, mbs_align_t align,
513
#ifdef HAVE_WIDECHAR
514
           int flags,
515
#else
516
           int flags __attribute__((__unused__)),
517
#endif
518
           int padchar)
519
0
{
520
0
  size_t ret = -1;
521
0
  size_t src_size = strlen (src) + 1;
522
0
  char *newstr = NULL;
523
0
  wchar_t *str_wc = NULL;
524
0
  const char *str_to_print = src;
525
0
  size_t n_cols = src_size - 1;
526
0
  size_t n_used_bytes = n_cols; /* Not including NUL */
527
0
  size_t n_spaces = 0, space_left;
528
529
0
#ifdef HAVE_WIDECHAR
530
0
  bool conversion = false;
531
0
  bool wc_enabled = false;
532
533
  /* In multi-byte locales convert to wide characters
534
     to allow easy truncation. Also determine number
535
     of screen columns used.  */
536
0
  if (MB_CUR_MAX > 1)
537
0
    {
538
0
      size_t src_chars = mbstowcs (NULL, src, 0);
539
0
      if (src_chars == (size_t) -1)
540
0
        {
541
0
          if (flags & MBA_UNIBYTE_FALLBACK)
542
0
            goto mbsalign_unibyte;
543
0
          else
544
0
            goto mbsalign_cleanup;
545
0
        }
546
0
      src_chars += 1; /* make space for NUL */
547
0
      str_wc = malloc (src_chars * sizeof (wchar_t));
548
0
      if (str_wc == NULL)
549
0
        {
550
0
          if (flags & MBA_UNIBYTE_FALLBACK)
551
0
            goto mbsalign_unibyte;
552
0
          else
553
0
            goto mbsalign_cleanup;
554
0
        }
555
0
      if (mbstowcs (str_wc, src, src_chars) != 0)
556
0
        {
557
0
          str_wc[src_chars - 1] = L'\0';
558
0
          wc_enabled = true;
559
0
          conversion = wc_ensure_printable (str_wc);
560
0
          n_cols = rpl_wcswidth (str_wc, src_chars);
561
0
        }
562
0
    }
563
564
  /* If we transformed or need to truncate the source string
565
     then create a modified copy of it.  */
566
0
  if (wc_enabled && (conversion || (n_cols > *width)))
567
0
    {
568
0
        if (conversion)
569
0
          {
570
             /* May have increased the size by converting
571
                \t to \uFFFD for example.  */
572
0
            src_size = wcstombs(NULL, str_wc, 0) + 1;
573
0
          }
574
0
        newstr = malloc (src_size);
575
0
        if (newstr == NULL)
576
0
        {
577
0
          if (flags & MBA_UNIBYTE_FALLBACK)
578
0
            goto mbsalign_unibyte;
579
0
          else
580
0
            goto mbsalign_cleanup;
581
0
        }
582
0
        str_to_print = newstr;
583
0
        n_cols = wc_truncate (str_wc, *width);
584
0
        n_used_bytes = wcstombs (newstr, str_wc, src_size);
585
0
    }
586
587
0
mbsalign_unibyte:
588
0
#endif
589
590
0
  if (n_cols > *width) /* Unibyte truncation required.  */
591
0
    {
592
0
      n_cols = *width;
593
0
      n_used_bytes = n_cols;
594
0
    }
595
596
0
  if (*width > n_cols) /* Padding required.  */
597
0
    n_spaces = *width - n_cols;
598
599
  /* indicate to caller how many cells needed (not including padding).  */
600
0
  *width = n_cols;
601
602
  /* indicate to caller how many bytes needed (not including NUL).  */
603
0
  ret = n_used_bytes + (n_spaces * 1);
604
605
  /* Write as much NUL terminated output to DEST as possible.  */
606
0
  if (dest_size != 0)
607
0
    {
608
0
      char *dest_end = dest + dest_size - 1;
609
0
      size_t start_spaces;
610
0
      size_t end_spaces;
611
612
0
      switch (align)
613
0
        {
614
0
        case MBS_ALIGN_CENTER:
615
0
          start_spaces = n_spaces / 2 + n_spaces % 2;
616
0
          end_spaces = n_spaces / 2;
617
0
          break;
618
0
        case MBS_ALIGN_LEFT:
619
0
          start_spaces = 0;
620
0
          end_spaces = n_spaces;
621
0
          break;
622
0
        case MBS_ALIGN_RIGHT:
623
0
          start_spaces = n_spaces;
624
0
          end_spaces = 0;
625
0
          break;
626
0
  default:
627
0
    abort();
628
0
        }
629
630
0
      dest = mbs_align_pad (dest, dest_end, start_spaces, padchar);
631
0
      space_left = dest_end - dest;
632
0
      dest = mempcpy (dest, str_to_print, min (n_used_bytes, space_left));
633
0
      mbs_align_pad (dest, dest_end, end_spaces, padchar);
634
0
    }
635
0
#ifdef HAVE_WIDECHAR
636
0
mbsalign_cleanup:
637
0
#endif
638
0
  free (str_wc);
639
0
  free (newstr);
640
641
0
  return ret;
642
0
}