Coverage Report

Created: 2025-10-10 06:51

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/util-linux/lib/strutils.c
Line
Count
Source
1
/*
2
 * No copyright is claimed.  This code is in the public domain; do with
3
 * it what you wish.
4
 *
5
 * Authors: Karel Zak <kzak@redhat.com> [2010]
6
 *          Davidlohr Bueso <dave@gnu.org> [2010]
7
 */
8
#include <stdio.h>
9
#include <stdlib.h>
10
#include <inttypes.h>
11
#include <ctype.h>
12
#include <errno.h>
13
#include <sys/stat.h>
14
#include <string.h>
15
#include <strings.h>
16
#include <assert.h>
17
18
#include "c.h"
19
#include "nls.h"
20
#include "strutils.h"
21
#include "bitops.h"
22
#include "pathnames.h"
23
24
static int STRTOXX_EXIT_CODE = EXIT_FAILURE;
25
26
0
void strutils_set_exitcode(int ex) {
27
0
  STRTOXX_EXIT_CODE = ex;
28
0
}
29
30
static int do_scale_by_power (uintmax_t *x, int base, int power)
31
0
{
32
0
  while (power--) {
33
0
    if (UINTMAX_MAX / base < *x)
34
0
      return -ERANGE;
35
0
    *x *= base;
36
0
  }
37
0
  return 0;
38
0
}
39
40
/*
41
 * strtosize() - convert string to size (uintmax_t).
42
 *
43
 * Supported suffixes:
44
 *
45
 * XiB or X for 2^N
46
 *     where X = {K,M,G,T,P,E,Z,Y}
47
 *        or X = {k,m,g,t,p,e}  (undocumented for backward compatibility only)
48
 * for example:
49
 *    10KiB = 10240
50
 *    10K = 10240
51
 *
52
 * XB for 10^N
53
 *     where X = {K,M,G,T,P,E,Z,Y}
54
 * for example:
55
 *    10KB  = 10000
56
 *
57
 * The optional 'power' variable returns number associated with used suffix
58
 * {K,M,G,T,P,E,Z,Y}  = {1,2,3,4,5,6,7,8}.
59
 *
60
 * The function also supports decimal point, for example:
61
 *              0.5MB   = 500000
62
 *              0.5MiB  = 512000
63
 *
64
 * Note that the function does not accept numbers with '-' (negative sign)
65
 * prefix.
66
 */
67
int ul_parse_size(const char *str, uintmax_t *res, int *power)
68
0
{
69
0
  const char *p;
70
0
  char *end;
71
0
  uintmax_t x, frac = 0;
72
0
  int base = 1024, rc = 0, pwr = 0, frac_zeros = 0;
73
74
0
  static const char *suf  = "KMGTPEZY";
75
0
  static const char *suf2 = "kmgtpezy";
76
0
  const char *sp;
77
78
0
  *res = 0;
79
80
0
  if (!str || !*str) {
81
0
    rc = -EINVAL;
82
0
    goto err;
83
0
  }
84
85
  /* Only positive numbers are acceptable
86
   *
87
   * Note that this check is not perfect, it would be better to
88
   * use lconv->negative_sign. But coreutils use the same solution,
89
   * so it's probably good enough...
90
   */
91
0
  p = str;
92
0
  while (isspace((unsigned char) *p))
93
0
    p++;
94
0
  if (*p == '-') {
95
0
    rc = -EINVAL;
96
0
    goto err;
97
0
  }
98
99
0
  errno = 0, end = NULL;
100
0
  x = strtoumax(str, &end, 0);
101
102
0
  if (end == str ||
103
0
      (errno != 0 && (x == UINTMAX_MAX || x == 0))) {
104
0
    rc = errno ? -errno : -EINVAL;
105
0
    goto err;
106
0
  }
107
0
  if (!end || !*end)
108
0
    goto done;     /* without suffix */
109
0
  p = end;
110
111
  /*
112
   * Check size suffixes
113
   */
114
0
check_suffix:
115
0
  if (*(p + 1) == 'i' && (*(p + 2) == 'B' || *(p + 2) == 'b') && !*(p + 3))
116
0
    base = 1024;     /* XiB, 2^N */
117
0
  else if ((*(p + 1) == 'B' || *(p + 1) == 'b') && !*(p + 2))
118
0
    base = 1000;     /* XB, 10^N */
119
0
  else if (*(p + 1)) {
120
0
    struct lconv const *l = localeconv();
121
0
    const char *dp = l ? l->decimal_point : NULL;
122
0
    size_t dpsz = dp ? strlen(dp) : 0;
123
124
0
    if (frac == 0 && *p && dp && strncmp(dp, p, dpsz) == 0) {
125
0
      const char *fstr = p + dpsz;
126
127
0
      for (p = fstr; *p == '0'; p++)
128
0
        frac_zeros++;
129
0
      fstr = p;
130
0
      if (isdigit(*fstr)) {
131
0
        errno = 0, end = NULL;
132
0
        frac = strtoumax(fstr, &end, 0);
133
0
        if (end == fstr ||
134
0
            (errno != 0 && (frac == UINTMAX_MAX || frac == 0))) {
135
0
          rc = errno ? -errno : -EINVAL;
136
0
          goto err;
137
0
        }
138
0
      } else
139
0
        end = (char *) p;
140
141
0
      if (frac && (!end  || !*end)) {
142
0
        rc = -EINVAL;
143
0
        goto err;   /* without suffix, but with frac */
144
0
      }
145
0
      p = end;
146
0
      goto check_suffix;
147
0
    }
148
0
    rc = -EINVAL;
149
0
    goto err;     /* unexpected suffix */
150
0
  }
151
152
0
  sp = strchr(suf, *p);
153
0
  if (sp)
154
0
    pwr = (sp - suf) + 1;
155
0
  else {
156
0
    sp = strchr(suf2, *p);
157
0
    if (sp)
158
0
      pwr = (sp - suf2) + 1;
159
0
    else {
160
0
      rc = -EINVAL;
161
0
      goto err;
162
0
    }
163
0
  }
164
165
0
  rc = do_scale_by_power(&x, base, pwr);
166
0
  if (power)
167
0
    *power = pwr;
168
0
  if (frac && pwr) {
169
0
    int i;
170
0
    uintmax_t frac_div = 10, frac_poz = 1, frac_base = 1;
171
172
    /* mega, giga, ... */
173
0
    do_scale_by_power(&frac_base, base, pwr);
174
175
    /* maximal divisor for last digit (e.g. for 0.05 is
176
     * frac_div=100, for 0.054 is frac_div=1000, etc.)
177
     *
178
     * Reduce frac if too large.
179
     */
180
0
    while (frac_div < frac) {
181
0
      if (frac_div <= UINTMAX_MAX/10)
182
0
        frac_div *= 10;
183
0
      else
184
0
        frac /= 10;
185
0
    }
186
187
    /* 'frac' is without zeros (5 means 0.5 as well as 0.05) */
188
0
    for (i = 0; i < frac_zeros; i++) {
189
0
      if (frac_div <= UINTMAX_MAX/10)
190
0
        frac_div *= 10;
191
0
      else
192
0
        frac /= 10;
193
0
    }
194
195
    /*
196
     * Go backwardly from last digit and add to result what the
197
     * digit represents in the frac_base. For example 0.25G
198
     *
199
     *  5 means 1GiB / (100/5)
200
     *  2 means 1GiB / (10/2)
201
     */
202
0
    do {
203
0
      unsigned int seg = frac % 10;    /* last digit of the frac */
204
0
      uintmax_t seg_div = frac_div / frac_poz; /* what represents the segment 1000, 100, .. */
205
206
0
      frac /= 10; /* remove last digit from frac */
207
0
      frac_poz *= 10;
208
209
0
      if (seg && seg_div / seg)
210
0
        x += frac_base / (seg_div / seg);
211
0
    } while (frac);
212
0
  }
213
0
done:
214
0
  *res = x;
215
0
err:
216
0
  if (rc < 0)
217
0
    errno = -rc;
218
0
  return rc;
219
0
}
220
221
int strtosize(const char *str, uintmax_t *res)
222
0
{
223
0
  return ul_parse_size(str, res, NULL);
224
0
}
225
226
int isdigit_strend(const char *str, const char **end)
227
0
{
228
0
  const char *p;
229
230
0
  for (p = str; p && *p && isdigit((unsigned char) *p); p++);
231
232
0
  if (end)
233
0
    *end = p;
234
0
  return p && p > str && !*p;
235
0
}
236
237
int isxdigit_strend(const char *str, const char **end)
238
0
{
239
0
  const char *p;
240
241
0
  for (p = str; p && *p && isxdigit((unsigned char) *p); p++);
242
243
0
  if (end)
244
0
    *end = p;
245
246
0
  return p && p > str && !*p;
247
0
}
248
249
/*
250
 *  For example: ul_parse_switch(argv[i], "on", "off",  "yes", "no",  NULL);
251
 */
252
int ul_parse_switch(const char *arg, ...)
253
0
{
254
0
  const char *a, *b;
255
0
  va_list ap;
256
257
0
  va_start(ap, arg);
258
0
  do {
259
0
    a = va_arg(ap, char *);
260
0
    if (!a)
261
0
      break;
262
0
    b = va_arg(ap, char *);
263
0
    if (!b)
264
0
      break;
265
266
0
    if (strcmp(arg, a) == 0) {
267
0
      va_end(ap);
268
0
      return 1;
269
0
    }
270
271
0
    if (strcmp(arg, b) == 0) {
272
0
      va_end(ap);
273
0
      return 0;
274
0
    }
275
0
  } while (1);
276
0
  va_end(ap);
277
278
0
  errx(STRTOXX_EXIT_CODE, _("unsupported argument: %s"), arg);
279
0
}
280
281
#ifndef HAVE_MEMPCPY
282
void *mempcpy(void *restrict dest, const void *restrict src, size_t n)
283
{
284
    return ((char *)memcpy(dest, src, n)) + n;
285
}
286
#endif
287
288
#ifndef HAVE_STRNLEN
289
size_t strnlen(const char *s, size_t maxlen)
290
{
291
        size_t i;
292
293
        for (i = 0; i < maxlen; i++) {
294
                if (s[i] == '\0')
295
                        return i;
296
        }
297
        return maxlen;
298
}
299
#endif
300
301
#ifndef HAVE_STRNCHR
302
char *strnchr(const char *s, size_t maxlen, int c)
303
0
{
304
0
  for (; maxlen-- && *s != '\0'; ++s)
305
0
    if (*s == (char)c)
306
0
      return (char *)s;
307
0
  return NULL;
308
0
}
309
#endif
310
311
#ifndef HAVE_STRNDUP
312
char *strndup(const char *s, size_t n)
313
{
314
  size_t len = strnlen(s, n);
315
  char *new = malloc((len + 1) * sizeof(char));
316
  if (!new)
317
    return NULL;
318
  new[len] = '\0';
319
  return (char *) memcpy(new, s, len);
320
}
321
#endif
322
323
/*
324
 * convert strings to numbers; returns <0 on error, and 0 on success
325
 */
326
int ul_strtos64(const char *str, int64_t *num, int base)
327
0
{
328
0
  char *end = NULL;
329
330
0
  if (str == NULL || *str == '\0')
331
0
    return -(errno = EINVAL);
332
333
0
  errno = 0;
334
0
  *num = (int64_t) strtoimax(str, &end, base);
335
336
0
  if (errno != 0)
337
0
    return -errno;
338
0
  if (str == end || (end && *end))
339
0
    return -(errno = EINVAL);
340
0
  return 0;
341
0
}
342
343
int ul_strtou64(const char *str, uint64_t *num, int base)
344
0
{
345
0
  char *end = NULL;
346
0
  int64_t tmp;
347
348
0
  if (str == NULL || *str == '\0')
349
0
    return -(errno = EINVAL);
350
351
  /* we need to ignore negative numbers, note that for invalid negative
352
   * number strtoimax() returns negative number too, so we do not
353
   * need to check errno here */
354
0
  errno = 0;
355
0
  tmp = (int64_t) strtoimax(str, &end, base);
356
0
  if (tmp < 0)
357
0
    errno = ERANGE;
358
0
  else {
359
0
    errno = 0;
360
0
    *num = strtoumax(str, &end, base);
361
0
  }
362
363
0
  if (errno != 0)
364
0
    return -errno;
365
0
  if (str == end || (end && *end))
366
0
    return -(errno = EINVAL);
367
0
  return 0;
368
0
}
369
370
int ul_strtos32(const char *str, int32_t *num, int base)
371
0
{
372
0
  int64_t tmp;
373
0
  int rc;
374
375
0
  rc = ul_strtos64(str, &tmp, base);
376
0
  if (rc == 0 && (tmp < INT32_MIN || tmp > INT32_MAX))
377
0
    rc = -(errno = ERANGE);
378
0
  if (rc == 0)
379
0
    *num = (int32_t) tmp;
380
0
  return rc;
381
0
}
382
383
int ul_strtou32(const char *str, uint32_t *num, int base)
384
0
{
385
0
  uint64_t tmp;
386
0
  int rc;
387
388
0
  rc = ul_strtou64(str, &tmp, base);
389
0
  if (rc == 0 && tmp > UINT32_MAX)
390
0
    rc = -(errno = ERANGE);
391
0
  if (rc == 0)
392
0
    *num = (uint32_t) tmp;
393
0
  return rc;
394
0
}
395
396
int ul_strtou16(const char *str, uint16_t *num, int base)
397
0
{
398
0
  uint64_t tmp;
399
0
  int rc;
400
401
0
  rc = ul_strtou64(str, &tmp, base);
402
0
  if (rc == 0 && tmp > UINT16_MAX)
403
0
    rc = -(errno = ERANGE);
404
0
  if (rc == 0)
405
0
    *num = (uint16_t) tmp;
406
0
  return rc;
407
0
}
408
409
/*
410
 * Convert strings to numbers in defined range and print message on error.
411
 *
412
 * These functions are used when we read input from users (getopt() etc.). It's
413
 * better to consolidate the code and keep it all based on 64-bit numbers than
414
 * implement it for 32 and 16-bit numbers too.
415
 */
416
int64_t str2num_or_err(const char *str, int base, const char *errmesg,
417
           int64_t low, int64_t up)
418
0
{
419
0
  int64_t num = 0;
420
0
  int rc;
421
422
0
  rc = ul_strtos64(str, &num, base);
423
0
  if (rc == 0 && ((low && num < low) || (up && num > up)))
424
0
    rc = -(errno = ERANGE);
425
426
0
  if (rc) {
427
0
    if (errno == ERANGE)
428
0
      err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
429
0
    errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
430
0
  }
431
0
  return num;
432
0
}
433
434
uint64_t str2unum_or_err(const char *str, int base, const char *errmesg, uint64_t up)
435
0
{
436
0
  uint64_t num = 0;
437
0
  int rc;
438
439
0
  rc = ul_strtou64(str, &num, base);
440
0
  if (rc == 0 && (up && num > up))
441
0
    rc = -(errno = ERANGE);
442
443
0
  if (rc) {
444
0
    if (errno == ERANGE)
445
0
      err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
446
0
    errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
447
0
  }
448
0
  return num;
449
0
}
450
451
double strtod_or_err(const char *str, const char *errmesg)
452
0
{
453
0
  double num;
454
0
  char *end = NULL;
455
456
0
  errno = 0;
457
0
  if (str == NULL || *str == '\0')
458
0
    goto err;
459
0
  num = strtod(str, &end);
460
461
0
  if (errno || str == end || (end && *end))
462
0
    goto err;
463
464
0
  return num;
465
0
err:
466
0
  if (errno == ERANGE)
467
0
    err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
468
469
0
  errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
470
0
}
471
472
int ul_strtold(const char *str, long double *num)
473
0
{
474
0
  char *end = NULL;
475
476
0
  errno = 0;
477
0
  if (str == NULL || *str == '\0')
478
0
    return -(errno = EINVAL);
479
0
  *num = strtold(str, &end);
480
481
0
  if (errno != 0)
482
0
    return -errno;
483
0
  if (str == end || (end && *end))
484
0
    return -(errno = EINVAL);
485
0
  return 0;
486
0
}
487
488
long double strtold_or_err(const char *str, const char *errmesg)
489
0
{
490
0
  long double num = 0;
491
492
0
  if (ul_strtold(str, &num) == 0)
493
0
    return num;
494
0
  if (errno == ERANGE)
495
0
    err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
496
497
0
  errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
498
0
}
499
500
uintmax_t strtosize_or_err(const char *str, const char *errmesg)
501
0
{
502
0
  uintmax_t num;
503
504
0
  if (strtosize(str, &num) == 0)
505
0
    return num;
506
507
0
  if (errno)
508
0
    err(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
509
510
0
  errx(STRTOXX_EXIT_CODE, "%s: '%s'", errmesg, str);
511
0
}
512
513
514
void strtotimeval_or_err(const char *str, struct timeval *tv, const char *errmesg)
515
0
{
516
0
  long double user_input;
517
518
0
  user_input = strtold_or_err(str, errmesg);
519
0
  tv->tv_sec = (time_t) user_input;
520
0
  tv->tv_usec = (suseconds_t)((user_input - tv->tv_sec) * 1000000);
521
0
}
522
523
void strtotimespec_or_err(const char *str, struct timespec *ts, const char *errmesg)
524
0
{
525
0
  long double user_input;
526
527
0
  user_input = strtold_or_err(str, errmesg);
528
0
  ts->tv_sec = (time_t) user_input;
529
0
  ts->tv_nsec = (long)((user_input - ts->tv_sec) * 1000000000);
530
0
}
531
532
time_t strtotime_or_err(const char *str, const char *errmesg)
533
0
{
534
0
  int64_t user_input;
535
536
0
  user_input = strtos64_or_err(str, errmesg);
537
0
  return (time_t) user_input;
538
0
}
539
540
bool hyperlinkwanted(const char *mode)
541
0
{
542
0
  if (mode && strcmp(mode, "never") == 0)
543
0
    return false;
544
545
0
  if (mode && strcmp(mode, "always") == 0)
546
0
    return true;
547
548
0
  if (!mode || strcmp(mode, "auto") == 0)
549
0
    return isatty(STDOUT_FILENO) ? true : false;
550
551
0
  errx(EXIT_FAILURE, _("invalid argument of --hyperlink: %s"), mode);
552
0
}
553
554
bool annotationwanted(const char *mode)
555
0
{
556
0
  if (mode && strcmp(mode, "never") == 0)
557
0
    return false;
558
559
0
  if (mode && strcmp(mode, "always") == 0)
560
0
    return true;
561
562
0
  if (!mode || strcmp(mode, "auto") == 0)
563
0
    return isatty(STDOUT_FILENO) ? true : false;
564
565
0
  errx(EXIT_FAILURE, _("invalid argument of --annotate: %s"), mode);
566
0
}
567
568
/*
569
 * Converts stat->st_mode to ls(1)-like mode string. The size of "str" must
570
 * be 11 bytes.
571
 */
572
char *xstrmode(mode_t mode, char *str)
573
0
{
574
0
  unsigned short i = 0;
575
576
0
  if (S_ISDIR(mode))
577
0
    str[i++] = 'd';
578
0
  else if (S_ISLNK(mode))
579
0
    str[i++] = 'l';
580
0
  else if (S_ISCHR(mode))
581
0
    str[i++] = 'c';
582
0
  else if (S_ISBLK(mode))
583
0
    str[i++] = 'b';
584
0
  else if (S_ISSOCK(mode))
585
0
    str[i++] = 's';
586
0
  else if (S_ISFIFO(mode))
587
0
    str[i++] = 'p';
588
0
  else if (S_ISREG(mode))
589
0
    str[i++] = '-';
590
591
0
  str[i++] = mode & S_IRUSR ? 'r' : '-';
592
0
  str[i++] = mode & S_IWUSR ? 'w' : '-';
593
0
  str[i++] = (mode & S_ISUID
594
0
    ? (mode & S_IXUSR ? 's' : 'S')
595
0
    : (mode & S_IXUSR ? 'x' : '-'));
596
0
  str[i++] = mode & S_IRGRP ? 'r' : '-';
597
0
  str[i++] = mode & S_IWGRP ? 'w' : '-';
598
0
  str[i++] = (mode & S_ISGID
599
0
    ? (mode & S_IXGRP ? 's' : 'S')
600
0
    : (mode & S_IXGRP ? 'x' : '-'));
601
0
  str[i++] = mode & S_IROTH ? 'r' : '-';
602
0
  str[i++] = mode & S_IWOTH ? 'w' : '-';
603
0
  str[i++] = (mode & S_ISVTX
604
0
    ? (mode & S_IXOTH ? 't' : 'T')
605
0
    : (mode & S_IXOTH ? 'x' : '-'));
606
0
  str[i] = '\0';
607
608
0
  return str;
609
0
}
610
611
/*
612
 * returns exponent (2^x=n) in range KiB..EiB (2^10..2^60)
613
 */
614
static int get_exp(uint64_t n)
615
0
{
616
0
  int shft;
617
618
0
  for (shft = 10; shft <= 60; shft += 10) {
619
0
    if (n < (1ULL << shft))
620
0
      break;
621
0
  }
622
0
  return shft - 10;
623
0
}
624
625
char *size_to_human_string(int options, uint64_t bytes)
626
0
{
627
0
  char buf[32];
628
0
  int dec, exp;
629
0
  uint64_t frac;
630
0
  const char *letters = "BKMGTPE";
631
0
  char suffix[sizeof(" KiB")], *psuf = suffix;
632
0
  char c;
633
634
0
  if (options & SIZE_SUFFIX_SPACE)
635
0
    *psuf++ = ' ';
636
637
638
0
  exp  = get_exp(bytes);
639
0
  c    = *(letters + (exp ? exp / 10 : 0));
640
0
  dec  = exp ? bytes / (1ULL << exp) : bytes;
641
0
  frac = exp ? bytes % (1ULL << exp) : 0;
642
643
0
  *psuf++ = c;
644
645
0
  if ((options & SIZE_SUFFIX_3LETTER) && (c != 'B')) {
646
0
    *psuf++ = 'i';
647
0
    *psuf++ = 'B';
648
0
  }
649
650
0
  *psuf = '\0';
651
652
  /* fprintf(stderr, "exp: %d, unit: %c, dec: %d, frac: %jd\n",
653
   *                 exp, suffix[0], dec, frac);
654
   */
655
656
  /* round */
657
0
  if (frac) {
658
    /* get 3 digits after decimal point */
659
0
    if (frac >= UINT64_MAX / 1000)
660
0
      frac = ((frac / 1024) * 1000) / (1ULL << (exp - 10)) ;
661
0
    else
662
0
      frac = (frac * 1000) / (1ULL << (exp)) ;
663
664
0
    if (options & SIZE_DECIMAL_2DIGITS) {
665
      /* round 4/5 and keep 2 digits after decimal point */
666
0
      frac = (frac + 5) / 10 ;
667
0
    } else {
668
      /* round 4/5 and keep 1 digit after decimal point */
669
0
      frac = ((frac + 50) / 100) * 10 ;
670
0
    }
671
672
    /* rounding could have overflowed */
673
0
    if (frac == 100) {
674
0
      dec++;
675
0
      frac = 0;
676
0
    }
677
0
  }
678
679
0
  if (frac) {
680
0
    struct lconv const *l = localeconv();
681
0
    char *dp = l ? l->decimal_point : NULL;
682
0
    int len;
683
684
0
    if (!dp || !*dp)
685
0
      dp = ".";
686
687
0
    len = snprintf(buf, sizeof(buf), "%d%s%02" PRIu64, dec, dp, frac);
688
0
    if (len > 0 && (size_t) len < sizeof(buf)) {
689
      /* remove potential extraneous zero */
690
0
      if (buf[len - 1] == '0')
691
0
        buf[len--] = '\0';
692
      /* append suffix */
693
0
      xstrncpy(buf+len, suffix, sizeof(buf) - len);
694
0
    } else
695
0
      *buf = '\0'; /* snprintf error */
696
0
  } else
697
0
    snprintf(buf, sizeof(buf), "%d%s", dec, suffix);
698
699
0
  return strdup(buf);
700
0
}
701
702
/*
703
 * Parses comma delimited list to array with IDs, for example:
704
 *
705
 * "aaa,bbb,ccc" --> ary[0] = FOO_AAA;
706
 *                   ary[1] = FOO_BBB;
707
 *                   ary[3] = FOO_CCC;
708
 *
709
 * The function name2id() provides conversion from string to ID.
710
 *
711
 * Returns: >= 0  : number of items added to ary[]
712
 *            -1  : parse error or unknown item
713
 *            -2  : arysz reached
714
 */
715
int string_to_idarray(const char *list, int ary[], size_t arysz,
716
      int (name2id)(const char *, size_t))
717
0
{
718
0
  const char *begin = NULL, *p;
719
0
  size_t n = 0;
720
721
0
  if (!list || !*list || !ary || !arysz || !name2id)
722
0
    return -1;
723
724
0
  for (p = list; p && *p; p++) {
725
0
    const char *end = NULL;
726
0
    int id;
727
728
0
    if (n >= arysz)
729
0
      return -2;
730
0
    if (!begin)
731
0
      begin = p;   /* begin of the column name */
732
0
    if (*p == ',')
733
0
      end = p;   /* terminate the name */
734
0
    if (*(p + 1) == '\0')
735
0
      end = p + 1;   /* end of string */
736
0
    if (!begin || !end)
737
0
      continue;
738
0
    if (end <= begin)
739
0
      return -1;
740
741
0
    id = name2id(begin, end - begin);
742
0
    if (id == -1)
743
0
      return -1;
744
0
    ary[ n++ ] = id;
745
0
    begin = NULL;
746
0
    if (end && !*end)
747
0
      break;
748
0
  }
749
0
  return n;
750
0
}
751
752
/*
753
 * Parses the array like string_to_idarray but if format is "+aaa,bbb"
754
 * it adds fields to array instead of replacing them.
755
 */
756
int string_add_to_idarray(const char *list, int ary[], size_t arysz,
757
      size_t *ary_pos, int (name2id)(const char *, size_t))
758
0
{
759
0
  const char *list_add;
760
0
  int r;
761
762
0
  if (!list || !*list || !ary_pos || *ary_pos > arysz)
763
0
    return -1;
764
765
0
  if (list[0] == '+')
766
0
    list_add = &list[1];
767
0
  else {
768
0
    list_add = list;
769
0
    *ary_pos = 0;
770
0
  }
771
772
0
  r = string_to_idarray(list_add, &ary[*ary_pos], arysz - *ary_pos, name2id);
773
0
  if (r > 0)
774
0
    *ary_pos += r;
775
0
  return r;
776
0
}
777
778
/*
779
 * LIST ::= <item> [, <item>]
780
 *
781
 * The <item> is translated to 'id' by name2id() function and the 'id' is used
782
 * as a position in the 'ary' bit array. It means that the 'id' has to be in
783
 * range <0..N> where N < sizeof(ary) * NBBY.
784
 *
785
 * If allow_range is enabled:
786
 * An item ending in '+' also sets all bits in <0..N>.
787
 * An item beginning with '+' also sets all bits in <N..allow_minus>.
788
 *
789
 * Returns: 0 on success, <0 on error.
790
 */
791
int string_to_bitarray(const char *list,
792
         char *ary,
793
         int (*name2bit)(const char *, size_t),
794
         size_t allow_range)
795
0
{
796
0
  const char *begin = NULL, *p;
797
798
0
  if (!list || !name2bit || !ary)
799
0
    return -EINVAL;
800
801
0
  for (p = list; p && *p; p++) {
802
0
    const char *end = NULL;
803
0
    int bit, set_lower = 0, set_higher = 0;
804
805
0
    if (!begin)
806
0
      begin = p;   /* begin of the level name */
807
0
    if (*p == ',')
808
0
      end = p;   /* terminate the name */
809
0
    if (*(p + 1) == '\0')
810
0
      end = p + 1;   /* end of string */
811
0
    if (!begin || !end)
812
0
      continue;
813
0
    if (end <= begin)
814
0
      return -1;
815
0
    if (allow_range) {
816
0
      if (*(end - 1) == '+') {
817
0
        end--;
818
0
        set_lower = 1;
819
0
      } else if (*begin == '+') {
820
0
        begin++;
821
0
        set_higher = 1;
822
0
      }
823
0
    }
824
825
0
    bit = name2bit(begin, end - begin);
826
0
    if (bit < 0)
827
0
      return bit;
828
0
    setbit(ary, bit);
829
0
    if (set_lower)
830
0
      while (--bit >= 0)
831
0
        setbit(ary, bit);
832
0
    else if (set_higher)
833
0
      while (++bit < (int) allow_range)
834
0
        setbit(ary, bit);
835
0
    begin = NULL;
836
0
    if (end && !*end)
837
0
      break;
838
0
  }
839
0
  return 0;
840
0
}
841
842
/*
843
 * LIST ::= <item> [, <item>]
844
 *
845
 * The <item> is translated to 'id' by name2flag() function and the flags is
846
 * set to the 'mask'
847
*
848
 * Returns: 0 on success, <0 on error.
849
 */
850
int string_to_bitmask(const char *list,
851
         unsigned long *mask,
852
         long (*name2flag)(const char *, size_t))
853
0
{
854
0
  const char *begin = NULL, *p;
855
856
0
  if (!list || !name2flag || !mask)
857
0
    return -EINVAL;
858
859
0
  for (p = list; p && *p; p++) {
860
0
    const char *end = NULL;
861
0
    long flag;
862
863
0
    if (!begin)
864
0
      begin = p;   /* begin of the level name */
865
0
    if (*p == ',')
866
0
      end = p;   /* terminate the name */
867
0
    if (*(p + 1) == '\0')
868
0
      end = p + 1;   /* end of string */
869
0
    if (!begin || !end)
870
0
      continue;
871
0
    if (end <= begin)
872
0
      return -1;
873
874
0
    flag = name2flag(begin, end - begin);
875
0
    if (flag < 0)
876
0
      return flag; /* error */
877
0
    *mask |= flag;
878
0
    begin = NULL;
879
0
    if (end && !*end)
880
0
      break;
881
0
  }
882
0
  return 0;
883
0
}
884
885
/*
886
 * Parse the lower and higher values in a string containing
887
 * "lower:higher" or "lower-higher" format. Note that either
888
 * the lower or the higher values may be missing, and the def
889
 * value will be assigned to it by default.
890
 *
891
 * Returns: 0 on success, <0 on error.
892
 */
893
int ul_parse_range(const char *str, int *lower, int *upper, int def)
894
0
{
895
0
  char *end = NULL;
896
897
0
  if (!str)
898
0
    return 0;
899
900
0
  *upper = *lower = def;
901
0
  errno = 0;
902
903
0
  if (*str == ':') {       /* <:N> */
904
0
    str++;
905
0
    *upper = strtol(str, &end, 10);
906
0
    if (errno || !end || *end || end == str)
907
0
      return -1;
908
0
  } else {
909
0
    *upper = *lower = strtol(str, &end, 10);
910
0
    if (errno || !end || end == str)
911
0
      return -1;
912
913
0
    if (*end == ':' && !*(end + 1))   /* <M:> */
914
0
      *upper = def;
915
0
    else if (*end == '-' || *end == ':') { /* <M:N> <M-N> */
916
0
      str = end + 1;
917
0
      end = NULL;
918
0
      errno = 0;
919
0
      *upper = strtol(str, &end, 10);
920
921
0
      if (errno || !end || *end || end == str)
922
0
        return -1;
923
0
    }
924
0
  }
925
0
  return 0;
926
0
}
927
928
static const char *next_path_segment(const char *str, size_t *sz)
929
0
{
930
0
  const char *start, *p;
931
932
0
  start = str;
933
0
  *sz = 0;
934
0
  while (start && *start == '/' && *(start + 1) == '/')
935
0
    start++;
936
937
0
  if (!start || !*start)
938
0
    return NULL;
939
940
0
  for (*sz = 1, p = start + 1; *p && *p != '/'; p++) {
941
0
    (*sz)++;
942
0
  }
943
944
0
  return start;
945
0
}
946
947
int streq_paths(const char *a, const char *b)
948
0
{
949
0
  while (a && b) {
950
0
    size_t a_sz, b_sz;
951
0
    const char *a_seg = next_path_segment(a, &a_sz);
952
0
    const char *b_seg = next_path_segment(b, &b_sz);
953
954
    /*
955
    fprintf(stderr, "A>>>(%zu) '%s'\n", a_sz, a_seg);
956
    fprintf(stderr, "B>>>(%zu) '%s'\n", b_sz, b_seg);
957
    */
958
959
    /* end of the path */
960
0
    if (a_sz + b_sz == 0)
961
0
      return 1;
962
963
    /* ignore trailing slash */
964
0
    if (a_sz + b_sz == 1 &&
965
0
        ((a_seg && *a_seg == '/') || (b_seg && *b_seg == '/')))
966
0
      return 1;
967
968
0
    if (!a_seg || !b_seg)
969
0
      break;
970
0
    if (a_sz != b_sz || strncmp(a_seg, b_seg, a_sz) != 0)
971
0
      break;
972
973
0
    a = a_seg + a_sz;
974
0
    b = b_seg + b_sz;
975
0
  };
976
977
0
  return 0;
978
0
}
979
980
/* concatenate two strings to a new string, the size of the second string is limited by @b */
981
char *ul_strnconcat(const char *s, const char *suffix, size_t b)
982
0
{
983
0
        size_t a;
984
0
        char *r;
985
986
0
        if (!s && !suffix)
987
0
                return strdup("");
988
0
        if (!s)
989
0
                return strndup(suffix, b);
990
0
        if (!suffix)
991
0
                return strdup(s);
992
993
0
        assert(s);
994
0
        assert(suffix);
995
996
0
        a = strlen(s);
997
0
        if (b > ((size_t) -1) - a)
998
0
                return NULL;
999
1000
0
        r = malloc(a + b + 1);
1001
0
        if (!r)
1002
0
                return NULL;
1003
1004
0
        memcpy(r, s, a);
1005
0
        memcpy(r + a, suffix, b);
1006
0
        r[a+b] = 0;
1007
1008
0
        return r;
1009
0
}
1010
1011
/* concatenate two strings to a new string */
1012
char *ul_strconcat(const char *s, const char *suffix)
1013
0
{
1014
0
        return ul_strnconcat(s, suffix, suffix ? strlen(suffix) : 0);
1015
0
}
1016
1017
/* concatenate @s and string defined by @format to a new string */
1018
char *ul_strfconcat(const char *s, const char *format, ...)
1019
0
{
1020
0
  va_list ap;
1021
0
  char *val, *res;
1022
0
  int sz;
1023
1024
0
  va_start(ap, format);
1025
0
  sz = vasprintf(&val, format, ap);
1026
0
  va_end(ap);
1027
1028
0
  if (sz < 0)
1029
0
    return NULL;
1030
1031
0
  res = ul_strnconcat(s, val, sz);
1032
0
  free(val);
1033
0
  return res;
1034
0
}
1035
1036
int ul_strappend(char **a, const char *b)
1037
0
{
1038
0
  size_t al, bl;
1039
0
  char *tmp;
1040
1041
0
  if (!a)
1042
0
    return -EINVAL;
1043
0
  if (!b || !*b)
1044
0
    return 0;
1045
0
  if (!*a) {
1046
0
    *a = strdup(b);
1047
0
    return !*a ? -ENOMEM : 0;
1048
0
  }
1049
1050
0
  al = strlen(*a);
1051
0
  bl = strlen(b);
1052
1053
0
  tmp = realloc(*a, al + bl + 1);
1054
0
  if (!tmp)
1055
0
    return -ENOMEM;
1056
0
  *a = tmp;
1057
0
  memcpy((*a) + al, b, bl + 1);
1058
0
  return 0;
1059
0
}
1060
1061
/* the hybrid version of strfconcat and strappend. */
1062
int strfappend(char **a, const char *format, ...)
1063
0
{
1064
0
  va_list ap;
1065
0
  int res;
1066
1067
0
  va_start(ap, format);
1068
0
  res = ul_strvfappend(a, format, ap);
1069
0
  va_end(ap);
1070
1071
0
  return res;
1072
0
}
1073
1074
extern int ul_strvfappend(char **a, const char *format, va_list ap)
1075
0
{
1076
0
  char *val;
1077
0
  int sz;
1078
0
  int res;
1079
1080
0
  sz = vasprintf(&val, format, ap);
1081
0
  if (sz < 0)
1082
0
    return -errno;
1083
1084
0
  res = ul_strappend(a, val);
1085
0
  free(val);
1086
0
  return res;
1087
0
}
1088
1089
static size_t strcspn_escaped(const char *s, const char *reject)
1090
0
{
1091
0
        int escaped = 0;
1092
0
        int n;
1093
1094
0
        for (n=0; s[n]; n++) {
1095
0
                if (escaped)
1096
0
                        escaped = 0;
1097
0
                else if (s[n] == '\\')
1098
0
                        escaped = 1;
1099
0
                else if (strchr(reject, s[n]))
1100
0
                        break;
1101
0
        }
1102
1103
        /* if s ends in \, return index of previous char */
1104
0
        return n - escaped;
1105
0
}
1106
1107
/*
1108
 * Like strchr() but ignores @c if escaped by '\', '\\' is interpreted like '\'.
1109
 *
1110
 * For example for @c='X':
1111
 *
1112
 *      "abcdXefgXh"    --> "XefgXh"
1113
 *  "abcd\XefgXh"   --> "Xh"
1114
 *  "abcd\\XefgXh"  --> "XefgXh"
1115
 *  "abcd\\\XefgXh" --> "Xh"
1116
 *  "abcd\Xefg\Xh"  --> (null)
1117
 *
1118
 *  "abcd\\XefgXh"  --> "\XefgXh"   for @c='\\'
1119
 */
1120
char *ul_strchr_escaped(const char *s, int c)
1121
0
{
1122
0
  char *p;
1123
0
  int esc = 0;
1124
1125
0
  for (p = (char *) s; p && *p; p++) {
1126
0
    if (!esc && *p == '\\') {
1127
0
      esc = 1;
1128
0
      continue;
1129
0
    }
1130
0
    if (*p == c && (!esc || c == '\\'))
1131
0
      return p;
1132
0
    esc = 0;
1133
0
  }
1134
1135
0
  return NULL;
1136
0
}
1137
1138
/* Split a string into words. */
1139
const char *ul_split(const char **state, size_t *l, const char *separator, int quoted)
1140
0
{
1141
0
        const char *current;
1142
1143
0
        current = *state;
1144
1145
0
        if (!*current) {
1146
0
                assert(**state == '\0');
1147
0
                return NULL;
1148
0
        }
1149
1150
0
        current += strspn(current, separator);
1151
0
        if (!*current) {
1152
0
                *state = current;
1153
0
                return NULL;
1154
0
        }
1155
1156
0
        if (quoted && strchr("\'\"", *current)) {
1157
0
                char quotechars[2] = {*current, '\0'};
1158
1159
0
                *l = strcspn_escaped(current + 1, quotechars);
1160
0
                if (current[*l + 1] == '\0' || current[*l + 1] != quotechars[0] ||
1161
0
                    (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
1162
                        /* right quote missing or garbage at the end */
1163
0
                        *state = current;
1164
0
                        return NULL;
1165
0
                }
1166
0
                *state = current++ + *l + 2;
1167
0
        } else if (quoted) {
1168
0
                *l = strcspn_escaped(current, separator);
1169
0
                if (current[*l] && !strchr(separator, current[*l])) {
1170
                        /* unfinished escape */
1171
0
                        *state = current;
1172
0
                        return NULL;
1173
0
                }
1174
0
                *state = current + *l;
1175
0
        } else {
1176
0
                *l = strcspn(current, separator);
1177
0
                *state = current + *l;
1178
0
        }
1179
1180
0
        return current;
1181
0
}
1182
1183
/* Rewind file pointer forward to new line.  */
1184
int skip_fline(FILE *fp)
1185
0
{
1186
0
  int ch;
1187
1188
0
  do {
1189
0
    if ((ch = fgetc(fp)) == EOF)
1190
0
      return 1;
1191
0
    if (ch == '\n')
1192
0
      return 0;
1193
0
  } while (1);
1194
0
}
1195
1196
1197
/* compare two strings, but ignoring non-alnum and case of the characters, for example
1198
 * "Hello (123)!" is the same as "hello123".
1199
 */
1200
int ul_stralnumcmp(const char *p1, const char *p2)
1201
0
{
1202
0
  const unsigned char *s1 = (const unsigned char *) p1;
1203
0
  const unsigned char *s2 = (const unsigned char *) p2;
1204
0
  unsigned char c1, c2;
1205
1206
0
  do {
1207
0
    do {
1208
0
      c1 = (unsigned char) *s1++;
1209
0
    } while (c1 != '\0' && !isalnum((unsigned int) c1));
1210
1211
0
    do {
1212
0
      c2 = (unsigned char) *s2++;
1213
0
    } while (c2 != '\0' && !isalnum((unsigned int) c2));
1214
1215
0
    if (c1 != '\0')
1216
0
      c1 = tolower(c1);
1217
0
    if (c2 != '\0')
1218
0
      c2 = tolower(c2);
1219
0
    if (c1 == '\0')
1220
0
      return c1 - c2;
1221
0
  } while (c1 == c2);
1222
1223
0
  return c1 - c2;
1224
0
}
1225
1226
/*
1227
 * Parses the first option from @optstr. The @optstr pointer is set to the beginning
1228
 * of the next option. The options string looks like 'aaa,bbb=data,foo,bar="xxx"'.
1229
 *
1230
 * Note this function is used by libmount to parse mount options. Be careful when modify.
1231
 *
1232
 * Returns -EINVAL on parse error, 1 at the end of optstr and 0 on success.
1233
 */
1234
int ul_optstr_next(char **optstr, char **name, size_t *namesz,
1235
       char **value, size_t *valsz)
1236
0
{
1237
0
  int open_quote = 0;
1238
0
  char *start = NULL, *stop = NULL, *p, *sep = NULL;
1239
0
  char *optstr0;
1240
1241
0
  assert(optstr);
1242
0
  assert(*optstr);
1243
1244
0
  optstr0 = *optstr;
1245
1246
0
  if (name)
1247
0
    *name = NULL;
1248
0
  if (namesz)
1249
0
    *namesz = 0;
1250
0
  if (value)
1251
0
    *value = NULL;
1252
0
  if (valsz)
1253
0
    *valsz = 0;
1254
1255
  /* trim leading commas as to not invalidate option
1256
   * strings with multiple consecutive commas */
1257
0
  while (optstr0 && *optstr0 == ',')
1258
0
    optstr0++;
1259
1260
0
  for (p = optstr0; p && *p; p++) {
1261
0
    if (!start && *p == '=')
1262
0
      return -EINVAL;
1263
0
    if (!start)
1264
0
      start = p;   /* beginning of the option item */
1265
0
    if (*p == '"' && (p == optstr0 || *(p - 1) != '\\'))
1266
0
      open_quote ^= 1; /* reverse the status */
1267
0
    if (open_quote)
1268
0
      continue;   /* still in quoted block */
1269
0
    if (!sep && p > start && *p == '=')
1270
0
      sep = p;   /* name and value separator */
1271
0
    if (*p == ',' && (p == optstr0 || *(p - 1) != '\\'))
1272
0
      stop = p;   /* terminate the option item */
1273
0
    else if (*(p + 1) == '\0')
1274
0
      stop = p + 1;   /* end of optstr */
1275
0
    if (!start || !stop)
1276
0
      continue;
1277
0
    if (stop <= start)
1278
0
      return -EINVAL;
1279
1280
0
    if (name)
1281
0
      *name = start;
1282
0
    if (namesz)
1283
0
      *namesz = sep ? sep - start : stop - start;
1284
0
    *optstr = *stop ? stop + 1 : stop;
1285
1286
0
    if (sep) {
1287
0
      if (value)
1288
0
        *value = sep + 1;
1289
0
      if (valsz)
1290
0
        *valsz = stop - sep - 1;
1291
0
    }
1292
0
    return 0;
1293
0
  }
1294
1295
0
  return 1;       /* end of optstr */
1296
0
}
1297
1298
int ul_optstr_is_valid(const char *optstr)
1299
0
{
1300
0
  int rc;
1301
0
  char *p = (char *) optstr;
1302
1303
0
  while ((rc = ul_optstr_next(&p, NULL, NULL, NULL, NULL)) == 0);
1304
0
  return rc < 0 ? 0 : 1;
1305
0
}
1306
1307
char *ul_optstr_get_value(const char *optstr, const char *key)
1308
0
{
1309
0
  size_t sz, namesz = 0, valsz = 0;
1310
0
  char *name = NULL, *value = NULL;
1311
0
  char *p = (char *) optstr;
1312
1313
0
  if (!optstr || !key || !*key)
1314
0
    return NULL;
1315
1316
0
  sz = strlen(key);
1317
0
  while (ul_optstr_next(&p, &name, &namesz, &value, &valsz) == 0) {
1318
0
    if (namesz != sz || !valsz)
1319
0
      continue;
1320
0
    if (strncmp(name, key, namesz) == 0)
1321
0
      return strndup(value, valsz);
1322
0
  }
1323
0
  return NULL;
1324
0
}
1325
1326
#ifdef TEST_PROGRAM_STRUTILS
1327
1328
#include "cctype.h"
1329
1330
struct testS {
1331
  char *name;
1332
  char *value;
1333
};
1334
1335
static int test_strdup_to_member(int argc, char *argv[])
1336
{
1337
  struct testS *xx;
1338
1339
  if (argc < 3)
1340
    return EXIT_FAILURE;
1341
1342
  xx = calloc(1, sizeof(*xx));
1343
  if (!xx)
1344
    err(EXIT_FAILURE, "calloc() failed");
1345
1346
  strdup_to_struct_member(xx, name, argv[1]);
1347
  strdup_to_struct_member(xx, value, argv[2]);
1348
1349
  if (strcmp(xx->name, argv[1]) != 0 &&
1350
      strcmp(xx->value, argv[2]) != 0)
1351
    errx(EXIT_FAILURE, "strdup_to_struct_member() failed");
1352
1353
  printf("1: '%s', 2: '%s'\n", xx->name, xx->value);
1354
1355
  free(xx->name);
1356
  free(xx->value);
1357
  free(xx);
1358
  return EXIT_SUCCESS;
1359
}
1360
1361
static int test_strutils_sizes(int argc, char *argv[])
1362
{
1363
  uintmax_t size = 0;
1364
  char *hum1, *hum2, *hum3;
1365
1366
  if (argc < 2)
1367
    return EXIT_FAILURE;
1368
1369
  if (strtosize(argv[1], &size))
1370
    errx(EXIT_FAILURE, "invalid size '%s' value", argv[1]);
1371
1372
  hum1 = size_to_human_string(SIZE_SUFFIX_1LETTER, size);
1373
  hum2 = size_to_human_string(SIZE_SUFFIX_3LETTER |
1374
            SIZE_SUFFIX_SPACE, size);
1375
  hum3 = size_to_human_string(SIZE_SUFFIX_3LETTER |
1376
            SIZE_SUFFIX_SPACE |
1377
            SIZE_DECIMAL_2DIGITS, size);
1378
1379
  printf("%25s : %20ju : %8s : %12s : %13s\n", argv[1], size, hum1, hum2, hum3);
1380
  free(hum1);
1381
  free(hum2);
1382
  free(hum3);
1383
1384
  return EXIT_SUCCESS;
1385
}
1386
1387
static int test_strutils_cmp_paths(int argc, char *argv[])
1388
{
1389
  int rc = streq_paths(argv[1], argv[2]);
1390
1391
  if (argc < 3)
1392
    return EXIT_FAILURE;
1393
1394
  printf("%s: '%s' '%s'\n", rc == 1 ? "YES" : "NOT", argv[1], argv[2]);
1395
  return EXIT_SUCCESS;
1396
}
1397
1398
static int test_strutils_normalize(int argc, char *argv[])
1399
{
1400
  unsigned char *src, *dst, *org;
1401
  size_t sz, len;
1402
1403
  if (argc < 2)
1404
    return EXIT_FAILURE;
1405
1406
  org = (unsigned char *) strdup(argv[1]);
1407
  src = (unsigned char *) strdup((char *) org);
1408
  len = strlen((char *) src);
1409
  dst = malloc(len + 1);
1410
1411
  if (!org || !src || !dst)
1412
    goto done;
1413
1414
  /* two buffers */
1415
  sz = __normalize_whitespace(src, len, dst, len + 1);
1416
  printf("1: '%s' --> '%s' [sz=%zu]\n", src, dst, sz);
1417
1418
  /* one buffer */
1419
  sz = normalize_whitespace(src);
1420
  printf("2: '%s' --> '%s' [sz=%zu]\n", org, src, sz);
1421
1422
done:
1423
  free(src);
1424
  free(dst);
1425
  free(org);
1426
1427
  return EXIT_SUCCESS;
1428
}
1429
1430
static int test_strutils_cstrcasecmp(int argc, char *argv[])
1431
{
1432
  char *a, *b;
1433
1434
  if (argc < 3)
1435
    return EXIT_FAILURE;
1436
1437
  a = argv[1];
1438
  b = argv[2];
1439
1440
  if (!a || !b)
1441
    return EXIT_FAILURE;
1442
1443
  printf("cmp    '%s' '%s' = %d\n", a, b, strcasecmp(a, b));
1444
  printf("c_cmp  '%s' '%s' = %d\n", a, b, c_strcasecmp(a, b));
1445
  printf("c_ncmp '%s' '%s' = %d\n", a, b, c_strncasecmp(a, b, strlen(a)));
1446
1447
  return EXIT_SUCCESS;
1448
}
1449
1450
int main(int argc, char *argv[])
1451
{
1452
  if (argc == 3 && strcmp(argv[1], "--size") == 0) {
1453
    return test_strutils_sizes(argc - 1, argv + 1);
1454
1455
  } else if (argc == 3 && strcmp(argv[1], "--parse-switch") == 0) {
1456
    printf("'%s'-->%d\n", argv[2], ul_parse_switch(argv[2],
1457
            "on", "off",
1458
            "enable", "disable",
1459
            "yes", "no",
1460
            "1", "0",
1461
            NULL));
1462
    return EXIT_SUCCESS;
1463
  } else if (argc == 4 && strcmp(argv[1], "--cmp-paths") == 0) {
1464
    return test_strutils_cmp_paths(argc - 1, argv + 1);
1465
1466
  } else if (argc == 4 && strcmp(argv[1], "--strdup-member") == 0) {
1467
    return test_strdup_to_member(argc - 1, argv + 1);
1468
1469
  } else if  (argc == 4 && strcmp(argv[1], "--stralnumcmp") == 0) {
1470
    printf("%s\n", ul_stralnumcmp(argv[2], argv[3]) == 0 ?
1471
        "match" : "dismatch");
1472
    return EXIT_SUCCESS;
1473
1474
  } else if (argc == 4 && strcmp(argv[1], "--cstrcasecmp") == 0) {
1475
    return test_strutils_cstrcasecmp(argc - 1, argv + 1);
1476
1477
  } else if (argc == 3 && strcmp(argv[1], "--normalize") == 0) {
1478
    return test_strutils_normalize(argc - 1, argv + 1);
1479
1480
  } else if (argc == 3 && strcmp(argv[1], "--strtos64") == 0) {
1481
    printf("'%s'-->%jd\n", argv[2], strtos64_or_err(argv[2], "strtos64 failed"));
1482
    return EXIT_SUCCESS;
1483
  } else if (argc == 3 && strcmp(argv[1], "--strtou64") == 0) {
1484
    printf("'%s'-->%ju\n", argv[2], strtou64_or_err(argv[2], "strtou64 failed"));
1485
    return EXIT_SUCCESS;
1486
  } else if (argc == 3 && strcmp(argv[1], "--strtos32") == 0) {
1487
    printf("'%s'-->%d\n", argv[2], strtos32_or_err(argv[2], "strtos32 failed"));
1488
    return EXIT_SUCCESS;
1489
  } else if (argc == 3 && strcmp(argv[1], "--strtou32") == 0) {
1490
    printf("'%s'-->%u\n", argv[2], strtou32_or_err(argv[2], "strtou32 failed"));
1491
    return EXIT_SUCCESS;
1492
  } else if (argc == 3 && strcmp(argv[1], "--strtos16") == 0) {
1493
    printf("'%s'-->%hd\n", argv[2], strtos16_or_err(argv[2], "strtos16 failed"));
1494
    return EXIT_SUCCESS;
1495
  } else if (argc == 3 && strcmp(argv[1], "--strtou16") == 0) {
1496
    printf("'%s'-->%hu\n", argv[2], strtou16_or_err(argv[2], "strtou16 failed"));
1497
    return EXIT_SUCCESS;
1498
1499
  } else if (argc == 4 && strcmp(argv[1], "--strchr-escaped") == 0) {
1500
    printf("\"%s\" --> \"%s\"\n", argv[2], ul_strchr_escaped(argv[2], *argv[3]));
1501
    return EXIT_SUCCESS;
1502
1503
  } else if (argc == 2 && strcmp(argv[1], "--next-string") == 0) {
1504
    char *buf = "abc\0Y\0\0xyz\0X";
1505
    char *end = buf + 12;
1506
    char *p = buf;
1507
1508
    do {
1509
      printf("str: '%s'\n", p);
1510
    } while ((p = ul_next_string(p, end)));
1511
1512
    return EXIT_SUCCESS;
1513
1514
  } else if (argc == 3 && strcmp(argv[1], "--optstr") == 0) {
1515
1516
    size_t namesz, valsz;
1517
    char *name = NULL, *val = NULL;
1518
    char *p = argv[2];
1519
    int rc;
1520
1521
    if (!ul_optstr_is_valid(p))
1522
      errx(EXIT_FAILURE, _("unsupported option format: %s"), p);
1523
1524
    while ((rc = ul_optstr_next(&p, &name, &namesz, &val, &valsz)) == 0) {
1525
      printf("'%.*s' : '%.*s'\n", (int) namesz, name,
1526
               (int) valsz, val);
1527
    }
1528
    if (rc == 1)
1529
      return EXIT_SUCCESS;
1530
  } else {
1531
    fprintf(stderr, "usage: %1$s --size <number>[suffix]\n"
1532
        "       %1$s --parse-switch <str>\n"
1533
        "       %1$s --cmp-paths <path> <path>\n"
1534
        "       %1$s --strdup-member <str> <str>\n"
1535
        "       %1$s --stralnumcmp <str> <str>\n"
1536
        "       %1$s --cstrcasecmp <str> <str>\n"
1537
        "       %1$s --normalize <str>\n"
1538
        "       %1$s --strto{s,u}{16,32,64} <str>\n"
1539
        "       %1$s --optstr <str>\n",
1540
        argv[0]);
1541
    exit(EXIT_FAILURE);
1542
  }
1543
1544
  return EXIT_FAILURE;
1545
}
1546
#endif /* TEST_PROGRAM_STRUTILS */