2 * Copyright (C) 2004-2013 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file string.c Memory allocation and string handling functions. */
10 #include <sys/utsname.h> /* uname() */
19 * Paraslash's version of realloc().
21 * \param p Pointer to the memory block, may be \p NULL.
22 * \param size The desired new size.
24 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
25 * i.e. there is no need to check the return value in the caller.
27 * \return A pointer to the newly allocated memory, which is suitably aligned
28 * for any kind of variable and may be different from \a p.
32 __must_check __malloc void *para_realloc(void *p, size_t size)
35 * No need to check for NULL pointers: If p is NULL, the call
36 * to realloc is equivalent to malloc(size)
39 if (!(p = realloc(p, size))) {
40 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
48 * Paraslash's version of malloc().
50 * \param size The desired new size.
52 * A wrapper for malloc(3) which exits on errors.
54 * \return A pointer to the allocated memory, which is suitably aligned for any
59 __must_check __malloc void *para_malloc(size_t size)
66 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
74 * Paraslash's version of calloc().
76 * \param size The desired new size.
78 * A wrapper for calloc(3) which exits on errors.
80 * \return A pointer to the allocated and zeroed-out memory, which is suitably
81 * aligned for any kind of variable.
85 __must_check __malloc void *para_calloc(size_t size)
87 void *ret = para_malloc(size);
94 * Paraslash's version of strdup().
96 * \param s The string to be duplicated.
98 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
99 * there is no need to check the return value in the caller.
101 * \return A pointer to the duplicated string. If \a s was the \p NULL pointer,
102 * an pointer to an empty string is returned.
106 __must_check __malloc char *para_strdup(const char *s)
110 if ((ret = strdup(s? s: "")))
112 PARA_EMERG_LOG("strdup failed, aborting\n");
117 * Print a formated message to a dynamically allocated string.
119 * \param result The formated string is returned here.
120 * \param fmt The format string.
121 * \param ap Initialized list of arguments.
123 * This function is similar to vasprintf(), a GNU extension which is not in C
124 * or POSIX. It allocates a string large enough to hold the output including
125 * the terminating null byte. The allocated string is returned via the first
126 * argument and must be freed by the caller. However, unlike vasprintf(), this
127 * function calls exit() if insufficient memory is available, while vasprintf()
128 * returns -1 in this case.
130 * \return Number of bytes written, not including the terminating \p NULL
133 * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
135 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
142 ret = vsnprintf(NULL, 0, fmt, aq);
146 *result = para_malloc(size);
148 ret = vsnprintf(*result, size, fmt, aq);
150 assert(ret >= 0 && ret < size);
155 * Print to a dynamically allocated string, variable number of arguments.
157 * \param result See \ref xvasprintf().
158 * \param fmt Usual format string.
160 * \return The return value of the underlying call to \ref xvasprintf().
162 * \sa \ref xvasprintf() and the references mentioned there.
164 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
170 ret = xvasprintf(result, fmt, ap);
176 * Allocate a sufficiently large string and print into it.
178 * \param fmt A usual format string.
180 * Produce output according to \p fmt. No artificial bound on the length of the
181 * resulting string is imposed.
183 * \return This function either returns a pointer to a string that must be
184 * freed by the caller or aborts without returning.
186 * \sa printf(3), xasprintf().
188 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
194 xvasprintf(&msg, fmt, ap);
200 * Free the content of a pointer and set it to \p NULL.
202 * This is equivalent to "free(*arg); *arg = NULL;".
204 * \param arg The pointer whose content should be freed.
206 void freep(void *arg)
208 void **ptr = (void **)arg;
214 * Paraslash's version of strcat().
216 * \param a String to be appended to.
217 * \param b String to append.
219 * Append \p b to \p a.
221 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
222 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
223 * return \a a without making a copy of \a a. Otherwise, construct the
224 * concatenation \a c, free \a a (but not \a b) and return \a c.
228 __must_check __malloc char *para_strcat(char *a, const char *b)
233 return para_strdup(b);
236 tmp = make_message("%s%s", a, b);
242 * Paraslash's version of dirname().
244 * \param name Pointer to the full path.
246 * Compute the directory component of \p name.
248 * \return If \a name is \p NULL or the empty string, return \p NULL.
249 * Otherwise, Make a copy of \a name and return its directory component. Caller
250 * is responsible to free the result.
252 __must_check __malloc char *para_dirname(const char *name)
258 ret = para_strdup(name);
259 p = strrchr(ret, '/');
268 * Paraslash's version of basename().
270 * \param name Pointer to the full path.
272 * Compute the filename component of \a name.
274 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
275 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
276 * must not free the result.
278 __must_check char *para_basename(const char *name)
284 ret = strrchr(name, '/');
292 * Cut trailing newline.
294 * \param buf The string to be chopped.
296 * Replace the last character in \p buf by zero if it is equal to
297 * the newline character.
305 if (buf[n - 1] == '\n')
310 * Get the logname of the current user.
312 * \return A dynamically allocated string that must be freed by the caller. On
313 * errors, the string "unknown_user" is returned, i.e. this function never
318 __must_check __malloc char *para_logname(void)
320 struct passwd *pw = getpwuid(getuid());
321 return para_strdup(pw? pw->pw_name : "unknown_user");
325 * Get the home directory of the current user.
327 * \return A dynamically allocated string that must be freed by the caller. If
328 * the home directory could not be found, this function returns "/tmp".
330 __must_check __malloc char *para_homedir(void)
332 struct passwd *pw = getpwuid(getuid());
333 return para_strdup(pw? pw->pw_dir : "/tmp");
337 * Get the own hostname.
339 * \return A dynamically allocated string containing the hostname.
343 __malloc char *para_hostname(void)
348 return para_strdup(u.nodename);
352 * Used to distinguish between read-only and read-write mode.
354 * \sa for_each_line(), for_each_line_ro().
356 enum for_each_line_modes{
357 /** Activate read-only mode. */
359 /** Activate read-write mode. */
363 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
364 size_t size, line_handler_t *line_handler, void *private_data)
366 char *start = buf, *end;
367 int ret, i, num_lines = 0;
369 // PARA_NOTICE_LOG("buf: %s\n", buf);
370 while (start < buf + size) {
374 next_cr = memchr(start, '\n', buf + size - start);
375 next_null = memchr(start, '\0', buf + size - start);
376 if (!next_cr && !next_null)
378 if (next_cr && next_null) {
379 end = next_cr < next_null? next_cr : next_null;
380 } else if (next_null) {
389 if (mode == LINE_MODE_RO) {
390 size_t s = end - start;
391 char *b = para_malloc(s + 1);
394 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
395 ret = line_handler(b, private_data);
399 ret = line_handler(start, private_data);
405 if (!line_handler || mode == LINE_MODE_RO)
407 i = buf + size - start;
409 memmove(buf, start, i);
414 * Call a custom function for each complete line.
416 * \param buf The buffer containing data separated by newlines.
417 * \param size The number of bytes in \a buf.
418 * \param line_handler The custom function.
419 * \param private_data Pointer passed to \a line_handler.
421 * If \p line_handler is \p NULL, the function returns the number of complete
422 * lines in \p buf. Otherwise, \p line_handler is called for each complete
423 * line in \p buf. The first argument to \p line_handler is the current line,
424 * and \p private_data is passed as the second argument. The function returns
425 * if \p line_handler returns a negative value or no more lines are in the
426 * buffer. The rest of the buffer (last chunk containing an incomplete line)
427 * is moved to the beginning of the buffer.
429 * \return If \p line_handler is not \p NULL, this function returns the number
430 * of bytes not handled to \p line_handler on success, or the negative return
431 * value of the \p line_handler on errors.
433 * \sa for_each_line_ro().
435 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
438 return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
443 * Call a custom function for each complete line.
445 * \param buf Same meaning as in \p for_each_line().
446 * \param size Same meaning as in \p for_each_line().
447 * \param line_handler Same meaning as in \p for_each_line().
448 * \param private_data Same meaning as in \p for_each_line().
450 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
452 * \return On success, the function returns the number of complete lines in \p
453 * buf, otherwise the (negative) return value of \p line_handler is returned.
455 * \sa for_each_line().
457 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
460 return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
464 /** Return the hex characters of the lower 4 bits. */
465 #define hex(a) (hexchar[(a) & 15])
467 static void write_size_header(char *buf, int n)
469 static char hexchar[] = "0123456789abcdef";
471 buf[0] = hex(n >> 12);
472 buf[1] = hex(n >> 8);
473 buf[2] = hex(n >> 4);
479 * Read a four-byte hex-number and return its value.
481 * Each status item sent by para_server is prefixed with such a hex number in
482 * ASCII which describes the size of the status item.
484 * \param buf The buffer which must be at least four bytes long.
486 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
487 * buffer did not contain only hex digits.
489 int read_size_header(const char *buf)
493 for (i = 0; i < 4; i++) {
494 unsigned char c = buf[i];
496 if (c >= '0' && c <= '9') {
500 if (c >= 'a' && c <= 'f') {
504 return -E_SIZE_PREFIX;
507 return -E_SIZE_PREFIX;
512 * Safely print into a buffer at a given offset.
514 * \param b Determines the buffer, its size, and the offset.
515 * \param fmt The format string.
517 * This function prints into the buffer given by \a b at the offset which is
518 * also given by \a b. If there is not enough space to hold the result, the
519 * buffer size is doubled until the underlying call to vsnprintf() succeeds
520 * or the size of the buffer exceeds the maximal size specified in \a b.
522 * In the latter case the unmodified \a buf and \a offset values as well as the
523 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
524 * If this function succeeds, i.e. returns a non-negative value, the offset of
525 * \a b is reset to zero and the given data is written to the beginning of the
526 * buffer. If \a max_size_handler() returns a negative value, this value is
527 * returned by \a para_printf().
529 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
530 * calls to this function append data to what is already contained in the
533 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
534 * initial buffer is allocated.
536 * \return The number of bytes printed into the buffer (not including the
537 * terminating \p NULL byte) on success, negative on errors. If there is no
538 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
541 * \sa make_message(), vsnprintf(3).
543 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
545 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
548 b->buf = para_malloc(128);
553 char *p = b->buf + b->offset;
554 size_t size = b->size - b->offset;
559 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
561 if (ret > -1 && ret < size - sz_off) { /* success */
562 b->offset += ret + sz_off;
564 write_size_header(p, ret);
568 /* check if we may grow the buffer */
569 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
570 /* try again with more space */
572 b->buf = para_realloc(b->buf, b->size);
575 /* can't grow buffer */
576 if (!b->offset || !b->max_size_handler) /* message too large */
577 return -ERRNO_TO_PARA_ERROR(ENOSPC);
578 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
585 /** \cond llong_minmax */
586 /* LLONG_MAX and LLONG_MIN might not be defined. */
588 #define LLONG_MAX 9223372036854775807LL
591 #define LLONG_MIN (-LLONG_MAX - 1LL)
593 /** \endcond llong_minmax */
596 * Convert a string to a 64-bit signed integer value.
598 * \param str The string to be converted.
599 * \param value Result pointer.
603 * \sa para_atoi32(), strtol(3), atoi(3).
605 int para_atoi64(const char *str, int64_t *value)
610 errno = 0; /* To distinguish success/failure after call */
611 tmp = strtoll(str, &endptr, 10);
612 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
613 return -E_ATOI_OVERFLOW;
614 if (errno != 0 && tmp == 0) /* other error */
617 return -E_ATOI_NO_DIGITS;
618 if (*endptr != '\0') /* Further characters after number */
619 return -E_ATOI_JUNK_AT_END;
625 * Convert a string to a 32-bit signed integer value.
627 * \param str The string to be converted.
628 * \param value Result pointer.
634 int para_atoi32(const char *str, int32_t *value)
638 const int32_t max = 2147483647;
640 ret = para_atoi64(str, &tmp);
643 if (tmp > max || tmp < -max - 1)
644 return -E_ATOI_OVERFLOW;
649 static inline int loglevel_equal(const char *arg, const char * const ll)
651 return !strncasecmp(arg, ll, strlen(ll));
655 * Compute the loglevel number from its name.
657 * \param txt The name of the loglevel (debug, info, ...).
659 * \return The numeric representation of the loglevel name.
661 int get_loglevel_by_name(const char *txt)
663 if (loglevel_equal(txt, "debug"))
665 if (loglevel_equal(txt, "info"))
667 if (loglevel_equal(txt, "notice"))
669 if (loglevel_equal(txt, "warning"))
671 if (loglevel_equal(txt, "error"))
673 if (loglevel_equal(txt, "crit"))
675 if (loglevel_equal(txt, "emerg"))
680 static int get_next_word(const char *buf, const char *delim, char **word)
682 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
683 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
688 out = para_malloc(strlen(buf) + 1);
691 for (in = buf; *in; in++) {
696 if (state & LSF_BACKSLASH) /* \\ */
698 state |= LSF_BACKSLASH;
699 state |= LSF_HAVE_WORD;
703 if (state & LSF_BACKSLASH) { /* \n or \t */
704 *out++ = (*in == 'n')? '\n' : '\t';
705 state &= ~LSF_BACKSLASH;
710 if (state & LSF_BACKSLASH) /* \" */
712 if (state & LSF_SINGLE_QUOTE) /* '" */
714 if (state & LSF_DOUBLE_QUOTE) {
715 state &= ~LSF_DOUBLE_QUOTE;
718 state |= LSF_HAVE_WORD;
719 state |= LSF_DOUBLE_QUOTE;
722 if (state & LSF_BACKSLASH) /* \' */
724 if (state & LSF_DOUBLE_QUOTE) /* "' */
726 if (state & LSF_SINGLE_QUOTE) {
727 state &= ~LSF_SINGLE_QUOTE;
730 state |= LSF_HAVE_WORD;
731 state |= LSF_SINGLE_QUOTE;
734 for (p = delim; *p; p++) {
737 if (state & LSF_BACKSLASH)
739 if (state & LSF_SINGLE_QUOTE)
741 if (state & LSF_DOUBLE_QUOTE)
743 if (state & LSF_HAVE_WORD)
747 if (*p) /* ignore delimiter at the beginning */
750 state |= LSF_HAVE_WORD;
752 state &= ~LSF_BACKSLASH;
755 if (!(state & LSF_HAVE_WORD))
757 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
758 if (state & LSF_BACKSLASH) {
759 PARA_ERROR_LOG("trailing backslash\n");
762 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
763 PARA_ERROR_LOG("unmatched quote character\n");
776 * Get the number of the word the cursor is on.
778 * \param buf The zero-terminated line buffer.
779 * \param delim Characters that separate words.
780 * \param point The cursor position.
782 * \return Zero-based word number.
784 int compute_word_num(const char *buf, const char *delim, int point)
790 for (p = buf, num_words = 0; ; p += ret, num_words++) {
791 ret = get_next_word(p, delim, &word);
795 if (p + ret >= buf + point)
802 * Free an array of words created by create_argv() or create_shifted_argv().
804 * \param argv A pointer previously obtained by \ref create_argv().
806 void free_argv(char **argv)
812 for (i = 0; argv[i]; i++)
817 static int create_argv_offset(int offset, const char *buf, const char *delim,
820 char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
824 for (i = 0; i < offset; i++)
826 for (p = buf; p && *p; p += ret, i++) {
827 ret = get_next_word(p, delim, &word);
832 argv = para_realloc(argv, (i + 2) * sizeof(char*));
847 * Split a buffer into words.
849 * This parser honors single and double quotes, backslash-escaped characters
850 * and special characters like \p \\n. The result contains pointers to copies
851 * of the words contained in \a buf and has to be freed by using \ref
854 * \param buf The buffer to be split.
855 * \param delim Each character in this string is treated as a separator.
856 * \param result The array of words is returned here.
858 * \return Number of words in \a buf, negative on errors.
860 int create_argv(const char *buf, const char *delim, char ***result)
862 return create_argv_offset(0, buf, delim, result);
866 * Split a buffer into words, offset one.
868 * This is similar to \ref create_argv() but the returned array is one element
869 * larger, words start at index one and element zero is initialized to \p NULL.
870 * Callers must set element zero to a non-NULL value before calling free_argv()
871 * on the returned array to avoid a memory leak.
873 * \param buf See \ref create_argv().
874 * \param delim See \ref create_argv().
875 * \param result See \ref create_argv().
877 * \return Number of words plus one on success, negative on errors.
879 int create_shifted_argv(const char *buf, const char *delim, char ***result)
881 return create_argv_offset(1, buf, delim, result);
885 * Find out if the given string is contained in the arg vector.
887 * \param arg The string to look for.
888 * \param argv The array to search.
890 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
891 * arg was not found in \a argv.
893 int find_arg(const char *arg, char **argv)
898 return -E_ARG_NOT_FOUND;
899 for (i = 0; argv[i]; i++)
900 if (strcmp(arg, argv[i]) == 0)
902 return -E_ARG_NOT_FOUND;
906 * Compile a regular expression.
908 * This simple wrapper calls regcomp() and logs a message on errors.
910 * \param preg See regcomp(3).
911 * \param regex See regcomp(3).
912 * \param cflags See regcomp(3).
916 int para_regcomp(regex_t *preg, const char *regex, int cflags)
920 int ret = regcomp(preg, regex, cflags);
924 size = regerror(ret, preg, NULL, 0);
925 buf = para_malloc(size);
926 regerror(ret, preg, buf, size);
927 PARA_ERROR_LOG("%s\n", buf);
933 * strdup() for not necessarily zero-terminated strings.
935 * \param src The source buffer.
936 * \param len The number of bytes to be copied.
938 * \return A 0-terminated buffer of length \a len + 1.
940 * This is similar to strndup(), which is a GNU extension. However, one
941 * difference is that strndup() returns \p NULL if insufficient memory was
942 * available while this function aborts in this case.
944 * \sa strdup(), \ref para_strdup().
946 char *safe_strdup(const char *src, size_t len)
950 assert(len < (size_t)-1);
951 p = para_malloc(len + 1);
959 * Copy the value of a key=value pair.
961 * This checks whether the given buffer starts with "key=", ignoring case. If
962 * yes, a copy of the value is returned. The source buffer may not be
965 * \param src The source buffer.
966 * \param len The number of bytes of the tag.
967 * \param key Only copy if it is the value of this key.
969 * \return A zero-terminated buffer, or \p NULL if the key was
970 * not of the given type.
972 char *key_value_copy(const char *src, size_t len, const char *key)
974 int keylen = strlen(key);
978 if (strncasecmp(src, key, keylen))
980 if (src[keylen] != '=')
982 return safe_strdup(src + keylen + 1, len - keylen - 1);