nDPI/doc/library_initialization.rst
Fábio Depin 14620854e3
ndpiReader: install custom memory allocators before any nDPI API usage (#3164)
ndpiReader was setting custom memory allocation hooks only inside
test_lib(), which is executed after several code paths that already
use nDPI APIs (e.g., parseOptions, help/extcap paths, host checks,
DoH initialization, etc.).

This could lead to inconsistent allocator usage where memory is
allocated using the default libc allocator (when hooks are unset)
and later freed using custom allocators, resulting in undefined
behavior with non-trivial allocators.

This partially addresses #1280.
2026-04-21 10:20:33 +02:00

113 lines
2.9 KiB
ReStructuredText

Library Initialization
=======================
# Library Initialization
A simple, common example
.. code:: c
struct ndpi_detection_module_struct *ndpi_struct;
ndpi_cfg_error rc;
int ret;
ndpi_struct = ndpi_init_detection_module(NULL);
if(!ndpi_struct) {
ERROR;
}
/* Configuration */
rc = ndpi_set_config(ndpi_struct, "tls", "certificate_expiration_threshold", "10");
if(rc != NDPI_CFG_OK) {
ERROR;
}
/* Finalization */
ret = ndpi_finalize_initialization(ndpi_struct);
if(ret != 0) {
ERROR;
}
/* Initialization done, now you can feed packets to the library */
/* Cleanup */
ndpi_exit_detection_module(ndpi_struct);
A more complex example, with global context and a shared Oookla LRU cache (all the others caches are local)
.. code:: c
struct ndpi_global_context *g_ctx;
struct ndpi_detection_module_struct *ndpi_structs[num_local_contexts];
ndpi_cfg_error rc;
int i, ret;
g_ctx = ndpi_global_init();
if(!g_ctx) {
ERROR;
}
for(i = 0; i < num_local_contexts; i++) {
ndpi_structs[i] = ndpi_init_detection_module(g_ctx);
if(!ndpi_struct[i]) {
ERROR;
}
rc = ndpi_set_config(ndpi_structs[i], NULL, "lru.ookla.scope", "1");
if(rc != NDPI_CFG_OK) {
ERROR;
}
ret = ndpi_finalize_initialization(ndpi_structs[i]);
if(ret != 0) {
ERROR;
}
}
/* Initialization done */
/* Cleanup */
for(i = 0; i < num_local_contexts; i++) {
ndpi_exit_detection_module(ndpi_structs[i]);
}
ndpi_global_deinit(g_ctx);
Another example, with a custom memory allocator
.. code:: c
struct ndpi_detection_module_struct *ndpi_struct;
ndpi_cfg_error rc;
int ret;
/* If you want to set a custom allocator for all memory allocations performed by
the library, you must call `ndpi_set_memory_alloction_functions() ONCE,
BEFORE ANY nDPI functions */
ndpi_set_memory_alloction_functions(malloc_wrapper,
free_wrapper,
calloc_wrapper,
realloc_wrapper,
aligned_malloc_wrapper,
aligned_free_wrapper,
flow_malloc_wrapper,
flow_free_wrapper);
ndpi_struct = ndpi_init_detection_module(NULL);
if(!ndpi_struct) {
ERROR;
}
/* Continue as the previous examples */