2 * Copyright (C) 2004-2012 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 * Allocate a sufficiently large string and print into it.
120 * \param fmt A usual format string.
122 * Produce output according to \p fmt. No artificial bound on the length of the
123 * resulting string is imposed.
125 * \return This function either returns a pointer to a string that must be
126 * freed by the caller or aborts without returning.
130 __must_check __printf_1_2 __malloc
char *make_message(const char *fmt
, ...)
134 PARA_VSPRINTF(fmt
, msg
);
139 * Free the content of a pointer and set it to \p NULL.
141 * This is equivalent to "free(*arg); *arg = NULL;".
143 * \param arg The pointer whose content should be freed.
145 void freep(void *arg
)
147 void **ptr
= (void **)arg
;
153 * Paraslash's version of strcat().
155 * \param a String to be appended to.
156 * \param b String to append.
158 * Append \p b to \p a.
160 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
161 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
162 * return \a a without making a copy of \a a. Otherwise, construct the
163 * concatenation \a c, free \a a (but not \a b) and return \a c.
167 __must_check __malloc
char *para_strcat(char *a
, const char *b
)
172 return para_strdup(b
);
175 tmp
= make_message("%s%s", a
, b
);
181 * Paraslash's version of dirname().
183 * \param name Pointer to the full path.
185 * Compute the directory component of \p name.
187 * \return If \a name is \p NULL or the empty string, return \p NULL.
188 * Otherwise, Make a copy of \a name and return its directory component. Caller
189 * is responsible to free the result.
191 __must_check __malloc
char *para_dirname(const char *name
)
197 ret
= para_strdup(name
);
198 p
= strrchr(ret
, '/');
207 * Paraslash's version of basename().
209 * \param name Pointer to the full path.
211 * Compute the filename component of \a name.
213 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
214 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
215 * must not free the result.
217 __must_check
char *para_basename(const char *name
)
223 ret
= strrchr(name
, '/');
231 * Cut trailing newline.
233 * \param buf The string to be chopped.
235 * Replace the last character in \p buf by zero if it is equal to
236 * the newline character.
244 if (buf
[n
- 1] == '\n')
249 * Get the logname of the current user.
251 * \return A dynamically allocated string that must be freed by the caller. On
252 * errors, the string "unknown_user" is returned, i.e. this function never
257 __must_check __malloc
char *para_logname(void)
259 struct passwd
*pw
= getpwuid(getuid());
260 return para_strdup(pw
? pw
->pw_name
: "unknown_user");
264 * Get the home directory of the current user.
266 * \return A dynamically allocated string that must be freed by the caller. If
267 * the home directory could not be found, this function returns "/tmp".
269 __must_check __malloc
char *para_homedir(void)
271 struct passwd
*pw
= getpwuid(getuid());
272 return para_strdup(pw
? pw
->pw_dir
: "/tmp");
276 * Get the own hostname.
278 * \return A dynamically allocated string containing the hostname.
282 __malloc
char *para_hostname(void)
287 return para_strdup(u
.nodename
);
291 * Used to distinguish between read-only and read-write mode.
293 * \sa for_each_line(), for_each_line_ro().
295 enum for_each_line_modes
{
296 /** Activate read-only mode. */
298 /** Activate read-write mode. */
302 static int for_each_complete_line(enum for_each_line_modes mode
, char *buf
,
303 size_t size
, line_handler_t
*line_handler
, void *private_data
)
305 char *start
= buf
, *end
;
306 int ret
, i
, num_lines
= 0;
308 // PARA_NOTICE_LOG("buf: %s\n", buf);
309 while (start
< buf
+ size
) {
313 next_cr
= memchr(start
, '\n', buf
+ size
- start
);
314 next_null
= memchr(start
, '\0', buf
+ size
- start
);
315 if (!next_cr
&& !next_null
)
317 if (next_cr
&& next_null
) {
318 end
= next_cr
< next_null
? next_cr
: next_null
;
319 } else if (next_null
) {
328 if (mode
== LINE_MODE_RO
) {
329 size_t s
= end
- start
;
330 char *b
= para_malloc(s
+ 1);
333 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
334 ret
= line_handler(b
, private_data
);
338 ret
= line_handler(start
, private_data
);
344 if (!line_handler
|| mode
== LINE_MODE_RO
)
346 i
= buf
+ size
- start
;
348 memmove(buf
, start
, i
);
353 * Call a custom function for each complete line.
355 * \param buf The buffer containing data separated by newlines.
356 * \param size The number of bytes in \a buf.
357 * \param line_handler The custom function.
358 * \param private_data Pointer passed to \a line_handler.
360 * If \p line_handler is \p NULL, the function returns the number of complete
361 * lines in \p buf. Otherwise, \p line_handler is called for each complete
362 * line in \p buf. The first argument to \p line_handler is the current line,
363 * and \p private_data is passed as the second argument. The function returns
364 * if \p line_handler returns a negative value or no more lines are in the
365 * buffer. The rest of the buffer (last chunk containing an incomplete line)
366 * is moved to the beginning of the buffer.
368 * \return If \p line_handler is not \p NULL, this function returns the number
369 * of bytes not handled to \p line_handler on success, or the negative return
370 * value of the \p line_handler on errors.
372 * \sa for_each_line_ro().
374 int for_each_line(char *buf
, size_t size
, line_handler_t
*line_handler
,
377 return for_each_complete_line(LINE_MODE_RW
, buf
, size
, line_handler
,
382 * Call a custom function for each complete line.
384 * \param buf Same meaning as in \p for_each_line().
385 * \param size Same meaning as in \p for_each_line().
386 * \param line_handler Same meaning as in \p for_each_line().
387 * \param private_data Same meaning as in \p for_each_line().
389 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
391 * \return On success, the function returns the number of complete lines in \p
392 * buf, otherwise the (negative) return value of \p line_handler is returned.
394 * \sa for_each_line().
396 int for_each_line_ro(char *buf
, size_t size
, line_handler_t
*line_handler
,
399 return for_each_complete_line(LINE_MODE_RO
, buf
, size
, line_handler
,
403 /** Return the hex characters of the lower 4 bits. */
404 #define hex(a) (hexchar[(a) & 15])
406 static void write_size_header(char *buf
, int n
)
408 static char hexchar
[] = "0123456789abcdef";
410 buf
[0] = hex(n
>> 12);
411 buf
[1] = hex(n
>> 8);
412 buf
[2] = hex(n
>> 4);
418 * Read a four-byte hex-number and return its value.
420 * Each status item sent by para_server is prefixed with such a hex number in
421 * ASCII which describes the size of the status item.
423 * \param buf The buffer which must be at least four bytes long.
425 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
426 * buffer did not contain only hex digits.
428 int read_size_header(const char *buf
)
432 for (i
= 0; i
< 4; i
++) {
433 unsigned char c
= buf
[i
];
435 if (c
>= '0' && c
<= '9') {
439 if (c
>= 'a' && c
<= 'f') {
443 return -E_SIZE_PREFIX
;
446 return -E_SIZE_PREFIX
;
451 * Safely print into a buffer at a given offset.
453 * \param b Determines the buffer, its size, and the offset.
454 * \param fmt The format string.
456 * This function prints into the buffer given by \a b at the offset which is
457 * also given by \a b. If there is not enough space to hold the result, the
458 * buffer size is doubled until the underlying call to vsnprintf() succeeds
459 * or the size of the buffer exceeds the maximal size specified in \a b.
461 * In the latter case the unmodified \a buf and \a offset values as well as the
462 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
463 * If this function succeeds, i.e. returns a non-negative value, the offset of
464 * \a b is reset to zero and the given data is written to the beginning of the
465 * buffer. If \a max_size_handler() returns a negative value, this value is
466 * returned by \a para_printf().
468 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
469 * calls to this function append data to what is already contained in the
472 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
473 * initial buffer is allocated.
475 * \return The number of bytes printed into the buffer (not including the
476 * terminating \p NULL byte) on success, negative on errors. If there is no
477 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
480 * \sa make_message(), vsnprintf(3).
482 __printf_2_3
int para_printf(struct para_buffer
*b
, const char *fmt
, ...)
484 int ret
, sz_off
= (b
->flags
& PBF_SIZE_PREFIX
)? 5 : 0;
487 b
->buf
= para_malloc(128);
492 char *p
= b
->buf
+ b
->offset
;
493 size_t size
= b
->size
- b
->offset
;
498 ret
= vsnprintf(p
+ sz_off
, size
- sz_off
, fmt
, ap
);
500 if (ret
> -1 && ret
< size
- sz_off
) { /* success */
501 b
->offset
+= ret
+ sz_off
;
503 write_size_header(p
, ret
);
507 /* check if we may grow the buffer */
508 if (!b
->max_size
|| 2 * b
->size
< b
->max_size
) { /* yes */
509 /* try again with more space */
511 b
->buf
= para_realloc(b
->buf
, b
->size
);
514 /* can't grow buffer */
515 if (!b
->offset
|| !b
->max_size_handler
) /* message too large */
516 return -ERRNO_TO_PARA_ERROR(ENOSPC
);
517 ret
= b
->max_size_handler(b
->buf
, b
->offset
, b
->private_data
);
524 /** \cond llong_minmax */
525 /* LLONG_MAX and LLONG_MIN might not be defined. */
527 #define LLONG_MAX 9223372036854775807LL
530 #define LLONG_MIN (-LLONG_MAX - 1LL)
532 /** \endcond llong_minmax */
535 * Convert a string to a 64-bit signed integer value.
537 * \param str The string to be converted.
538 * \param value Result pointer.
542 * \sa para_atoi32(), strtol(3), atoi(3).
544 int para_atoi64(const char *str
, int64_t *value
)
549 errno
= 0; /* To distinguish success/failure after call */
550 tmp
= strtoll(str
, &endptr
, 10);
551 if (errno
== ERANGE
&& (tmp
== LLONG_MAX
|| tmp
== LLONG_MIN
))
552 return -E_ATOI_OVERFLOW
;
553 if (errno
!= 0 && tmp
== 0) /* other error */
556 return -E_ATOI_NO_DIGITS
;
557 if (*endptr
!= '\0') /* Further characters after number */
558 return -E_ATOI_JUNK_AT_END
;
564 * Convert a string to a 32-bit signed integer value.
566 * \param str The string to be converted.
567 * \param value Result pointer.
573 int para_atoi32(const char *str
, int32_t *value
)
577 const int32_t max
= 2147483647;
579 ret
= para_atoi64(str
, &tmp
);
582 if (tmp
> max
|| tmp
< -max
- 1)
583 return -E_ATOI_OVERFLOW
;
588 static inline int loglevel_equal(const char *arg
, const char * const ll
)
590 return !strncasecmp(arg
, ll
, strlen(ll
));
594 * Compute the loglevel number from its name.
596 * \param txt The name of the loglevel (debug, info, ...).
598 * \return The numeric representation of the loglevel name.
600 int get_loglevel_by_name(const char *txt
)
602 if (loglevel_equal(txt
, "debug"))
604 if (loglevel_equal(txt
, "info"))
606 if (loglevel_equal(txt
, "notice"))
608 if (loglevel_equal(txt
, "warning"))
610 if (loglevel_equal(txt
, "error"))
612 if (loglevel_equal(txt
, "crit"))
614 if (loglevel_equal(txt
, "emerg"))
619 static int get_next_word(const char *buf
, const char *delim
, char **word
)
621 enum line_state_flags
{LSF_HAVE_WORD
= 1, LSF_BACKSLASH
= 2,
622 LSF_SINGLE_QUOTE
= 4, LSF_DOUBLE_QUOTE
= 8};
627 out
= para_malloc(strlen(buf
) + 1);
630 for (in
= buf
; *in
; in
++) {
635 if (state
& LSF_BACKSLASH
) /* \\ */
637 state
|= LSF_BACKSLASH
;
638 state
|= LSF_HAVE_WORD
;
642 if (state
& LSF_BACKSLASH
) { /* \n or \t */
643 *out
++ = (*in
== 'n')? '\n' : '\t';
644 state
&= ~LSF_BACKSLASH
;
649 if (state
& LSF_BACKSLASH
) /* \" */
651 if (state
& LSF_SINGLE_QUOTE
) /* '" */
653 if (state
& LSF_DOUBLE_QUOTE
) {
654 state
&= ~LSF_DOUBLE_QUOTE
;
657 state
|= LSF_HAVE_WORD
;
658 state
|= LSF_DOUBLE_QUOTE
;
661 if (state
& LSF_BACKSLASH
) /* \' */
663 if (state
& LSF_DOUBLE_QUOTE
) /* "' */
665 if (state
& LSF_SINGLE_QUOTE
) {
666 state
&= ~LSF_SINGLE_QUOTE
;
669 state
|= LSF_HAVE_WORD
;
670 state
|= LSF_SINGLE_QUOTE
;
673 for (p
= delim
; *p
; p
++) {
676 if (state
& LSF_BACKSLASH
)
678 if (state
& LSF_SINGLE_QUOTE
)
680 if (state
& LSF_DOUBLE_QUOTE
)
682 if (state
& LSF_HAVE_WORD
)
686 if (*p
) /* ignore delimiter at the beginning */
689 state
|= LSF_HAVE_WORD
;
691 state
&= ~LSF_BACKSLASH
;
694 if (!(state
& LSF_HAVE_WORD
))
696 ret
= -ERRNO_TO_PARA_ERROR(EINVAL
);
697 if (state
& LSF_BACKSLASH
) {
698 PARA_ERROR_LOG("trailing backslash\n");
701 if ((state
& LSF_SINGLE_QUOTE
) || (state
& LSF_DOUBLE_QUOTE
)) {
702 PARA_ERROR_LOG("unmatched quote character\n");
715 * Get the number of the word the cursor is on.
717 * \param buf The zero-terminated line buffer.
718 * \param delim Characters that separate words.
719 * \param point The cursor position.
721 * \return Zero-based word number.
723 int compute_word_num(const char *buf
, const char *delim
, int point
)
729 for (p
= buf
, num_words
= 0; ; p
+= ret
, num_words
++) {
730 ret
= get_next_word(p
, delim
, &word
);
734 if (p
+ ret
>= buf
+ point
)
741 * Free an array of words created by create_argv().
743 * \param argv A pointer previously obtained by \ref create_argv().
745 void free_argv(char **argv
)
751 for (i
= 0; argv
[i
]; i
++)
757 * Split a buffer into words.
759 * This parser honors single and double quotes, backslash-escaped characters
760 * and special characters like \p \\n. The result contains pointers to copies
761 * of the words contained in \a buf and has to be freed by using \ref
764 * \param buf The buffer to be split.
765 * \param delim Each character in this string is treated as a separator.
766 * \param result The array of words is returned here.
768 * \return Number of words in \a buf, negative on errors.
770 int create_argv(const char *buf
, const char *delim
, char ***result
)
772 char *word
, **argv
= para_malloc(2 * sizeof(char *));
776 for (p
= buf
, num_words
= 0; ; p
+= ret
, num_words
++) {
777 ret
= get_next_word(p
, delim
, &word
);
782 argv
= para_realloc(argv
, (num_words
+ 2) * sizeof(char*));
783 argv
[num_words
] = word
;
785 argv
[num_words
] = NULL
;
789 while (num_words
> 0)
790 free(argv
[--num_words
]);
797 * Compile a regular expression.
799 * This simple wrapper calls regcomp() and logs a message on errors.
801 * \param preg See regcomp(3).
802 * \param regex See regcomp(3).
803 * \param cflags See regcomp(3).
807 int para_regcomp(regex_t
*preg
, const char *regex
, int cflags
)
811 int ret
= regcomp(preg
, regex
, cflags
);
815 size
= regerror(ret
, preg
, NULL
, 0);
816 buf
= para_malloc(size
);
817 regerror(ret
, preg
, buf
, size
);
818 PARA_ERROR_LOG("%s\n", buf
);
824 * strdup() for not necessarily zero-terminated strings.
826 * \param src The source buffer.
827 * \param len The number of bytes to be copied.
829 * \return A 0-terminated buffer of length \a len + 1.
831 * This is similar to strndup(), which is a GNU extension. However, one
832 * difference is that strndup() returns \p NULL if insufficient memory was
833 * available while this function aborts in this case.
835 * \sa strdup(), \ref para_strdup().
837 char *safe_strdup(const char *src
, size_t len
)
841 assert(len
< (size_t)-1);
842 p
= para_malloc(len
+ 1);
850 * Copy the value of a key=value pair.
852 * This checks whether the given buffer starts with "key=", ignoring case. If
853 * yes, a copy of the value is returned. The source buffer may not be
856 * \param src The source buffer.
857 * \param len The number of bytes of the tag.
858 * \param key Only copy if it is the value of this key.
860 * \return A zero-terminated buffer, or \p NULL if the key was
861 * not of the given type.
863 char *key_value_copy(const char *src
, size_t len
, const char *key
)
865 int keylen
= strlen(key
);
869 if (strncasecmp(src
, key
, keylen
))
871 if (src
[keylen
] != '=')
873 return safe_strdup(src
+ keylen
+ 1, len
- keylen
- 1);