virstring.c 35.1 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * Copyright (C) 2012-2015 Red Hat, Inc.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

21
#include <regex.h>
22
#include <locale.h>
23

24
#include "base64.h"
25
#include "c-ctype.h"
26
#include "virstring.h"
27
#include "virthread.h"
28
#include "viralloc.h"
29
#include "virbuffer.h"
30
#include "virerror.h"
31
#include "virlog.h"
32 33 34

#define VIR_FROM_THIS VIR_FROM_NONE

35 36
VIR_LOG_INIT("util.string");

37
/*
38
 * The following virStringSplit & virStringListJoin methods
39 40 41 42 43
 * are derived from g_strsplit / g_strjoin in glib2,
 * also available under the LGPLv2+ license terms
 */

/**
44
 * virStringSplitCount:
45 46 47 48 49 50
 * @string: a string to split
 * @delim: a string which specifies the places at which to split
 *     the string. The delimiter is not included in any of the resulting
 *     strings, unless @max_tokens is reached.
 * @max_tokens: the maximum number of pieces to split @string into.
 *     If this is 0, the string is split completely.
51 52
 * @tokcount: If provided, the value is set to the count of pieces the string
 *            was split to excluding the terminating NULL element.
53 54 55 56 57 58 59
 *
 * Splits a string into a maximum of @max_tokens pieces, using the given
 * @delim. If @max_tokens is reached, the remainder of @string is
 * appended to the last token.
 *
 * As a special case, the result of splitting the empty string "" is an empty
 * vector, not a vector containing a single string. The reason for this
Y
Yuri Chornoivan 已提交
60
 * special case is that being able to represent an empty vector is typically
61 62 63 64 65
 * more useful than consistent handling of empty elements. If you do need
 * to represent empty elements, you'll need to check for the empty string
 * before calling virStringSplit().
 *
 * Return value: a newly-allocated NULL-terminated array of strings. Use
66
 *    virStringListFree() to free it.
67
 */
68 69 70 71 72
char **
virStringSplitCount(const char *string,
                    const char *delim,
                    size_t max_tokens,
                    size_t *tokcount)
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
{
    char **tokens = NULL;
    size_t ntokens = 0;
    size_t maxtokens = 0;
    const char *remainder = string;
    char *tmp;
    size_t i;

    if (max_tokens == 0)
        max_tokens = INT_MAX;

    tmp = strstr(remainder, delim);
    if (tmp) {
        size_t delimlen = strlen(delim);

        while (--max_tokens && tmp) {
            size_t len = tmp - remainder;

            if (VIR_RESIZE_N(tokens, maxtokens, ntokens, 1) < 0)
92
                goto error;
93

94 95
            if (VIR_STRNDUP(tokens[ntokens], remainder, len) < 0)
                goto error;
96 97 98 99 100 101 102
            ntokens++;
            remainder = tmp + delimlen;
            tmp = strstr(remainder, delim);
        }
    }
    if (*string) {
        if (VIR_RESIZE_N(tokens, maxtokens, ntokens, 1) < 0)
103
            goto error;
104

105 106
        if (VIR_STRDUP(tokens[ntokens], remainder) < 0)
            goto error;
107 108 109 110
        ntokens++;
    }

    if (VIR_RESIZE_N(tokens, maxtokens, ntokens, 1) < 0)
111
        goto error;
112 113
    tokens[ntokens++] = NULL;

114 115 116
    if (tokcount)
        *tokcount = ntokens - 1;

117 118
    return tokens;

119
 error:
120
    for (i = 0; i < ntokens; i++)
121 122 123 124 125 126
        VIR_FREE(tokens[i]);
    VIR_FREE(tokens);
    return NULL;
}


127 128 129 130 131 132 133 134 135
char **
virStringSplit(const char *string,
               const char *delim,
               size_t max_tokens)
{
    return virStringSplitCount(string, delim, max_tokens, NULL);
}


136
/**
137
 * virStringListJoin:
138 139 140 141 142 143 144 145 146 147
 * @strings: a NULL-terminated array of strings to join
 * @delim: a string to insert between each of the strings
 *
 * Joins a number of strings together to form one long string, with the
 * @delim inserted between each of them. The returned string
 * should be freed with VIR_FREE().
 *
 * Returns: a newly-allocated string containing all of the strings joined
 *     together, with @delim between them
 */
148 149
char *virStringListJoin(const char **strings,
                        const char *delim)
150 151 152 153 154 155 156 157 158
{
    char *ret;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    while (*strings) {
        virBufferAdd(&buf, *strings, -1);
        if (*(strings+1))
            virBufferAdd(&buf, delim, -1);
        strings++;
    }
159
    if (virBufferCheckError(&buf) < 0)
160 161
        return NULL;
    ret = virBufferContentAndReset(&buf);
162 163
    if (!ret)
        ignore_value(VIR_STRDUP(ret, ""));
164 165 166 167
    return ret;
}


168 169 170 171 172
/**
 * virStringListAdd:
 * @strings: a NULL-terminated array of strings
 * @item: string to add
 *
M
Michal Privoznik 已提交
173 174 175 176 177
 * Appends @item into string list @strings. If *@strings is not
 * allocated yet new string list is created.
 *
 * Returns: 0 on success,
 *         -1 otherwise
178
 */
M
Michal Privoznik 已提交
179 180
int
virStringListAdd(char ***strings,
181 182
                 const char *item)
{
M
Michal Privoznik 已提交
183
    size_t i = virStringListLength((const char **) *strings);
184

M
Michal Privoznik 已提交
185 186 187
    if (VIR_EXPAND_N(*strings, i, 2) < 0 ||
        VIR_STRDUP((*strings)[i - 2], item) < 0)
        return -1;
188

M
Michal Privoznik 已提交
189
    return 0;
190 191 192
}


193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
/**
 * virStringListRemove:
 * @strings: a NULL-terminated array of strings
 * @item: string to remove
 *
 * Remove every occurrence of @item in list of @strings.
 */
void
virStringListRemove(char ***strings,
                    const char *item)
{
    size_t r, w = 0;

    if (!strings || !*strings)
        return;

    for (r = 0; (*strings)[r]; r++) {
        if (STREQ((*strings)[r], item)) {
            VIR_FREE((*strings)[r]);
            continue;
        }
        if (r != w)
            (*strings)[w] = (*strings)[r];
        w++;
    }

    if (w == 0) {
        VIR_FREE(*strings);
    } else {
        (*strings)[w] = NULL;
        ignore_value(VIR_REALLOC_N(*strings, w + 1));
    }
}


228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
/**
 * virStringListMerge:
 * @dst: a NULL-terminated array of strings to expand
 * @src: a NULL-terminated array of strings
 *
 * Merges @src into @dst. Upon successful return from this
 * function, @dst is resized to $(dst + src) elements and @src is
 * freed.
 *
 * Returns 0 on success, -1 otherwise.
 */
int
virStringListMerge(char ***dst,
                   char ***src)
{
    size_t dst_len, src_len, i;

    if (!src || !*src)
        return 0;

    dst_len = virStringListLength((const char **) *dst);
    src_len = virStringListLength((const char **) *src);

    if (VIR_REALLOC_N(*dst, dst_len + src_len + 1) < 0)
        return -1;

    for (i = 0; i <= src_len; i++)
        (*dst)[i + dst_len] = (*src)[i];

    /* Don't call virStringListFree() as it would free strings in
     * @src. */
    VIR_FREE(*src);
    return 0;
}


J
Jiri Denemark 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
/**
 * virStringListCopy:
 * @dst: where to store the copy of @strings
 * @src: a NULL-terminated array of strings
 *
 * Makes a deep copy of the @src string list and stores it in @dst. Callers
 * are responsible for freeing @dst.
 *
 * Returns 0 on success, -1 on error.
 */
int
virStringListCopy(char ***dst,
                  const char **src)
{
    char **copy = NULL;
    size_t i;

    *dst = NULL;

    if (!src)
        return 0;

    if (VIR_ALLOC_N(copy, virStringListLength(src) + 1) < 0)
        goto error;

    for (i = 0; src[i]; i++) {
        if (VIR_STRDUP(copy[i], src[i]) < 0)
            goto error;
    }

    *dst = copy;
    return 0;

 error:
    virStringListFree(copy);
    return -1;
}


303
/**
304
 * virStringListFree:
305
 * @strings: a NULL-terminated array of strings to free
306 307
 *
 * Frees a NULL-terminated array of strings, and the array itself.
308
 * If called on a NULL value, virStringListFree() simply returns.
309
 */
310
void virStringListFree(char **strings)
311 312 313 314 315 316 317 318
{
    char **tmp = strings;
    while (tmp && *tmp) {
        VIR_FREE(*tmp);
        tmp++;
    }
    VIR_FREE(strings);
}
319 320


321 322 323 324 325 326 327 328 329 330
void virStringListAutoFree(char ***strings)
{
    if (!*strings)
        return;

    virStringListFree(*strings);
    *strings = NULL;
}


331
/**
332
 * virStringListFreeCount:
333 334 335 336 337 338
 * @strings: array of strings to free
 * @count: number of elements in the array
 *
 * Frees a string array of @count length.
 */
void
339
virStringListFreeCount(char **strings,
340 341 342 343
                       size_t count)
{
    size_t i;

344 345 346
    if (!strings)
        return;

347 348 349 350 351 352 353
    for (i = 0; i < count; i++)
        VIR_FREE(strings[i]);

    VIR_FREE(strings);
}


354
bool
355 356
virStringListHasString(const char **strings,
                       const char *needle)
357 358 359
{
    size_t i = 0;

360 361 362
    if (!strings)
        return false;

363 364 365 366 367 368 369
    while (strings[i]) {
        if (STREQ(strings[i++], needle))
            return true;
    }

    return false;
}
370

371
char *
372 373
virStringListGetFirstWithPrefix(char **strings,
                                const char *prefix)
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
{
    size_t i = 0;

    if (!strings)
        return NULL;

    while (strings[i]) {
        if (STRPREFIX(strings[i], prefix))
            return strings[i] + strlen(prefix);
        i++;
    }

    return NULL;
}

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
/* Like strtol, but produce an "int" result, and check more carefully.
   Return 0 upon success;  return -1 to indicate failure.
   When END_PTR is NULL, the byte after the final valid digit must be NUL.
   Otherwise, it's like strtol and lets the caller check any suffix for
   validity.  This function is careful to return -1 when the string S
   represents a number that is not representable as an "int". */
int
virStrToLong_i(char const *s, char **end_ptr, int base, int *result)
{
    long int val;
    char *p;
    int err;

    errno = 0;
    val = strtol(s, &p, base); /* exempt from syntax-check */
    err = (errno || (!end_ptr && *p) || p == s || (int) val != val);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

413 414 415
/* Just like virStrToLong_i, above, but produce an "unsigned int"
 * value.  This version allows twos-complement wraparound of negative
 * numbers. */
416 417 418 419 420
int
virStrToLong_ui(char const *s, char **end_ptr, int base, unsigned int *result)
{
    unsigned long int val;
    char *p;
421
    bool err = false;
422 423 424

    errno = 0;
    val = strtoul(s, &p, base); /* exempt from syntax-check */
425 426 427 428 429 430 431 432 433 434 435 436 437

    /* This one's tricky.  We _want_ to allow "-1" as shorthand for
     * UINT_MAX regardless of whether long is 32-bit or 64-bit.  But
     * strtoul treats "-1" as ULONG_MAX, and going from ulong back
     * to uint differs depending on the size of long. */
    if (sizeof(long) > sizeof(int) && memchr(s, '-', p - s)) {
        if (-val > UINT_MAX)
            err = true;
        else
            val &= 0xffffffff;
    }

    err |= (errno || (!end_ptr && *p) || p == s || (unsigned int) val != val);
438 439 440 441 442 443 444 445
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
/* Just like virStrToLong_i, above, but produce an "unsigned int"
 * value.  This version rejects any negative signs.  */
int
virStrToLong_uip(char const *s, char **end_ptr, int base, unsigned int *result)
{
    unsigned long int val;
    char *p;
    bool err = false;

    errno = 0;
    val = strtoul(s, &p, base); /* exempt from syntax-check */
    err = (memchr(s, '-', p - s) ||
           errno || (!end_ptr && *p) || p == s || (unsigned int) val != val);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
/* Just like virStrToLong_i, above, but produce a "long" value.  */
int
virStrToLong_l(char const *s, char **end_ptr, int base, long *result)
{
    long int val;
    char *p;
    int err;

    errno = 0;
    val = strtol(s, &p, base); /* exempt from syntax-check */
    err = (errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

486 487 488
/* Just like virStrToLong_i, above, but produce an "unsigned long"
 * value.  This version allows twos-complement wraparound of negative
 * numbers. */
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
int
virStrToLong_ul(char const *s, char **end_ptr, int base, unsigned long *result)
{
    unsigned long int val;
    char *p;
    int err;

    errno = 0;
    val = strtoul(s, &p, base); /* exempt from syntax-check */
    err = (errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
/* Just like virStrToLong_i, above, but produce an "unsigned long"
 * value.  This version rejects any negative signs.  */
int
virStrToLong_ulp(char const *s, char **end_ptr, int base,
                 unsigned long *result)
{
    unsigned long int val;
    char *p;
    int err;

    errno = 0;
    val = strtoul(s, &p, base); /* exempt from syntax-check */
    err = (memchr(s, '-', p - s) ||
           errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
/* Just like virStrToLong_i, above, but produce a "long long" value.  */
int
virStrToLong_ll(char const *s, char **end_ptr, int base, long long *result)
{
    long long val;
    char *p;
    int err;

    errno = 0;
    val = strtoll(s, &p, base); /* exempt from syntax-check */
    err = (errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

548 549 550
/* Just like virStrToLong_i, above, but produce an "unsigned long
 * long" value.  This version allows twos-complement wraparound of
 * negative numbers. */
551
int
552 553
virStrToLong_ull(char const *s, char **end_ptr, int base,
                 unsigned long long *result)
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
{
    unsigned long long val;
    char *p;
    int err;

    errno = 0;
    val = strtoull(s, &p, base); /* exempt from syntax-check */
    err = (errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
/* Just like virStrToLong_i, above, but produce an "unsigned long
 * long" value.  This version rejects any negative signs.  */
int
virStrToLong_ullp(char const *s, char **end_ptr, int base,
                  unsigned long long *result)
{
    unsigned long long val;
    char *p;
    int err;

    errno = 0;
    val = strtoull(s, &p, base); /* exempt from syntax-check */
    err = (memchr(s, '-', p - s) ||
           errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

592 593 594
/* In case thread-safe locales are available */
#if HAVE_NEWLOCALE

595 596
typedef locale_t virLocale;
static virLocale virLocaleRaw;
597 598 599 600

static int
virLocaleOnceInit(void)
{
601 602
    virLocaleRaw = newlocale(LC_ALL_MASK, "C", (locale_t)0);
    if (!virLocaleRaw)
603 604 605 606 607
        return -1;
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virLocale);
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

/**
 * virLocaleSetRaw:
 *
 * @oldlocale: set to old locale pointer
 *
 * Sets the locale to 'C' to allow operating on non-localized objects.
 * Returns 0 on success -1 on error.
 */
static int
virLocaleSetRaw(virLocale *oldlocale)
{
    if (virLocaleInitialize() < 0)
        return -1;
    *oldlocale = uselocale(virLocaleRaw);
    return 0;
}

static void
virLocaleRevert(virLocale *oldlocale)
{
    uselocale(*oldlocale);
}

static void
virLocaleFixupRadix(char **strp ATTRIBUTE_UNUSED)
{
}

#else /* !HAVE_NEWLOCALE */

typedef int virLocale;

static int
virLocaleSetRaw(virLocale *oldlocale ATTRIBUTE_UNUSED)
{
    return 0;
}

static void
virLocaleRevert(virLocale *oldlocale ATTRIBUTE_UNUSED)
{
}

static void
virLocaleFixupRadix(char **strp)
{
    char *radix, *tmp;
    struct lconv *lc;

    lc = localeconv();
    radix = lc->decimal_point;
    tmp = strstr(*strp, radix);
    if (tmp) {
        *tmp = '.';
        if (strlen(radix) > 1)
            memmove(tmp + 1, tmp + strlen(radix), strlen(*strp) - (tmp - *strp));
    }
}

#endif /* !HAVE_NEWLOCALE */

670

671 672 673 674 675 676 677
/**
 * virStrToDouble
 *
 * converts string with C locale (thread-safe) to double.
 *
 * Returns -1 on error or returns 0 on success.
 */
678 679 680 681 682
int
virStrToDouble(char const *s,
               char **end_ptr,
               double *result)
{
683
    virLocale oldlocale;
684 685 686 687 688
    double val;
    char *p;
    int err;

    errno = 0;
689
    if (virLocaleSetRaw(&oldlocale) < 0)
690
        return -1;
691
    val = strtod(s, &p); /* exempt from syntax-check */
692 693
    virLocaleRevert(&oldlocale);

694 695 696 697 698 699 700 701 702
    err = (errno || (!end_ptr && *p) || p == s);
    if (end_ptr)
        *end_ptr = p;
    if (err)
        return -1;
    *result = val;
    return 0;
}

703 704 705 706 707 708 709 710 711 712
/**
 * virDoubleToStr
 *
 * converts double to string with C locale (thread-safe).
 *
 * Returns -1 on error, size of the string otherwise.
 */
int
virDoubleToStr(char **strp, double number)
{
713
    virLocale oldlocale;
714 715
    int ret = -1;

716 717
    if (virLocaleSetRaw(&oldlocale) < 0)
        return -1;
718 719 720

    ret = virAsprintf(strp, "%lf", number);

721 722
    virLocaleRevert(&oldlocale);
    virLocaleFixupRadix(strp);
723 724 725 726 727

    return ret;
}


728
int
729 730 731 732 733 734 735 736
virVasprintfInternal(bool report,
                     int domcode,
                     const char *filename,
                     const char *funcname,
                     size_t linenr,
                     char **strp,
                     const char *fmt,
                     va_list list)
737 738 739
{
    int ret;

740 741 742
    if ((ret = vasprintf(strp, fmt, list)) == -1) {
        if (report)
            virReportOOMErrorFull(domcode, filename, funcname, linenr);
743
        *strp = NULL;
744
    }
745 746 747 748
    return ret;
}

int
749 750 751 752 753 754 755
virAsprintfInternal(bool report,
                    int domcode,
                    const char *filename,
                    const char *funcname,
                    size_t linenr,
                    char **strp,
                    const char *fmt, ...)
756 757 758 759 760
{
    va_list ap;
    int ret;

    va_start(ap, fmt);
761 762
    ret = virVasprintfInternal(report, domcode, filename,
                               funcname, linenr, strp, fmt, ap);
763 764 765 766 767
    va_end(ap);
    return ret;
}

/**
768 769 770 771 772
 * virStrncpy:
 *
 * @dest: destination buffer
 * @src: source buffer
 * @n: number of bytes to copy
773
 * @destbytes: number of bytes the destination can accommodate
774 775 776 777 778 779 780 781
 *
 * Copies the first @n bytes of @src to @dest.
 *
 * @src must be NULL-terminated; if successful, @dest is guaranteed to
 * be NULL-terminated as well.
 *
 * @n must be a reasonable value, that is, it must not exceed either
 * the length of @src or the size of @dest. For the latter constraint,
782
 * the fact that @dest needs to accommodate a NULL byte in addition to
783 784 785 786 787 788
 * the bytes copied from @src must be taken into account.
 *
 * If you want to copy *all* of @src to @dest, use virStrcpy() or
 * virStrcpyStatic() instead.
 *
 * Returns: 0 on success, <0 on failure.
789
 */
790
int
791 792
virStrncpy(char *dest, const char *src, size_t n, size_t destbytes)
{
793 794 795 796 797 798 799 800 801 802
    size_t src_len = strlen(src);

    /* As a special case, -1 means "copy the entire string".
     *
     * This is to avoid calling strlen() twice, once in the virStrcpy()
     * wrapper and once here for bound checking purposes. */
    if (n == -1)
        n = src_len;

    if (n <= 0 || n > src_len || n > (destbytes - 1))
803
        return -1;
804

805
    memcpy(dest, src, n);
806 807
    dest[n] = '\0';

808
    return 0;
809 810 811
}

/**
812 813 814 815
 * virStrcpy:
 *
 * @dest: destination buffer
 * @src: source buffer
816
 * @destbytes: number of bytes the destination can accommodate
817 818 819 820 821 822
 *
 * Copies @src to @dest.
 *
 * See virStrncpy() for more information.
 *
 * Returns: 0 on success, <0 on failure.
823
 */
824
int
825 826
virStrcpy(char *dest, const char *src, size_t destbytes)
{
827
    return virStrncpy(dest, src, -1, destbytes);
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
}

/**
 * virSkipSpaces:
 * @str: pointer to the char pointer used
 *
 * Skip potential blanks, this includes space tabs, line feed,
 * carriage returns.
 */
void
virSkipSpaces(const char **str)
{
    const char *cur = *str;

    while (c_isspace(*cur))
        cur++;
    *str = cur;
}

/**
 * virSkipSpacesAndBackslash:
 * @str: pointer to the char pointer used
 *
 * Like virSkipSpaces, but also skip backslashes erroneously emitted
 * by xend
 */
void
virSkipSpacesAndBackslash(const char **str)
{
    const char *cur = *str;

    while (c_isspace(*cur) || *cur == '\\')
        cur++;
    *str = cur;
}

/**
 * virTrimSpaces:
 * @str: string to modify to remove all trailing spaces
 * @endp: track the end of the string
 *
 * If @endp is NULL on entry, then all spaces prior to the trailing
 * NUL in @str are removed, by writing NUL into the appropriate
 * location.  If @endp is non-NULL but points to a NULL pointer,
 * then all spaces prior to the trailing NUL in @str are removed,
 * NUL is written to the new string end, and endp is set to the
 * location of the (new) string end.  If @endp is non-NULL and
 * points to a non-NULL pointer, then that pointer is used as
 * the end of the string, endp is set to the (new) location, but
 * no NUL pointer is written into the string.
 */
void
virTrimSpaces(char *str, char **endp)
{
    char *end;

    if (!endp || !*endp)
        end = str + strlen(str);
    else
        end = *endp;
    while (end > str && c_isspace(end[-1]))
        end--;
    if (endp) {
        if (!*endp)
            *end = '\0';
        *endp = end;
    } else {
        *end = '\0';
    }
}

/**
 * virSkipSpacesBackwards:
 * @str: start of string
 * @endp: on entry, *endp must be NULL or a location within @str, on exit,
 * will be adjusted to skip trailing spaces, or to NULL if @str had nothing
 * but spaces.
 */
void
virSkipSpacesBackwards(const char *str, char **endp)
{
    /* Casting away const is safe, since virTrimSpaces does not
     * modify string with this particular usage.  */
    char *s = (char*) str;

    if (!*endp)
        *endp = s + strlen(s);
    virTrimSpaces(s, endp);
    if (s == *endp)
        *endp = NULL;
}

920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
/**
 * virStringIsEmpty:
 * @str: string to check
 *
 * Returns true if string is empty (may contain only whitespace) or NULL.
 */
bool
virStringIsEmpty(const char *str)
{
    if (!str)
        return true;

    virSkipSpaces(&str);
    return str[0] == '\0';
}

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
/**
 * virStrdup:
 * @dest: where to store duplicated string
 * @src: the source string to duplicate
 * @report: whether to report OOM error, if there is one
 * @domcode: error domain code
 * @filename: caller's filename
 * @funcname: caller's funcname
 * @linenr: caller's line number
 *
 * Wrapper over strdup, which reports OOM error if told so,
 * in which case callers wants to pass @domcode, @filename,
 * @funcname and @linenr which should represent location in
 * caller's body where virStrdup is called from. Consider
 * using VIR_STRDUP which sets these automatically.
 *
952
 * Returns: 0 for NULL src, 1 on successful copy, -1 otherwise.
953 954 955 956 957 958 959 960 961 962
 */
int
virStrdup(char **dest,
          const char *src,
          bool report,
          int domcode,
          const char *filename,
          const char *funcname,
          size_t linenr)
{
963
    *dest = NULL;
964 965
    if (!src)
        return 0;
966 967 968 969 970 971
    if (!(*dest = strdup(src))) {
        if (report)
            virReportOOMErrorFull(domcode, filename, funcname, linenr);
        return -1;
    }

972
    return 1;
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
}

/**
 * virStrndup:
 * @dest: where to store duplicated string
 * @src: the source string to duplicate
 * @n: how many bytes to copy
 * @report: whether to report OOM error, if there is one
 * @domcode: error domain code
 * @filename: caller's filename
 * @funcname: caller's funcname
 * @linenr: caller's line number
 *
 * Wrapper over strndup, which reports OOM error if told so,
 * in which case callers wants to pass @domcode, @filename,
 * @funcname and @linenr which should represent location in
 * caller's body where virStrndup is called from. Consider
 * using VIR_STRNDUP which sets these automatically.
 *
992 993 994
 * In case @n is smaller than zero, the whole @src string is
 * copied.
 *
995
 * Returns: 0 for NULL src, 1 on successful copy, -1 otherwise.
996 997 998 999
 */
int
virStrndup(char **dest,
           const char *src,
1000
           ssize_t n,
1001 1002 1003 1004 1005 1006
           bool report,
           int domcode,
           const char *filename,
           const char *funcname,
           size_t linenr)
{
1007
    *dest = NULL;
1008 1009
    if (!src)
        return 0;
1010 1011
    if (n < 0)
        n = strlen(src);
1012 1013 1014 1015 1016 1017
    if (!(*dest = strndup(src, n))) {
        if (report)
            virReportOOMErrorFull(domcode, filename, funcname, linenr);
        return -1;
    }

1018
   return 1;
1019
}
1020 1021


1022
size_t virStringListLength(const char * const *strings)
1023 1024 1025 1026 1027 1028 1029 1030
{
    size_t i = 0;

    while (strings && strings[i])
        i++;

    return i;
}
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059


/**
 * virStringSortCompare:
 *
 * A comparator function for sorting strings in
 * normal order with qsort().
 */
int virStringSortCompare(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;

    return strcmp(*sa, *sb);
}

/**
 * virStringSortRevCompare:
 *
 * A comparator function for sorting strings in
 * reverse order with qsort().
 */
int virStringSortRevCompare(const void *a, const void *b)
{
    const char **sa = (const char**)a;
    const char **sb = (const char**)b;

    return strcmp(*sb, *sa);
}
1060 1061 1062 1063 1064 1065

/**
 * virStringSearch:
 * @str: string to search
 * @regexp: POSIX Extended regular expression pattern used for matching
 * @max_matches: maximum number of substrings to return
1066
 * @matches: pointer to an array to be filled with NULL terminated list of matches
1067 1068
 *
 * Performs a POSIX extended regex search against a string and return all matching substrings.
1069
 * The @matches value should be freed with virStringListFree() when no longer
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
 * required.
 *
 * @code
 *  char *source = "6853a496-1c10-472e-867a-8244937bd6f0
 *                  773ab075-4cd7-4fc2-8b6e-21c84e9cb391
 *                  bbb3c75c-d60f-43b0-b802-fd56b84a4222
 *                  60c04aa1-0375-4654-8d9f-e149d9885273
 *                  4548d465-9891-4c34-a184-3b1c34a26aa8";
 *  char **matches = NULL;
 *  virStringSearch(source,
 *                  "([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})",
 *                  3,
 *                  &matches);
 *
 *  // matches[0] == "6853a496-1c10-472e-867a-8244937bd6f0";
 *  // matches[1] == "773ab075-4cd7-4fc2-8b6e-21c84e9cb391";
 *  // matches[2] == "bbb3c75c-d60f-43b0-b802-fd56b84a4222"
 *  // matches[3] == NULL;
 *
1089
 *  virStringListFree(matches);
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
 * @endcode
 *
 * Returns: -1 on error, or number of matches
 */
ssize_t
virStringSearch(const char *str,
                const char *regexp,
                size_t max_matches,
                char ***matches)
{
    regex_t re;
    regmatch_t rem;
    size_t nmatches = 0;
    ssize_t ret = -1;
    int rv = -1;

    *matches = NULL;

    VIR_DEBUG("search '%s' for '%s'", str, regexp);

    if ((rv = regcomp(&re, regexp, REG_EXTENDED)) != 0) {
        char error[100];
        regerror(rv, &re, error, sizeof(error));
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Error while compiling regular expression '%s': %s"),
                       regexp, error);
        return -1;
    }

    if (re.re_nsub != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Regular expression '%s' must have exactly 1 match group, not %zu"),
                       regexp, re.re_nsub);
        goto cleanup;
    }

    /* '*matches' must always be NULL terminated in every iteration
     * of the loop, so start by allocating 1 element
     */
    if (VIR_EXPAND_N(*matches, nmatches, 1) < 0)
        goto cleanup;

    while ((nmatches - 1) < max_matches) {
        char *match;

        if (regexec(&re, str, 1, &rem, 0) != 0)
            break;

        if (VIR_EXPAND_N(*matches, nmatches, 1) < 0)
            goto cleanup;

        if (VIR_STRNDUP(match, str + rem.rm_so,
                        rem.rm_eo - rem.rm_so) < 0)
            goto cleanup;

        VIR_DEBUG("Got '%s'", match);

        (*matches)[nmatches-2] = match;

        str = str + rem.rm_eo;
    }

    ret = nmatches - 1; /* don't count the trailing null */

1154
 cleanup:
1155 1156
    regfree(&re);
    if (ret < 0) {
1157
        virStringListFree(*matches);
1158 1159 1160 1161
        *matches = NULL;
    }
    return ret;
}
1162

P
Pavel Hrdina 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
/**
 * virStringMatch:
 * @str: string to match
 * @regexp: POSIX Extended regular expression pattern used for matching
 *
 * Performs a POSIX extended regex match against a string.
 * Returns true on match, false on error or no match.
 */
bool
virStringMatch(const char *str,
               const char *regexp)
{
    regex_t re;
    int rv;

    VIR_DEBUG("match '%s' for '%s'", str, regexp);

    if ((rv = regcomp(&re, regexp, REG_EXTENDED | REG_NOSUB)) != 0) {
        char error[100];
        regerror(rv, &re, error, sizeof(error));
        VIR_WARN("error while compiling regular expression '%s': %s",
                 regexp, error);
        return false;
    }

    rv = regexec(&re, str, 0, NULL, 0);

    regfree(&re);

    return rv == 0;
}

1195 1196 1197 1198 1199 1200
/**
 * virStringReplace:
 * @haystack: the source string to process
 * @oldneedle: the substring to locate
 * @newneedle: the substring to insert
 *
N
Nehal J Wani 已提交
1201
 * Search @haystack and replace all occurrences of @oldneedle with @newneedle.
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
 *
 * Returns: a new string with all the replacements, or NULL on error
 */
char *
virStringReplace(const char *haystack,
                 const char *oldneedle,
                 const char *newneedle)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    const char *tmp1, *tmp2;
    size_t oldneedlelen = strlen(oldneedle);
    size_t newneedlelen = strlen(newneedle);

    tmp1 = haystack;
    tmp2 = NULL;

    while (tmp1) {
        tmp2 = strstr(tmp1, oldneedle);

        if (tmp2) {
            virBufferAdd(&buf, tmp1, (tmp2 - tmp1));
            virBufferAdd(&buf, newneedle, newneedlelen);
            tmp2 += oldneedlelen;
        } else {
            virBufferAdd(&buf, tmp1, -1);
        }

        tmp1 = tmp2;
    }

1232
    if (virBufferCheckError(&buf) < 0)
1233 1234 1235 1236
        return NULL;

    return virBufferContentAndReset(&buf);
}
J
Ján Tomko 已提交
1237

1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
bool
virStringHasSuffix(const char *str,
                   const char *suffix)
{
    int len = strlen(str);
    int suffixlen = strlen(suffix);

    if (len < suffixlen)
        return false;

    return STREQ(str + len - suffixlen, suffix);
}

1251
bool
1252 1253 1254 1255 1256 1257 1258
virStringHasCaseSuffix(const char *str,
                       const char *suffix)
{
    int len = strlen(str);
    int suffixlen = strlen(suffix);

    if (len < suffixlen)
1259
        return false;
1260 1261 1262

    return STRCASEEQ(str + len - suffixlen, suffix);
}
J
Ján Tomko 已提交
1263

1264
bool
1265 1266 1267 1268 1269 1270 1271
virStringStripSuffix(char *str,
                     const char *suffix)
{
    int len = strlen(str);
    int suffixlen = strlen(suffix);

    if (len < suffixlen)
1272
        return false;
1273 1274

    if (STRNEQ(str + len - suffixlen, suffix))
1275
        return false;
1276 1277 1278

    str[len - suffixlen] = '\0';

1279
    return true;
1280 1281
}

1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
int
virStringMatchesNameSuffix(const char *file,
                           const char *name,
                           const char *suffix)
{
    int filelen = strlen(file);
    int namelen = strlen(name);
    int suffixlen = strlen(suffix);

    if (filelen == (namelen + suffixlen) &&
        STREQLEN(file, name, namelen) &&
        STREQLEN(file + namelen, suffix, suffixlen))
        return 1;
    else
        return 0;
}

J
Ján Tomko 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
/**
 * virStringStripIPv6Brackets:
 * @str: the string to strip
 *
 * Modify the string in-place to remove the leading and closing brackets
 * from an IPv6 address.
 */
void
virStringStripIPv6Brackets(char *str)
{
    size_t len;

    if (!str)
        return;

    len = strlen(str);
    if (str[0] == '[' && str[len - 1] == ']' && strchr(str, ':')) {
        memmove(&str[0], &str[1], len - 2);
        str[len - 2] = '\0';
    }
}
1320 1321


1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
/**
 * virStringHasChars:
 * @str: string to look for chars in
 * @chars: chars to find in string @str
 *
 * Returns true if @str contains any of the chars in @chars.
 */
bool
virStringHasChars(const char *str,
                  const char *chars)
{
    if (!str)
        return false;

    return str[strcspn(str, chars)] != '\0';
}


1340 1341 1342 1343 1344 1345 1346 1347 1348
static const char control_chars[] =
    "\x01\x02\x03\x04\x05\x06\x07"
    "\x08" /* \t \n */ "\x0B\x0C" /* \r */ "\x0E\x0F"
    "\x10\x11\x12\x13\x14\x15\x16\x17"
    "\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";

bool
virStringHasControlChars(const char *str)
{
1349
    return virStringHasChars(str, control_chars);
1350 1351 1352
}


1353
VIR_WARNINGS_NO_WLOGICALOP_STRCHR
1354 1355


1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
/**
 * virStringStripControlChars:
 * @str: the string to strip
 *
 * Modify the string in-place to remove the control characters
 * in the interval: [0x01, 0x20)
 */
void
virStringStripControlChars(char *str)
{
    size_t len, i, j;

    if (!str)
        return;

    len = strlen(str);
    for (i = 0, j = 0; i < len; i++) {
E
Eric Blake 已提交
1373
        if (strchr(control_chars, str[i]))
1374 1375 1376 1377 1378 1379
            continue;

        str[j++] = str[i];
    }
    str[j] = '\0';
}
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
/**
 * virStringFilterChars:
 * @str: the string to strip
 * @valid: the valid characters for the string
 *
 * Modify the string in-place to remove the characters that aren't
 * in the list of valid ones.
 */
void
virStringFilterChars(char *str, const char *valid)
{
    size_t len, i, j;

    if (!str)
        return;

    len = strlen(str);
    for (i = 0, j = 0; i < len; i++) {
        if (strchr(valid, str[i]))
            str[j++] = str[i];
    }
    str[j] = '\0';
}

1405 1406
/**
 * virStringToUpper:
1407
 * @src string to capitalize
1408 1409 1410 1411 1412
 * @dst: where to store the new capitalized string
 *
 * Capitalize the string with replacement of all '-' characters for '_'
 * characters. Caller frees the result.
 *
N
Nitesh Konkar 已提交
1413
 * Returns 0 if src is NULL, 1 if capitalization was successful, -1 on failure.
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
 */
int
virStringToUpper(char **dst, const char *src)
{
    char *cap = NULL;
    size_t i;

    if (!src)
        return 0;

    if (VIR_ALLOC_N(cap, strlen(src) + 1) < 0)
        return -1;

    for (i = 0; src[i]; i++) {
        cap[i] = c_toupper(src[i]);
        if (cap[i] == '-')
            cap[i] = '_';
    }

    *dst = cap;
    return 1;
}
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453


/**
 * virStringIsPrintable:
 *
 * Returns true @str contains only printable characters.
 */
bool
virStringIsPrintable(const char *str)
{
    size_t i;

    for (i = 0; str[i]; i++)
        if (!c_isprint(str[i]))
            return false;

    return true;
}
1454 1455


1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
/**
 * virBufferIsPrintable:
 *
 * Returns true if @buf of @buflen contains only printable characters
 */
bool
virStringBufferIsPrintable(const uint8_t *buf,
                           size_t buflen)
{
    size_t i;

    for (i = 0; i < buflen; i++)
        if (!c_isprint(buf[i]))
            return false;

    return true;
}


1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
/**
 * virStringEncodeBase64:
 * @buf: buffer of bytes to encode
 * @buflen: number of bytes to encode
 *
 * Encodes @buf to base 64 and returns the resulting string. The caller is
 * responsible for freeing the result.
 */
char *
virStringEncodeBase64(const uint8_t *buf, size_t buflen)
{
    char *ret;

    base64_encode_alloc((const char *) buf, buflen, &ret);
    if (!ret) {
        virReportOOMError();
        return NULL;
    }

    return ret;
}
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505

/**
 * virStringTrimOptionalNewline:
 * @str: the string to modify in-place
 *
 * Modify @str to remove a single '\n' character
 * from its end, if one exists.
 */
void virStringTrimOptionalNewline(char *str)
{
1506 1507 1508 1509 1510 1511 1512
    size_t len = strlen(str);

    if (!len)
        return;

    if (str[len - 1] == '\n')
        str[len - 1] = '\0';
1513
}
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525


/**
 * virStringParsePort:
 * @str: port number to parse
 * @port: pointer to parse port into
 *
 * Parses a string representation of a network port and validates it. Returns
 * 0 on success and -1 on error.
 */
int
virStringParsePort(const char *str,
1526
                   unsigned int *port)
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
{
    unsigned int p = 0;

    *port = 0;

    if (!str)
        return 0;

    if (virStrToLong_uip(str, NULL, 10, &p) < 0) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("failed to parse port number '%s'"), str);
        return -1;
    }

    if (p > UINT16_MAX) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("port '%s' out of range"), str);
        return -1;
    }

    *port = p;

    return 0;
}