OpenVPN
Data Structures | Macros | Functions
buffer.h File Reference

Buffer management functions and garbage collection. More...

#include "basic.h"
#include "error.h"
#include "integer.h"
Include dependency graph for buffer.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  buffer
 Wrapper structure for dynamically allocated memory. More...
 
struct  gc_entry
 Garbage collection entry for one dynamically allocated block of memory. More...
 
struct  gc_entry_special
 Garbage collection entry for a specially allocated structure that needs a custom free function to be freed like struct addrinfo. More...
 
struct  gc_arena
 Garbage collection arena used to keep track of dynamically allocated memory. More...
 
struct  buffer_entry
 One node in a buffer_list linked list. More...
 
struct  buffer_list
 A singly-linked list of buffers, with head/tail pointers for O(1) push. More...
 

Macros

#define BUF_SIZE_MAX   1000000
 Maximum allowed size (in bytes) for a single buffer allocation.
 
#define BPTR(buf)   (buf_bptr(buf))
 Return a pointer to the start of the buffer content.
 
#define CBPTR(buf)   (buf_cbptr(buf))
 Return a const pointer to the start of the buffer content.
 
#define BEND(buf)   (buf_bend(buf))
 Return a pointer one past the end of the buffer content.
 
#define CBEND(buf)   (buf_cbend(buf))
 Return a const pointer one past the end of the buffer content.
 
#define BLAST(buf)   (buf_blast(buf))
 Return a pointer to the last byte of the buffer content, or NULL if empty.
 
#define CBLAST(buf)   (buf_cblast(buf))
 Return a const pointer to the last byte of the buffer content, or NULL if empty.
 
#define BLEN(buf)   (buf_len(buf))
 Return the length of the buffer content in bytes.
 
#define BLENZ(buf)   ((size_t)buf_len(buf))
 Return the length of the buffer content as a size_t.
 
#define BDEF(buf)   (buf_defined(buf))
 Return true iff the buffer is defined (has non-NULL data pointer).
 
#define BSTR(buf)   (buf_str(buf))
 Return the buffer content pointer cast to char *.
 
#define CBSTR(buf)   (buf_cstr(buf))
 Return the buffer content pointer cast to const char *.
 
#define BCAP(buf)   (buf_forward_capacity(buf))
 Return the number of bytes available for appending to the buffer.
 
#define PA_BRACKET   (1 << 0)
 Flag for print_argv(): wrap each argument in square brackets.
 
#define buf_init(buf, offset)   buf_init_dowork(buf, offset)
 
#define verify_align_4(ptr)
 

Functions

void buf_clear (struct buffer *buf)
 Zeroise and reset a buffer.
 
void free_buf (struct buffer *buf)
 Free the memory allocated for a buffer.
 
bool buf_assign (struct buffer *dest, const struct buffer *src)
 Assign the content of one buffer to another.
 
void string_clear (char *str)
 Securely clear a null-terminated string.
 
int string_array_len (const char **array)
 Return the number of elements in a NULL-terminated array of strings.
 
size_t array_mult_safe (const size_t m1, const size_t m2, const size_t extra)
 Safely compute the product of two sizes plus an extra amount.
 
char * print_argv (const char **p, struct gc_arena *gc, const unsigned int flags)
 Format a NULL-terminated argument vector as a single string.
 
void buf_size_error (const size_t size)
 Report a buffer size error and abort.
 
struct buffer alloc_buf (size_t size)
 Allocate a buffer of the given size.
 
struct buffer alloc_buf_gc (size_t size, struct gc_arena *gc)
 Allocate a buffer of the given size under garbage collection.
 
struct buffer clone_buf (const struct buffer *buf)
 Duplicate a buffer, including its content.
 
void * gc_malloc (size_t size, bool clear, struct gc_arena *a)
 Allocate memory and, optionally, zero it.
 
char * string_alloc (const char *str, struct gc_arena *gc)
 Duplicate a string, allocating memory under garbage collection.
 
struct buffer string_alloc_buf (const char *str, struct gc_arena *gc)
 Allocate a buffer containing a copy of the given string.
 
void gc_addspecial (void *addr, void(*free_function)(void *), struct gc_arena *a)
 Register an address with a custom free function in a garbage collection arena.
 
void * gc_realloc (void *ptr, size_t size, struct gc_arena *a)
 allows to realloc a pointer previously allocated by gc_malloc or gc_realloc
 
static void gc_freeaddrinfo_callback (void *addr)
 Callback to free a struct addrinfo, suitable for use with gc_addspecial().
 
static struct buffer clear_buf (void)
 Return an empty, undefined struct buffer (all fields zero).
 
static bool buf_defined (const struct buffer *buf)
 Return true iff buf has a non-NULL data pointer.
 
static bool buf_valid (const struct buffer *buf)
 Return true iff buf is valid.
 
static const uint8_t * buf_cbptr (const struct buffer *buf)
 Return a const pointer to the start of the buffer content.
 
static uint8_t * buf_bptr (struct buffer *buf)
 Return a pointer to the start of the buffer content.
 
static int buf_len (const struct buffer *buf)
 Return the length of the buffer content.
 
static uint8_t * buf_bend (struct buffer *buf)
 Return a pointer one past the end of the buffer content.
 
static const uint8_t * buf_cbend (const struct buffer *buf)
 Return a const pointer one past the end of the buffer content.
 
static const uint8_t * buf_cblast (const struct buffer *buf)
 Return a const pointer to the last byte of the buffer content.
 
static uint8_t * buf_blast (struct buffer *buf)
 Return a pointer to the last byte of the buffer content.
 
static bool buf_size_valid (const size_t size)
 Return true iff size is within the allowed buffer size range.
 
static bool buf_size_valid_signed (const int size)
 Return true iff a signed size is within the allowed buffer size range.
 
static char * buf_str (struct buffer *buf)
 Return the buffer content pointer cast to char *.
 
static const char * buf_cstr (const struct buffer *buf)
 Return the buffer content pointer cast to const char *.
 
static void buf_reset (struct buffer *buf)
 Reset a buffer to an undefined (unallocated) state.
 
static void buf_reset_len (struct buffer *buf)
 Reset the length and offset of a buffer to zero.
 
static bool buf_init_dowork (struct buffer *buf, int offset)
 Initialise a buffer with a given initial offset.
 
static void buf_set_write (struct buffer *buf, uint8_t *data, int size)
 Initialise a buffer with an externally provided writable memory region.
 
static void buf_set_read (struct buffer *buf, const uint8_t *data, size_t size)
 Initialise a buffer with an externally provided read-only memory region.
 
static void strncpynt (char *dest, const char *src, size_t maxlen)
 Like strncpy() but always null-terminates the destination.
 
static bool has_digit (const char *src)
 Return true if the string contains at least one decimal digit.
 
static void secure_memzero (void *data, size_t len)
 Securely zeroise memory.
 
bool buf_printf (struct buffer *buf, const char *format,...)
 printf-style append to a buffer with overflow check.
 
bool buf_puts (struct buffer *buf, const char *str)
 Append a string to a buffer with overflow check.
 
void buf_null_terminate (struct buffer *buf)
 Force a null terminator at the end of the buffer content.
 
void buf_chomp (struct buffer *buf)
 Remove trailing newline and carriage-return characters from a buffer.
 
void buf_rmtail (struct buffer *buf, uint8_t remove)
 Remove all occurrences of a specific byte from the end of a buffer.
 
bool buffer_write_file (const char *filename, const struct buffer *buf)
 Write buffer contents to file.
 
void buf_catrunc (struct buffer *buf, const char *str)
 Append a string to the physical end of a buffer that was truncated by buf_printf().
 
bool buf_parse (struct buffer *buf, const int delim, char *line, const int size)
 Extract the next token from a buffer, delimited by a given character.
 
struct buffer buf_sub (struct buffer *buf, int size, bool prepend)
 Return a sub-buffer of another buffer.
 
static bool buf_safe (const struct buffer *buf, size_t len)
 Check whether len bytes can be appended to a buffer.
 
static bool buf_safe_bidir (const struct buffer *buf, int len)
 Check whether len bytes can be added to or removed from a buffer.
 
static int buf_forward_capacity (const struct buffer *buf)
 Return the number of bytes that can still be appended to the buffer.
 
static int buf_forward_capacity_total (const struct buffer *buf)
 Return the total number of bytes available from the current offset to the end of the allocated memory.
 
static int buf_reverse_capacity (const struct buffer *buf)
 Return the number of bytes available for prepending to the buffer.
 
static bool buf_inc_len (struct buffer *buf, int inc)
 Increase or decrease the length of a buffer.
 
static uint8_t * buf_prepend (struct buffer *buf, ssize_t size)
 Make space at the front of a buffer for prepending data.
 
static bool buf_advance (struct buffer *buf, ssize_t size)
 Advance the content start of a buffer, consuming bytes from the front.
 
static uint8_t * buf_write_alloc (struct buffer *buf, size_t size)
 Reserve space at the end of a buffer for writing.
 
static uint8_t * buf_read_alloc (struct buffer *buf, int size)
 Consume bytes from the front of a buffer for reading.
 
static bool buf_write (struct buffer *dest, const void *src, size_t size)
 Append data to a buffer.
 
static bool buf_write_prepend (struct buffer *dest, const void *src, int size)
 Prepend data to a buffer.
 
static bool buf_write_u8 (struct buffer *dest, uint8_t data)
 Append a uint8_t to a buffer.
 
static bool buf_write_u16 (struct buffer *dest, uint16_t data)
 Append a uint16_t to a buffer in network byte order.
 
static bool buf_write_u32 (struct buffer *dest, uint32_t data)
 Append a uint32_t to a buffer in network byte order.
 
static bool buf_write_u64 (struct buffer *dest, uint64_t data)
 Append a uint64_t to a buffer in network byte order.
 
static bool buf_copy (struct buffer *dest, const struct buffer *src)
 Copy the content of one buffer to the end of another.
 
static bool buf_copy_n (struct buffer *dest, struct buffer *src, int n)
 Read n bytes from src and append them to dest.
 
static bool buf_copy_range (struct buffer *dest, int dest_index, const struct buffer *src, int src_index, int src_len)
 Copy a range of bytes from one buffer into a specific position in another.
 
static bool buf_copy_excess (struct buffer *dest, struct buffer *src, int len)
 Truncate src to len bytes and copy any excess to dest.
 
static bool buf_read (struct buffer *src, void *dest, int size)
 Read bytes from the front of a buffer into a caller-supplied destination.
 
static int buf_peek_u8 (const struct buffer *buf)
 Return the first byte of the buffer without consuming it.
 
static int buf_read_u8 (struct buffer *buf)
 Read and consume a uint8_t from the front of a buffer.
 
static int buf_read_u16 (struct buffer *buf)
 Read and consume a uint16_t from the front of a buffer.
 
static uint32_t buf_read_u32 (struct buffer *buf, bool *good)
 Read and consume a uint32_t from the front of a buffer.
 
static uint64_t buf_read_u64 (struct buffer *buf, bool *good)
 Read and consume a uint64_t from the front of a buffer.
 
static bool buf_equal (const struct buffer *a, const struct buffer *b)
 Return true if buffer contents are equal.
 
static bool buf_string_match (const struct buffer *src, const void *match, int size)
 Compare src buffer contents with match.
 
static bool buf_string_match_head (const struct buffer *src, const void *match, int size)
 Compare first size bytes of src buffer contents with match.
 
bool buf_string_match_head_str (const struct buffer *src, const char *match)
 Return true if the head of src matches the string match.
 
bool buf_string_compare_advance (struct buffer *src, const char *match)
 Compare the head of src with match and advance past it if equal.
 
int buf_substring_len (const struct buffer *buf, int delim)
 Return the number of bytes in a buffer up to and including a delimiter.
 
const char * np (const char *str)
 Return a printable representation of a string that might be NULL.
 
void string_replace_leading (char *str, const char match, const char replace)
 Replace all leading occurrences of a character in a string.
 
static bool strprefix (const char *str, const char *prefix)
 Return true iff str starts with prefix.
 
bool string_defined_equal (const char *s1, const char *s2)
 
char * string_substitute (const char *src, char from, char to, struct gc_arena *gc)
 
bool checked_snprintf (char *str, size_t size, const char *format,...)
 Like snprintf() but returns an boolean.
 
char * buf_extract_field (struct buffer *buf, char sep, struct gc_arena *gc)
 Extract a field from buf that ends with the sep character.
 
String Utility Functions

Non-buffer string functions

void chomp (char *str)
 Remove trailing newline and carriage-return characters from a string.
 
void rm_trailing_chars (char *str, const char *what_to_delete)
 Remove all trailing characters that appear in a given set.
 
const char * skip_leading_whitespace (const char *str)
 Return a pointer past any leading whitespace in a string.
 
void string_null_terminate (char *str, int len, int capacity)
 Null-terminate a fixed-length string buffer.
 
Buffer Lists

Manage lists of buffers

struct buffer_listbuffer_list_new (void)
 Allocate an empty buffer list of capacity max_size.
 
void buffer_list_free (struct buffer_list *ol)
 Frees a buffer list and all the buffers in it.
 
bool buffer_list_defined (const struct buffer_list *ol)
 Checks if the list is valid and non-empty.
 
void buffer_list_reset (struct buffer_list *ol)
 Empty the list ol and frees all the contained buffers.
 
void buffer_list_push (struct buffer_list *ol, const char *str)
 Allocates and appends a new buffer containing str as data to ol.
 
struct buffer_entrybuffer_list_push_data (struct buffer_list *ol, const void *data, size_t size)
 Allocates and appends a new buffer containing data of length size.
 
struct bufferbuffer_list_peek (struct buffer_list *ol)
 Retrieve the head buffer.
 
void buffer_list_advance (struct buffer_list *ol, ssize_t n)
 Advance past n bytes in the head buffer, popping it if it becomes empty.
 
void buffer_list_pop (struct buffer_list *ol)
 Remove and free the head buffer of the list.
 
void buffer_list_aggregate (struct buffer_list *bl, const size_t max)
 Aggregates as many buffers as possible from bl in a new buffer of maximum length max_len .
 
void buffer_list_aggregate_separator (struct buffer_list *bl, const size_t max_len, const char *sep)
 Aggregates as many buffers as possible from bl in a new buffer of maximum length max_len .
 
struct buffer_listbuffer_list_file (const char *fn, int max_line_len)
 Read a file into a buffer list, one buffer per line.
 
struct buffer buffer_read_from_file (const char *filename, struct gc_arena *gc)
 buffer_read_from_file - copy the content of a file into a buffer
 

Hex Dump

Output a binary buffer to a hex string and return it.

#define FHE_SPACE_BREAK_MASK   0xFF
 Mask for the space_break_flags field of format_hex_ex(): number of bytes between separators (lower 8 bits).
 
#define FHE_CAPS   0x100
 Flag for format_hex_ex(): output hex digits in upper case.
 
char * format_hex_ex (const uint8_t *data, size_t size, size_t maxoutput, unsigned int space_break_flags, const char *separator, struct gc_arena *gc)
 Format a binary buffer as a hex string.
 
static char * format_hex (const uint8_t *data, size_t size, size_t maxoutput, struct gc_arena *gc)
 Format a binary buffer as a hex string with spaces every 4 bytes.
 

Character classes

Check or modify strings based on classes of allowed or forbidden characters.

#define CC_ANY   (1 << 0)
 any character
 
#define CC_NULL   (1 << 1)
 null character \0
 
#define CC_ALNUM   (1 << 2)
 alphanumeric isalnum()
 
#define CC_ALPHA   (1 << 3)
 alphabetic isalpha()
 
#define CC_ASCII   (1 << 4)
 ASCII character.
 
#define CC_CNTRL   (1 << 5)
 control character iscntrl()
 
#define CC_DIGIT   (1 << 6)
 digit isdigit()
 
#define CC_PRINT   (1 << 7)
 printable (>= 32, != 127)
 
#define CC_PUNCT   (1 << 8)
 punctuation ispunct()
 
#define CC_SPACE   (1 << 9)
 whitespace isspace()
 
#define CC_XDIGIT   (1 << 10)
 hex digit isxdigit()
 
#define CC_BLANK   (1 << 11)
 space or tab
 
#define CC_NEWLINE   (1 << 12)
 newline
 
#define CC_CR   (1 << 13)
 carriage return
 
#define CC_BACKSLASH   (1 << 14)
 backslash
 
#define CC_UNDERBAR   (1 << 15)
 underscore
 
#define CC_DASH   (1 << 16)
 dash
 
#define CC_DOT   (1 << 17)
 dot
 
#define CC_COMMA   (1 << 18)
 comma
 
#define CC_COLON   (1 << 19)
 colon
 
#define CC_SLASH   (1 << 20)
 slash
 
#define CC_SINGLE_QUOTE   (1 << 21)
 single quote
 
#define CC_DOUBLE_QUOTE   (1 << 22)
 double quote
 
#define CC_REVERSE_QUOTE   (1 << 23)
 reverse quote
 
#define CC_PERCENT   (1 << 24)
 percent sign
 
#define CC_EXCLAMATION   (1 << 25)
 exclamation mark
 
#define CC_LESS_THAN   (1 << 26)
 less than sign
 
#define CC_GREATER_THAN   (1 << 27)
 greater than sign
 
#define CC_PIPE   (1 << 28)
 pipe
 
#define CC_QUESTION_MARK   (1 << 29)
 question mark
 
#define CC_ASTERISK   (1 << 30)
 asterisk
 
#define CC_NAME   (CC_ALNUM | CC_UNDERBAR)
 alphanumeric plus underscore
 
#define CC_CRLF   (CC_CR | CC_NEWLINE)
 carriage return or newline
 
bool char_class (const unsigned char c, const unsigned int flags)
 Test whether a character belongs to one or more character classes.
 
bool string_class (const char *str, const unsigned int inclusive, const unsigned int exclusive)
 Test whether all characters in a string satisfy a character class filter.
 
bool string_mod (char *str, const unsigned int inclusive, const unsigned int exclusive, const char replace)
 Modifies a string in place by replacing certain classes of characters of it with a specified character.
 
bool string_check_buf (const struct buffer *buf, const unsigned int inclusive, const unsigned int exclusive)
 Check a buffer if it only consists of allowed characters.
 
const char * string_mod_const (const char *str, const unsigned int inclusive, const unsigned int exclusive, const char replace, struct gc_arena *gc)
 Returns a copy of a string with certain classes of characters of it replaced with a specified character.
 

Garbage Collection

Basic garbage collection, mostly for routines that return char ptrs to malloced strings.

#define ALLOC_SIZE_MAX   (1u << 30)
 Maximum size for a single array allocation (checked by array_mult_safe()).
 
#define ALLOC_OBJ(dptr, type)
 Allocate memory for a single object of the given type.
 
#define ALLOC_OBJ_CLEAR(dptr, type)
 Allocate and zero-initialise memory for a single object of the given type.
 
#define ALLOC_ARRAY(dptr, type, n)
 Allocate memory for an array of n elements of the given type.
 
#define ALLOC_ARRAY_GC(dptr, type, n, gc)
 Allocate a garbage-collected array of n elements of the given type.
 
#define ALLOC_ARRAY_CLEAR(dptr, type, n)
 Allocate and zero-initialise an array of n elements of the given type.
 
#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc)
 Allocate and zero-initialise a garbage-collected array of n elements.
 
#define ALLOC_VAR_ARRAY_CLEAR_GC(dptr, type, atype, n, gc)
 Allocate and zero-initialise a garbage-collected variable-length structure.
 
#define ALLOC_OBJ_GC(dptr, type, gc)
 Allocate a garbage-collected object of the given type (uninitialised).
 
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
 Allocate and zero-initialise a garbage-collected object of the given type.
 
void gc_transfer (struct gc_arena *dest, struct gc_arena *src)
 Move all allocations from one garbage collection arena to another.
 
void x_gc_free (struct gc_arena *a)
 Free all plain allocations in a garbage collection arena.
 
void x_gc_freespecial (struct gc_arena *a)
 Free all specially-allocated entries in a garbage collection arena.
 
static bool gc_defined (struct gc_arena *a)
 Return true iff the arena contains at least one allocation.
 
static void gc_init (struct gc_arena *a)
 Initialise a garbage collection arena to an empty state.
 
static void gc_detach (struct gc_arena *a)
 Detach all allocations from an arena without freeing them.
 
static struct gc_arena gc_new (void)
 Allocate and return a new, empty garbage collection arena.
 
static void gc_free (struct gc_arena *a)
 Free all allocations in a garbage collection arena.
 
static void gc_reset (struct gc_arena *a)
 Free all allocations in a garbage collection arena and reinitialise it.
 
static void check_malloc_return (void *p)
 Abort if a memory allocation returned NULL.
 

Detailed Description

Buffer management functions and garbage collection.

This module provides the core buffer type used throughout OpenVPN to hold packet data, as well as a simple memory management system (gc_arena / gc_malloc()) and various string/memory utility functions.

Definition in file buffer.h.

Macro Definition Documentation

◆ ALLOC_ARRAY

#define ALLOC_ARRAY (   dptr,
  type,
 
)
Value:
{ \
check_malloc_return((dptr) = (type *)malloc(array_mult_safe(sizeof(type), (n), 0))); \
}
size_t array_mult_safe(const size_t m1, const size_t m2, const size_t extra)
Safely compute the product of two sizes plus an extra amount.
Definition buffer.c:40

Allocate memory for an array of n elements of the given type.

Uses array_mult_safe() to guard against size overflow. Calls check_malloc_return() to abort on allocation failure.

Parameters
dptrPointer variable that receives the allocation.
typeElement type of the array.
nNumber of elements.

Definition at line 2052 of file buffer.h.

◆ ALLOC_ARRAY_CLEAR

#define ALLOC_ARRAY_CLEAR (   dptr,
  type,
 
)
Value:
{ \
ALLOC_ARRAY(dptr, type, n); \
memset((dptr), 0, (array_mult_safe(sizeof(type), (n), 0))); \
}

Allocate and zero-initialise an array of n elements of the given type.

Parameters
dptrPointer variable that receives the allocation.
typeElement type of the array.
nNumber of elements.

Definition at line 2077 of file buffer.h.

◆ ALLOC_ARRAY_CLEAR_GC

#define ALLOC_ARRAY_CLEAR_GC (   dptr,
  type,
  n,
  gc 
)
Value:
{ \
(dptr) = (type *)gc_malloc(array_mult_safe(sizeof(type), (n), 0), true, (gc)); \
}
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:318
struct gc_arena gc
Definition test_ssl.c:122

Allocate and zero-initialise a garbage-collected array of n elements.

Parameters
dptrPointer variable that receives the allocation.
typeElement type of the array.
nNumber of elements.
gcGarbage collection arena to register the allocation with.

Definition at line 2091 of file buffer.h.

◆ ALLOC_ARRAY_GC

#define ALLOC_ARRAY_GC (   dptr,
  type,
  n,
  gc 
)
Value:
{ \
(dptr) = (type *)gc_malloc(array_mult_safe(sizeof(type), (n), 0), false, (gc)); \
}

Allocate a garbage-collected array of n elements of the given type.

Parameters
dptrPointer variable that receives the allocation.
typeElement type of the array.
nNumber of elements.
gcGarbage collection arena to register the allocation with.

Definition at line 2065 of file buffer.h.

◆ ALLOC_OBJ

#define ALLOC_OBJ (   dptr,
  type 
)
Value:
{ \
check_malloc_return((dptr) = (type *)malloc(sizeof(type))); \
}

Allocate memory for a single object of the given type.

Calls check_malloc_return() to abort on allocation failure.

Parameters
dptrPointer variable that receives the allocation.
typeType of the object to allocate.

Definition at line 2025 of file buffer.h.

◆ ALLOC_OBJ_CLEAR

#define ALLOC_OBJ_CLEAR (   dptr,
  type 
)
Value:
{ \
ALLOC_OBJ(dptr, type); \
memset((dptr), 0, sizeof(type)); \
}

Allocate and zero-initialise memory for a single object of the given type.

Parameters
dptrPointer variable that receives the allocation.
typeType of the object to allocate.

Definition at line 2036 of file buffer.h.

◆ ALLOC_OBJ_CLEAR_GC

#define ALLOC_OBJ_CLEAR_GC (   dptr,
  type,
  gc 
)
Value:
{ \
(dptr) = (type *)gc_malloc(sizeof(type), true, (gc)); \
}

Allocate and zero-initialise a garbage-collected object of the given type.

Parameters
dptrPointer variable that receives the allocation.
typeType of the object to allocate.
gcGarbage collection arena to register the allocation with.

Definition at line 2132 of file buffer.h.

◆ ALLOC_OBJ_GC

#define ALLOC_OBJ_GC (   dptr,
  type,
  gc 
)
Value:
{ \
(dptr) = (type *)gc_malloc(sizeof(type), false, (gc)); \
}

Allocate a garbage-collected object of the given type (uninitialised).

Parameters
dptrPointer variable that receives the allocation.
typeType of the object to allocate.
gcGarbage collection arena to register the allocation with.

Definition at line 2120 of file buffer.h.

◆ ALLOC_SIZE_MAX

#define ALLOC_SIZE_MAX   (1u << 30)

Maximum size for a single array allocation (checked by array_mult_safe()).

Definition at line 2011 of file buffer.h.

◆ ALLOC_VAR_ARRAY_CLEAR_GC

#define ALLOC_VAR_ARRAY_CLEAR_GC (   dptr,
  type,
  atype,
  n,
  gc 
)
Value:
{ \
(dptr) = (type *)gc_malloc(array_mult_safe(sizeof(atype), (n), sizeof(type)), true, (gc)); \
}

Allocate and zero-initialise a garbage-collected variable-length structure.

Allocates sizeof(type) + n * sizeof(atype) bytes for a structure that embeds a variable-length array of atype as its last member.

Parameters
dptrPointer variable that receives the allocation.
typeType of the enclosing structure.
atypeElement type of the variable-length array member.
nNumber of array elements.
gcGarbage collection arena to register the allocation with.

Definition at line 2108 of file buffer.h.

◆ BCAP

#define BCAP (   buf)    (buf_forward_capacity(buf))

Return the number of bytes available for appending to the buffer.

See also
buf_forward_capacity()

Definition at line 161 of file buffer.h.

◆ BDEF

#define BDEF (   buf)    (buf_defined(buf))

Return true iff the buffer is defined (has non-NULL data pointer).

See also
buf_defined()

Definition at line 155 of file buffer.h.

◆ BEND

#define BEND (   buf)    (buf_bend(buf))

Return a pointer one past the end of the buffer content.

See also
buf_bend()

Definition at line 143 of file buffer.h.

◆ BLAST

#define BLAST (   buf)    (buf_blast(buf))

Return a pointer to the last byte of the buffer content, or NULL if empty.

See also
buf_blast()

Definition at line 147 of file buffer.h.

◆ BLEN

#define BLEN (   buf)    (buf_len(buf))

Return the length of the buffer content in bytes.

See also
buf_len()

Definition at line 151 of file buffer.h.

◆ BLENZ

#define BLENZ (   buf)    ((size_t)buf_len(buf))

Return the length of the buffer content as a size_t.

See also
buf_len()

Definition at line 153 of file buffer.h.

◆ BPTR

#define BPTR (   buf)    (buf_bptr(buf))

Return a pointer to the start of the buffer content.

See also
buf_bptr()

Definition at line 139 of file buffer.h.

◆ BSTR

#define BSTR (   buf)    (buf_str(buf))

Return the buffer content pointer cast to char *.

See also
buf_str()

Definition at line 157 of file buffer.h.

◆ buf_init

#define buf_init (   buf,
  offset 
)    buf_init_dowork(buf, offset)

Definition at line 364 of file buffer.h.

◆ BUF_SIZE_MAX

#define BUF_SIZE_MAX   1000000

Maximum allowed size (in bytes) for a single buffer allocation.

Definition at line 40 of file buffer.h.

◆ CBEND

#define CBEND (   buf)    (buf_cbend(buf))

Return a const pointer one past the end of the buffer content.

See also
buf_cbend()

Definition at line 145 of file buffer.h.

◆ CBLAST

#define CBLAST (   buf)    (buf_cblast(buf))

Return a const pointer to the last byte of the buffer content, or NULL if empty.

See also
buf_cblast()

Definition at line 149 of file buffer.h.

◆ CBPTR

#define CBPTR (   buf)    (buf_cbptr(buf))

Return a const pointer to the start of the buffer content.

See also
buf_cbptr()

Definition at line 141 of file buffer.h.

◆ CBSTR

#define CBSTR (   buf)    (buf_cstr(buf))

Return the buffer content pointer cast to const char *.

See also
buf_cstr()

Definition at line 159 of file buffer.h.

◆ CC_ALNUM

#define CC_ALNUM   (1 << 2)

alphanumeric isalnum()

Definition at line 1701 of file buffer.h.

◆ CC_ALPHA

#define CC_ALPHA   (1 << 3)

alphabetic isalpha()

Definition at line 1702 of file buffer.h.

◆ CC_ANY

#define CC_ANY   (1 << 0)

any character

Definition at line 1698 of file buffer.h.

◆ CC_ASCII

#define CC_ASCII   (1 << 4)

ASCII character.

Definition at line 1703 of file buffer.h.

◆ CC_ASTERISK

#define CC_ASTERISK   (1 << 30)

asterisk

Definition at line 1731 of file buffer.h.

◆ CC_BACKSLASH

#define CC_BACKSLASH   (1 << 14)

backslash

Definition at line 1715 of file buffer.h.

◆ CC_BLANK

#define CC_BLANK   (1 << 11)

space or tab

Definition at line 1711 of file buffer.h.

◆ CC_CNTRL

#define CC_CNTRL   (1 << 5)

control character iscntrl()

Definition at line 1704 of file buffer.h.

◆ CC_COLON

#define CC_COLON   (1 << 19)

colon

Definition at line 1720 of file buffer.h.

◆ CC_COMMA

#define CC_COMMA   (1 << 18)

comma

Definition at line 1719 of file buffer.h.

◆ CC_CR

#define CC_CR   (1 << 13)

carriage return

Definition at line 1713 of file buffer.h.

◆ CC_CRLF

#define CC_CRLF   (CC_CR | CC_NEWLINE)

carriage return or newline

Definition at line 1735 of file buffer.h.

◆ CC_DASH

#define CC_DASH   (1 << 16)

dash

Definition at line 1717 of file buffer.h.

◆ CC_DIGIT

#define CC_DIGIT   (1 << 6)

digit isdigit()

Definition at line 1705 of file buffer.h.

◆ CC_DOT

#define CC_DOT   (1 << 17)

dot

Definition at line 1718 of file buffer.h.

◆ CC_DOUBLE_QUOTE

#define CC_DOUBLE_QUOTE   (1 << 22)

double quote

Definition at line 1723 of file buffer.h.

◆ CC_EXCLAMATION

#define CC_EXCLAMATION   (1 << 25)

exclamation mark

Definition at line 1726 of file buffer.h.

◆ CC_GREATER_THAN

#define CC_GREATER_THAN   (1 << 27)

greater than sign

Definition at line 1728 of file buffer.h.

◆ CC_LESS_THAN

#define CC_LESS_THAN   (1 << 26)

less than sign

Definition at line 1727 of file buffer.h.

◆ CC_NAME

#define CC_NAME   (CC_ALNUM | CC_UNDERBAR)

alphanumeric plus underscore

Definition at line 1734 of file buffer.h.

◆ CC_NEWLINE

#define CC_NEWLINE   (1 << 12)

newline

Definition at line 1712 of file buffer.h.

◆ CC_NULL

#define CC_NULL   (1 << 1)

null character \0

Definition at line 1699 of file buffer.h.

◆ CC_PERCENT

#define CC_PERCENT   (1 << 24)

percent sign

Definition at line 1725 of file buffer.h.

◆ CC_PIPE

#define CC_PIPE   (1 << 28)

pipe

Definition at line 1729 of file buffer.h.

◆ CC_PRINT

#define CC_PRINT   (1 << 7)

printable (>= 32, != 127)

Definition at line 1706 of file buffer.h.

◆ CC_PUNCT

#define CC_PUNCT   (1 << 8)

punctuation ispunct()

Definition at line 1707 of file buffer.h.

◆ CC_QUESTION_MARK

#define CC_QUESTION_MARK   (1 << 29)

question mark

Definition at line 1730 of file buffer.h.

◆ CC_REVERSE_QUOTE

#define CC_REVERSE_QUOTE   (1 << 23)

reverse quote

Definition at line 1724 of file buffer.h.

◆ CC_SINGLE_QUOTE

#define CC_SINGLE_QUOTE   (1 << 21)

single quote

Definition at line 1722 of file buffer.h.

◆ CC_SLASH

#define CC_SLASH   (1 << 20)

slash

Definition at line 1721 of file buffer.h.

◆ CC_SPACE

#define CC_SPACE   (1 << 9)

whitespace isspace()

Definition at line 1708 of file buffer.h.

◆ CC_UNDERBAR

#define CC_UNDERBAR   (1 << 15)

underscore

Definition at line 1716 of file buffer.h.

◆ CC_XDIGIT

#define CC_XDIGIT   (1 << 10)

hex digit isxdigit()

Definition at line 1709 of file buffer.h.

◆ FHE_CAPS

#define FHE_CAPS   0x100

Flag for format_hex_ex(): output hex digits in upper case.

Definition at line 948 of file buffer.h.

◆ FHE_SPACE_BREAK_MASK

#define FHE_SPACE_BREAK_MASK   0xFF

Mask for the space_break_flags field of format_hex_ex(): number of bytes between separators (lower 8 bits).

Definition at line 946 of file buffer.h.

◆ PA_BRACKET

#define PA_BRACKET   (1 << 0)

Flag for print_argv(): wrap each argument in square brackets.

Definition at line 229 of file buffer.h.

◆ verify_align_4

#define verify_align_4 (   ptr)

Definition at line 1876 of file buffer.h.

Function Documentation

◆ alloc_buf()

struct buffer alloc_buf ( size_t  size)

Allocate a buffer of the given size.

Calls out_of_memory() if the allocation fails. The caller is responsible for freeing the memory.

Parameters
sizeNumber of bytes to allocate.
Returns
Newly allocated buffer of capacity size.

Definition at line 60 of file buffer.c.

References buf_size_error(), buf_size_valid(), buffer::capacity, check_malloc_return(), CLEAR, buffer::data, and buffer::len.

Referenced by alloc_buf_sock_tun(), auth_token_init_secret(), buffer_list_aggregate_separator(), buffer_list_push_data(), check_inline_file(), command_line_new(), fragment_frame_init(), fragment_list_buf_init(), init_context_buffers(), init_tas_auth(), init_tas_crypt(), key_state_init(), management_query_cert(), management_query_pk_sig(), mutate_ncp_cipher_list(), openvpn_PRF(), options_string(), read_inline_file(), reliable_init(), send_line_crlf(), status_open(), stream_buf_init(), test_generate_reset_packet_plain(), test_incoming_push_continuation_route_accumulation(), test_incoming_push_message_1(), test_incoming_push_message_bad_format(), test_incoming_push_message_basic(), test_incoming_push_message_error1(), test_incoming_push_message_error2(), test_incoming_push_message_mix(), test_incoming_push_message_mix2(), test_incoming_push_message_not_updatable_option(), test_mbuf_add_remove(), test_parse_ack(), test_tls_crypt_setup(), test_tls_decrypt_lite_auth(), test_tls_decrypt_lite_crypt(), test_tls_decrypt_lite_none(), test_verify_hmac_none(), test_verify_hmac_none_out_of_range_ack(), test_verify_hmac_tls_auth(), tls_crypt_v2_extract_client_key(), tls_crypt_v2_init_client_key(), tls_session_generate_dynamic_tls_crypt_key(), tls_session_init(), tun_show_debug(), and tuntap_dhcp_mask().

◆ alloc_buf_gc()

struct buffer alloc_buf_gc ( size_t  size,
struct gc_arena gc 
)

Allocate a buffer of the given size under garbage collection.

The allocated memory is registered with gc so that it is freed when gc_free() is called on the arena. Calls out_of_memory() if the allocation fails.

Parameters
sizeNumber of bytes to allocate.
gcGarbage collection arena to register the allocation with.
Returns
Newly allocated buffer of capacity size.

Definition at line 77 of file buffer.c.

References buf_size_error(), buf_size_valid(), buffer::capacity, CLEAR, buffer::data, gc, gc_malloc(), and buffer::len.

Referenced by __wrap_buffer_read_from_file(), add_option(), buffer_read_from_file(), ce_management_query_proxy(), ce_management_query_remote(), check_incoming_control_channel(), construct_name_value(), create_client_key_input(), create_metadata_days_ago(), crypto_pem_encode(), dco_version_string(), do_data_channel_round_trip(), do_init_frame_tls(), encrypt_one_packet(), extract_command_buffer(), forge_msg(), fork_dhcp_action(), fork_register_dns_action(), format_common_name(), format_hex_ex(), format_ip_addr_string(), format_route_entry(), frame_print(), generate_auth_token(), get_device_guid(), get_unspecified_device_guid(), get_user_pass_cr(), hostname_randomize(), ifconfig_options_string(), ifconfig_pool_read(), ipset2ascii_all(), link_socket_connection_initiated(), log_entry_print(), management_callback_send_cc_message(), management_hold(), management_query_multiline(), management_query_user_pass(), mroute_addr_print_ex(), mroute_helper_regenerate(), msg_flags_string(), multi_instance_string(), ncp_expanded_ciphers(), netsh_get_id(), options_string_compat_lzo(), options_string_version(), options_warning_safe_ml(), ovpn_expand_label(), p2p_mode_ncp(), packet_id_net_print(), packet_id_persist_print(), platform_gen_path(), plugin_mask_string(), prepare_push_reply(), prepend_dir(), print_argv(), print_default_gateway(), print_in_port_t(), print_key_id(), print_link_socket_actual_ex(), print_netmask(), print_opt_route(), print_opt_route_gateway(), print_opt_route_gateway_dhcp(), print_opt_topology(), print_sockaddr_ex(), print_str_int(), proto2ascii_all(), protocol_dump(), push_peer_info(), read_control_auth(), reliable_ack_print(), send_auth_failed(), send_auth_pending_messages(), send_push_reply(), send_push_reply_auth_token(), server_pushed_info(), setenv_format_indexed_name(), setenv_route(), setenv_route_addr(), setenv_route_ipv6(), socket_stat(), strerror_win32(), system_error_message(), tap_win_getinfo(), test_buffer_chomp(), test_buffer_extract_field(), test_buffer_free_gc_one(), test_buffer_free_gc_two(), test_buffer_null_terminate(), test_buffer_parse(), test_buffer_printf_catrunc(), test_character_string_mod_buf(), test_crypto(), test_data_channel_known_vectors_run(), test_extract_control_message(), test_load_certificate_and_key_uri(), test_packet_id_write_epoch(), test_tls_crypt_v2_setup(), test_write_dhcp_search_str(), time_string(), tls_crypt_v2_wrap_client_key(), tls_crypt_v2_wrap_unwrap_dst_too_small(), tls_crypt_v2_wrap_unwrap_max_metadata(), tls_crypt_v2_wrap_unwrap_no_metadata(), tls_crypt_v2_write_client_key_file(), tun_stat(), tv_string(), username_password_as_base64(), verify_cert(), wide_cmd_line(), win32_version_string(), window_title_generate(), write_key_file(), write_outgoing_tls_ciphertext(), x509_get_sha1_fingerprint(), and x509_get_sha256_fingerprint().

◆ array_mult_safe()

size_t array_mult_safe ( const size_t  m1,
const size_t  m2,
const size_t  extra 
)

Safely compute the product of two sizes plus an extra amount.

Each of m1, m2, and extra, as well as the final result, are checked against ALLOC_SIZE_MAX. If any value exceeds the limit the function calls msg(M_FATAL) and does not return.

Parameters
m1First multiplicand.
m2Second multiplicand.
extraValue to add to the product.
Returns
m1 * m2 + extra.

Definition at line 40 of file buffer.c.

References ALLOC_SIZE_MAX, M_FATAL, msg, and unlikely.

◆ buf_advance()

static bool buf_advance ( struct buffer buf,
ssize_t  size 
)
inlinestatic

◆ buf_assign()

bool buf_assign ( struct buffer dest,
const struct buffer src 
)

Assign the content of one buffer to another.

Copies the content of src into dest. The destination buffer must already be allocated with sufficient capacity.

Parameters
destDestination buffer to write into.
srcSource buffer to read from.
Returns
true on success, false if dest has insufficient capacity.

Definition at line 159 of file buffer.c.

References BLENZ, buf_init, buf_write(), CBPTR, buffer::len, and buffer::offset.

Referenced by buffer_turnover().

◆ buf_bend()

static uint8_t * buf_bend ( struct buffer buf)
inlinestatic

Return a pointer one past the end of the buffer content.

Parameters
bufThe buffer to query.
Returns
Pointer to the byte immediately after the last content byte.

Definition at line 480 of file buffer.h.

References buf_bptr(), and buf_len().

◆ buf_blast()

static uint8_t * buf_blast ( struct buffer buf)
inlinestatic

Return a pointer to the last byte of the buffer content.

Parameters
bufThe buffer to query.
Returns
Pointer to the last byte, or NULL if the buffer is empty or invalid.

Definition at line 528 of file buffer.h.

References buf_cblast().

◆ buf_bptr()

static uint8_t * buf_bptr ( struct buffer buf)
inlinestatic

Return a pointer to the start of the buffer content.

Parameters
bufThe buffer to query.
Returns
Pointer to buf->data + buf->offset, or NULL if buf is not valid.

Definition at line 447 of file buffer.h.

References buf_cbptr().

Referenced by buf_bend(), buf_str(), calculate_session_id_hmac(), management_query_cert(), management_query_pk_sig(), ovpn_expand_label(), test_buffer_extract_field(), tls_crypt_v2_unwrap_checks(), and tls_crypt_v2_wrap_unwrap_invalid().

◆ buf_catrunc()

void buf_catrunc ( struct buffer buf,
const char *  str 
)

Append a string to the physical end of a buffer that was truncated by buf_printf().

If the buffer's forward capacity is one byte or less (i.e. it is full), str is written at the very end of the allocated memory to act as a truncation marker, provided it fits within the total buffer capacity. This is used to append a "[more...]" suffix after hex-dump truncation.

Parameters
bufThe buffer to append the truncation marker to.
strThe null-terminated marker string to write.

Definition at line 273 of file buffer.c.

References buf_forward_capacity(), buf_forward_capacity_total(), buf_size_valid(), buffer::capacity, buffer::data, and buffer::len.

Referenced by format_hex_ex(), and test_buffer_printf_catrunc().

◆ buf_cbend()

static const uint8_t * buf_cbend ( const struct buffer buf)
inlinestatic

Return a const pointer one past the end of the buffer content.

Parameters
bufThe buffer to query.
Returns
Pointer to the byte immediately after the last content byte.

Definition at line 493 of file buffer.h.

References buf_cbptr(), and buf_len().

◆ buf_cblast()

static const uint8_t * buf_cblast ( const struct buffer buf)
inlinestatic

Return a const pointer to the last byte of the buffer content.

Parameters
bufThe buffer to query.
Returns
Pointer to the last byte, or NULL if the buffer is empty or invalid.

Definition at line 507 of file buffer.h.

References buf_cbptr(), and buf_len().

Referenced by buf_blast().

◆ buf_cbptr()

static const uint8_t * buf_cbptr ( const struct buffer buf)
inlinestatic

Return a const pointer to the start of the buffer content.

Parameters
bufThe buffer to query.
Returns
Pointer to buf->data + buf->offset, or NULL if buf is not valid.

Definition at line 426 of file buffer.h.

References buf_valid(), buffer::data, and buffer::offset.

Referenced by buf_bptr(), buf_cbend(), buf_cblast(), and buf_cstr().

◆ buf_chomp()

void buf_chomp ( struct buffer buf)

Remove trailing newline and carriage-return characters from a buffer.

Parameters
bufThe buffer to chomp.

Definition at line 522 of file buffer.c.

References BLAST, buf_inc_len(), buf_null_terminate(), CC_CRLF, CC_NULL, char_class(), and buffer::len.

Referenced by command_line_get(), extract_command_buffer(), key_state_check_auth_pending_file(), and test_buffer_chomp().

◆ buf_clear()

void buf_clear ( struct buffer buf)

◆ buf_copy()

static bool buf_copy ( struct buffer dest,
const struct buffer src 
)
inlinestatic

◆ buf_copy_excess()

static bool buf_copy_excess ( struct buffer dest,
struct buffer src,
int  len 
)
inlinestatic

Truncate src to len bytes and copy any excess to dest.

If src->len > len, src is truncated to len bytes and the remaining bytes are appended to dest. If src->len <= len, nothing is copied and true is returned.

Parameters
destDestination buffer for the excess data.
srcSource buffer to truncate.
lenMaximum number of bytes to keep in src.
Returns
true on success, false if len is negative or copying fails.

Definition at line 1438 of file buffer.h.

References buf_advance(), buf_copy(), and buffer::len.

Referenced by command_line_get(), and stream_buf_added().

◆ buf_copy_n()

static bool buf_copy_n ( struct buffer dest,
struct buffer src,
int  n 
)
inlinestatic

Read n bytes from src and append them to dest.

Consumes the bytes from src.

Parameters
destDestination buffer.
srcSource buffer (modified).
nNumber of bytes to copy.
Returns
true on success, false if src has fewer than n bytes or dest has insufficient capacity.

Definition at line 1381 of file buffer.h.

References buf_read_alloc(), buf_write(), and buffer::len.

Referenced by fragment_ready_to_send(), ipv6_send_icmp_unreachable(), and write_outgoing_tls_ciphertext().

◆ buf_copy_range()

static bool buf_copy_range ( struct buffer dest,
int  dest_index,
const struct buffer src,
int  src_index,
int  src_len 
)
inlinestatic

Copy a range of bytes from one buffer into a specific position in another.

Copies src_len bytes starting at src_index within src content into dest at dest_index relative to the content start. Updates dest->len if the write extends beyond the current content. Does not advance either buffer's offset.

Parameters
destDestination buffer.
dest_indexByte offset within dest content to write at.
srcSource buffer.
src_indexByte offset within src content to read from.
src_lenNumber of bytes to copy.
Returns
true on success, false if any index or length is out of range.

Definition at line 1408 of file buffer.h.

References buffer::capacity, buffer::data, buffer::len, and buffer::offset.

Referenced by fragment_incoming().

◆ buf_cstr()

static const char * buf_cstr ( const struct buffer buf)
inlinestatic

Return the buffer content pointer cast to const char *.

Parameters
bufThe buffer to query.
Returns
The content pointer as a const char *, or NULL if buf is invalid.

Definition at line 583 of file buffer.h.

References buf_cbptr().

◆ buf_defined()

static bool buf_defined ( const struct buffer buf)
inlinestatic

Return true iff buf has a non-NULL data pointer.

A defined buffer has been allocated but may have zero length or negative len (i.e. it is not necessarily valid).

Parameters
bufThe buffer to test.

Definition at line 398 of file buffer.h.

References buffer::data.

Referenced by buf_printf(), recv_line(), socks_process_outgoing_udp(), status_close(), status_flush(), status_read(), and stream_buf_get_final().

◆ buf_equal()

static bool buf_equal ( const struct buffer a,
const struct buffer b 
)
inlinestatic

Return true if buffer contents are equal.

Definition at line 1610 of file buffer.h.

References BLEN, BLENZ, CBPTR, and buffer::len.

Referenced by tls_crypt_v2_wrap_unwrap_max_metadata().

◆ buf_extract_field()

char * buf_extract_field ( struct buffer buf,
char  sep,
struct gc_arena gc 
)

Extract a field from buf that ends with the sep character.

The returned string is allocated in the gc_arena. If the separator character is not found, the function returns the nullptr.

The buffer is also forwarded to the point after the separator character.

Definition at line 1389 of file buffer.c.

References buf_advance(), buf_len(), buf_valid(), CBPTR, gc, gc_malloc(), and buffer::len.

Referenced by test_buffer_extract_field().

◆ buf_forward_capacity()

static int buf_forward_capacity ( const struct buffer buf)
inlinestatic

Return the number of bytes that can still be appended to the buffer.

This is the space between the end of the current content and the end of the allocated memory.

Parameters
bufThe buffer to query.
Returns
Number of bytes available for appending, or 0 if buf is invalid.

Definition at line 1059 of file buffer.h.

References buf_valid(), buffer::capacity, buffer::len, and buffer::offset.

Referenced by bio_read(), buf_catrunc(), buf_printf(), buf_puts(), mutate_ncp_cipher_list(), and tls_crypt_v2_wrap_client_key().

◆ buf_forward_capacity_total()

static int buf_forward_capacity_total ( const struct buffer buf)
inlinestatic

Return the total number of bytes available from the current offset to the end of the allocated memory.

Unlike buf_forward_capacity(), this includes the bytes already occupied by the current content.

Parameters
bufThe buffer to query.
Returns
Capacity minus offset, or 0 if buf is invalid.

Definition at line 1088 of file buffer.h.

References buf_valid(), buffer::capacity, buffer::len, and buffer::offset.

Referenced by buf_catrunc(), read_control_auth(), and test_write_dhcp_search_str().

◆ buf_inc_len()

static bool buf_inc_len ( struct buffer buf,
int  inc 
)
inlinestatic

Increase or decrease the length of a buffer.

Adjusts buf->len by inc bytes. A negative inc shrinks the buffer. The operation is bounds-checked via buf_safe_bidir().

Parameters
bufThe buffer to modify.
incNumber of bytes to add to the length (may be negative).
Returns
true on success, false if the adjustment would violate bounds.

Definition at line 1140 of file buffer.h.

References buf_safe_bidir(), and buffer::len.

Referenced by buf_chomp(), buf_null_terminate(), buffer_read_from_file(), generate_ephemeral_key(), openvpn_decrypt_aead(), openvpn_decrypt_v1(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), status_read(), test_buffer_null_terminate(), test_character_string_mod_buf(), test_verify_hmac_none(), tls_crypt_unwrap(), tls_crypt_v2_extract_client_key(), tls_crypt_v2_unwrap_client_key(), tls_crypt_v2_wrap_client_key(), tls_crypt_v2_wrap_too_long_metadata(), tls_crypt_v2_write_client_key_file(), tls_crypt_wrap(), x509_get_sha1_fingerprint(), and x509_get_sha256_fingerprint().

◆ buf_init_dowork()

static bool buf_init_dowork ( struct buffer buf,
int  offset 
)
inlinestatic

Initialise a buffer with a given initial offset.

Sets buf->len to zero and buf->offset to offset. The buffer must already be allocated. Returns false (without modifying buf) if offset is negative, exceeds the buffer capacity, or the data pointer is NULL.

Parameters
bufThe buffer to initialise.
offsetInitial byte offset from the start of the allocated memory.
Returns
true on success, false if the parameters are invalid.

Definition at line 633 of file buffer.h.

References buffer::capacity, buffer::data, buffer::len, and buffer::offset.

◆ buf_len()

static int buf_len ( const struct buffer buf)
static

◆ buf_null_terminate()

void buf_null_terminate ( struct buffer buf)

Force a null terminator at the end of the buffer content.

If there is free capacity, a '\0' byte is appended. If the buffer is full, the last content byte is overwritten with '\0' (i.e. the last character is truncated to make room). The function has no effect on an empty or invalid buffer.

Parameters
bufThe buffer to null-terminate.

Definition at line 501 of file buffer.c.

References BLAST, buf_inc_len(), buf_safe(), buf_write_u8(), and buffer::len.

Referenced by buf_chomp(), buffer_read_from_file(), mutate_ncp_cipher_list(), status_read(), test_buffer_null_terminate(), and tls_crypt_v2_write_client_key_file().

◆ buf_parse()

bool buf_parse ( struct buffer buf,
const int  delim,
char *  line,
const int  size 
)

Extract the next token from a buffer, delimited by a given character.

Reads bytes from buf one at a time until delim or end-of-buffer is encountered. The token (without the delimiter) is written into line, which is always null-terminated. The delimiter byte is consumed from buf but not included in line.

Parameters
bufSource buffer to parse. The consumed portion is advanced.
delimDelimiter character.
lineOutput buffer for the extracted token.
sizeSize of line in bytes (must be > 0).
Returns
false only when end-of-buffer is reached and no characters were extracted; true otherwise (including when a delimiter was found or line was truncated).

Definition at line 775 of file buffer.c.

References ASSERT, buf_advance(), buf_peek_u8(), and buffer::len.

Referenced by apply_push_options(), get_user_pass_cr(), ifconfig_pool_read(), in_src_get(), make_inline_array(), man_kill(), man_output_peer_info_env(), options_warning_extract_parm1(), options_warning_safe_scan1(), options_warning_safe_scan2(), output_peer_info_env(), parse_auth_challenge(), parse_auth_pending_keywords(), push_update_digest(), read_config_string(), and test_buffer_parse().

◆ buf_peek_u8()

static int buf_peek_u8 ( const struct buffer buf)
inlinestatic

Return the first byte of the buffer without consuming it.

Parameters
bufThe buffer to peek at.
Returns
The first byte as an unsigned value (0–255), or -1 if the buffer is empty.

Definition at line 1492 of file buffer.h.

References BLEN, CBPTR, and buffer::len.

Referenced by buf_parse(), and buf_read_u8().

◆ buf_prepend()

static uint8_t * buf_prepend ( struct buffer buf,
ssize_t  size 
)
inlinestatic

Make space at the front of a buffer for prepending data.

Moves the content start backwards by size bytes, increasing len and decreasing offset by the same amount.

Parameters
bufThe buffer to modify.
sizeNumber of bytes to reserve for prepending.
Returns
Pointer to the newly reserved space (new content start), or NULL if buf is invalid or there is insufficient prepend capacity.

Definition at line 1163 of file buffer.h.

References BPTR, buf_valid(), buffer::len, and buffer::offset.

Referenced by buf_sub(), buf_write_prepend(), openvpn_encrypt_v1(), and vlan_encapsulate().

◆ buf_printf()

bool buf_printf ( struct buffer buf,
const char *  format,
  ... 
)

printf-style append to a buffer with overflow check.

Formats a string and appends it to buf. Due to the use of vsnprintf(), one byte of forward capacity is reserved for a null terminator, so at most buf_forward_capacity(buf) - 1 bytes of formatted output are written.

Parameters
bufThe buffer to append to.
formatprintf-style format string.
...Format arguments.
Returns
true if the entire formatted string fit in the buffer, false if it was truncated.

Definition at line 226 of file buffer.c.

References BEND, buf_defined(), buf_forward_capacity(), buffer::capacity, buffer::data, and buffer::len.

Referenced by add_delim_if_non_empty(), add_option(), ce_management_query_proxy(), ce_management_query_remote(), check_inline_file(), construct_name_value(), dco_version_string(), forge_msg(), fork_dhcp_action(), fork_register_dns_action(), format_common_name(), format_hex_ex(), format_ip_addr_string(), format_route_entry(), frame_print(), get_device_guid(), get_unspecified_device_guid(), get_user_pass_cr(), hostname_randomize(), ifconfig_options_string(), ipset2ascii_all(), link_socket_connection_initiated(), log_entry_print(), management_callback_send_cc_message(), management_hold(), management_query_multiline(), management_query_user_pass(), mroute_addr_print_ex(), mroute_helper_regenerate(), msg_flags_string(), multi_instance_string(), ncp_expanded_ciphers(), options_string(), options_string_compat_lzo(), options_warning_safe_ml(), p2p_mode_ncp(), packet_id_net_print(), packet_id_persist_print(), platform_gen_path(), plugin_mask_string(), prepare_push_reply(), prepend_dir(), print_argv(), print_default_gateway(), print_in_port_t(), print_key_id(), print_link_socket_actual_ex(), print_netmask(), print_opt_route(), print_opt_route_gateway(), print_opt_route_gateway_dhcp(), print_opt_topology(), print_sockaddr_ex(), print_str_int(), proto2ascii_all(), protocol_dump(), push_peer_info(), push_peer_info_peerid(), read_inline_file(), reliable_ack_print(), send_auth_failed(), send_auth_pending_messages(), send_push_options(), send_push_reply(), send_push_reply_auth_token(), server_pushed_info(), setenv_format_indexed_name(), setenv_route(), setenv_route_addr(), setenv_route_ipv6(), setenv_str_safe(), socket_stat(), strerror_win32(), system_error_message(), test_buffer_printf_catrunc(), test_load_certificate_and_key_uri(), time_string(), tls_print_deferred_options_results(), tun_stat(), tv_string(), username_password_as_base64(), verify_cert(), wide_cmd_line(), win32_print_arch(), win32_version_string(), window_title_generate(), and write_key_file().

◆ buf_puts()

bool buf_puts ( struct buffer buf,
const char *  str 
)

Append a string to a buffer with overflow check.

Parameters
bufThe buffer to append to.
strThe null-terminated string to append.
Returns
true if the string fit in the buffer, false if it was truncated.

Definition at line 253 of file buffer.c.

References BEND, buf_forward_capacity(), buffer::capacity, buffer::data, buffer::len, and strncpynt().

Referenced by mutate_ncp_cipher_list(), and print_sockaddr_ex().

◆ buf_read()

static bool buf_read ( struct buffer src,
void *  dest,
int  size 
)
inlinestatic

Read bytes from the front of a buffer into a caller-supplied destination.

Consumes size bytes from src and copies them to dest.

Parameters
srcSource buffer (modified).
destDestination memory.
sizeNumber of bytes to read.
Returns
true on success, false if src has fewer than size bytes.

Definition at line 1472 of file buffer.h.

References buf_read_alloc(), and buffer::len.

Referenced by auth_token_init_secret(), buf_read_u16(), buf_read_u32(), buf_read_u64(), fragment_incoming(), key_source2_read(), packet_id_read(), packet_id_read_epoch(), protocol_dump(), read_string(), read_string_alloc(), reliable_ack_parse(), reliable_ack_print(), reliable_ack_read_packet_id(), session_id_read(), socks_process_incoming_udp(), stream_buf_added(), and tls_crypt_v2_init_client_key().

◆ buf_read_alloc()

static uint8_t * buf_read_alloc ( struct buffer buf,
int  size 
)
inlinestatic

Consume bytes from the front of a buffer for reading.

Returns a pointer to the current content start and advances the buffer by size bytes.

Parameters
bufThe buffer to read from.
sizeNumber of bytes to consume.
Returns
Pointer to the start of the consumed region, or NULL if size is negative or exceeds the current length.

Definition at line 1235 of file buffer.h.

References BPTR, buffer::len, and buffer::offset.

Referenced by buf_copy_n(), and buf_read().

◆ buf_read_u16()

static int buf_read_u16 ( struct buffer buf)
inlinestatic

Read and consume a uint16_t from the front of a buffer.

The value is converted from network byte order via ntohs().

Parameters
bufThe buffer to read from.
Returns
The host-byte-order value, or -1 if the buffer has fewer than 2 bytes.

Definition at line 1532 of file buffer.h.

References buf_read(), and buffer::len.

Referenced by parse_early_negotiation_tlvs(), process_received_occ_msg(), read_string(), read_string_alloc(), and socks_process_incoming_udp().

◆ buf_read_u32()

static uint32_t buf_read_u32 ( struct buffer buf,
bool *  good 
)
inlinestatic

Read and consume a uint32_t from the front of a buffer.

The value is converted from network byte order via ntohl().

Parameters
bufThe buffer to read from.
goodIf non-NULL, set to true on success or false on failure.
Returns
The host-byte-order value, or 0 if the buffer has fewer than 4 bytes (check *good to distinguish from a legitimate zero).

Definition at line 1554 of file buffer.h.

References buf_read(), and buffer::len.

◆ buf_read_u64()

static uint64_t buf_read_u64 ( struct buffer buf,
bool *  good 
)
inlinestatic

Read and consume a uint64_t from the front of a buffer.

The value is converted from network byte order via ntohll().

Parameters
bufThe buffer to read from.
goodIf non-NULL, set to true on success or false on failure.
Returns
The host-byte-order value, or 0 if the buffer has fewer than 8 bytes (check *good to distinguish from a legitimate zero).

Definition at line 1587 of file buffer.h.

References buf_read(), buffer::len, and ntohll.

◆ buf_read_u8()

static int buf_read_u8 ( struct buffer buf)
inlinestatic

Read and consume a uint8_t from the front of a buffer.

Parameters
bufThe buffer to read from.
Returns
The byte value (0–255), or -1 if the buffer is empty.

Definition at line 1511 of file buffer.h.

References buf_advance(), buf_peek_u8(), and buffer::len.

Referenced by buf_substring_len(), key_method_2_read(), parse_auth_pending_keywords(), process_incoming_push_reply(), process_push_update(), process_received_occ_msg(), receive_cr_response(), server_pushed_info(), server_pushed_signal(), socks_process_incoming_udp(), status_read(), and tls_crypt_v2_verify_metadata().

◆ buf_reset()

static void buf_reset ( struct buffer buf)
inlinestatic

Reset a buffer to an undefined (unallocated) state.

Sets all fields to zero/NULL without freeing any memory. Use free_buf() first if the buffer owns allocated memory.

Parameters
bufThe buffer to reset.

Definition at line 597 of file buffer.h.

References buffer::capacity, buffer::data, buffer::len, and buffer::offset.

Referenced by multi_process_drop_outgoing_tun(), multi_tcp_process_outgoing_link(), process_incoming_link_part1(), process_incoming_link_part2(), process_incoming_tun(), process_outgoing_link(), process_outgoing_tun(), and status_open().

◆ buf_reset_len()

static void buf_reset_len ( struct buffer buf)
inlinestatic

Reset the length and offset of a buffer to zero.

The underlying allocation is preserved and capacity is unchanged. Equivalent to rewinding the buffer to the beginning for fresh writing.

Parameters
bufThe buffer to reset.

Definition at line 614 of file buffer.h.

References buffer::len, and buffer::offset.

Referenced by create_client_key_input(), multi_process_incoming_tun(), send_push_options(), send_push_reply(), test_buffer_parse(), test_parse_ack(), test_tls_decrypt_lite_auth(), test_tls_decrypt_lite_crypt(), test_tls_decrypt_lite_none(), test_verify_hmac_none(), test_verify_hmac_none_out_of_range_ack(), and test_verify_hmac_tls_auth().

◆ buf_reverse_capacity()

static int buf_reverse_capacity ( const struct buffer buf)
inlinestatic

Return the number of bytes available for prepending to the buffer.

This is the number of bytes between the start of the allocated memory and the current content start (i.e. buf->offset).

Parameters
bufThe buffer to query.
Returns
buf->offset, or 0 if buf is invalid.

Definition at line 1116 of file buffer.h.

References buf_valid(), and buffer::offset.

Referenced by vlan_encapsulate().

◆ buf_rmtail()

void buf_rmtail ( struct buffer buf,
uint8_t  remove 
)

Remove all occurrences of a specific byte from the end of a buffer.

Parameters
bufThe buffer to modify.
removeThe byte value to strip from the tail.

Definition at line 486 of file buffer.c.

References BLAST, and buffer::len.

◆ buf_safe()

static bool buf_safe ( const struct buffer buf,
size_t  len 
)
inlinestatic

Check whether len bytes can be appended to a buffer.

Parameters
bufThe buffer to check.
lenNumber of bytes to append.
Returns
true if buf is valid, len is within the allowed range, and there is sufficient capacity after the current content.

Definition at line 1015 of file buffer.h.

References buf_size_valid(), buf_valid(), buffer::capacity, buffer::len, and buffer::offset.

Referenced by alloc_buf_sock_tun(), buf_null_terminate(), buf_write_alloc(), build_dhcp_options_string(), check_ping_send_dowork(), check_send_occ_msg_dowork(), ipv6_send_icmp_unreachable(), openvpn_decrypt_aead(), openvpn_decrypt_v1(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), push_peer_info(), read_incoming_tun(), read_inline_file(), stream_buf_get_next(), tls_crypt_unwrap(), tls_crypt_wrap(), write_dhcp_search_str(), write_dhcp_str(), write_dhcp_u32_array(), and write_dhcp_u8().

◆ buf_safe_bidir()

static bool buf_safe_bidir ( const struct buffer buf,
int  len 
)
inlinestatic

Check whether len bytes can be added to or removed from a buffer.

Accepts negative len to verify that bytes can be removed (length decreased).

Parameters
bufThe buffer to check.
lenNumber of bytes to add (positive) or remove (negative).
Returns
true if the resulting length would remain non-negative and within the allocated capacity.

Definition at line 1034 of file buffer.h.

References buf_size_valid_signed(), buf_valid(), buffer::capacity, buffer::len, and buffer::offset.

Referenced by buf_inc_len().

◆ buf_set_read()

static void buf_set_read ( struct buffer buf,
const uint8_t *  data,
size_t  size 
)
inlinestatic

Initialise a buffer with an externally provided read-only memory region.

Sets up buf so that the entire data region is the buffer content (offset is 0, len and capacity are both set to size). The data pointer is cast away from const. Calls buf_size_error() (which does not return) if size exceeds BUF_SIZE_MAX.

Parameters
bufThe buffer to initialise.
dataPointer to the read-only memory region.
sizeSize of the memory region in bytes.

Definition at line 685 of file buffer.h.

References buf_size_error(), buf_size_valid(), buffer::capacity, buffer::data, buffer::len, and buffer::offset.

Referenced by crypto_pem_encode_decode_loopback(), get_user_pass_cr(), make_inline_array(), man_kill(), man_output_peer_info_env(), openvpn_decrypt_v1(), output_peer_info_env(), parse_auth_challenge(), read_config_string(), read_key_file(), read_pem_key_file(), string_alloc_buf(), and write_pem_key_file().

◆ buf_set_write()

static void buf_set_write ( struct buffer buf,
uint8_t *  data,
int  size 
)
inlinestatic

Initialise a buffer with an externally provided writable memory region.

Sets up buf to use data as its backing store for writing. The first byte of data is set to zero. Calls buf_size_error() (which does not return) if size exceeds BUF_SIZE_MAX.

Parameters
bufThe buffer to initialise.
dataPointer to the memory region to use.
sizeSize of the memory region in bytes.

Definition at line 656 of file buffer.h.

References buf_size_error(), buf_size_valid(), buffer::capacity, buffer::data, buffer::len, and buffer::offset.

Referenced by calculate_session_id_hmac(), crypto_pem_encode_decode_loopback(), get_device_guid(), get_unspecified_device_guid(), get_user_pass_cr(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), replace_default_in_ncp_ciphers_option(), setenv_str_safe(), tls_crypt_v2_init_server_key(), tls_crypt_v2_unwrap_client_key(), and tls_print_deferred_options_results().

◆ buf_size_error()

void buf_size_error ( const size_t  size)

Report a buffer size error and abort.

Called when a requested buffer size exceeds BUF_SIZE_MAX or is otherwise invalid. Calls msg(M_FATAL) and does not return.

Parameters
sizeThe invalid size that was requested.

Definition at line 54 of file buffer.c.

References M_FATAL, and msg.

Referenced by alloc_buf(), alloc_buf_gc(), buf_set_read(), and buf_set_write().

◆ buf_size_valid()

static bool buf_size_valid ( const size_t  size)
inlinestatic

Return true iff size is within the allowed buffer size range.

Parameters
sizeThe size to check.
Returns
true if size < BUF_SIZE_MAX.

Definition at line 541 of file buffer.h.

References BUF_SIZE_MAX, and likely.

Referenced by alloc_buf(), alloc_buf_gc(), buf_catrunc(), buf_safe(), buf_set_read(), buf_set_write(), and buf_string_match_head_str().

◆ buf_size_valid_signed()

static bool buf_size_valid_signed ( const int  size)
inlinestatic

Return true iff a signed size is within the allowed buffer size range.

Accepts negative values (used for bidirectional length adjustments) as long as the absolute value is below BUF_SIZE_MAX.

Parameters
sizeThe signed size to check.
Returns
true if -BUF_SIZE_MAX <= size < BUF_SIZE_MAX.

Definition at line 557 of file buffer.h.

References BUF_SIZE_MAX, and likely.

Referenced by buf_safe_bidir().

◆ buf_str()

static char * buf_str ( struct buffer buf)
inlinestatic

Return the buffer content pointer cast to char *.

Parameters
bufThe buffer to query.
Returns
The content pointer as a char *, or NULL if buf is invalid.

Definition at line 570 of file buffer.h.

References buf_bptr().

Referenced by mutate_ncp_cipher_list(), and prepare_push_reply().

◆ buf_string_compare_advance()

bool buf_string_compare_advance ( struct buffer src,
const char *  match 
)

Compare the head of src with match and advance past it if equal.

If the buffer starts with match, the matched bytes are consumed from src. NOT constant time. Do not use when comparing HMACs.

Parameters
srcBuffer to compare and advance.
matchNull-terminated string to compare against.
Returns
true if the buffer started with match (and was advanced).

Definition at line 739 of file buffer.c.

References buf_advance(), buf_string_match_head_str(), and buffer::len.

Referenced by process_incoming_push_msg(), receive_auth_failed(), and send_single_push_update().

◆ buf_string_match()

static bool buf_string_match ( const struct buffer src,
const void *  match,
int  size 
)
inlinestatic

Compare src buffer contents with match.

NOT constant time. Do not use when comparing HMACs.

Definition at line 1620 of file buffer.h.

References CBPTR, and buffer::len.

Referenced by is_ping_msg().

◆ buf_string_match_head()

static bool buf_string_match_head ( const struct buffer src,
const void *  match,
int  size 
)
inlinestatic

Compare first size bytes of src buffer contents with match.

NOT constant time. Do not use when comparing HMACs.

Definition at line 1634 of file buffer.h.

References CBPTR, and buffer::len.

Referenced by is_occ_msg().

◆ buf_string_match_head_str()

bool buf_string_match_head_str ( const struct buffer src,
const char *  match 
)

Return true if the head of src matches the string match.

Compares the first strlen(match) bytes of src content with match. NOT constant time. Do not use when comparing HMACs.

Parameters
srcBuffer whose head is compared.
matchNull-terminated string to compare against.
Returns
true if the buffer starts with match.

Definition at line 728 of file buffer.c.

References buf_size_valid(), CBPTR, and buffer::len.

Referenced by buf_string_compare_advance(), parse_incoming_control_channel_command(), and receive_auth_failed().

◆ buf_sub()

struct buffer buf_sub ( struct buffer buf,
int  size,
bool  prepend 
)

Return a sub-buffer of another buffer.

Either allocates size bytes from the front or back of buf, shrinking buf accordingly, and returns a buffer pointing into the same memory.

Parameters
bufSource buffer to carve the sub-buffer from.
sizeNumber of bytes to include in the sub-buffer.
prependIf true, take bytes from the front of buf (prepend space); if false, take bytes from the end (append space).
Returns
A buffer referencing the allocated region, or an undefined buffer if buf has insufficient capacity.

Definition at line 207 of file buffer.c.

References buf_prepend(), buf_write_alloc(), CLEAR, buffer::data, and buffer::len.

Referenced by reliable_ack_write(), and socks_process_outgoing_udp().

◆ buf_substring_len()

int buf_substring_len ( const struct buffer buf,
int  delim 
)

Return the number of bytes in a buffer up to and including a delimiter.

The count includes the delimiter byte, so it can be passed straight to buf_copy_excess() to split off a complete record, keeping the delimiter with it.

Parameters
bufThe buffer to scan.
delimDelimiter byte to search for.
Returns
Byte count including the first delim, or -1 if the buffer contains no delim.

Definition at line 753 of file buffer.c.

References buf_read_u8(), and buffer::len.

Referenced by command_line_get().

◆ buf_valid()

static bool buf_valid ( const struct buffer buf)
inlinestatic

Return true iff buf is valid.

A buffer is valid when its data pointer is non-NULL and its len is non-negative.

Parameters
bufThe buffer to test.

Definition at line 412 of file buffer.h.

References buffer::data, buffer::len, and likely.

Referenced by buf_advance(), buf_cbptr(), buf_extract_field(), buf_forward_capacity(), buf_forward_capacity_total(), buf_len(), buf_prepend(), buf_reverse_capacity(), buf_safe(), buf_safe_bidir(), connection_entry_preload_key(), read_key_file(), and read_pem_key_file().

◆ buf_write()

static bool buf_write ( struct buffer dest,
const void *  src,
size_t  size 
)
inlinestatic

Append data to a buffer.

Copies size bytes from src to the end of dest.

Parameters
destDestination buffer.
srcData to append.
sizeNumber of bytes to append.
Returns
true on success, false if there is insufficient capacity.

Definition at line 1260 of file buffer.h.

References buf_write_alloc(), and buffer::len.

Referenced by __wrap_buffer_read_from_file(), buf_assign(), buf_copy(), buf_copy_n(), buf_write_u16(), buf_write_u32(), buf_write_u64(), buf_write_u8(), buffer_list_aggregate_separator(), calculate_session_id_hmac(), check_ping_send_dowork(), check_send_occ_msg_dowork(), create_metadata_days_ago(), crypto_pem_encode(), extract_command_buffer(), generate_auth_token(), management_query_cert(), management_query_pk_sig(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), openvpn_PRF(), options_string_compat_lzo(), ovpn_expand_label(), packet_id_write(), packet_id_write_epoch(), random_bytes_to_buf(), reliable_ack_write(), replace_default_in_ncp_ciphers_option(), send_line_crlf(), session_id_write(), socks_process_outgoing_udp(), test_buffer_chomp(), test_buffer_extract_field(), test_buffer_null_terminate(), test_buffer_parse(), test_character_string_mod_buf(), test_data_channel_known_vectors_run(), test_extract_control_message(), test_incoming_push_continuation_route_accumulation(), test_incoming_push_message_1(), test_incoming_push_message_bad_format(), test_incoming_push_message_basic(), test_incoming_push_message_error1(), test_incoming_push_message_error2(), test_incoming_push_message_mix(), test_incoming_push_message_mix2(), test_incoming_push_message_not_updatable_option(), test_parse_ack(), test_tls_crypt_setup(), test_tls_decrypt_lite_auth(), test_tls_decrypt_lite_crypt(), test_tls_decrypt_lite_none(), test_verify_hmac_none(), test_verify_hmac_none_out_of_range_ack(), test_verify_hmac_tls_auth(), tls_crypt_v2_wrap_client_key(), tls_crypt_v2_write_client_key_file(), tls_reset_standalone(), tls_wrap_control(), write_dhcp_search_str(), write_dhcp_str(), and write_string().

◆ buf_write_alloc()

static uint8_t * buf_write_alloc ( struct buffer buf,
size_t  size 
)
inlinestatic

Reserve space at the end of a buffer for writing.

Increases buf->len by size and returns a pointer to the start of the newly reserved region.

Parameters
bufThe buffer to allocate space in.
sizeNumber of bytes to reserve.
Returns
Pointer to the start of the reserved space, or NULL if there is insufficient capacity.

Definition at line 1210 of file buffer.h.

References BPTR, buf_safe(), and buffer::len.

Referenced by buf_sub(), buf_write(), crypto_pem_decode(), do_data_channel_round_trip(), encrypt_one_packet(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), test_crypto(), test_data_channel_known_vectors_run(), tls_crypt_fail_msg_too_long(), tls_crypt_loopback_max_len(), tls_crypt_v2_wrap_client_key(), tls_crypt_v2_wrap_unwrap_dst_too_small(), tls_crypt_v2_wrap_unwrap_max_metadata(), and tls_crypt_wrap().

◆ buf_write_prepend()

static bool buf_write_prepend ( struct buffer dest,
const void *  src,
int  size 
)
inlinestatic

Prepend data to a buffer.

Copies size bytes from src into the prepend space at the front of dest.

Parameters
destDestination buffer.
srcData to prepend.
sizeNumber of bytes to prepend.
Returns
true on success, false if there is insufficient prepend capacity.

Definition at line 1284 of file buffer.h.

References buf_prepend(), and buffer::len.

Referenced by fragment_prepend_flags(), ipv6_send_icmp_unreachable(), link_socket_write_tcp(), link_socket_write_win32(), openvpn_encrypt_v1(), packet_id_write(), reliable_mark_active_outgoing(), session_id_write_prepend(), tls_prepend_opcode_v1(), tls_prepend_opcode_v2(), and tls_wrap_control().

◆ buf_write_u16()

static bool buf_write_u16 ( struct buffer dest,
uint16_t  data 
)
inlinestatic

Append a uint16_t to a buffer in network byte order.

Parameters
destDestination buffer.
dataValue to append (converted with htons()).
Returns
true on success, false if there is insufficient capacity.

Definition at line 1318 of file buffer.h.

References buf_write(), buffer::data, and buffer::len.

Referenced by check_send_occ_msg_dowork(), ovpn_expand_label(), socks_process_outgoing_udp(), tls_reset_standalone(), write_empty_string(), and write_string().

◆ buf_write_u32()

static bool buf_write_u32 ( struct buffer dest,
uint32_t  data 
)
inlinestatic

Append a uint32_t to a buffer in network byte order.

Parameters
destDestination buffer.
dataValue to append (converted with htonl()).
Returns
true on success, false if there is insufficient capacity.

Definition at line 1333 of file buffer.h.

References buf_write(), buffer::data, and buffer::len.

Referenced by build_dhcp_options_string(), key_method_2_write(), test_verify_hmac_none(), tls_reset_standalone(), and write_dhcp_u32_array().

◆ buf_write_u64()

static bool buf_write_u64 ( struct buffer dest,
uint64_t  data 
)
inlinestatic

Append a uint64_t to a buffer in network byte order.

Parameters
destDestination buffer.
dataValue to append (converted with htonll()).
Returns
true on success, false if there is insufficient capacity.

Definition at line 1348 of file buffer.h.

References buf_write(), buffer::data, htonll, and buffer::len.

◆ buf_write_u8()

static bool buf_write_u8 ( struct buffer dest,
uint8_t  data 
)
inlinestatic

◆ buffer_list_advance()

void buffer_list_advance ( struct buffer_list ol,
ssize_t  n 
)

Advance past n bytes in the head buffer, popping it if it becomes empty.

n must not exceed the length of the head buffer; passing a larger value triggers an assertion failure.

Parameters
olThe list whose head buffer is to be advanced.
nNumber of bytes to skip in the head buffer.

Definition at line 1319 of file buffer.c.

References ASSERT, BLEN, buf_advance(), buffer_list_pop(), buffer_list::head, and buffer::len.

Referenced by man_write().

◆ buffer_list_aggregate()

void buffer_list_aggregate ( struct buffer_list bl,
const size_t  max 
)

Aggregates as many buffers as possible from bl in a new buffer of maximum length max_len .

All the aggregated buffers are removed from the list and replaced by the new one, followed by any additional (non-aggregated) data.

Parameters
blthe list of buffer to aggregate
maxthe maximum length of the aggregated buffer

Definition at line 1296 of file buffer.c.

References buffer_list_aggregate_separator().

Referenced by in_extra_dispatch(), man_write(), and management_query_multiline_flatten().

◆ buffer_list_aggregate_separator()

void buffer_list_aggregate_separator ( struct buffer_list bl,
const size_t  max_len,
const char *  sep 
)

Aggregates as many buffers as possible from bl in a new buffer of maximum length max_len .

sep is written after each copied buffer (also after the last one). All the aggregated buffers are removed from the list and replaced by the new one, followed by any additional (non-aggregated) data. Nothing happens if max_len is not enough to aggregate at least 2 buffers.

Parameters
blthe list of buffer to aggregate
max_lenthe maximum length of the aggregated buffer
septhe separator to put between buffers during aggregation

Definition at line 1251 of file buffer.c.

References alloc_buf(), ALLOC_OBJ_CLEAR, BLENZ, buffer_entry::buf, buf_copy(), buf_write(), free_buf(), buffer_list::head, buffer::len, buffer_entry::next, buffer_list::size, and buffer_list::tail.

Referenced by buffer_list_aggregate(), management_query_multiline_flatten_newline(), test_buffer_list_aggregate_separator_all(), test_buffer_list_aggregate_separator_empty(), test_buffer_list_aggregate_separator_emptybuffers(), test_buffer_list_aggregate_separator_noop(), test_buffer_list_aggregate_separator_nosep(), test_buffer_list_aggregate_separator_two(), and test_buffer_list_aggregate_separator_zerolen().

◆ buffer_list_defined()

bool buffer_list_defined ( const struct buffer_list ol)

Checks if the list is valid and non-empty.

Parameters
olthe list to check
Returns
true iff ol is not NULL and contains at least one buffer

Definition at line 1175 of file buffer.c.

References buffer_list::head, and buffer_list::size.

Referenced by buffer_list_pop(), man_update_io_state(), management_query_multiline_flatten(), and management_query_multiline_flatten_newline().

◆ buffer_list_file()

struct buffer_list * buffer_list_file ( const char *  fn,
int  max_line_len 
)

Read a file into a buffer list, one buffer per line.

Opens fn for reading and pushes each line into a newly allocated buffer list using fgets(). Lines longer than max_line_len - 1 bytes are split across multiple consecutive buffers.

Parameters
fnPath to the file to read.
max_line_lenMaximum number of bytes (including null terminator) read per fgets() call.
Returns
Pointer to the new buffer list, or NULL if the file could not be opened or memory allocation failed.

Definition at line 1333 of file buffer.c.

References buffer_list_new(), buffer_list_push(), and platform_fopen().

Referenced by key_state_check_auth_pending_file().

◆ buffer_list_free()

void buffer_list_free ( struct buffer_list ol)

◆ buffer_list_new()

struct buffer_list * buffer_list_new ( void  )

Allocate an empty buffer list of capacity max_size.

Returns
the new list

Definition at line 1156 of file buffer.c.

References ALLOC_OBJ_CLEAR, and buffer_list::size.

Referenced by buffer_list_file(), in_extra_reset(), man_connection_init(), send_push_update(), test_buffer_list_setup(), and tls_send_payload().

◆ buffer_list_peek()

struct buffer * buffer_list_peek ( struct buffer_list ol)

◆ buffer_list_pop()

void buffer_list_pop ( struct buffer_list ol)

Remove and free the head buffer of the list.

Does nothing if ol is NULL or empty.

Parameters
olThe list to pop from.

Definition at line 1302 of file buffer.c.

References buffer_entry::buf, buffer_list_defined(), free_buf(), buffer_list::head, buffer_entry::next, buffer_list::size, and buffer_list::tail.

Referenced by buffer_list_advance(), and flush_payload_buffer().

◆ buffer_list_push()

void buffer_list_push ( struct buffer_list ol,
const char *  str 
)

Allocates and appends a new buffer containing str as data to ol.

Parameters
olthe list to append the new buffer to
strthe string to copy into the new buffer

Definition at line 1196 of file buffer.c.

References buffer_entry::buf, buffer_list_push_data(), and buffer::len.

Referenced by buffer_list_file(), man_output_list_push_str(), man_read(), message_splitter(), and test_buffer_list_setup().

◆ buffer_list_push_data()

struct buffer_entry * buffer_list_push_data ( struct buffer_list ol,
const void *  data,
size_t  size 
)

Allocates and appends a new buffer containing data of length size.

Parameters
olthe list to append the new buffer to
datathe data to copy into the new buffer
sizethe length of data to copy into the buffer
Returns
the new buffer

Definition at line 1210 of file buffer.c.

References alloc_buf(), ALLOC_OBJ_CLEAR, ASSERT, buffer_entry::buf, buffer::data, buffer_list::head, buffer::len, buffer_entry::next, buffer_list::size, and buffer_list::tail.

Referenced by buffer_list_push(), test_buffer_list_setup(), and tls_send_payload().

◆ buffer_list_reset()

void buffer_list_reset ( struct buffer_list ol)

Empty the list ol and frees all the contained buffers.

Parameters
olthe list to reset

Definition at line 1181 of file buffer.c.

References buffer_entry::buf, free_buf(), buffer_list::head, buffer_entry::next, buffer_list::size, and buffer_list::tail.

Referenced by buffer_list_free(), man_new_connection_post(), man_read(), and man_reset_client_socket().

◆ buffer_read_from_file()

struct buffer buffer_read_from_file ( const char *  filename,
struct gc_arena gc 
)

buffer_read_from_file - copy the content of a file into a buffer

Parameters
filenamepath to the file to read
gcthe garbage collector to use when allocating the buffer. It is passed to alloc_buf_gc() and therefore can be NULL.
Returns
the buffer storing the file content or an invalid buffer in case of error

Definition at line 1356 of file buffer.c.

References alloc_buf_gc(), ASSERT, BPTR, buf_inc_len(), buf_null_terminate(), cleanup(), free_buf_gc(), gc, buffer::len, platform_fopen(), and platform_stat().

Referenced by connection_entry_preload_key(), crypto_pem_encode_certificate(), key_state_check_auth_failed_message_file(), read_key_file(), and read_pem_key_file().

◆ buffer_write_file()

bool buffer_write_file ( const char *  filename,
const struct buffer buf 
)

Write buffer contents to file.

Parameters
filenameThe filename to write the buffer to.
bufThe buffer to write to the file.
Returns
true on success, false otherwise.

Definition at line 286 of file buffer.c.

References BLEN, CBPTR, cleanup(), buffer::len, M_ERRNO, msg, platform_open(), and write.

Referenced by tls_crypt_v2_verify_metadata(), tls_crypt_v2_write_client_key_file(), write_key_file(), and write_pem_key_file().

◆ char_class()

bool char_class ( const unsigned char  c,
const unsigned int  flags 
)

Test whether a character belongs to one or more character classes.

Parameters
cThe character to test.
flagsBitmask of CC_* character class flags.
Returns
true if c matches any of the classes specified in flags.

Definition at line 839 of file buffer.c.

References CC_ALNUM, CC_ALPHA, CC_ANY, CC_ASCII, CC_ASTERISK, CC_BACKSLASH, CC_BLANK, CC_CNTRL, CC_COLON, CC_COMMA, CC_CR, CC_DASH, CC_DIGIT, CC_DOT, CC_DOUBLE_QUOTE, CC_EXCLAMATION, CC_GREATER_THAN, CC_LESS_THAN, CC_NEWLINE, CC_NULL, CC_PERCENT, CC_PIPE, CC_PRINT, CC_PUNCT, CC_QUESTION_MARK, CC_REVERSE_QUOTE, CC_SINGLE_QUOTE, CC_SLASH, CC_SPACE, CC_UNDERBAR, CC_XDIGIT, and buffer::len.

Referenced by buf_chomp(), char_inc_exc(), and command_line_add().

◆ check_malloc_return()

static void check_malloc_return ( void *  p)
inlinestatic

◆ checked_snprintf()

bool checked_snprintf ( char *  str,
size_t  size,
const char *  format,
  ... 
)

Like snprintf() but returns an boolean.

To check the return value of snprintf() one needs to do multiple comparisons of the size parameter against the return value. Doesn't get prettier by them being different types with different signedness and size.

So this function allows to wrap all of that into one boolean return value.

Returns
true if snprintf() was successful and not truncated.

Definition at line 1121 of file buffer.c.

References ASSERT, and buffer::len.

Referenced by append_cipher_to_ncp_list(), env_block(), establish_http_proxy_passthru(), get_panel_reg(), get_tap_reg(), platform_create_temp_file(), setenv_str_incr(), socks_username_password_auth(), test_checked_snprintf(), and verify_check_crl_dir().

◆ chomp()

void chomp ( char *  str)

Remove trailing newline and carriage-return characters from a string.

Parameters
strThe null-terminated string to chomp.

Definition at line 584 of file buffer.c.

References buffer::len, and rm_trailing_chars().

Referenced by establish_http_proxy_passthru(), get_console_input(), get_console_input_win32(), get_proxy_authenticate(), get_user_pass_cr(), make_inline_array(), man_output_peer_info_env(), output_peer_info_env(), and status_printf().

◆ clear_buf()

static struct buffer clear_buf ( void  )
inlinestatic

Return an empty, undefined struct buffer (all fields zero).

Definition at line 384 of file buffer.h.

Referenced by get_device_guid(), get_unspecified_device_guid(), read_control_auth(), tls_wrap_control(), and write_pem_key_file().

◆ clone_buf()

struct buffer clone_buf ( const struct buffer buf)

Duplicate a buffer, including its content.

Allocates a new buffer with the same capacity as buf and copies its content. Calls out_of_memory() if the allocation fails.

Parameters
bufThe buffer to duplicate.
Returns
A newly allocated copy of buf.

Definition at line 99 of file buffer.c.

References BLENZ, BPTR, buffer::capacity, CBPTR, check_malloc_return(), buffer::data, buffer::len, and buffer::offset.

Referenced by mbuf_alloc_buf(), and tls_pre_decrypt_lite().

◆ format_hex()

static char * format_hex ( const uint8_t *  data,
size_t  size,
size_t  maxoutput,
struct gc_arena gc 
)
inlinestatic

Format a binary buffer as a hex string with spaces every 4 bytes.

Convenience wrapper around format_hex_ex().

Parameters
dataPointer to the binary data to format.
sizeNumber of bytes to format.
maxoutputMaximum number of output characters (0 = unlimited).
gcGarbage collection arena for the returned string.
Returns
Null-terminated hex string allocated from gc.

Definition at line 981 of file buffer.h.

References format_hex_ex(), and gc.

Referenced by establish_http_proxy_passthru(), extract_command_buffer(), generate_key_random(), init_key_ctx(), key_print(), key_source_print(), openvpn_decrypt_aead(), openvpn_decrypt_v1(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), protocol_dump(), session_id_print(), tls_crypt_unwrap(), tls_crypt_v2_unwrap_client_key(), tls_crypt_v2_wrap_client_key(), tls_crypt_wrap(), and tuntap_dhcp_mask().

◆ format_hex_ex()

char * format_hex_ex ( const uint8_t *  data,
size_t  size,
size_t  maxoutput,
unsigned int  space_break_flags,
const char *  separator,
struct gc_arena gc 
)

Format a binary buffer as a hex string.

Parameters
dataPointer to the binary data to format.
sizeNumber of bytes to format.
maxoutputMaximum number of output characters (0 = unlimited). If the output is truncated, a "[more...]" suffix is appended via buf_catrunc().
space_break_flagsLower 8 bits (FHE_SPACE_BREAK_MASK) give the number of bytes between separator insertions. Use FHE_CAPS to output upper-case hex digits.
separatorString to insert between groups of bytes.
gcGarbage collection arena for the returned string.
Returns
Null-terminated hex string allocated from gc.

Definition at line 452 of file buffer.c.

References alloc_buf_gc(), buf_catrunc(), buf_printf(), buffer::data, FHE_CAPS, FHE_SPACE_BREAK_MASK, gc, and buffer::len.

Referenced by backend_x509_get_serial_hex(), export_user_keying_material(), format_hex(), hostname_randomize(), mroute_addr_print_ex(), print_default_gateway(), push_peer_info(), read_key_file(), show_adapter(), show_settings(), test_buffer_format_hex_ex(), verify_cert(), verify_cert_set_env(), write_key_file(), and x509_setenv_track().

◆ free_buf()

void free_buf ( struct buffer buf)

Free the memory allocated for a buffer.

Frees buf->data and resets the buffer to an undefined state.

Parameters
bufThe buffer whose memory is to be freed.

Definition at line 169 of file buffer.c.

References CLEAR, and buffer::data.

Referenced by auth_token_init_secret(), buffer_list_aggregate_separator(), buffer_list_pop(), buffer_list_reset(), check_inline_file(), command_line_free(), do_close_free_key_schedule(), fragment_free(), fragment_list_buf_free(), free_context_buffers(), free_tas(), free_tls_pre_decrypt_state(), key_state_free(), link_socket_close(), management_query_cert(), management_query_pk_sig(), mbuf_free_buf(), mutate_ncp_cipher_list(), openvpn_PRF(), overlapped_io_close(), read_inline_file(), reliable_free(), send_line_crlf(), status_close(), stream_buf_close(), test_generate_reset_packet_plain(), test_incoming_push_continuation_route_accumulation(), test_incoming_push_message_1(), test_incoming_push_message_bad_format(), test_incoming_push_message_basic(), test_incoming_push_message_error1(), test_incoming_push_message_error2(), test_incoming_push_message_mix(), test_incoming_push_message_mix2(), test_incoming_push_message_not_updatable_option(), test_mbuf_add_remove(), test_parse_ack(), test_tls_crypt_teardown(), test_tls_decrypt_lite_auth(), test_tls_decrypt_lite_crypt(), test_tls_decrypt_lite_none(), test_verify_hmac_none(), test_verify_hmac_none_out_of_range_ack(), test_verify_hmac_tls_auth(), tls_crypt_v2_extract_client_key(), tls_crypt_v2_write_client_key_file(), tls_wrap_free(), tun_show_debug(), and tuntap_dhcp_mask().

◆ gc_addspecial()

void gc_addspecial ( void *  addr,
void(*)(void *)  free_function,
struct gc_arena a 
)

Register an address with a custom free function in a garbage collection arena.

When gc_free() is called on a, free_function(addr) will be invoked to release the memory. Use this for allocations that require something other than plain free(), such as freeaddrinfo().

Parameters
addrPointer to the memory to register.
free_functionFunction to call to free addr.
aGarbage collection arena to register with.

Definition at line 411 of file buffer.c.

References gc_entry_special::addr, ASSERT, check_malloc_return(), gc_entry_special::free_fnc, gc_arena::list_special, and gc_entry_special::next.

Referenced by do_preresolve_host(), gc_realloc(), and init_route_list().

◆ gc_defined()

static bool gc_defined ( struct gc_arena a)
inlinestatic

Return true iff the arena contains at least one allocation.

Parameters
aThe arena to test.

Definition at line 1921 of file buffer.h.

References buffer::len.

◆ gc_detach()

static void gc_detach ( struct gc_arena a)
inlinestatic

Detach all allocations from an arena without freeing them.

After this call the arena is empty. The caller takes responsibility for freeing the previously registered allocations.

Parameters
aThe arena to detach.

Definition at line 1947 of file buffer.h.

References gc_init(), and buffer::len.

Referenced by inherit_context_top(), and options_detach().

◆ gc_free()

static void gc_free ( struct gc_arena a)
inlinestatic

Free all allocations in a garbage collection arena.

Calls x_gc_free() and x_gc_freespecial() as needed to release all registered memory.

Parameters
aThe arena to free.

Definition at line 1974 of file buffer.h.

References gc_arena::list, gc_arena::list_special, x_gc_free(), and x_gc_freespecial().

Referenced by adapter_index_of_ip(), add_option(), add_route(), add_route_ipapi(), add_route_ipv6(), argv_free(), argv_msg(), argv_msg_prefix(), argv_str__empty_argv__empty_output(), argv_str__multiple_argv__correct_output(), ccs_gen_config_file(), ccs_gen_deferred_ret_file(), ce_management_query_proxy(), ce_management_query_remote(), check_addr_clash(), check_auth_pending_method(), check_file_access_chroot(), check_for_client_reason(), check_incoming_control_channel(), check_mapped_ipv4_address(), check_session_cipher(), check_stale_routes(), cleanup(), clear_route_ipv6_list(), clear_route_list(), close_instance(), close_tun(), context_gc_free(), crypto_pem_encode_certificate(), crypto_pem_encode_decode_loopback(), crypto_test_epoch_teardown(), crypto_test_print_cert_details(), dco_get_peer_stats_multi(), dco_win_add_iroute_ipv4(), dco_win_add_iroute_ipv6(), dco_win_del_iroute_ipv4(), dco_win_del_iroute_ipv6(), del_route_ipapi(), delete_route(), delete_route_ipv6(), delete_temp_addresses(), dhcp_extract_router_msg(), dhcp_masq_addr(), dhcp_release_by_adapter_index(), dhcp_renew_by_adapter_index(), dhcp_status(), do_address_service(), do_close_tun(), do_compute_occ_strings(), do_create_adapter_service(), do_data_channel_round_trip(), do_dns_domain_service(), do_dns_service(), do_ifconfig_ipv4(), do_ifconfig_ipv6(), do_ifconfig_setenv(), do_open_tun(), do_pre_decrypt_check(), do_route_service(), do_set_mtu_service(), do_wins_service(), drop_if_recursive_routing(), ecdsa_sign_sig(), encrypt_one_packet(), establish_http_proxy_passthru(), export_user_keying_material(), fork_dhcp_action(), fork_register_dns_action(), frame_print(), gc_reset(), generate_auth_token(), generate_key_random(), generate_prefix(), get_adapter_index_method_2(), get_bypass_addresses(), get_default_gateway(), get_default_gateway_ipv6(), get_default_gateway_row(), get_p2p_ncp_cipher(), get_user_pass_cr(), handle_connection_attempt(), handle_data_channel_packet(), helper_client_server(), ifconfig_pool_init(), ifconfig_pool_list(), ifconfig_pool_read(), ifconfig_pool_verify_range(), ifconfig_sanity_check(), incoming_push_message(), init_key_ctx(), init_route_ipv6_list(), init_route_list(), init_ssl(), init_static(), ip_addr_string_to_array(), key_method_2_read(), key_print(), key_source_print(), key_state_gen_auth_control_files(), learn_address_script(), link_socket_bad_incoming_addr(), link_socket_connection_initiated(), linksock_print_addr(), man_connect(), man_dispatch_command(), man_history(), man_io_error(), man_kill(), man_listen(), man_new_connection_post(), man_output_extra_env(), man_process_command(), management_callback_send_cc_message(), management_echo(), management_hold(), management_learn_addr(), management_notify_client_cr_response(), management_query_multiline(), management_query_user_pass(), management_set_state(), mroute_extract_addr_ip(), mroute_helper_regenerate(), multi_add_iroutes(), multi_check_dest_addr_allowed(), multi_client_connect_call_script(), multi_client_connect_late_setup(), multi_client_connect_setenv(), multi_client_set_protocol_options(), multi_create_instance(), multi_create_instance_tcp(), multi_get_create_instance_udp(), multi_get_instance_by_virtual_addr(), multi_get_instance_udp_data(), multi_instance_dec_refcount(), multi_io_post(), multi_learn_addr(), multi_print_status(), multi_process_float(), multi_process_incoming_link_data(), multi_reap_range(), multi_select_virtual_addr(), multi_unlearn_addr(), ncp_get_best_cipher(), netsh_ifconfig(), netsh_ifconfig_options(), netsh_set_dns6_servers(), open_tun(), open_tun_afunix(), openvpn_decrypt_aead(), openvpn_decrypt_v1(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), openvpn_execve(), openvpn_execve_check(), openvpn_getaddrinfo(), openvpn_popen(), options_cmp_equal_safe(), options_warning_extract_parm1(), options_warning_safe_ml(), options_warning_safe_scan1(), options_warning_safe_scan2(), ovpn_dco_init_mp(), ovpn_expand_label(), p2p_mode_ncp(), packet_id_persist_load(), packet_id_persist_save(), parse_auth_failed_temp(), parse_hash_fingerprint_multiline(), platform_access(), platform_chdir(), platform_fopen(), platform_open(), platform_stat(), platform_unlink(), plugin_call_item(), plugin_call_ssl(), plugin_common_open(), plugin_init_item(), plugin_open_item(), plugin_option_list_print(), plugin_vlog(), pre_connect_restore(), print_client_nat_list(), print_default_gateway(), print_key_id_not_found_reason(), print_pkt(), print_status(), process_incoming_link_part1(), process_incoming_push_request(), process_outgoing_link(), push_peer_info(), read_control_auth(), read_key_file(), read_pem_key_file(), recv_socks_reply(), redirect_stdout_stderr(), register_dns_service(), reliable_ack_read(), reliable_can_get(), reliable_can_send(), reliable_get_buf_output_sequenced(), reliable_not_replay(), reliable_send_timeout(), reliable_wont_break_sequentiality(), remove_iroutes_from_push_route_list(), remove_option(), resolve_bind_local(), resolve_remote(), route_ipv6_ipapi(), route_quota_exceeded(), run_up_down(), schedule_debug_entry(), schedule_print_work(), schedule_test(), schedule_verify(), send_auth_failed(), send_auth_pending_messages(), send_control_channel_string_dowork(), send_msg_iservice(), send_push_reply(), send_push_reply_auth_token(), send_push_update(), server_pushed_info(), service_enable_dhcp(), session_move_pre_start(), setenv_int_i(), setenv_route(), setenv_route_addr(), setenv_route_ipv6(), setenv_str_ex(), setenv_str_i(), show_adapters(), show_dco_version(), show_dhcp_option_addrs(), show_dns_options(), show_p2mp_parms(), show_routes(), show_settings(), show_tap_win_adapters(), show_windows_version(), socket_bind(), socket_connect(), socket_do_listen(), socket_listen_accept(), socket_recv_queue(), socket_send_queue(), ssl_test_escape_rfc_2253_chars_in_subject(), ssl_test_extract_peer_info(), ssl_test_reject_null_in_cert_subject(), tap_allow_nonadmin_access(), tcp_connection_established(), test_add_in6_addr_tc(), test_buffer_chomp(), test_buffer_extract_field(), test_buffer_format_hex_ex(), test_buffer_free_gc_one(), test_buffer_free_gc_two(), test_buffer_gc_realloc(), test_buffer_null_terminate(), test_buffer_parse(), test_buffer_printf_catrunc(), test_character_string_mod_buf(), test_check_ncp_ciphers_list(), test_cipher_names(), test_compat_lzo_string(), test_crypto(), test_data_channel_known_vectors_run(), test_extract_client_ciphers(), test_extract_control_message(), test_list(), test_local_addr(), test_mssfix_mtu_calculation(), test_ncp_best(), test_ncp_default(), test_ncp_expand(), test_occ_mtu_calculation(), test_packet_id_write_teardown(), test_parse_line(), test_poor_man(), test_read_config(), test_routes(), test_tls_crypt_secure_reneg_key(), test_tls_crypt_v2_teardown(), test_write_dhcp_search_str(), tls_authentication_status(), tls_crypt_unwrap(), tls_crypt_v2_unwrap_client_key(), tls_crypt_v2_verify_metadata(), tls_crypt_v2_write_client_key_file(), tls_crypt_wrap(), tls_ctx_set_tls_groups(), tls_multi_process(), tls_pre_decrypt(), tls_pre_decrypt_lite(), tls_pre_encrypt(), tls_session_init(), tls_update_remote_addr(), trigger_ping_timeout_signal(), tun_read_queue(), tun_write_queue(), tuntap_dhcp_mask(), tuntap_set_ip_addr(), tuntap_set_ptp(), undo_ifconfig_ipv4(), undo_ifconfig_ipv6(), uninit_options(), update_option(), verify_255_255_255_252(), verify_callback(), verify_cert(), verify_cert_call_command(), verify_cert_set_env(), verify_check_crl_dir(), verify_common_subnet(), verify_crresponse_script(), verify_final_auth_checks(), verify_user_pass_script(), virtual_output_callback_func(), warn_on_use_of_common_subnets(), wide_cmd_line__quotes_only_what_cmd_would_reinterpret(), wide_cmd_line__replaces_cmd_expansion(), win32_signal_open(), win_wfp_block_service(), win_wfp_msg_handler(), window_title_generate(), windows_route_find_if_index(), write_key_file(), write_outgoing_tls_ciphertext(), write_pem_key_file(), x509_setenv_track(), x_check_status(), and x_msg_va().

◆ gc_freeaddrinfo_callback()

static void gc_freeaddrinfo_callback ( void *  addr)
inlinestatic

Callback to free a struct addrinfo, suitable for use with gc_addspecial().

Parameters
addrPointer to the struct addrinfo to free.

Definition at line 377 of file buffer.h.

Referenced by do_preresolve_host(), and init_route_list().

◆ gc_init()

static void gc_init ( struct gc_arena a)
inlinestatic

Initialise a garbage collection arena to an empty state.

Parameters
aThe arena to initialise.

Definition at line 1932 of file buffer.h.

References buffer::len.

Referenced by gc_detach(), gc_new(), init_instance(), init_options(), openvpn_decrypt_aead(), openvpn_decrypt_v1(), openvpn_encrypt_aead(), openvpn_encrypt_v1(), openvpn_main(), plugin_vlog(), test_read_config(), tls_crypt_unwrap(), tls_crypt_wrap(), and x_msg_va().

◆ gc_malloc()

void * gc_malloc ( size_t  size,
bool  clear,
struct gc_arena a 
)

◆ gc_new()

static struct gc_arena gc_new ( void  )
inlinestatic

Allocate and return a new, empty garbage collection arena.

Returns
An initialised gc_arena with empty lists.

Definition at line 1958 of file buffer.h.

References gc_init().

Referenced by adapter_index_of_ip(), add_option(), add_route(), add_route_ipapi(), add_route_ipv6(), argv_init(), argv_msg(), argv_msg_prefix(), argv_str__empty_argv__empty_output(), argv_str__multiple_argv__correct_output(), ccs_gen_config_file(), ccs_gen_deferred_ret_file(), ce_management_query_proxy(), ce_management_query_remote(), check_addr_clash(), check_auth_pending_method(), check_file_access_chroot(), check_for_client_reason(), check_incoming_control_channel(), check_mapped_ipv4_address(), check_session_cipher(), check_stale_routes(), close_tun(), crypto_pem_encode_certificate(), crypto_pem_encode_decode_loopback(), crypto_test_epoch_setup(), crypto_test_print_cert_details(), dco_get_peer_stats_multi(), dco_win_add_iroute_ipv4(), dco_win_add_iroute_ipv6(), dco_win_del_iroute_ipv4(), dco_win_del_iroute_ipv6(), del_route_ipapi(), delete_route(), delete_route_ipv6(), delete_temp_addresses(), dhcp_extract_router_msg(), dhcp_masq_addr(), dhcp_release_by_adapter_index(), dhcp_renew_by_adapter_index(), dhcp_status(), do_address_service(), do_close_tun(), do_compute_occ_strings(), do_create_adapter_service(), do_data_channel_round_trip(), do_dns_domain_service(), do_dns_service(), do_ifconfig_ipv4(), do_ifconfig_ipv6(), do_ifconfig_setenv(), do_open_tun(), do_pre_decrypt_check(), do_route_service(), do_set_mtu_service(), do_wins_service(), drop_if_recursive_routing(), ecdsa_sign_sig(), encrypt_one_packet(), establish_http_proxy_passthru(), export_user_keying_material(), fork_dhcp_action(), fork_register_dns_action(), frame_print(), generate_auth_token(), generate_key_random(), generate_prefix(), get_adapter_index_method_2(), get_bypass_addresses(), get_default_gateway(), get_default_gateway_ipv6(), get_default_gateway_row(), get_p2p_ncp_cipher(), get_user_pass_cr(), handle_connection_attempt(), handle_data_channel_packet(), helper_client_server(), ifconfig_pool_init(), ifconfig_pool_list(), ifconfig_pool_read(), ifconfig_pool_verify_range(), ifconfig_sanity_check(), incoming_push_message(), inherit_context_child(), init(), init_key_ctx(), init_route_ipv6_list(), init_route_list(), init_ssl(), init_static(), ip_addr_string_to_array(), key_method_2_read(), key_print(), key_source_print(), key_state_gen_auth_control_files(), learn_address_script(), link_socket_bad_incoming_addr(), link_socket_connection_initiated(), linksock_print_addr(), man_connect(), man_dispatch_command(), man_history(), man_io_error(), man_kill(), man_listen(), man_new_connection_post(), man_output_extra_env(), man_process_command(), management_callback_send_cc_message(), management_echo(), management_hold(), management_learn_addr(), management_notify_client_cr_response(), management_query_multiline(), management_query_user_pass(), management_set_state(), mroute_extract_addr_ip(), mroute_helper_regenerate(), multi_add_iroutes(), multi_check_dest_addr_allowed(), multi_client_connect_call_script(), multi_client_connect_late_setup(), multi_client_connect_setenv(), multi_client_set_protocol_options(), multi_create_instance(), multi_create_instance_tcp(), multi_get_create_instance_udp(), multi_get_instance_by_virtual_addr(), multi_get_instance_udp_data(), multi_io_post(), multi_learn_addr(), multi_print_status(), multi_process_float(), multi_process_incoming_link_data(), multi_reap_range(), multi_select_virtual_addr(), multi_unlearn_addr(), ncp_get_best_cipher(), netsh_ifconfig(), netsh_ifconfig_options(), netsh_set_dns6_servers(), open_tun(), open_tun_afunix(), openvpn_execve(), openvpn_execve_check(), openvpn_getaddrinfo(), openvpn_popen(), options_cmp_equal_safe(), options_warning_extract_parm1(), options_warning_safe_ml(), options_warning_safe_scan1(), options_warning_safe_scan2(), ovpn_dco_init_mp(), ovpn_expand_label(), p2p_mode_ncp(), packet_id_persist_load(), packet_id_persist_save(), parse_auth_failed_temp(), parse_hash_fingerprint_multiline(), platform_access(), platform_chdir(), platform_fopen(), platform_open(), platform_stat(), platform_unlink(), plugin_call_item(), plugin_call_ssl(), plugin_common_open(), plugin_init_item(), plugin_open_item(), plugin_option_list_print(), pre_connect_restore(), print_client_nat_list(), print_default_gateway(), print_key_id_not_found_reason(), print_pkt(), print_status(), process_incoming_link_part1(), process_incoming_push_request(), process_outgoing_link(), push_peer_info(), read_control_auth(), read_key_file(), read_pem_key_file(), recv_socks_reply(), redirect_stdout_stderr(), register_dns_service(), reliable_ack_read(), reliable_can_get(), reliable_can_send(), reliable_get_buf_output_sequenced(), reliable_not_replay(), reliable_send_timeout(), reliable_wont_break_sequentiality(), remove_iroutes_from_push_route_list(), resolve_bind_local(), resolve_remote(), route_ipv6_ipapi(), route_quota_exceeded(), run_up_down(), schedule_debug_entry(), schedule_print_work(), schedule_test(), schedule_verify(), send_auth_failed(), send_auth_pending_messages(), send_control_channel_string_dowork(), send_msg_iservice(), send_push_reply(), send_push_reply_auth_token(), send_push_update(), server_pushed_info(), service_enable_dhcp(), session_move_pre_start(), setenv_int_i(), setenv_route(), setenv_route_addr(), setenv_route_ipv6(), setenv_str_ex(), setenv_str_i(), show_adapters(), show_dco_version(), show_dhcp_option_addrs(), show_dns_options(), show_p2mp_parms(), show_routes(), show_settings(), show_tap_win_adapters(), show_windows_version(), socket_bind(), socket_connect(), socket_do_listen(), socket_listen_accept(), socket_recv_queue(), socket_send_queue(), ssl_test_escape_rfc_2253_chars_in_subject(), ssl_test_extract_peer_info(), ssl_test_reject_null_in_cert_subject(), tap_allow_nonadmin_access(), tcp_connection_established(), test_add_in6_addr_tc(), test_buffer_chomp(), test_buffer_extract_field(), test_buffer_format_hex_ex(), test_buffer_free_gc_one(), test_buffer_free_gc_two(), test_buffer_gc_realloc(), test_buffer_null_terminate(), test_buffer_parse(), test_buffer_printf_catrunc(), test_character_string_mod_buf(), test_check_ncp_ciphers_list(), test_cipher_names(), test_compat_lzo_string(), test_crypto(), test_data_channel_known_vectors_run(), test_extract_client_ciphers(), test_extract_control_message(), test_list(), test_local_addr(), test_mssfix_mtu_calculation(), test_ncp_best(), test_ncp_default(), test_ncp_expand(), test_occ_mtu_calculation(), test_packet_id_write_setup(), test_parse_line(), test_poor_man(), test_routes(), test_tls_crypt_secure_reneg_key(), test_tls_crypt_v2_setup(), test_write_dhcp_search_str(), tls_authentication_status(), tls_crypt_v2_unwrap_client_key(), tls_crypt_v2_verify_metadata(), tls_crypt_v2_write_client_key_file(), tls_ctx_set_tls_groups(), tls_multi_process(), tls_pre_decrypt(), tls_pre_decrypt_lite(), tls_pre_encrypt(), tls_session_init(), tls_update_remote_addr(), trigger_ping_timeout_signal(), tun_read_queue(), tun_write_queue(), tuntap_dhcp_mask(), tuntap_set_ip_addr(), tuntap_set_ptp(), undo_ifconfig_ipv4(), undo_ifconfig_ipv6(), verify_255_255_255_252(), verify_callback(), verify_cert(), verify_cert_call_command(), verify_cert_set_env(), verify_check_crl_dir(), verify_common_subnet(), verify_crresponse_script(), verify_final_auth_checks(), verify_user_pass_script(), virtual_output_callback_func(), warn_on_use_of_common_subnets(), wide_cmd_line__quotes_only_what_cmd_would_reinterpret(), wide_cmd_line__replaces_cmd_expansion(), win32_signal_open(), win_wfp_block_service(), win_wfp_msg_handler(), window_title_generate(), windows_route_find_if_index(), windows_set_mtu(), write_key_file(), write_outgoing_tls_ciphertext(), write_pem_key_file(), x509_setenv_track(), and x_check_status().

◆ gc_realloc()

void * gc_realloc ( void *  ptr,
size_t  size,
struct gc_arena a 
)

allows to realloc a pointer previously allocated by gc_malloc or gc_realloc

Note
only use this function on pointers returned by gc_malloc or re_alloc with the same gc_arena
Parameters
ptrPointer of the previously allocated memory
sizeNew size
agc_arena to use
Returns
new pointer

Definition at line 343 of file buffer.c.

References gc_entry_special::addr, ASSERT, check_malloc_return(), gc_addspecial(), gc_arena::list_special, and gc_entry_special::next.

Referenced by alloc_connection_entry(), alloc_local_entry(), alloc_remote_entry(), and test_buffer_gc_realloc().

◆ gc_reset()

static void gc_reset ( struct gc_arena a)
inlinestatic

Free all allocations in a garbage collection arena and reinitialise it.

Equivalent to calling gc_free() followed by gc_init().

Parameters
aThe arena to reset.

Definition at line 1994 of file buffer.h.

References gc_free().

Referenced by openvpn_main().

◆ gc_transfer()

void gc_transfer ( struct gc_arena dest,
struct gc_arena src 
)

Move all allocations from one garbage collection arena to another.

After the call src is empty and all entries previously in src are owned by dest.

Parameters
destArena to move allocations into.
srcArena to move allocations from (emptied on return).

Definition at line 429 of file buffer.c.

References gc_arena::list, and gc_entry::next.

Referenced by add_option().

◆ has_digit()

static bool has_digit ( const char *  src)
inlinestatic

Return true if the string contains at least one decimal digit.

Parameters
srcThe null-terminated string to scan.
Returns
true if any character in src satisfies isdigit().

Definition at line 725 of file buffer.h.

Referenced by tun_name_is_fixed().

◆ np()

const char * np ( const char *  str)

Return a printable representation of a string that might be NULL.

Parameters
strString to print, or NULL.
Returns
str if non-NULL, otherwise the string "[NULL]".

Definition at line 814 of file buffer.c.

References buffer::len.

◆ print_argv()

char * print_argv ( const char **  p,
struct gc_arena gc,
const unsigned int  flags 
)

Format a NULL-terminated argument vector as a single string.

Parameters
pNULL-terminated array of string pointers to format.
gcGarbage collection arena for the returned string.
flagsFormatting flags (e.g. PA_BRACKET).
Returns
Newly allocated string representation of p.

Definition at line 675 of file buffer.c.

References alloc_buf_gc(), BSTR, buf_printf(), gc, buffer::len, and PA_BRACKET.

Referenced by argv_str(), plugin_open_item(), plugin_option_list_print(), and push_options().

◆ rm_trailing_chars()

void rm_trailing_chars ( char *  str,
const char *  what_to_delete 
)

Remove all trailing characters that appear in a given set.

Parameters
strThe null-terminated string to modify in place.
what_to_deleteNull-terminated set of characters to strip.

Definition at line 593 of file buffer.c.

References buffer::len.

Referenced by chomp().

◆ secure_memzero()

static void secure_memzero ( void *  data,
size_t  len 
)
inlinestatic

Securely zeroise memory.

This code and description are based on code supplied by Zhaomo Yang, of the University of California, San Diego (which was released into the public domain).

The secure_memzero function attempts to ensure that an optimizing compiler does not remove the intended operation if cleared memory is not accessed again by the program. This code has been tested under Clang 3.9.0 and GCC 6.2 with optimization flags -O, -Os, -O0, -O1, -O2, and -O3 on Ubuntu 16.04.1 LTS; under Clang 3.9.0 with optimization flags -O, -Os, -O0, -O1, -O2, and -O3 on FreeBSD 10.2-RELEASE; under Microsoft Visual Studio 2015 with optimization flags /O1, /O2 and /Ox on Windows 10.

Theory of operation:

  1. On Windows, use the SecureZeroMemory which ensures that data is overwritten.
  2. Under GCC or Clang, use a memory barrier, which forces the preceding memset to be carried out. The overhead of a memory barrier is usually negligible.
  3. If none of the above are available, use the volatile pointer technique to zero memory one byte at a time.
Parameters
dataPointer to data to zeroise.
lenLength of data, in bytes.

Definition at line 767 of file buffer.h.

Referenced by buf_clear(), crypto_read_openvpn_key(), establish_http_proxy_passthru(), export_user_keying_material(), free_tls_pre_decrypt_state(), generate_key_expansion(), generate_key_expansion_openvpn_prf(), in_extra_dispatch(), init_epoch_keys(), key_method_2_read(), key_method_2_write(), key_state_export_keying_material(), key_state_free(), management_query_user_pass(), move_session(), purge_user_pass(), read_config_file(), read_config_string(), read_inline_file(), remove_env_item(), socks_username_password_auth(), string_clear(), tls_crypt_v2_extract_client_key(), tls_crypt_v2_init_server_key(), tls_crypt_v2_unwrap_client_key(), tls_crypt_v2_write_client_key_file(), tls_multi_free(), tls_session_free(), tls_session_generate_data_channel_keys(), tls_session_generate_dynamic_tls_crypt_key(), tls_wrap_free(), username_password_as_base64(), wipe_auth_token(), write_key_file(), and write_pem_key_file().

◆ skip_leading_whitespace()

const char * skip_leading_whitespace ( const char *  str)

Return a pointer past any leading whitespace in a string.

Parameters
strThe string to skip whitespace in.
Returns
Pointer to the first non-whitespace character, or to the null terminator if str is all whitespace.

Definition at line 547 of file buffer.c.

References buffer::len.

Referenced by make_inline_array().

◆ string_alloc()

char * string_alloc ( const char *  str,
struct gc_arena gc 
)

Duplicate a string, allocating memory under garbage collection.

Parameters
strThe string to duplicate. May be NULL, in which case NULL is returned.
gcGarbage collection arena for the returned string, or NULL to use plain malloc().
Returns
A newly allocated copy of str, or NULL if str is NULL.

Definition at line 616 of file buffer.c.

References check_malloc_return(), gc, gc_malloc(), and buffer::len.

Referenced by add_env_item(), argv_clone(), argv_insert_head(), argv_parse_cmd(), auth_set_client_reason(), backend_x509_get_serial(), ccs_gen_config_file(), ccs_gen_deferred_ret_file(), check_file_access(), check_inline_file(), cipher_kt_block_size(), clone_push_list(), do_close_tun(), do_init_route_ipv6_list(), extract_var_peer_info(), fork_to_self(), generate_auth_token(), get_device_instance_id_interface(), get_ipv6_addr_no_netbits(), get_p2p_ncp_cipher(), get_pa_var(), get_panel_reg(), get_proxy_authenticate(), get_tap_reg(), ifconfig_pool_acquire(), ifconfig_pool_set(), init_options_dev(), key_method_2_read(), key_state_gen_auth_control_files(), log_history_add(), make_arg_array(), make_base64_string2(), make_inline_array(), management_callback_proxy_cmd(), mutate_ncp_cipher_list(), ncp_get_best_cipher(), open_syslog(), open_tun_afunix(), open_tun_null(), options_warning_extract_parm1(), parse_auth_challenge(), parse_auth_failed_temp(), parse_hash_fingerprint_multiline(), parse_http_proxy_override(), push_option_fmt(), read_inline_file(), set_common_name(), set_win_sys_path(), ssl_put_auth_challenge(), status_open(), string_alloc_buf(), string_mod_const(), test_cipher_names(), test_list(), tls_ctx_set_tls_groups(), tls_item_in_cipher_list(), tls_lock_common_name(), tls_lock_username(), tls_poor_mans_ncp(), and tun_open_device().

◆ string_alloc_buf()

struct buffer string_alloc_buf ( const char *  str,
struct gc_arena gc 
)

Allocate a buffer containing a copy of the given string.

Wraps string_alloc(), so gc may be NULL (plain malloc() is used in that case). The buffer len reflects the string length, excluding the null terminator, even though the terminator is present in the allocated memory.

Parameters
strThe string to copy into the buffer. Must not be NULL.
gcGarbage collection arena for the allocation, or NULL.
Returns
A buffer whose content is a copy of str.

Definition at line 707 of file buffer.c.

References ASSERT, buf_set_read(), gc, buffer::len, and string_alloc().

Referenced by options_warning_extract_parm1().

◆ string_array_len()

int string_array_len ( const char **  array)

Return the number of elements in a NULL-terminated array of strings.

Parameters
arrayNULL-terminated array of string pointers.
Returns
Number of non-NULL elements.

Definition at line 661 of file buffer.c.

References buffer::len.

Referenced by make_arg_copy(), make_extended_arg_array(), no_more_than_n_args(), and openvpn_plugin_open_v3().

◆ string_check_buf()

bool string_check_buf ( const struct buffer buf,
const unsigned int  inclusive,
const unsigned int  exclusive 
)

Check a buffer if it only consists of allowed characters.

Parameters
bufThe buffer to be checked.
inclusiveThe character classes that are allowed.
exclusiveCharacter classes that are not allowed even if they are also in inclusive.
Returns
True if the string consists only of allowed characters, false otherwise.

Definition at line 1038 of file buffer.c.

References ASSERT, BLEN, CBSTR, char_inc_exc(), and buffer::len.

Referenced by extract_command_buffer(), test_buffer_chomp(), and test_character_string_mod_buf().

◆ string_class()

bool string_class ( const char *  str,
const unsigned int  inclusive,
const unsigned int  exclusive 
)

Test whether all characters in a string satisfy a character class filter.

Parameters
strThe null-terminated string to test.
inclusiveClasses that are permitted (characters must match at least one of these).
exclusiveClasses that are forbidden (characters must not match any of these, even if they also match inclusive).
Returns
true if every character in str is permitted.

Definition at line 986 of file buffer.c.

References ASSERT, char_inc_exc(), and buffer::len.

Referenced by dns_addr_safe(), openvpn_inet_aton(), and push_option_ex().

◆ string_clear()

void string_clear ( char *  str)

Securely clear a null-terminated string.

Overwrites all characters of str with zeroes.

Parameters
strThe string to clear.

Definition at line 649 of file buffer.c.

References buffer::len, and secure_memzero().

Referenced by do_init_crypto_tls_c1(), get_user_pass_cr(), and openvpn_plugin_string_list_item_free().

◆ string_defined_equal()

bool string_defined_equal ( const char *  s1,
const char *  s2 
)

Definition at line 1089 of file buffer.c.

References buffer::len.

Referenced by options_postprocess_verify_ce().

◆ string_mod()

bool string_mod ( char *  str,
const unsigned int  inclusive,
const unsigned int  exclusive,
const char  replace 
)

Modifies a string in place by replacing certain classes of characters of it with a specified character.

Guaranteed to not increase the length of the string. If replace is 0, characters are skipped instead of replaced.

Parameters
strThe string to be modified.
inclusiveThe character classes not to be replaced.
exclusiveCharacter classes to be replaced even if they are also in inclusive.
replaceThe character to replace the specified character classes with.
Returns
True if the string was not modified, false otherwise.

Definition at line 1005 of file buffer.c.

References ASSERT, char_inc_exc(), and buffer::len.

Referenced by do_setenv_x509(), get_user_pass_cr(), string_mod_const(), string_mod_remap_name(), test_character_class(), test_load_certificate_and_key_uri(), verify_user_pass(), wide_cmd_line(), and x509_setenv().

◆ string_mod_const()

const char * string_mod_const ( const char *  str,
const unsigned int  inclusive,
const unsigned int  exclusive,
const char  replace,
struct gc_arena gc 
)

Returns a copy of a string with certain classes of characters of it replaced with a specified character.

If replace is 0, characters are skipped instead of replaced.

Parameters
strThe input string to be modified.
inclusiveCharacter classes not to be replaced.
exclusiveCharacter classes to be replaced even if they are also in inclusive.
replaceThe character to replace the specified character classes with.
gcThe garbage collector arena to allocate memory from.
Returns
The modified string with characters replaced within the specified range.

Definition at line 1055 of file buffer.c.

References gc, buffer::len, string_alloc(), and string_mod().

Referenced by platform_gen_path(), safe_print(), and setenv_str_ex().

◆ string_null_terminate()

void string_null_terminate ( char *  str,
int  len,
int  capacity 
)

Null-terminate a fixed-length string buffer.

Ensures that str[len] is '\0', clamping len to capacity - 1 if necessary.

Parameters
strThe character buffer to null-terminate.
lenCurrent string length.
capacityTotal size of the character buffer in bytes.

Definition at line 566 of file buffer.c.

References ASSERT, buffer::capacity, and buffer::len.

Referenced by get_console_input_win32().

◆ string_replace_leading()

void string_replace_leading ( char *  str,
const char  match,
const char  replace 
)

Replace all leading occurrences of a character in a string.

Scans from the start of str and replaces every consecutive match character with replace, stopping at the first character that does not match.

Parameters
strThe null-terminated string to modify in place.
matchThe character to replace.
replaceThe replacement character.

Definition at line 1071 of file buffer.c.

References ASSERT, and buffer::len.

Referenced by verify_cert().

◆ string_substitute()

char * string_substitute ( const char *  src,
char  from,
char  to,
struct gc_arena gc 
)

Definition at line 1102 of file buffer.c.

References gc, gc_malloc(), and buffer::len.

Referenced by add_option().

◆ strncpynt()

static void strncpynt ( char *  dest,
const char *  src,
size_t  maxlen 
)
inlinestatic

Like strncpy() but always null-terminates the destination.

Copies at most maxlen - 1 characters from src into dest and writes a null terminator at dest[maxlen - 1]. Does nothing if maxlen is zero.

Parameters
destDestination buffer.
srcSource string.
maxlenSize of the destination buffer in bytes.

Definition at line 708 of file buffer.h.

Referenced by buf_puts(), check_send_auth_token(), do_dns_domain_service(), do_set_mtu_service(), EVP_PKEY_get_group_name(), extract_x509_extension(), extract_x509_field_ssl(), generate_prefix(), get_user_pass_cr(), get_user_pass_cr(), key_method_2_write(), man_query_user_pass(), management_callback_remote_cmd(), options_string_version(), override_locked_username(), pem_password_callback(), run_up_down_service(), set_auth_token(), and socks_proxy_new().

◆ strprefix()

static bool strprefix ( const char *  str,
const char *  prefix 
)
inlinestatic

Return true iff str starts with prefix.

Parameters
strThe string to test.
prefixThe prefix to look for.

Definition at line 1826 of file buffer.h.

References buffer::len.

Referenced by is_tun_afunix(), options_warning_safe_scan2(), push_update_digest(), and test_buffer_strprefix().

◆ x_gc_free()

void x_gc_free ( struct gc_arena a)

Free all plain allocations in a garbage collection arena.

Internal implementation called by gc_free(). Do not call directly.

Parameters
aThe arena whose list entries are to be freed.

Definition at line 376 of file buffer.c.

References gc_arena::list, and gc_entry::next.

Referenced by gc_free().

◆ x_gc_freespecial()

void x_gc_freespecial ( struct gc_arena a)

Free all specially-allocated entries in a garbage collection arena.

Internal implementation called by gc_free(). Do not call directly. Invokes the custom free function stored in each gc_entry_special.

Parameters
aThe arena whose list_special entries are to be freed.

Definition at line 395 of file buffer.c.

References gc_entry_special::addr, gc_entry_special::free_fnc, gc_arena::list_special, and gc_entry_special::next.

Referenced by gc_free().