2 * Copyright (C) 2004-2009 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. */
12 #include <sys/time.h> /* gettimeofday */
14 #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 \p s was the 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 * Paraslash's version of strcat().
141 * \param a String to be appended to.
142 * \param b String to append.
144 * Append \p b to \p a.
146 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
147 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
148 * return \a a without making a copy of \a a. Otherwise, construct the
149 * concatenation \a c, free \a a (but not \a b) and return \a c.
153 __must_check __malloc char *para_strcat(char *a, const char *b)
158 return para_strdup(b);
161 tmp = make_message("%s%s", a, b);
167 * Paraslash's version of dirname().
169 * \param name Pointer to the full path.
171 * Compute the directory component of \p name.
173 * \return If \a name is \p NULL or the empty string, return \p NULL.
174 * Otherwise, Make a copy of \a name and return its directory component. Caller
175 * is responsible to free the result.
177 __must_check __malloc char *para_dirname(const char *name)
183 ret = para_strdup(name);
184 p = strrchr(ret, '/');
193 * Paraslash's version of basename().
195 * \param name Pointer to the full path.
197 * Compute the filename component of \a name.
199 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
200 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
201 * must not free the result.
203 __must_check const char *para_basename(const char *name)
209 ret = strrchr(name, '/');
217 * Cut trailing newline.
219 * \param buf The string to be chopped.
221 * Replace the last character in \p buf by zero if it is euqal to
222 * the newline character.
229 if (buf[n - 1] == '\n')
234 * Get a random filename.
236 * This is by no means a secure way to create temporary files in a hostile
237 * direcory like \p /tmp. However, it is OK to use for temp files, fifos,
238 * sockets that are created in ~/.paraslash. Result must be freed by the
241 * \return A pointer to a random filename.
243 __must_check __malloc char *para_tmpname(void)
248 gettimeofday(&now, NULL);
251 return make_message("%08i", rand());
255 * Get the logname of the current user.
257 * \return A dynammically allocated string that must be freed by the caller. On
258 * errors, the string "unknown user" is returned, i.e. this function never
263 __must_check __malloc char *para_logname(void)
265 struct passwd *pw = getpwuid(getuid());
266 return para_strdup(pw? pw->pw_name : "unknown_user");
270 * Get the home directory of the current user.
272 * \return A dynammically allocated string that must be freed by the caller. If
273 * the home directory could not be found, this function returns "/tmp".
275 __must_check __malloc char *para_homedir(void)
277 struct passwd *pw = getpwuid(getuid());
278 return para_strdup(pw? pw->pw_dir : "/tmp");
282 * Split string and return pointers to its parts.
284 * \param args The string to be split.
285 * \param argv_ptr Pointer to the list of substrings.
286 * \param delim Delimiter.
288 * This function modifies \a args by replacing each occurance of \a delim by
289 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
290 * and these pointers are initialized to point to the broken-up substrings
291 * within \a args. A pointer to this array is returned via \a argv_ptr.
293 * \return The number of substrings found in \a args.
295 unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
301 p = args + strspn(args, delim);
303 i = strcspn(p, delim);
308 p += strspn(p, delim);
310 *argv_ptr = para_malloc((n + 1) * sizeof(char *));
313 p = args + strspn(args, delim);
316 j = strcspn(p, delim);
319 p += strcspn(p, delim);
323 p += strspn(p, delim);
332 * Get the own hostname.
334 * \return A dynammically allocated string containing the hostname.
338 __malloc char *para_hostname(void)
343 return para_strdup(u.nodename);
347 * Used to distinguish between read-only and read-write mode.
349 * \sa for_each_line(), for_each_line_ro().
351 enum for_each_line_modes{
352 /** Activate read-only mode. */
354 /** Activate read-write mode. */
358 static int for_each_complete_line(enum for_each_line_modes mode, char *buf,
359 size_t size, line_handler_t *line_handler, void *private_data)
361 char *start = buf, *end;
362 int ret, i, num_lines = 0;
364 // PARA_NOTICE_LOG("buf: %s\n", buf);
365 while (start < buf + size) {
369 next_cr = memchr(start, '\n', buf + size - start);
370 next_null = memchr(start, '\0', buf + size - start);
371 if (!next_cr && !next_null)
373 if (next_cr && next_null) {
374 end = next_cr < next_null? next_cr : next_null;
375 } else if (next_null) {
384 if (mode == LINE_MODE_RO) {
385 size_t s = end - start;
386 char *b = para_malloc(s + 1);
389 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
390 ret = line_handler(b, private_data);
394 ret = line_handler(start, private_data);
400 if (!line_handler || mode == LINE_MODE_RO)
402 i = buf + size - start;
404 memmove(buf, start, i);
409 * Call a custom function for each complete line.
411 * \param buf The buffer containing data seperated by newlines.
412 * \param size The number of bytes in \a buf.
413 * \param line_handler The custom function.
414 * \param private_data Pointer passed to \a line_handler.
416 * If \p line_handler is \p NULL, the function returns the number of complete
417 * lines in \p buf. Otherwise, \p line_handler is called for each complete
418 * line in \p buf. The first argument to \p line_handler is the current line,
419 * and \p private_data is passed as the second argument. The function returns
420 * if \p line_handler returns a negative value or no more lines are in the
421 * buffer. The rest of the buffer (last chunk containing an incomplete line)
422 * is moved to the beginning of the buffer.
424 * \return If \p line_handler is not \p NULL, this function returns the number
425 * of bytes not handled to \p line_handler on success, or the negative return
426 * value of the \p line_handler on errors.
428 * \sa for_each_line_ro().
430 int for_each_line(char *buf, size_t size, line_handler_t *line_handler,
433 return for_each_complete_line(LINE_MODE_RW, buf, size, line_handler,
438 * Call a custom function for each complete line.
440 * \param buf Same meaning as in \p for_each_line().
441 * \param size Same meaning as in \p for_each_line().
442 * \param line_handler Same meaning as in \p for_each_line().
443 * \param private_data Same meaning as in \p for_each_line().
445 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
447 * \return On success, the function returns the number of complete lines in \p
448 * buf, otherwise the (negative) return value of \p line_handler is returned.
450 * \sa for_each_line().
452 int for_each_line_ro(char *buf, size_t size, line_handler_t *line_handler,
455 return for_each_complete_line(LINE_MODE_RO, buf, size, line_handler,
460 * Safely print into a buffer at a given offset
462 * \param b Determines the buffer, its size, and the offset.
463 * \param fmt The format string.
465 * This function prints into the buffer given by \a b at the offset which is
466 * also given by \a b. If there is not enough space to hold the result, the
467 * buffer size is doubled until the underlying call to vsnprintf() succeeds
468 * or the size of the buffer exceeds the maximal size specified in \a pb.
470 * In the latter case the unmodified \a buf and \a offset values as well as the
471 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
472 * If this function succeeds, i.e. returns a non-negative value, the offset of
473 * \a b is reset to zero and the given data is written to the beginning of the
476 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
477 * calls to this function append data to what is already contained in the
480 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
481 * initial buffer is allocated.
483 * \return The number of bytes printed into the buffer (not including the
484 * therminating \p NULL byte).
486 * \sa make_message(), vsnprintf(3).
488 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
493 b->buf = para_malloc(128);
498 char *p = b->buf + b->offset;
499 size_t size = b->size - b->offset;
503 ret = vsnprintf(p, size, fmt, ap);
505 if (ret > -1 && ret < size) { /* success */
510 /* check if we may grow the buffer */
511 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
512 /* try again with more space */
514 b->buf = para_realloc(b->buf, b->size);
517 /* can't grow buffer */
518 if (!b->offset || !b->max_size_handler) /* message too large */
519 return -ERRNO_TO_PARA_ERROR(ENOSPC);
520 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
527 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
529 #define LLONG_MAX (1 << (sizeof(long) - 1))
532 #define LLONG_MIN (-LLONG_MAX - 1LL)
537 * Convert a string to a 64-bit signed integer value.
539 * \param str The string to be converted.
540 * \param value Result pointer.
544 * \sa para_atoi32(), strtol(3), atoi(3).
546 int para_atoi64(const char *str, int64_t *value)
551 errno = 0; /* To distinguish success/failure after call */
552 tmp = strtoll(str, &endptr, 10);
553 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
554 return -E_ATOI_OVERFLOW;
555 if (errno != 0 && tmp == 0) /* other error */
558 return -E_ATOI_NO_DIGITS;
559 if (*endptr != '\0') /* Further characters after number */
560 return -E_ATOI_JUNK_AT_END;
566 * Convert a string to a 32-bit signed integer value.
568 * \param str The string to be converted.
569 * \param value Result pointer.
575 int para_atoi32(const char *str, int32_t *value)
579 const int32_t max = 2147483647;
581 ret = para_atoi64(str, &tmp);
584 if (tmp > max || tmp < -max - 1)
585 return -E_ATOI_OVERFLOW;
590 int get_loglevel_by_name(const char *txt)
592 if (!strcasecmp(txt, "debug"))
594 if (!strcasecmp(txt, "info"))
596 if (!strcasecmp(txt, "notice"))
598 if (!strcasecmp(txt, "warning"))
600 if (!strcasecmp(txt, "error"))
602 if (!strcasecmp(txt, "crit"))
604 if (!strcasecmp(txt, "emerg"))