paraslash Paraslash Audio Streaming
About   News   Download   Documentation   Development

Macros | Functions
string.c File Reference

Memory allocation and string handling functions. More...

#include "para.h"
#include <pwd.h>
#include <sys/utsname.h>
#include <regex.h>
#include <langinfo.h>
#include <wchar.h>
#include <wctype.h>
#include "string.h"
#include "error.h"

Macros

#define hex(a)   (hexchar[(a) & 15])
 Return the hex characters of the lower 4 bits. More...
 

Functions

__must_check void * arr_realloc (void *ptr, size_t nmemb, size_t size)
 Reallocate an array, abort on failure or bugs. More...
 
__must_check __malloc void * arr_alloc (size_t nmemb, size_t size)
 Allocate an array, abort on failure or bugs. More...
 
__must_check __malloc void * arr_zalloc (size_t nmemb, size_t size)
 Allocate and initialize an array, abort on failure or bugs. More...
 
__must_check void * zalloc (size_t size)
 Allocate and initialize memory. More...
 
__must_check void * para_realloc (void *p, size_t size)
 Paraslash's version of realloc(). More...
 
__must_check __malloc void * alloc (size_t size)
 Paraslash's version of malloc(). More...
 
__must_check __malloc char * para_strdup (const char *s)
 Paraslash's version of strdup(). More...
 
__printf_2_0 unsigned xvasprintf (char **result, const char *fmt, va_list ap)
 Print a formatted message to a dynamically allocated string. More...
 
__printf_2_3 unsigned xasprintf (char **result, const char *fmt,...)
 Print to a dynamically allocated string, variable number of arguments. More...
 
__must_check __printf_1_2 __malloc char * make_message (const char *fmt,...)
 Allocate a sufficiently large string and print into it. More...
 
void freep (void *arg)
 Free the content of a pointer and set it to NULL. More...
 
__must_check __malloc char * para_strcat (char *a, const char *b)
 Paraslash's version of strcat(). More...
 
__must_check __malloc char * para_logname (void)
 Get the logname of the current user. More...
 
__must_check __malloc char * para_homedir (void)
 Get the home directory of the calling user. More...
 
__malloc char * para_hostname (void)
 Get the own hostname. More...
 
int for_each_line (unsigned flags, char *buf, size_t size, line_handler_t *line_handler, void *private_data)
 Call a custom function for each complete line. More...
 
int read_size_header (const char *buf)
 Read a four-byte hex-number and return its value. More...
 
__printf_2_3 int para_printf (struct para_buffer *b, const char *fmt,...)
 Safely print into a buffer at a given offset. More...
 
int para_atoi64 (const char *str, int64_t *value)
 llong_minmax More...
 
int para_atoi32 (const char *str, int32_t *value)
 Convert a string to a 32-bit signed integer value. More...
 
int compute_word_num (const char *buf, const char *delim, int point)
 Get the number of the word the cursor is on. More...
 
void free_argv (char **argv)
 Free an array of words created by create_argv() or create_shifted_argv(). More...
 
int create_argv (const char *buf, const char *delim, char ***result)
 Split a buffer into words. More...
 
int create_shifted_argv (const char *buf, const char *delim, char ***result)
 Split a buffer into words, offset one. More...
 
int para_regcomp (regex_t *preg, const char *regex, int cflags)
 Compile a regular expression. More...
 
char * safe_strdup (const char *src, size_t len)
 strdup() for not necessarily zero-terminated strings. More...
 
char * key_value_copy (const char *src, size_t len, const char *key)
 Copy the value of a key=value pair. More...
 
int skip_cells (const char *s, size_t cells_to_skip, size_t *bytes_to_skip)
 Skip a given number of cells at the beginning of a string. More...
 
__must_check int strwidth (const char *s, size_t *result)
 Compute the width of an UTF-8 string. More...
 
__must_check int sanitize_str (const char *src, size_t max_width, char **result, size_t *width)
 Truncate and sanitize a (wide character) string. More...
 

Detailed Description

Memory allocation and string handling functions.

Macro Definition Documentation

◆ hex

#define hex (   a)    (hexchar[(a) & 15])

Return the hex characters of the lower 4 bits.

Function Documentation

◆ arr_realloc()

__must_check void* arr_realloc ( void *  ptr,
size_t  nmemb,
size_t  size 
)

Reallocate an array, abort on failure or bugs.

Parameters
ptrPointer to the memory block, may be NULL.
nmembNumber of elements.
sizeThe size of one element in bytes.

A wrapper for realloc(3) which aborts on invalid arguments or integer overflow. The wrapper also terminates the current process on allocation errors, so the caller does not need to check for failure.

Returns
A pointer to newly allocated memory which is suitably aligned for any kind of variable and may be different from ptr.
See also
realloc(3).

Referenced by arr_alloc(), and para_realloc().

◆ arr_alloc()

__must_check __malloc void* arr_alloc ( size_t  nmemb,
size_t  size 
)

Allocate an array, abort on failure or bugs.

Parameters
nmembSee arr_realloc().
sizeSee arr_realloc().

Like arr_realloc(), this aborts on invalid arguments, integer overflow and allocation errors.

Returns
A pointer to newly allocated memory which is suitably aligned for any kind of variable.
See also
See arr_realloc().

References arr_realloc().

Referenced by alloc(), arr_zalloc(), and imdct_init().

◆ arr_zalloc()

__must_check __malloc void* arr_zalloc ( size_t  nmemb,
size_t  size 
)

Allocate and initialize an array, abort on failure or bugs.

Parameters
nmembSee arr_realloc().
sizeSee arr_realloc().

This calls arr_alloc() and zeroes-out the array.

Returns
See arr_alloc().

References arr_alloc().

Referenced by zalloc().

◆ zalloc()

__must_check void* zalloc ( size_t  size)

Allocate and initialize memory.

Parameters
sizeThe desired new size.
Returns
A pointer to the allocated and zeroed-out memory, which is suitably aligned for any kind of variable.
See also
alloc(), calloc(3).

References arr_zalloc().

Referenced by accept_sender_client(), check_wav_init(), imdct_init(), mp_init(), oac_custom_header_new(), playlist_load(), ringbuffer_new(), sb_new_recv(), sb_new_send(), and vss_add_fec_client().

◆ para_realloc()

__must_check void* para_realloc ( void *  p,
size_t  size 
)

Paraslash's version of realloc().

Parameters
pPointer to the memory block, may be NULL.
sizeThe desired new size.

A wrapper for realloc(3). It calls exit(EXIT_FAILURE) on errors, i.e. there is no need to check the return value in the caller.

Returns
A pointer to newly allocated memory which is suitably aligned for any kind of variable and may be different from p.
See also
realloc(3).

References arr_realloc().

Referenced by oac_custom_header_flush(), and xvasprintf().

◆ alloc()

__must_check __malloc void* alloc ( size_t  size)

Paraslash's version of malloc().

Parameters
sizeThe desired new size.

A wrapper for malloc(3) which exits on errors.

Returns
A pointer to the allocated memory, which is suitably aligned for any kind of variable.
See also
malloc(3).

References arr_alloc().

Referenced by acl_add_entry(), add_close_on_fork_list(), apc_get_pubkey(), apc_priv_decrypt(), base64_decode(), btr_new_node(), btr_pool_new(), check_receiver_arg(), cq_enqueue(), cq_new(), decode_private_key(), flowopt_add(), flowopt_new(), for_each_line(), handle_connect(), i9e_extract_completions(), init_sender_status(), para_printf(), para_regcomp(), parse_quoted_string(), read_and_compare(), safe_strdup(), sc_new(), task_register(), and xvasprintf().

◆ para_strdup()

__must_check __malloc char* para_strdup ( const char *  s)

Paraslash's version of strdup().

Parameters
sThe string to be duplicated.

A strdup(3)-like function which aborts if insufficient memory was available to allocate the duplicated string, absolving the caller from the responsibility to check for failure.

Returns
A pointer to the duplicated string. Unlike strdup(3), the caller may pass NULL, in which case the function returns a pointer to an empty string. Regardless of whether or not NULL was passed, the returned string is allocated on the heap and has to be freed by the caller.
See also
strdup(3).

Referenced by accept_sender_client(), audiod_get_decoder_flags(), btr_new_node(), btr_pool_new(), check_receiver_arg(), daemon_drop_privileges_or_die(), flowopt_add(), format_url(), init_sender_status(), mp4_get_tag_value(), para_homedir(), para_hostname(), para_logname(), para_strcat(), and parse_fec_url().

◆ xvasprintf()

__printf_2_0 unsigned xvasprintf ( char **  result,
const char *  fmt,
va_list  ap 
)

Print a formatted message to a dynamically allocated string.

Parameters
resultThe formatted string is returned here.
fmtThe format string.
apInitialized list of arguments.

This function is similar to vasprintf(), a GNU extension which is not in C or POSIX. It allocates a string large enough to hold the output including the terminating null byte. The allocated string is returned via the first argument and must be freed by the caller. However, unlike vasprintf(), this function calls exit() if insufficient memory is available, while vasprintf() returns -1 in this case.

Returns
Number of bytes written, not including the terminating NULL character.
See also
printf(3), vsnprintf(3), va_start(3), vasprintf(3), xasprintf().

References alloc(), and para_realloc().

Referenced by afs_error(), make_message(), mp_parse_error(), send_sb_va(), write_va_buffer(), and xasprintf().

◆ xasprintf()

__printf_2_3 unsigned xasprintf ( char **  result,
const char *  fmt,
  ... 
)

Print to a dynamically allocated string, variable number of arguments.

Parameters
resultSee xvasprintf().
fmtUsual format string.
Returns
The return value of the underlying call to xvasprintf().
See also
xvasprintf() and the references mentioned there.

References xvasprintf().

Referenced by afh_get_afhi_txt(), and mp_parse_error().

◆ make_message()

__must_check __printf_1_2 __malloc char* make_message ( const char *  fmt,
  ... 
)

Allocate a sufficiently large string and print into it.

Parameters
fmtA usual format string.

Produce output according to fmt. No artificial bound on the length of the resulting string is imposed.

Returns
This function either returns a pointer to a string that must be freed by the caller or aborts without returning.
See also
printf(3), xasprintf().

References xvasprintf().

Referenced by acl_get_contents(), daemon_get_uptime_str(), format_url(), generic_sender_help(), generic_sender_status(), get_task_list(), para_strcat(), and playlist_load().

◆ freep()

void freep ( void *  arg)

Free the content of a pointer and set it to NULL.

Parameters
argA pointer to the pointer whose content should be freed.

If arg is NULL, the function returns immediately. Otherwise it frees the memory pointed to by arg and sets *arg to NULL. Hence callers have to pass the *address of the pointer variable that points to the memory which should be freed.

Referenced by free_status_items(), and free_vlc().

◆ para_strcat()

__must_check __malloc char* para_strcat ( char *  a,
const char *  b 
)

Paraslash's version of strcat().

Parameters
aString to be appended to.
bString to append.

Append b to a.

Returns
If a is NULL, return a pointer to a copy of b, i.e. para_strcat(NULL, b) is equivalent to para_strdup(b). If b is NULL, return a without making a copy of a. Otherwise, construct the concatenation c, free a (but not b) and return c.
See also
strcat(3).

References make_message(), and para_strdup().

◆ para_logname()

__must_check __malloc char* para_logname ( void  )

Get the logname of the current user.

Returns
A dynamically allocated string that must be freed by the caller. On errors, the string "unknown_user" is returned, i.e. this function never returns NULL.
See also
getpwuid(3).

References para_strdup().

◆ para_homedir()

__must_check __malloc char* para_homedir ( void  )

Get the home directory of the calling user.

Returns
A dynamically allocated string that must be freed by the caller. If no entry is found which matches the UID of the calling process, or any other error occurs, the function prints an error message and aborts.
See also
getpwuid(3), getuid(2).

References PARA_EMERG_LOG, and para_strdup().

◆ para_hostname()

__malloc char* para_hostname ( void  )

Get the own hostname.

Returns
A dynamically allocated string containing the hostname.
See also
uname(2).

References para_strdup().

◆ for_each_line()

int for_each_line ( unsigned  flags,
char *  buf,
size_t  size,
line_handler_t line_handler,
void *  private_data 
)

Call a custom function for each complete line.

Parameters
flagsAny combination of flags defined in for_each_line_flags.
bufThe buffer containing data separated by newlines.
sizeThe number of bytes in buf.
line_handlerThe custom function.
private_dataPointer passed to line_handler.

For each complete line in buf, line_handler is called. The first argument to line_handler is (a copy of) the current line, and private_data is passed as the second argument. If the FELF_READ_ONLY flag is unset, a pointer into buf is passed to the line handler, otherwise a pointer to a copy of the current line is passed instead. This copy is freed immediately after the line handler returns.

The function returns if line_handler returns a negative value or no more lines are in the buffer. The rest of the buffer (last chunk containing an incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is unset.

Returns
On success this function returns the number of bytes not handled to line_handler. The only possible error is a negative return value from the line handler. In this case processing stops and the return value of the line handler is returned to indicate failure.
See also
for_each_line_flags.

References alloc(), FELF_DISCARD_FIRST, and FELF_READ_ONLY.

Referenced by playlist_load().

◆ read_size_header()

int read_size_header ( const char *  buf)

Read a four-byte hex-number and return its value.

Each status item sent by para_server is prefixed with such a hex number in ASCII which describes the size of the status item.

Parameters
bufThe buffer which must be at least four bytes long.
Returns
The value of the hex number on success, -E_SIZE_PREFIX if the buffer did not contain only hex digits.

Referenced by for_each_stat_item().

◆ para_printf()

__printf_2_3 int para_printf ( struct para_buffer b,
const char *  fmt,
  ... 
)

Safely print into a buffer at a given offset.

Parameters
bDetermines the buffer, its size, and the offset.
fmtThe format string.

This function prints into the buffer given by b at the offset which is also given by b. If there is not enough space to hold the result, the buffer size is doubled until the underlying call to vsnprintf() succeeds or the size of the buffer exceeds the maximal size specified in b.

In the latter case the unmodified buf and offset values as well as the private_data pointer of b are passed to the max_size_handler of b. If this function succeeds, i.e. returns a non-negative value, the offset of b is reset to zero and the given data is written to the beginning of the buffer. If max_size_handler() returns a negative value, this value is returned by para_printf().

Upon return, the offset of b is adjusted accordingly so that subsequent calls to this function append data to what is already contained in the buffer.

It's OK to call this function with b->buf being NULL. In this case, an initial buffer is allocated.

Returns
The number of bytes printed into the buffer (not including the terminating NULL byte) on success, negative on errors. If there is no size-bound on b, i.e. if b->max_size is zero, this function never fails.
See also
make_message(), vsnprintf(3).

References alloc(), para_buffer::buf, para_buffer::flags, para_buffer::offset, PBF_SIZE_PREFIX, and para_buffer::size.

Referenced by aft_check_attributes(), aft_check_callback(), mood_check_callback(), and playlist_check_callback().

◆ para_atoi64()

int para_atoi64 ( const char *  str,
int64_t *  value 
)

llong_minmax

Convert a string to a 64-bit signed integer value.

Parameters
strThe string to be converted.
valueResult pointer.
Returns
Standard.
See also
para_atoi32(), strtol(3), atoi(3).

Referenced by para_atoi32().

◆ para_atoi32()

int para_atoi32 ( const char *  str,
int32_t *  value 
)

Convert a string to a 32-bit signed integer value.

Parameters
strThe string to be converted.
valueResult pointer.
Returns
Standard.
See also
para_atoi64().

References para_atoi64().

Referenced by parse_cidr(), and parse_url().

◆ compute_word_num()

int compute_word_num ( const char *  buf,
const char *  delim,
int  point 
)

Get the number of the word the cursor is on.

Parameters
bufThe zero-terminated line buffer.
delimCharacters that separate words.
pointThe cursor position.
Returns
Zero-based word number.

◆ free_argv()

void free_argv ( char **  argv)

Free an array of words created by create_argv() or create_shifted_argv().

Parameters
argvA pointer previously obtained by create_argv().

Referenced by check_receiver_arg(), and filter_setup().

◆ create_argv()

int create_argv ( const char *  buf,
const char *  delim,
char ***  result 
)

Split a buffer into words.

This parser honors single and double quotes, backslash-escaped characters and special characters like \n. The result contains pointers to copies of the words contained in buf and has to be freed by using free_argv().

Parameters
bufThe buffer to be split.
delimEach character in this string is treated as a separator.
resultThe array of words is returned here.

It's OK to pass NULL as the buffer argument. This is equivalent to passing the empty string.

Returns
Number of words in buf, negative on errors. The array returned through the result pointer is NULL terminated.

Referenced by check_receiver_arg(), filter_setup(), and para_exec_cmdline_pid().

◆ create_shifted_argv()

int create_shifted_argv ( const char *  buf,
const char *  delim,
char ***  result 
)

Split a buffer into words, offset one.

This is similar to create_argv() but the returned array is one element larger, words start at index one and element zero is initialized to NULL. Callers must set element zero to a non-NULL value before calling free_argv() on the returned array to avoid a memory leak.

Parameters
bufSee create_argv().
delimSee create_argv().
resultSee create_argv().
Returns
Number of words plus one on success, negative on errors.

◆ para_regcomp()

int para_regcomp ( regex_t *  preg,
const char *  regex,
int  cflags 
)

Compile a regular expression.

This simple wrapper calls regcomp() and logs a message on errors.

Parameters
pregSee regcomp(3).
regexSee regcomp(3).
cflagsSee regcomp(3).
Returns
Standard.

References alloc(), and PARA_ERROR_LOG.

Referenced by mp_parse_regex_pattern().

◆ safe_strdup()

char* safe_strdup ( const char *  src,
size_t  len 
)

strdup() for not necessarily zero-terminated strings.

Parameters
srcThe source buffer.
lenThe number of bytes to be copied.
Returns
A 0-terminated buffer of length len + 1.

This is similar to strndup(), which is a GNU extension. However, one difference is that strndup() returns NULL if insufficient memory was available while this function aborts in this case.

See also
strdup(), para_strdup().

References alloc().

Referenced by key_value_copy().

◆ key_value_copy()

char* key_value_copy ( const char *  src,
size_t  len,
const char *  key 
)

Copy the value of a key=value pair.

This checks whether the given buffer starts with "key=", ignoring case. If yes, a copy of the value is returned. The source buffer may not be zero-terminated.

Parameters
srcThe source buffer.
lenThe number of bytes of the tag.
keyOnly copy if it is the value of this key.
Returns
A zero-terminated buffer, or NULL if the key was not of the given type.

References safe_strdup().

◆ skip_cells()

int skip_cells ( const char *  s,
size_t  cells_to_skip,
size_t *  bytes_to_skip 
)

Skip a given number of cells at the beginning of a string.

Parameters
sThe input string.
cells_to_skipDesired number of cells that should be skipped.
bytes_to_skipResult.

This function computes how many input bytes must be skipped to advance a string by the given width. If the current character encoding is not UTF-8, this is simply the given number of cells, i.e. cells_to_skip. Otherwise, s is treated as a multibyte string and on successful return, s + bytes_to_skip points to the start of a multibyte string such that the total width of the multibyte characters that are skipped by advancing s that many bytes equals at least cells_to_skip.

Returns
Standard.

◆ strwidth()

__must_check int strwidth ( const char *  s,
size_t *  result 
)

Compute the width of an UTF-8 string.

Parameters
sThe string.
resultThe width of s is returned here.

If not in UTF8-mode. this function is just a wrapper for strlen(3). Otherwise s is treated as an UTF-8 string and its display width is computed. Note that this function may fail if the underlying call to mbsrtowcs(3) fails, so the caller must check the return value.

See also
nl_langinfo(3), wcswidth(3).
Returns
Standard.

◆ sanitize_str()

__must_check int sanitize_str ( const char *  src,
size_t  max_width,
char **  result,
size_t *  width 
)

Truncate and sanitize a (wide character) string.

This replaces all non-printable characters by spaces and makes sure that the modified string does not exceed the given maximal width.

Parameters
srcThe source string in multi-byte form.
max_widthThe maximal number of cells the result may occupy.
resultSanitized multi-byte string, must be freed by caller.
widthThe width of the sanitized string, always <= max_width.

The function is wide-character aware but falls back to C strings for non-UTF-8 locales.

Returns
Standard. On success, *result points to a sanitized copy of the given string. This copy was allocated with malloc() and should hence be freed when the caller is no longer interested in the result.

The function fails if the given string contains an invalid multibyte sequence. In this case, *result is set to NULL, and *width to zero.