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. */
9 #include <sys/time.h> /* gettimeofday */
11 #include <sys/utsname.h> /* uname() */
20 * Paraslash's version of realloc().
22 * \param p Pointer to the memory block, may be \p NULL.
23 * \param size The desired new size.
25 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
26 * i.e. there is no need to check the return value in the caller.
28 * \return A pointer to the newly allocated memory, which is suitably aligned
29 * for any kind of variable and may be different from \a p.
33 __must_check __malloc void *para_realloc(void *p, size_t size)
36 * No need to check for NULL pointers: If p is NULL, the call
37 * to realloc is equivalent to malloc(size)
40 if (!(p = realloc(p, size))) {
41 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
49 * Paraslash's version of malloc().
51 * \param size The desired new size.
53 * A wrapper for malloc(3) which exits on errors.
55 * \return A pointer to the allocated memory, which is suitably aligned for any
60 __must_check __malloc void *para_malloc(size_t size)
67 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
75 * Paraslash's version of calloc().
77 * \param size The desired new size.
79 * A wrapper for calloc(3) which exits on errors.
81 * \return A pointer to the allocated and zeroed-out memory, which is suitably
82 * aligned for any kind of variable.
86 __must_check __malloc void *para_calloc(size_t size)
88 void *ret = para_malloc(size);
95 * Paraslash's version of strdup().
97 * \param s The string to be duplicated.
99 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
100 * there is no need to check the return value in the caller.
102 * \return A pointer to the duplicated string. If \a s was the \p NULL pointer,
103 * an pointer to an empty string is returned.
107 __must_check __malloc char *para_strdup(const char *s)
111 if ((ret = strdup(s? s: "")))
113 PARA_EMERG_LOG("strdup failed, aborting\n");
118 * Print a formated message to a dynamically allocated string.
120 * \param result The formated string is returned here.
121 * \param fmt The format string.
122 * \param ap Initialized list of arguments.
124 * This function is similar to vasprintf(), a GNU extension which is not in C
125 * or POSIX. It allocates a string large enough to hold the output including
126 * the terminating null byte. The allocated string is returned via the first
127 * argument and must be freed by the caller. However, unlike vasprintf(), this
128 * function calls exit() if insufficient memory is available, while vasprintf()
129 * returns -1 in this case.
131 * \return Number of bytes written, not including the terminating \p NULL
134 * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
136 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
143 ret = vsnprintf(NULL, 0, fmt, aq);
147 *result = para_malloc(size);
149 ret = vsnprintf(*result, size, fmt, aq);
151 assert(ret >= 0 && ret < size);
156 * Print to a dynamically allocated string, variable number of arguments.
158 * \param result See \ref xvasprintf().
159 * \param fmt Usual format string.
161 * \return The return value of the underlying call to \ref xvasprintf().
163 * \sa \ref xvasprintf() and the references mentioned there.
165 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
171 ret = xvasprintf(result, fmt, ap);
177 * Allocate a sufficiently large string and print into it.
179 * \param fmt A usual format string.
181 * Produce output according to \p fmt. No artificial bound on the length of the
182 * resulting string is imposed.
184 * \return This function either returns a pointer to a string that must be
185 * freed by the caller or aborts without returning.
187 * \sa printf(3), xasprintf().
189 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
195 xvasprintf(&msg, fmt, ap);
201 * Free the content of a pointer and set it to \p NULL.
203 * This is equivalent to "free(*arg); *arg = NULL;".
205 * \param arg The pointer whose content should be freed.
207 void freep(void *arg)
209 void **ptr = (void **)arg;
215 * Paraslash's version of strcat().
217 * \param a String to be appended to.
218 * \param b String to append.
220 * Append \p b to \p a.
222 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
223 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
224 * return \a a without making a copy of \a a. Otherwise, construct the
225 * concatenation \a c, free \a a (but not \a b) and return \a c.
229 __must_check __malloc char *para_strcat(char *a, const char *b)
234 return para_strdup(b);
237 tmp = make_message("%s%s", a, b);
243 * Paraslash's version of dirname().
245 * \param name Pointer to the full path.
247 * Compute the directory component of \p name.
249 * \return If \a name is \p NULL or the empty string, return \p NULL.
250 * Otherwise, Make a copy of \a name and return its directory component. Caller
251 * is responsible to free the result.
253 __must_check __malloc char *para_dirname(const char *name)
259 ret = para_strdup(name);
260 p = strrchr(ret, '/');
269 * Paraslash's version of basename().
271 * \param name Pointer to the full path.
273 * Compute the filename component of \a name.
275 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
276 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
277 * must not free the result.
279 __must_check char *para_basename(const char *name)
285 ret = strrchr(name, '/');
293 * Cut trailing newline.
295 * \param buf The string to be chopped.
297 * Replace the last character in \p buf by zero if it is equal to
298 * the newline character.
306 if (buf[n - 1] == '\n')
311 * Get the logname of the current user.
313 * \return A dynamically allocated string that must be freed by the caller. On
314 * errors, the string "unknown_user" is returned, i.e. this function never
319 __must_check __malloc char *para_logname(void)
321 struct passwd *pw = getpwuid(getuid());
322 return para_strdup(pw? pw->pw_name : "unknown_user");
326 * Get the home directory of the current user.
328 * \return A dynamically allocated string that must be freed by the caller. If
329 * the home directory could not be found, this function returns "/tmp".
331 __must_check __malloc char *para_homedir(void)
333 struct passwd *pw = getpwuid(getuid());
334 return para_strdup(pw? pw->pw_dir : "/tmp");
338 * Get the own hostname.
340 * \return A dynamically allocated string containing the hostname.
344 __malloc char *para_hostname(void)
349 return para_strdup(u.nodename);
353 * Controls behavior of for_each_complete_line().
355 * \sa for_each_line(), for_each_line_ro().
357 enum for_each_line_flags {
358 /** Activate read-only mode. */
359 FELF_READ_ONLY = 1 << 0,
362 static int for_each_complete_line(unsigned flags, char *buf,
363 size_t size, line_handler_t *line_handler, void *private_data)
365 char *start = buf, *end;
366 int ret, i, num_lines = 0;
368 // PARA_NOTICE_LOG("buf: %s\n", buf);
369 while (start < buf + size) {
373 next_cr = memchr(start, '\n', buf + size - start);
374 next_null = memchr(start, '\0', buf + size - start);
375 if (!next_cr && !next_null)
377 if (next_cr && next_null) {
378 end = next_cr < next_null? next_cr : next_null;
379 } else if (next_null) {
388 if (flags & FELF_READ_ONLY) {
389 size_t s = end - start;
390 char *b = para_malloc(s + 1);
393 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
394 ret = line_handler(b, private_data);
398 ret = line_handler(start, private_data);
404 if (!line_handler || (flags & FELF_READ_ONLY))
406 i = buf + size - start;
408 memmove(buf, start, i);
413 * Call a custom function for each complete line.
415 * \param buf The buffer containing data separated by newlines.
416 * \param size The number of bytes in \a buf.
417 * \param line_handler The custom function.
418 * \param private_data Pointer passed to \a line_handler.
420 * If \p line_handler is \p NULL, the function returns the number of complete
421 * lines in \p buf. Otherwise, \p line_handler is called for each complete
422 * line in \p buf. The first argument to \p line_handler is the current line,
423 * and \p private_data is passed as the second argument. The function returns
424 * if \p line_handler returns a negative value or no more lines are in the
425 * buffer. The rest of the buffer (last chunk containing an incomplete line)
426 * is moved to the beginning of the buffer.
428 * \return If \p line_handler is not \p NULL, this function returns the number
429 * of bytes not handled to \p line_handler on success, or the negative return
430 * value of the \p line_handler on errors.
432 * \sa for_each_line_ro().
434 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
437 return for_each_complete_line(0, buf, size, line_handler, private_data);
441 * Call a custom function for each complete line.
443 * \param buf Same meaning as in \p for_each_line().
444 * \param size Same meaning as in \p for_each_line().
445 * \param line_handler Same meaning as in \p for_each_line().
446 * \param private_data Same meaning as in \p for_each_line().
448 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
450 * \return On success, the function returns the number of complete lines in \p
451 * buf, otherwise the (negative) return value of \p line_handler is returned.
453 * \sa for_each_line().
455 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
458 return for_each_complete_line(FELF_READ_ONLY, buf, size, line_handler,
462 /** Return the hex characters of the lower 4 bits. */
463 #define hex(a) (hexchar[(a) & 15])
465 static void write_size_header(char *buf, int n)
467 static char hexchar[] = "0123456789abcdef";
469 buf[0] = hex(n >> 12);
470 buf[1] = hex(n >> 8);
471 buf[2] = hex(n >> 4);
477 * Read a four-byte hex-number and return its value.
479 * Each status item sent by para_server is prefixed with such a hex number in
480 * ASCII which describes the size of the status item.
482 * \param buf The buffer which must be at least four bytes long.
484 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
485 * buffer did not contain only hex digits.
487 int read_size_header(const char *buf)
491 for (i = 0; i < 4; i++) {
492 unsigned char c = buf[i];
494 if (c >= '0' && c <= '9') {
498 if (c >= 'a' && c <= 'f') {
502 return -E_SIZE_PREFIX;
505 return -E_SIZE_PREFIX;
510 * Safely print into a buffer at a given offset.
512 * \param b Determines the buffer, its size, and the offset.
513 * \param fmt The format string.
515 * This function prints into the buffer given by \a b at the offset which is
516 * also given by \a b. If there is not enough space to hold the result, the
517 * buffer size is doubled until the underlying call to vsnprintf() succeeds
518 * or the size of the buffer exceeds the maximal size specified in \a b.
520 * In the latter case the unmodified \a buf and \a offset values as well as the
521 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
522 * If this function succeeds, i.e. returns a non-negative value, the offset of
523 * \a b is reset to zero and the given data is written to the beginning of the
524 * buffer. If \a max_size_handler() returns a negative value, this value is
525 * returned by \a para_printf().
527 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
528 * calls to this function append data to what is already contained in the
531 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
532 * initial buffer is allocated.
534 * \return The number of bytes printed into the buffer (not including the
535 * terminating \p NULL byte) on success, negative on errors. If there is no
536 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
539 * \sa make_message(), vsnprintf(3).
541 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
543 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
546 b->buf = para_malloc(128);
551 char *p = b->buf + b->offset;
552 size_t size = b->size - b->offset;
557 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
559 if (ret > -1 && ret < size - sz_off) { /* success */
560 b->offset += ret + sz_off;
562 write_size_header(p, ret);
566 /* check if we may grow the buffer */
567 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
568 /* try again with more space */
570 b->buf = para_realloc(b->buf, b->size);
573 /* can't grow buffer */
574 if (!b->offset || !b->max_size_handler) /* message too large */
575 return -ERRNO_TO_PARA_ERROR(ENOSPC);
576 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
583 /** \cond llong_minmax */
584 /* LLONG_MAX and LLONG_MIN might not be defined. */
586 #define LLONG_MAX 9223372036854775807LL
589 #define LLONG_MIN (-LLONG_MAX - 1LL)
591 /** \endcond llong_minmax */
594 * Convert a string to a 64-bit signed integer value.
596 * \param str The string to be converted.
597 * \param value Result pointer.
601 * \sa para_atoi32(), strtol(3), atoi(3).
603 int para_atoi64(const char *str, int64_t *value)
608 errno = 0; /* To distinguish success/failure after call */
609 tmp = strtoll(str, &endptr, 10);
610 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
611 return -E_ATOI_OVERFLOW;
612 if (errno != 0 && tmp == 0) /* other error */
615 return -E_ATOI_NO_DIGITS;
616 if (*endptr != '\0') /* Further characters after number */
617 return -E_ATOI_JUNK_AT_END;
623 * Convert a string to a 32-bit signed integer value.
625 * \param str The string to be converted.
626 * \param value Result pointer.
632 int para_atoi32(const char *str, int32_t *value)
636 const int32_t max = 2147483647;
638 ret = para_atoi64(str, &tmp);
641 if (tmp > max || tmp < -max - 1)
642 return -E_ATOI_OVERFLOW;
647 static inline int loglevel_equal(const char *arg, const char * const ll)
649 return !strncasecmp(arg, ll, strlen(ll));
653 * Compute the loglevel number from its name.
655 * \param txt The name of the loglevel (debug, info, ...).
657 * \return The numeric representation of the loglevel name.
659 int get_loglevel_by_name(const char *txt)
661 if (loglevel_equal(txt, "debug"))
663 if (loglevel_equal(txt, "info"))
665 if (loglevel_equal(txt, "notice"))
667 if (loglevel_equal(txt, "warning"))
669 if (loglevel_equal(txt, "error"))
671 if (loglevel_equal(txt, "crit"))
673 if (loglevel_equal(txt, "emerg"))
678 static int get_next_word(const char *buf, const char *delim, char **word)
680 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
681 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
686 out = para_malloc(strlen(buf) + 1);
689 for (in = buf; *in; in++) {
694 if (state & LSF_BACKSLASH) /* \\ */
696 state |= LSF_BACKSLASH;
697 state |= LSF_HAVE_WORD;
701 if (state & LSF_BACKSLASH) { /* \n or \t */
702 *out++ = (*in == 'n')? '\n' : '\t';
703 state &= ~LSF_BACKSLASH;
708 if (state & LSF_BACKSLASH) /* \" */
710 if (state & LSF_SINGLE_QUOTE) /* '" */
712 if (state & LSF_DOUBLE_QUOTE) {
713 state &= ~LSF_DOUBLE_QUOTE;
716 state |= LSF_HAVE_WORD;
717 state |= LSF_DOUBLE_QUOTE;
720 if (state & LSF_BACKSLASH) /* \' */
722 if (state & LSF_DOUBLE_QUOTE) /* "' */
724 if (state & LSF_SINGLE_QUOTE) {
725 state &= ~LSF_SINGLE_QUOTE;
728 state |= LSF_HAVE_WORD;
729 state |= LSF_SINGLE_QUOTE;
732 for (p = delim; *p; p++) {
735 if (state & LSF_BACKSLASH)
737 if (state & LSF_SINGLE_QUOTE)
739 if (state & LSF_DOUBLE_QUOTE)
741 if (state & LSF_HAVE_WORD)
745 if (*p) /* ignore delimiter at the beginning */
748 state |= LSF_HAVE_WORD;
750 state &= ~LSF_BACKSLASH;
753 if (!(state & LSF_HAVE_WORD))
755 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
756 if (state & LSF_BACKSLASH) {
757 PARA_ERROR_LOG("trailing backslash\n");
760 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
761 PARA_ERROR_LOG("unmatched quote character\n");
774 * Get the number of the word the cursor is on.
776 * \param buf The zero-terminated line buffer.
777 * \param delim Characters that separate words.
778 * \param point The cursor position.
780 * \return Zero-based word number.
782 int compute_word_num(const char *buf, const char *delim, int point)
788 for (p = buf, num_words = 0; ; p += ret, num_words++) {
789 ret = get_next_word(p, delim, &word);
793 if (p + ret >= buf + point)
800 * Free an array of words created by create_argv() or create_shifted_argv().
802 * \param argv A pointer previously obtained by \ref create_argv().
804 void free_argv(char **argv)
810 for (i = 0; argv[i]; i++)
815 static int create_argv_offset(int offset, const char *buf, const char *delim,
818 char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
822 for (i = 0; i < offset; i++)
824 for (p = buf; p && *p; p += ret, i++) {
825 ret = get_next_word(p, delim, &word);
830 argv = para_realloc(argv, (i + 2) * sizeof(char*));
845 * Split a buffer into words.
847 * This parser honors single and double quotes, backslash-escaped characters
848 * and special characters like \p \\n. The result contains pointers to copies
849 * of the words contained in \a buf and has to be freed by using \ref
852 * \param buf The buffer to be split.
853 * \param delim Each character in this string is treated as a separator.
854 * \param result The array of words is returned here.
856 * \return Number of words in \a buf, negative on errors.
858 int create_argv(const char *buf, const char *delim, char ***result)
860 return create_argv_offset(0, buf, delim, result);
864 * Split a buffer into words, offset one.
866 * This is similar to \ref create_argv() but the returned array is one element
867 * larger, words start at index one and element zero is initialized to \p NULL.
868 * Callers must set element zero to a non-NULL value before calling free_argv()
869 * on the returned array to avoid a memory leak.
871 * \param buf See \ref create_argv().
872 * \param delim See \ref create_argv().
873 * \param result See \ref create_argv().
875 * \return Number of words plus one on success, negative on errors.
877 int create_shifted_argv(const char *buf, const char *delim, char ***result)
879 return create_argv_offset(1, buf, delim, result);
883 * Find out if the given string is contained in the arg vector.
885 * \param arg The string to look for.
886 * \param argv The array to search.
888 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
889 * arg was not found in \a argv.
891 int find_arg(const char *arg, char **argv)
896 return -E_ARG_NOT_FOUND;
897 for (i = 0; argv[i]; i++)
898 if (strcmp(arg, argv[i]) == 0)
900 return -E_ARG_NOT_FOUND;
904 * Compile a regular expression.
906 * This simple wrapper calls regcomp() and logs a message on errors.
908 * \param preg See regcomp(3).
909 * \param regex See regcomp(3).
910 * \param cflags See regcomp(3).
914 int para_regcomp(regex_t *preg, const char *regex, int cflags)
918 int ret = regcomp(preg, regex, cflags);
922 size = regerror(ret, preg, NULL, 0);
923 buf = para_malloc(size);
924 regerror(ret, preg, buf, size);
925 PARA_ERROR_LOG("%s\n", buf);
931 * strdup() for not necessarily zero-terminated strings.
933 * \param src The source buffer.
934 * \param len The number of bytes to be copied.
936 * \return A 0-terminated buffer of length \a len + 1.
938 * This is similar to strndup(), which is a GNU extension. However, one
939 * difference is that strndup() returns \p NULL if insufficient memory was
940 * available while this function aborts in this case.
942 * \sa strdup(), \ref para_strdup().
944 char *safe_strdup(const char *src, size_t len)
948 assert(len < (size_t)-1);
949 p = para_malloc(len + 1);
957 * Copy the value of a key=value pair.
959 * This checks whether the given buffer starts with "key=", ignoring case. If
960 * yes, a copy of the value is returned. The source buffer may not be
963 * \param src The source buffer.
964 * \param len The number of bytes of the tag.
965 * \param key Only copy if it is the value of this key.
967 * \return A zero-terminated buffer, or \p NULL if the key was
968 * not of the given type.
970 char *key_value_copy(const char *src, size_t len, const char *key)
972 int keylen = strlen(key);
976 if (strncasecmp(src, key, keylen))
978 if (src[keylen] != '=')
980 return safe_strdup(src + keylen + 1, len - keylen - 1);