1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 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 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 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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 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 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 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 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
|
/*
Copyright (C) CFEngine AS
This file is part of CFEngine 3 - written and maintained by CFEngine AS.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; version 3.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
To the extent this program is licensed as part of the Enterprise
versions of CFEngine, the applicable Commercial Open Source License
(COSL) may apply to this file if you as a licensee so wish it. See
included file COSL.txt.
*/
#include <platform.h>
#include <string_lib.h>
#include <openssl/buffer.h> /* BUF_MEM */
#include <openssl/bio.h> /* BIO_* */
#include <openssl/evp.h> /* BIO_f_base64 */
#include <alloc.h>
#include <writer.h>
#include <misc_lib.h>
#include <logging.h>
char *StringVFormat(const char *fmt, va_list ap)
{
char *value;
int ret = xvasprintf(&value, fmt, ap);
if (ret < 0)
{
return NULL;
}
else
{
return value;
}
}
char *StringFormat(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
char *res = StringVFormat(fmt, ap);
va_end(ap);
return res;
}
unsigned int StringHash(const char *str, unsigned int seed, unsigned int max)
{
unsigned const char *p = str;
unsigned int h = seed;
size_t len = strlen(str);
for (size_t i = 0; i < len; i++)
{
h += p[i];
h += (h << 10);
h ^= (h >> 6);
}
h += (h << 3);
h ^= (h >> 11);
h += (h << 15);
return (h & (max - 1));
}
char ToLower(char ch)
{
if (isupper((unsigned char) ch))
{
return (ch - 'A' + 'a');
}
else
{
return (ch);
}
}
/*********************************************************************/
char ToUpper(char ch)
{
if ((isdigit((unsigned char) ch)) || (ispunct((unsigned char) ch)))
{
return (ch);
}
if (isupper((unsigned char) ch))
{
return (ch);
}
else
{
return (ch - 'a' + 'A');
}
}
/*********************************************************************/
void ToUpperStrInplace(char *str)
{
for (; *str != '\0'; str++)
{
*str = ToUpper(*str);
}
}
/*********************************************************************/
void ToLowerStrInplace(char *str)
{
for (; *str != '\0'; str++)
{
*str = ToLower(*str);
}
}
/*********************************************************************/
char *SafeStringDuplicate(const char *str)
{
if (str == NULL)
{
return NULL;
}
return xstrdup(str);
}
/*********************************************************************/
int SafeStringLength(const char *str)
{
if (str == NULL)
{
return 0;
}
return strlen(str);
}
int StringSafeCompare(const char *a, const char *b)
{
if (a == b)
{
return 0;
}
if (a && b)
{
return strcmp(a, b);
}
if (a == NULL)
{
return -1;
}
assert(b == NULL);
return +1;
}
bool StringSafeEqual(const char *a, const char *b)
{
if (a == b)
{
return true;
}
if ((a == NULL) || (b == NULL))
{
return false;
}
return strcmp(a, b) == 0;
}
/*********************************************************************/
char *SearchAndReplace(const char *source, const char *search, const char *replace)
{
const char *source_ptr = source;
if ((source == NULL) || (search == NULL) || (replace == NULL))
{
ProgrammingError("Programming error: NULL argument is passed to SearchAndReplace");
}
if (strcmp(search, "") == 0)
{
return xstrdup(source);
}
Writer *w = StringWriter();
for (;;)
{
const char *found_ptr = strstr(source_ptr, search);
if (found_ptr == NULL)
{
WriterWrite(w, source_ptr);
return StringWriterClose(w);
}
WriterWriteLen(w, source_ptr, found_ptr - source_ptr);
WriterWrite(w, replace);
source_ptr += found_ptr - source_ptr + strlen(search);
}
}
/*********************************************************************/
char *StringConcatenate(size_t count, const char *first, ...)
{
if (count < 1)
{
return NULL;
}
size_t total_length = first ? strlen(first) : 0;
va_list args;
va_start(args, first);
for (size_t i = 1; i < count; i++)
{
const char *arg = va_arg(args, const char*);
if (arg)
{
total_length += strlen(arg);
}
}
va_end(args);
char *result = xcalloc(total_length + 1, sizeof(char));
if (first)
{
strcat(result, first);
}
va_start(args, first);
for (size_t i = 1; i < count; i++)
{
const char *arg = va_arg(args, const char *);
if (arg)
{
strcat(result, arg);
}
}
va_end(args);
return result;
}
/*********************************************************************/
char *StringSubstring(const char *source, size_t source_len, int start, int len)
{
size_t end = -1;
if (len == 0)
{
return SafeStringDuplicate("");
}
else if (len < 0)
{
end = source_len + len - 1;
}
else
{
end = start + len - 1;
}
end = MIN(end, source_len - 1);
if (start < 0)
{
start = source_len + start;
}
if (start >= end)
{
return NULL;
}
char *result = xcalloc(end - start + 2, sizeof(char));
memcpy(result, source + start, end - start + 1);
return result;
}
/*********************************************************************/
bool StringIsNumeric(const char *s)
{
for (; *s; s++)
{
if (!isdigit((unsigned char)*s))
{
return false;
}
}
return true;
}
bool StringIsPrintable(const char *s)
{
for (; *s; s++)
{
if (!isprint((unsigned char)*s))
{
return false;
}
}
return true;
}
bool EmptyString(const char *s)
{
const char *sp;
for (sp = s; *sp != '\0'; sp++)
{
if (!isspace((unsigned char)*sp))
{
return false;
}
}
return true;
}
/*********************************************************************/
long StringToLong(const char *str)
{
assert(str);
char *end;
long result = strtol(str, &end, 10);
assert(!*end && "Failed to convert string to long");
return result;
}
char *StringFromLong(long number)
{
char *str = xcalloc(32, sizeof(char));
snprintf(str, 32, "%ld", number);
return str;
}
/*********************************************************************/
double StringToDouble(const char *str)
{
assert(str);
char *end;
double result = strtod(str, &end);
assert(!*end && "Failed to convert string to double");
return result;
}
char *StringFromDouble(double number)
{
return StringFormat("%.2f", number);
}
/*********************************************************************/
char *NULLStringToEmpty(char *str)
{
if(!str)
{
return "";
}
return str;
}
/**
* @NOTE this function always '\0'-terminates the destination string #dst.
* @return length of written string #dst.
*/
size_t StringBytesToHex(char *dst, size_t dst_size,
const unsigned char *src_bytes, size_t src_len)
{
static const char *const hex_chars = "0123456789abcdef";
size_t i = 0;
while ((i < src_len) &&
(i*2 + 2 < dst_size)) /* room for 2 more hex chars */
{
dst[2*i] = hex_chars[(src_bytes[i] >> 4) & 0xf];
dst[2*i + 1] = hex_chars[src_bytes[i] & 0xf];
i++;
}
assert(2*i < dst_size);
dst[2*i] = '\0';
return 2*i;
}
bool IsStrIn(const char *str, const char *const strs[])
{
int i;
for (i = 0; strs[i]; ++i)
{
if (strcmp(str, strs[i]) == 0)
{
return true;
}
}
return false;
}
bool IsStrCaseIn(const char *str, const char *const strs[])
{
int i;
for (i = 0; strs[i]; ++i)
{
if (strcasecmp(str, strs[i]) == 0)
{
return true;
}
}
return false;
}
int CountChar(const char *string, char sep)
{
int count = 0;
if (string == NULL)
{
return 0;
}
if (string && (strlen(string) == 0))
{
return 0;
}
for (const char *sp = string; *sp != '\0'; sp++)
{
if ((*sp == '\\') && (*(sp + 1) == sep))
{
++sp;
}
else if (*sp == sep)
{
count++;
}
}
return count;
}
void ReplaceChar(char *in, char *out, int outSz, char from, char to)
/* Replaces all occurences of 'from' to 'to' in preallocated
* string 'out'. */
{
int len;
int i;
memset(out, 0, outSz);
len = strlen(in);
for (i = 0; (i < len) && (i < outSz - 1); i++)
{
if (in[i] == from)
{
out[i] = to;
}
else
{
out[i] = in[i];
}
}
}
/* TODO replace with StringReplace. This one is pretty slow, calls strncmp
* O(n) times even if string matches nowhere. */
bool ReplaceStr(const char *in, char *out, int outSz, const char *from, const char *to)
/* Replaces all occurences of strings 'from' to 'to' in preallocated
* string 'out'. Returns true on success, false otherwise. */
{
int inSz;
int outCount;
int inCount;
int fromSz, toSz;
memset(out, 0, outSz);
inSz = strlen(in);
fromSz = strlen(from);
toSz = strlen(to);
inCount = 0;
outCount = 0;
while ((inCount < inSz) && (outCount < outSz))
{
if (strncmp(in + inCount, from, fromSz) == 0)
{
if (outCount + toSz >= outSz)
{
return false;
}
strcat(out, to);
inCount += fromSz;
outCount += toSz;
}
else
{
out[outCount] = in[inCount];
inCount++;
outCount++;
}
}
return true;
}
void ReplaceTrailingChar(char *str, char from, char to)
/* Replaces any unwanted last char in str. */
{
int strLen;
strLen = SafeStringLength(str);
if (strLen == 0)
{
return;
}
if (str[strLen - 1] == from)
{
str[strLen - 1] = to;
}
}
static StringRef StringRefNull(void)
{
return (StringRef) { .data = NULL, .len = 0 };
}
size_t StringCountTokens(const char *str, size_t len, const char *seps)
{
size_t num_tokens = 0;
bool in_token = false;
for (size_t i = 0; i < len; i++)
{
if (strchr(seps, str[i]))
{
in_token = false;
}
else
{
if (!in_token)
{
num_tokens++;
}
in_token = true;
}
}
return num_tokens;
}
static StringRef StringNextToken(const char *str, size_t len, const char *seps)
{
size_t start = 0;
bool found = false;
for (size_t i = 0; i < len; i++)
{
if (strchr(seps, str[i]))
{
if (found)
{
assert(i > 0);
return (StringRef) { .data = str + start, .len = i - start };
}
}
else
{
if (!found)
{
found = true;
start = i;
}
}
}
if (found)
{
return (StringRef) { .data = str + start, .len = len - start };
}
else
{
return StringRefNull();
}
}
StringRef StringGetToken(const char *str, size_t len, size_t index, const char *seps)
{
StringRef ref = StringNextToken(str, len, seps);
for (size_t i = 0; i < index; i++)
{
if (!ref.data)
{
return ref;
}
len = len - (ref.data - str + ref.len);
str = ref.data + ref.len;
ref = StringNextToken(str, len, seps);
}
return ref;
}
char **String2StringArray(const char *str, char separator)
/**
* Parse CSVs into char **.
* MEMORY NOTE: Caller must free return value with FreeStringArray().
**/
{
int i = 0, len;
if (str == NULL)
{
return NULL;
}
for (const char *sp = str; *sp != '\0'; sp++)
{
if (*sp == separator)
{
i++;
}
}
char **arr = (char **) xcalloc(i + 2, sizeof(char *));
const char *sp = str;
i = 0;
while (sp)
{
const char *esp = strchr(sp, separator);
if (esp)
{
len = esp - sp;
esp++;
}
else
{
len = strlen(sp);
}
arr[i] = xcalloc(len + 1, sizeof(char));
memcpy(arr[i], sp, len);
sp = esp;
i++;
}
return arr;
}
void FreeStringArray(char **strs)
{
int i;
if (strs == NULL)
{
return;
}
for (i = 0; strs[i] != NULL; i++)
{
free(strs[i]);
strs[i] = NULL;
}
free(strs);
}
char *EscapeCharCopy(const char *str, char to_escape, char escape_with)
/*
* Escapes the 'to_escape'-chars found in str, by prefixing them with 'escape_with'.
* Returns newly allocated string.
*/
{
assert(str);
int in_size = strlen(str);
int out_size = in_size + CountChar(str, to_escape) + 1;
char *out = xcalloc(1, out_size);
const char *in_pos = str;
char *out_pos = out;
for(; *in_pos != '\0'; in_pos++, out_pos++)
{
if(*in_pos == to_escape)
{
*out_pos = escape_with;
out_pos++;
}
*out_pos = *in_pos;
}
return out;
}
int StringInArray(char **array, char *string)
{
for (int i = 0; array[i] != NULL; i++)
{
if (strcmp(string, array[i]) == 0)
{
return true;
}
}
return false;
}
char *ScanPastChars(char *scanpast, char *input)
{
char *pos = input;
while ((*pos != '\0') && (strchr(scanpast, *pos)))
{
pos++;
}
return pos;
}
int StripTrailingNewline(char *str, size_t max_length)
{
if (str)
{
size_t i = strnlen(str, max_length + 1);
if (i > max_length) /* See off-by-one comment below */
{
return -1;
}
while (i > 0 && str[i - 1] == '\n')
{
i--;
}
assert(str[i] == '\0' || str[i] == '\n');
str[i] = '\0';
}
return 0;
}
/* Off-by-one quirk in max_length.
*
* Both StripTrailngNewline() and Chop() have long allowed callers to
* pass (effectively) the strlen(str) rather than the size of memory
* (which is at least strlen() + 1) in the buffer. The present
* incarnation thus reads max_length as max-strlen(), not as size of
* the buffer. It may be sensible to review all callers and change so
* that max_length is the buffer size instead.
*
* TODO: assess practicality of that change in behaviour.
*/
int Chop(char *str, size_t max_length)
{
if (str)
{
size_t i = strnlen(str, max_length + 1);
if (i > max_length) /* See off-by-one comment above */
{
return -1;
}
while (i > 0 && isspace((unsigned char)str[i-1]))
{
i--;
}
assert(str[i] == '\0' || isspace((unsigned char)str[i]));
str[i] = '\0';
}
return 0;
}
bool StringEndsWith(const char *str, const char *suffix)
{
size_t str_len = strlen(str);
size_t suffix_len = strlen(suffix);
if (suffix_len > str_len)
{
return false;
}
for (size_t i = 0; i < suffix_len; i++)
{
if (str[str_len - i - 1] != suffix[suffix_len - i - 1])
{
return false;
}
}
return true;
}
bool StringStartsWith(const char *str, const char *prefix)
{
int str_len = strlen(str);
int prefix_len = strlen(prefix);
if (prefix_len > str_len)
{
return false;
}
for (int i = 0; i < prefix_len; i++)
{
if (str[i] != prefix[i])
{
return false;
}
}
return true;
}
void *MemSpan(const void *mem, char c, size_t n)
{
const char *end = mem + n;
for (; (char*)mem < end; ++mem)
{
if (*((char *)mem) != c)
{
return (char *)mem;
}
}
return (char *)mem;
}
void *MemSpanInverse(const void *mem, char c, size_t n)
{
const char *end = mem + n;
for (; (char*)mem < end; ++mem)
{
if (*((char*)mem) == c)
{
return (char *)mem;
}
}
return (char *)mem;
}
/*
* @brief extract info from input string given two types of constraints:
* - length of the extracted string is bounded
* - extracted string should stop at first element of an exclude list
*
* @param[in] isp : the string to scan
* @param[in] limit : size limit on the output string (including '\0')
* @param[in] exclude : characters to be excluded from output buffer
* @param[out] obuf : the output buffer
* @retval true if string was capped, false if not
*/
bool StringNotMatchingSetCapped(const char *isp, int limit,
const char *exclude, char *obuf)
{
size_t l = strcspn(isp, exclude);
if (l < limit-1)
{
memcpy(obuf, isp, l);
obuf[l]='\0';
return false;
}
else
{
memcpy(obuf, isp, limit-1);
obuf[limit-1]='\0';
return true;
}
}
bool StringAppend(char *dst, const char *src, size_t n)
{
int i, j;
n--;
for (i = 0; i < n && dst[i]; i++)
{
}
for (j = 0; i < n && src[j]; i++, j++)
{
dst[i] = src[j];
}
dst[i] = '\0';
return (i < n || !src[j]);
}
|