2 * Copyright (C) 2004-2007 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 NULL
23 * \param size 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 \p 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 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
)
63 void *p
= malloc(size
);
66 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
74 * paraslash's version of calloc()
76 * \param size 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 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 \p s was the 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("%s", "strdup failed, aborting\n");
117 * allocate a sufficiently large string and print into it
119 * \param fmt usual format string
121 * Produce output according to \p fmt. No artificial bound on the length of the
122 * resulting string is imposed.
124 * \return This function either returns a pointer to a string that must be
125 * freed by the caller or aborts without returning.
129 __must_check __printf_1_2 __malloc
char *make_message(const char *fmt
, ...)
133 PARA_VSPRINTF(fmt
, msg
);
138 * paraslash's version of strcat()
140 * \param a string to be appended to
141 * \param b string to append
143 * Append \p b to \p a.
145 * \return If \p a is NULL, return a pointer to a copy of \p b, i.e.
146 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \p b is NULL,
147 * return \p a without making a copy of \p a. Otherwise, construct the
148 * concatenation \p c, free \p a (but not \p b) and return \p c.
152 __must_check __malloc
char *para_strcat(char *a
, const char *b
)
157 return para_strdup(b
);
160 tmp
= make_message("%s%s", a
, b
);
166 * paraslash's version of dirname()
168 * \param name pointer to the full path
170 * Compute the directory component of \p name
172 * \return If \p name is \รพ NULL or the empty string, return \p NULL.
173 * Otherwise, Make a copy of \p name and return its directory component. Caller
174 * is responsible to free the result.
176 __must_check __malloc
char *para_dirname(const char *name
)
182 ret
= para_strdup(name
);
183 p
= strrchr(ret
, '/');
192 * paraslash's version of basename()
194 * \param name Pointer to the full path
196 * Compute the filename component of \p name
198 * \return If \p name is \p NULL or the empty string, return \p NULL,
199 * Otherwise, make a copy of \p name and return its filename component. Caller
200 * is responsible to free the result.
202 __must_check __malloc
char *para_basename(const char *name
)
208 p
= strrchr(name
, '/');
210 return para_strdup(name
);
214 return para_strdup(p
);
218 * cut trailing newline
220 * \param buf the string to be chopped.
222 * Replace the last character in \p buf by zero if it is euqal to
223 * the newline character.
230 if (buf
[n
- 1] == '\n')
235 * get a random filename
237 * This is by no means a secure way to create temporary files in a hostile
238 * direcory like \p /tmp. However, it is OK to use for temp files, fifos,
239 * sockets that are created in ~/.paraslash. Result must be freed by the
242 * \return a pointer to a random filename.
244 __must_check __malloc
char *para_tmpname(void)
249 gettimeofday(&now
, NULL
);
252 return make_message("%08i", rand());
256 * create unique temporary file
258 * \param template the template to be passed to mkstemp()
259 * \param mode the desired mode of the tempfile
261 * This wrapper for mkstemp additionally uses fchmod() to
262 * set the given mode of the tempfile if mkstemp() returned success.
264 * \return The file descriptor of the temp file just created on success.
265 * On errors, -E_MKSTEMP or -E_FCHMOD is returned.
267 __must_check
int para_mkstemp(char *template, mode_t mode
)
269 int tmp
, fd
= mkstemp(template);
273 tmp
= fchmod(fd
, mode
);
282 * get the logname of the current user
284 * \return A dynammically allocated string that must be freed by the caller. On
285 * errors, the string "unknown user" is returned, i.e. this function never
290 __must_check __malloc
char *para_logname(void)
292 struct passwd
*pw
= getpwuid(getuid());
293 return para_strdup(pw
? pw
->pw_name
: "unknown_user");
297 * get the home directory of the current user
299 * \return A dynammically allocated string that must be freed by the caller. If
300 * the home directory could not be found, this function returns "/tmp".
302 __must_check __malloc
char *para_homedir(void)
304 struct passwd
*pw
= getpwuid(getuid());
305 return para_strdup(pw
? pw
->pw_dir
: "/tmp");
309 * split string and return pointers to its parts.
311 * \param args the string to be split
312 * \param argv_ptr pointer to the list of substrings
313 * \param delim delimiter
315 * This function modifies \a args by replacing each occurance of \a delim by
316 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
317 * and these pointers are initialized to point to the broken-up substrings
318 * within \a args. A pointer to this array is returned via \a argv_ptr. It's OK
319 * to call this function with \a args \a == \p NULL.
321 * \return The number of substrings found in \a args.
323 __must_check
unsigned split_args(char *args
, char *** const argv_ptr
, const char *delim
)
329 p
= args
+ strspn(args
, delim
);
331 i
= strcspn(p
, delim
);
336 p
+= strspn(p
, delim
);
338 *argv_ptr
= para_malloc((n
+ 1) * sizeof(char *));
341 p
= args
+ strspn(args
, delim
);
344 j
= strcspn(p
, delim
);
347 p
+= strcspn(p
, delim
);
351 p
+= strspn(p
, delim
);
360 * ensure that file descriptors 0, 1, and 2 are valid
362 * Common approach that opens /dev/null until it gets a file descriptor greater
365 * \sa okir's Black Hats Manual.
367 void valid_fd_012(void)
372 fd
= open("/dev/null", O_RDWR
);
383 * get the own hostname
385 * \return A dynammically allocated string containing the hostname.
389 __malloc
char *para_hostname(void)
394 return para_strdup(u
.nodename
);
398 * Used to distinguish between read-only and read-write mode.
400 * \sa for_each_line(), for_each_line_ro().
402 enum for_each_line_modes
{
403 /** Activate read-only mode. */
405 /** Activate read-write mode. */
409 static int for_each_complete_line(enum for_each_line_modes mode
, char *buf
,
410 size_t size
, line_handler_t
*line_handler
, void *private_data
)
412 char *start
= buf
, *end
;
413 int ret
, i
, num_lines
= 0;
415 // PARA_NOTICE_LOG("buf: %s\n", buf);
416 while (start
< buf
+ size
) {
420 next_cr
= memchr(start
, '\n', buf
+ size
- start
);
421 next_null
= memchr(start
, '\0', buf
+ size
- start
);
422 if (!next_cr
&& !next_null
)
424 if (next_cr
&& next_null
) {
425 end
= next_cr
< next_null
? next_cr
: next_null
;
426 } else if (next_null
) {
435 if (mode
== LINE_MODE_RO
) {
436 size_t s
= end
- start
;
437 char *b
= para_malloc(s
+ 1);
440 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
441 ret
= line_handler(b
, private_data
);
445 ret
= line_handler(start
, private_data
);
451 if (!line_handler
|| mode
== LINE_MODE_RO
)
453 i
= buf
+ size
- start
;
455 memmove(buf
, start
, i
);
460 * Call a custom function for each complete line.
462 * \param buf The buffer containing data seperated by newlines.
463 * \param size The number of bytes in \a buf.
464 * \param line_handler The custom function.
465 * \param private_data Pointer passed to \a line_handler.
467 * If \p line_handler is \p NULL, the function returns the number of complete
468 * lines in \p buf. Otherwise, \p line_handler is called for each complete
469 * line in \p buf. The first argument to \p line_handler is the current line,
470 * and \p private_data is passed as the second argument. The function returns
471 * if \p line_handler returns a negative value or no more lines are in the
472 * buffer. The rest of the buffer (last chunk containing an incomplete line)
473 * is moved to the beginning of the buffer.
475 * \return If \p line_handler is not \p NULL, this function returns the number
476 * of bytes not handled to \p line_handler on success, or the negative return
477 * value of the \p line_handler on errors.
479 * \sa for_each_line_ro().
481 int for_each_line(char *buf
, size_t size
, line_handler_t
*line_handler
,
484 return for_each_complete_line(LINE_MODE_RW
, buf
, size
, line_handler
,
489 * Call a custom function for each complete line.
491 * \param buf Same meaning as in \p for_each_line().
492 * \param size Same meaning as in \p for_each_line().
493 * \param line_handler Same meaning as in \p for_each_line().
494 * \param private_data Same meaning as in \p for_each_line().
496 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
498 * \return On success, the function returns the number of complete lines in \p
499 * buf, otherwise the (negative) return value of \p line_handler is returned.
501 * \sa for_each_line().
503 int for_each_line_ro(char *buf
, size_t size
, line_handler_t
*line_handler
,
506 return for_each_complete_line(LINE_MODE_RO
, buf
, size
, line_handler
,
511 * Safely print into a buffer at a given offset
513 * \param b Determines the buffer, its size, and the offset.
514 * \param fmt The format string.
516 * This function prints into the buffer given by \a b at the offset which is
517 * also given by \a b. If there is not enough space to hold the result, the
518 * buffer size is doubled until the underlying call to vsnprintf() succeeds.
519 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
520 * calls to this function append data to what is already contained in the
523 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
524 * initial buffer is allocated.
526 * \return The number of bytes printed into the buffer (not including the
527 * therminating \p NULL byte).
529 * \sa make_message(), vsnprintf(3).
531 __printf_2_3
int para_printf(struct para_buffer
*b
, const char *fmt
, ...)
536 b
->buf
= para_malloc(128);
539 } else if (b
->size
<= b
->offset
+ 1) {
541 b
->buf
= para_realloc(b
->buf
, b
->size
);
544 char *p
= b
->buf
+ b
->offset
;
545 size_t size
= b
->size
- b
->offset
;
548 ret
= vsnprintf(p
, size
, fmt
, ap
);
550 if (ret
> -1 && ret
< size
) { /* success */
554 /* try again with more space */
556 b
->buf
= para_realloc(b
->buf
, b
->size
);
561 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
563 #define LLONG_MAX (1 << (sizeof(long) - 1))
566 #define LLONG_MIN (-LLONG_MAX - 1LL)
571 * Convert a string to a 64-bit signed integer value.
573 * \param str The string to be converted.
574 * \param value Result pointer.
576 * \return Positive on success, negative on errors.
578 * \sa para_atoi32(), strtol(3), atoi(3).
580 int para_atoi64(const char *str
, int64_t *value
)
585 errno
= 0; /* To distinguish success/failure after call */
586 tmp
= strtoll(str
, &endptr
, 10);
587 if (errno
== ERANGE
&& (tmp
== LLONG_MAX
|| tmp
== LLONG_MIN
))
588 return -E_ATOI_OVERFLOW
;
589 if (errno
!= 0 && tmp
== 0) /* other error */
592 return -E_ATOI_NO_DIGITS
;
593 if (*endptr
!= '\0') /* Further characters after number */
594 return -E_ATOI_JUNK_AT_END
;
600 * Convert a string to a 32-bit signed integer value.
602 * \param str The string to be converted.
603 * \param value Result pointer.
605 * \return Positive on success, negative on errors.
609 int para_atoi32(const char *str
, int32_t *value
)
613 const int32_t max
= 2147483647;
615 ret
= para_atoi64(str
, &tmp
);
618 if (tmp
> max
|| tmp
< -max
- 1)
619 return -E_ATOI_OVERFLOW
;