### Conditional Example Build Source: https://github.com/ngtcp2/nghttp3/blob/main/examples/CMakeLists.txt Includes example build logic if ENABLE_EXAMPLES is set. Links against nghttp3 or nghttp3_static based on ENABLE_SHARED_LIB. ```cmake if(ENABLE_EXAMPLES) include_directories( ${CMAKE_SOURCE_DIR}/lib/includes ${CMAKE_BINARY_DIR}/lib/includes ) if(ENABLE_SHARED_LIB) link_libraries( nghttp3 ) else() link_libraries( nghttp3_static ) endif() set(qpack_SOURCES qpack.cc qpack_encode.cc qpack_decode.cc util.cc ) add_executable(qpack ${qpack_SOURCES}) set_target_properties(qpack PROPERTIES COMPILE_FLAGS "${WARNCXXFLAGS}" CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON ) # TODO prevent qpack example from being installed? endif() ``` -------------------------------- ### Install nghttp3 Headers Source: https://github.com/ngtcp2/nghttp3/blob/main/lib/includes/CMakeLists.txt Installs the main nghttp3 header file and the generated version header to the system's include directory. ```cmake install(FILES nghttp3/nghttp3.h "${CMAKE_CURRENT_BINARY_DIR}/nghttp3/version.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/nghttp3") ``` -------------------------------- ### Initialize nghttp3_nv array Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Example of initializing an array of nghttp3_nv structures with header data and flags. ```c nghttp3_nv headers[] = { {(uint8_t *)":method", (uint8_t *)"GET", 7, 3, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)"authorization", (uint8_t *)"Bearer token", 13, 12, NGHTTP3_NV_FLAG_NEVER_INDEX}, }; ``` -------------------------------- ### Build nghttp3 from Git Source: https://github.com/ngtcp2/nghttp3/blob/main/README.rst Instructions for cloning the nghttp3 repository, initializing submodules, configuring, and building the project. Ensure you have necessary build tools installed. ```shell git clone https://github.com/ngtcp2/nghttp3 cd nghttp3 git submodule update --init autoreconf -i ./configure make -j$(nproc) check ``` -------------------------------- ### Submit HTTP/3 Request in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Defines the signature for submitting a client request and provides an example of header initialization and submission. ```c int nghttp3_conn_submit_request(nghttp3_conn *conn, int64_t stream_id, const nghttp3_nv *nva, size_t nvlen, const nghttp3_data_reader *dr, void *stream_user_data); ``` ```c nghttp3_nv headers[] = { {(uint8_t *)":method", (uint8_t *)"GET", 7, 3, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":scheme", (uint8_t *)"https", 7, 5, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":authority", (uint8_t *)"example.com", 10, 11, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":path", (uint8_t *)"/index.html", 5, 11, NGHTTP3_NV_FLAG_NONE}, }; int rv = nghttp3_conn_submit_request(conn, stream_id, headers, sizeof(headers)/sizeof(headers[0]), NULL, NULL); if (rv != 0) { // Handle error } ``` -------------------------------- ### Submit HTTP/3 Response in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Defines the signature for submitting a server response and provides an example of header initialization and submission. ```c int nghttp3_conn_submit_response(nghttp3_conn *conn, int64_t stream_id, const nghttp3_nv *nva, size_t nvlen, const nghttp3_data_reader *dr); ``` ```c nghttp3_nv headers[] = { {(uint8_t *)":status", (uint8_t *)"200", 7, 3, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)"content-type", (uint8_t *)"text/html", 12, 9, NGHTTP3_NV_FLAG_NONE}, }; int rv = nghttp3_conn_submit_response(conn, stream_id, headers, sizeof(headers)/sizeof(headers[0]), NULL); if (rv != 0) { // Handle error } ``` -------------------------------- ### nghttp3_buf_reset Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Resets read and write positions to the start of the buffer. ```APIDOC ## void nghttp3_buf_reset(nghttp3_buf *buf) ### Description Sets both pos and last to begin, clearing the logical content while keeping allocated memory. ### Parameters - **buf** (nghttp3_buf *) - Required - Buffer to reset ``` -------------------------------- ### Get Default Memory Allocator Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Retrieves the default allocator using standard C library functions. Recommended for most applications. ```c const nghttp3_mem *mem = nghttp3_mem_default(); nghttp3_conn *conn = NULL; int rv = nghttp3_conn_client_new(&conn, &callbacks, &settings, mem, NULL); ``` -------------------------------- ### Reset buffer positions with nghttp3_buf_reset Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Clears logical content by resetting read and write positions to the start of the buffer while retaining allocated memory. ```c nghttp3_buf pbuf, rbuf, ebuf; // ... use buffers for encoding ... nghttp3_buf_reset(&pbuf); nghttp3_buf_reset(&rbuf); nghttp3_buf_reset(&ebuf); // Now ready to reuse for next encoding ``` -------------------------------- ### Initialize HTTP/3 Server Connection Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Creates a new server connection. Control and QPACK streams must be bound before the connection is usable. ```c int nghttp3_conn_server_new(nghttp3_conn **pconn, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, const nghttp3_mem *mem, void *conn_user_data); ``` ```c nghttp3_conn *conn = NULL; int rv = nghttp3_conn_server_new(&conn, &callbacks, &settings, nghttp3_mem_default(), app_state); if (rv != 0) { // Handle error } ``` -------------------------------- ### Initialize HTTP/3 Client Connection Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Creates a new client connection. Control and QPACK streams must be bound after initialization. ```c int nghttp3_conn_client_new(nghttp3_conn **pconn, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, const nghttp3_mem *mem, void *conn_user_data); ``` ```c nghttp3_callbacks callbacks = {0}; nghttp3_settings settings = {0}; settings.qpack_max_dtable_capacity = 4096; nghttp3_conn *conn = NULL; int rv = nghttp3_conn_client_new(&conn, &callbacks, &settings, nghttp3_mem_default(), NULL); if (rv != 0) { // Handle error } // Use conn... nghttp3_conn_del(conn); ``` -------------------------------- ### Initialize nghttp3_settings Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Demonstrates how to initialize and populate the nghttp3_settings structure for a server connection. ```c #include void init_server_settings(nghttp3_settings *settings) { memset(settings, 0, sizeof(*settings)); // Advertising our limits to client settings->max_field_section_size = 65536; // 64KB max header block settings->qpack_max_dtable_capacity = 4096; // 4KB dynamic table settings->qpack_blocked_streams = 100; // Allow 100 blocked streams // Rate limiting for HTTP/3 attack detection (if using read_stream2) settings->glitch_ratelim_burst = 1000; // 1000 tokens settings->glitch_ratelim_rate = 500; // 500 tokens/sec // Extended features settings->enable_connect_protocol = 1; // Enable WebSocket/CONNECT settings->h3_datagram = 0; // Disable datagrams // ORIGIN frame (optional, send empty frame) static const uint8_t origin_data[] = {0, 0}; // Empty ORIGIN static nghttp3_vec origin = { .base = (uint8_t*)origin_data, .len = sizeof(origin_data) }; settings->origin_list = &origin; } // Usage nghttp3_conn *conn = NULL; nghttp3_settings settings; nghttp3_callbacks callbacks = {0}; init_server_settings(&settings); int rv = nghttp3_conn_server_new(&conn, &callbacks, &settings, nghttp3_mem_default(), NULL); ``` -------------------------------- ### Get required insert count Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Retrieves the insert count required for decoding, typically used for sending acknowledgments. ```c uint64_t nghttp3_qpack_stream_context_get_ricnt2( const nghttp3_qpack_stream_context *sctx); ``` -------------------------------- ### Initialize QPACK Encoder Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Create and configure a QPACK encoder instance with a specified hard limit and dynamic behavior settings. ```c nghttp3_qpack_encoder *encoder = NULL; const nghttp3_mem *mem = nghttp3_mem_default(); // Create encoder with 8KB hard limit int rv = nghttp3_qpack_encoder_new2(&encoder, 8192, (uint64_t)time(NULL), mem); if (rv != 0) { // Handle error } // Configure dynamic behavior nghttp3_qpack_encoder_set_max_dtable_capacity(encoder, 4096); nghttp3_qpack_encoder_set_max_blocked_streams(encoder, 100); nghttp3_qpack_encoder_set_indexing_strat(encoder, NGHTTP3_QPACK_INDEXING_STRAT_DEFAULT); ``` -------------------------------- ### Retrieve Library Version and Capabilities Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/README.md Use this to verify the library version and supported protocols at runtime. ```c const nghttp3_info *info = nghttp3_version(0); printf("Version: %s\n", info->version_str); printf("Protocols: %s\n", info->proto_str); ``` -------------------------------- ### Initialize and manage nghttp3 connection Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/README.md Demonstrates the full lifecycle of an nghttp3 connection, from callback registration and stream binding to the I/O loop and cleanup. ```c // 1. Create connection with settings and callbacks nghttp3_callbacks callbacks = { .recv_header = my_recv_header, .recv_data = my_recv_data, .end_stream = my_end_stream, // ... other callbacks }; nghttp3_settings settings = {0}; settings.qpack_max_dtable_capacity = 4096; // ... configure other settings nghttp3_conn *conn = NULL; nghttp3_conn_client_new(&conn, &callbacks, &settings, nghttp3_mem_default(), app_state); // 2. Bind QUIC streams for control and QPACK nghttp3_conn_bind_control_stream(conn, 2); // Local unidirectional nghttp3_conn_bind_qpack_streams(conn, 6, 10); // Encoder, decoder // 3. Submit requests/responses nghttp3_nv headers[] = { /* ... */ }; nghttp3_conn_submit_request(conn, stream_id, headers, nheaders, NULL, NULL); // 4. I/O loop while (active) { // Receive from QUIC nghttp3_ssize processed = nghttp3_conn_read_stream(conn, stream_id, quic_data, quic_len); // Send to QUIC nghttp3_vec vec[16]; size_t veclen = 16; nghttp3_ssize written = nghttp3_conn_writev_stream(conn, stream_id, vec, &veclen); if (written > 0) { send_to_quic(vec, veclen); nghttp3_conn_add_write_offset(conn, stream_id, written); } } // 5. Cleanup nghttp3_conn_del(conn); ``` -------------------------------- ### Initialize QPACK Decoder Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Create and configure a QPACK decoder instance with defined hard limits and stream concurrency settings. ```c nghttp3_qpack_decoder *decoder = NULL; const nghttp3_mem *mem = nghttp3_mem_default(); // Create decoder with 8KB hard limit, 100 max blocked streams int rv = nghttp3_qpack_decoder_new(&decoder, 8192, 100, mem); if (rv != 0) { // Handle error } // Set max concurrent streams to optimize decoder state nghttp3_qpack_decoder_set_max_concurrent_streams(decoder, 100); ``` -------------------------------- ### Get current number of blocked QPACK streams Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Retrieves the count of streams currently waiting for dynamic table updates, useful for diagnostic purposes. ```c size_t nghttp3_qpack_encoder_get_num_blocked_streams2( const nghttp3_qpack_encoder *encoder); ``` -------------------------------- ### Initialize connection with default memory allocator Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Uses the built-in default memory allocator for connection creation. ```c const nghttp3_mem *mem = nghttp3_mem_default(); int rv = nghttp3_conn_client_new(&conn, &callbacks, &settings, mem, NULL); ``` -------------------------------- ### Configure Build Options Source: https://github.com/ngtcp2/nghttp3/blob/main/CMakeLists.txt Sets various build-time options based on user configuration. ```cmake if(ENABLE_STATIC_CRT) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") endif() if(ENABLE_DEBUG) set(DEBUGBUILD 1) endif() if(ENABLE_LIB_ONLY) set(ENABLE_EXAMPLES 0) else() enable_language(CXX) set(ENABLE_EXAMPLES 1) endif() add_definitions(-DHAVE_CONFIG_H) configure_file(cmakeconfig.h.in config.h) ``` -------------------------------- ### Define Test Source Files Source: https://github.com/ngtcp2/nghttp3/blob/main/tests/CMakeLists.txt Lists the C source files used to build the main test executable. ```cmake set(main_SOURCES main.c nghttp3_qpack_test.c nghttp3_conn_test.c nghttp3_stream_test.c nghttp3_tnode_test.c nghttp3_http_test.c nghttp3_conv_test.c nghttp3_settings_test.c nghttp3_callbacks_test.c nghttp3_str_test.c nghttp3_test_helper.c munit/munit.c ) ``` -------------------------------- ### Initialize a buffer with nghttp3_buf_init Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Sets all internal pointers to NULL to prepare the buffer for allocation. ```c nghttp3_buf buf; nghttp3_buf_init(&buf); // buf is now in initial state ``` -------------------------------- ### Configure Debug Logging Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/README.md Enable debug logging by defining the DEBUGBUILD macro and registering a vprintf callback. ```c #ifdef NDEBUG #undef NDEBUG #endif void debug_callback(const char *format, va_list args) { vfprintf(stderr, format, args); } nghttp3_set_debug_vprintf_callback(debug_callback); ``` -------------------------------- ### Configure ORIGIN Frame Support Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Prepare and register an ORIGIN frame payload for server-side origin advertisement. ```c // Prepare ORIGIN frame payload (sequence of length-prefixed origins) // Format: [2-byte-len][origin_bytes]...[2-byte-len][origin_bytes] uint8_t origin_payload[256]; size_t payload_len = 0; // Add first origin: "https://example.com" const char *origin1 = "https://example.com"; uint16_t len1 = strlen(origin1); origin_payload[payload_len++] = (len1 >> 8) & 0xFF; origin_payload[payload_len++] = len1 & 0xFF; memcpy(origin_payload + payload_len, origin1, len1); payload_len += len1; nghttp3_settings settings = {0}; settings.origin_list = &(nghttp3_vec){ .base = origin_payload, .len = payload_len }; int rv = nghttp3_conn_server_new(&conn, &callbacks, &settings, mem, NULL); ``` -------------------------------- ### Define Test Executable and Dependencies Source: https://github.com/ngtcp2/nghttp3/blob/main/tests/CMakeLists.txt Creates the main test executable, links it against the static library, and registers the test with CTest. ```cmake add_executable(main EXCLUDE_FROM_ALL ${main_SOURCES} ) # FIXME enable and fix warnings #set_target_properties(main PROPERTIES COMPILE_FLAGS "${WARNCFLAGS}") target_link_libraries(main nghttp3_static ) add_test(main main) add_dependencies(check main) ``` -------------------------------- ### nghttp3_buf_init Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Initializes an empty buffer by setting all pointers to NULL. ```APIDOC ## void nghttp3_buf_init(nghttp3_buf *buf) ### Description Initializes an empty buffer. Sets all pointers (begin, end, pos, last) to NULL. The buffer is empty and ready for allocation. ### Parameters - **buf** (nghttp3_buf *) - Required - Buffer structure to initialize ``` -------------------------------- ### Configure Debug Build and Callback Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Enables debug logging during compilation and registers a custom vprintf callback for output handling. ```bash # Build with debug support ./configure CFLAGS="-g -O2 -DDEBUGBUILD" make # In code, set callback before using library void my_debug_callback(const char *format, va_list args) { vfprintf(stderr, format, args); fflush(stderr); } nghttp3_set_debug_vprintf_callback(my_debug_callback); ``` -------------------------------- ### Configure nghttp3 callbacks Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Initialize the nghttp3_callbacks structure and assign only the necessary callback functions, leaving others as NULL. ```c nghttp3_callbacks callbacks = {0}; // Only set callbacks you need callbacks.recv_header = my_recv_header_callback; callbacks.recv_data = my_recv_data_callback; callbacks.end_stream = my_end_stream_callback; // ... others remain NULL ``` -------------------------------- ### nghttp3_conn_server_new Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Initializes a new HTTP/3 server connection. ```APIDOC ## nghttp3_conn_server_new ### Description Initializes a server HTTP/3 connection. Like client connections, control and QPACK streams must be bound before use. ### Signature int nghttp3_conn_server_new(nghttp3_conn **pconn, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, const nghttp3_mem *mem, void *conn_user_data); ### Parameters - **pconn** (nghttp3_conn **) - Required - Pointer to store the allocated connection object - **callbacks** (const nghttp3_callbacks *) - Required - Callback function handlers for connection events - **settings** (const nghttp3_settings *) - Required - HTTP/3 settings for this connection - **mem** (const nghttp3_mem *) - Required - Memory allocator - **conn_user_data** (void *) - Required - Arbitrary user data passed to callbacks ### Returns int - 0 on success, or NGHTTP3_ERR_NOMEM if memory allocation fails. ``` -------------------------------- ### Configure Include Directories Source: https://github.com/ngtcp2/nghttp3/blob/main/tests/CMakeLists.txt Sets the search paths for header files required by the test suite. ```cmake include_directories( "${CMAKE_SOURCE_DIR}/lib" "${CMAKE_SOURCE_DIR}/lib/includes" "${CMAKE_SOURCE_DIR}/tests/munit" "${CMAKE_BINARY_DIR}/lib/includes" ) ``` -------------------------------- ### nghttp3_conn_client_new Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/README.md Initializes a new client-side HTTP/3 connection instance. ```APIDOC ## nghttp3_conn_client_new ### Description Creates a new nghttp3 connection object for a client. This function sets up the internal state, registers application callbacks, and applies configuration settings. ### Signature int nghttp3_conn_client_new(nghttp3_conn **pconn, const nghttp3_callbacks *callbacks, const nghttp3_settings *settings, const nghttp3_mem *mem, void *user_data); ### Parameters - **pconn** (nghttp3_conn**) - Required - Pointer to store the created connection object. - **callbacks** (nghttp3_callbacks*) - Required - Struct containing function pointers for event handling. - **settings** (nghttp3_settings*) - Required - Configuration settings for the connection. - **mem** (nghttp3_mem*) - Required - Memory allocator configuration. - **user_data** (void*) - Optional - Application-specific state pointer. ``` -------------------------------- ### Create a QPACK stream context Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Initializes a new per-stream context required for decoding header blocks. ```c int nghttp3_qpack_stream_context_new(nghttp3_qpack_stream_context **psctx, int64_t stream_id, const nghttp3_mem *mem); ``` -------------------------------- ### Check System Headers Source: https://github.com/ngtcp2/nghttp3/blob/main/CMakeLists.txt Verifies the existence of various system header files. ```cmake include(CheckIncludeFile) check_include_file("arpa/inet.h" HAVE_ARPA_INET_H) check_include_file("unistd.h" HAVE_UNISTD_H) check_include_file("sys/endian.h" HAVE_SYS_ENDIAN_H) check_include_file("endian.h" HAVE_ENDIAN_H) check_include_file("byteswap.h" HAVE_BYTESWAP_H) ``` -------------------------------- ### Configure custom memory allocator Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Defines custom allocation callbacks and initializes an nghttp3_mem structure for use with connection functions. ```c // Custom allocator callbacks void *my_malloc(size_t size, void *user_data) { struct MyAllocator *alloc = (struct MyAllocator *)user_data; return my_allocator_alloc(alloc, size); } void my_free(void *ptr, void *user_data) { struct MyAllocator *alloc = (struct MyAllocator *)user_data; my_allocator_free(alloc, ptr); } void *my_calloc(size_t nmemb, size_t size, void *user_data) { size_t total = nmemb * size; void *ptr = my_malloc(total, user_data); if (ptr) memset(ptr, 0, total); return ptr; } void *my_realloc(void *ptr, size_t size, void *user_data) { struct MyAllocator *alloc = (struct MyAllocator *)user_data; return my_allocator_realloc(alloc, ptr, size); } // Configure custom allocator struct MyAllocator my_alloc = { /* ... */ }; nghttp3_mem custom_mem = { .user_data = &my_alloc, .malloc = my_malloc, .free = my_free, .calloc = my_calloc, .realloc = my_realloc }; int rv = nghttp3_conn_client_new(&conn, &callbacks, &settings, &custom_mem, NULL); ``` -------------------------------- ### Define nghttp3_proto_settings structure Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Represents a subset of settings recognized from a remote HTTP/3 endpoint. ```c typedef struct nghttp3_proto_settings { uint64_t max_field_section_size; size_t qpack_max_dtable_capacity; size_t qpack_blocked_streams; uint8_t enable_connect_protocol; uint8_t h3_datagram; } nghttp3_proto_settings; ``` -------------------------------- ### Handle NGHTTP3_ERR_QPACK_ENCODER_STREAM_ERROR in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Detects malformed instructions within the encoder stream. ```c nghttp3_ssize rv = nghttp3_qpack_decoder_read_encoder(decoder, src, srclen); if (rv < 0) { if (rv == NGHTTP3_ERR_QPACK_ENCODER_STREAM_ERROR) { fprintf(stderr, "Encoder stream error\n"); nghttp3_conn_del(conn); } } ``` -------------------------------- ### nghttp3_settings Structure Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md The nghttp3_settings structure is used to initialize an HTTP/3 connection. It contains fields for managing header sizes, QPACK dynamic table capacities, and various protocol feature flags. ```APIDOC ## nghttp3_settings ### Description Configuration structure passed to connection creation functions to define HTTP/3 negotiated parameters. ### Fields - **max_field_section_size** (uint64_t) - Optional - Maximum HTTP header section size in bytes. - **qpack_max_dtable_capacity** (size_t) - Optional - Maximum QPACK dynamic table capacity advertised to remote. - **qpack_encoder_max_dtable_capacity** (size_t) - Optional - Maximum QPACK dynamic table capacity the encoder will use. - **qpack_blocked_streams** (size_t) - Optional - Maximum number of streams blocked for QPACK synchronization. - **enable_connect_protocol** (uint8_t) - Optional - Enable RFC 9220 Extended CONNECT protocol. - **h3_datagram** (uint8_t) - Optional - Enable RFC 9297 HTTP/3 Datagrams. - **origin_list** (const nghttp3_vec *) - Optional - Server-only. Pointer to serialized ORIGIN frame payload. - **glitch_ratelim_burst** (uint64_t) - Optional - Maximum tokens for glitch rate limiting. - **glitch_ratelim_rate** (uint64_t) - Optional - Tokens generated per second for glitch detection. - **qpack_indexing_strat** (nghttp3_qpack_indexing_strat) - Optional - Strategy for QPACK dynamic table indexing. ``` -------------------------------- ### Handle NGHTTP3_ERR_QPACK_FATAL in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Detects a fatal QPACK encoder error requiring a connection reset. ```c int rv = nghttp3_qpack_encoder_encode(encoder, pbuf, rbuf, ebuf, stream_id, headers, 1); if (rv == NGHTTP3_ERR_QPACK_FATAL) { fprintf(stderr, "QPACK encoder fatal error\n"); nghttp3_conn_del(conn); // Establish new connection } ``` -------------------------------- ### Define nghttp3_settings structure Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Represents the full set of HTTP/3 connection settings used for configuration. ```c typedef struct nghttp3_settings { uint64_t max_field_section_size; size_t qpack_max_dtable_capacity; size_t qpack_encoder_max_dtable_capacity; size_t qpack_blocked_streams; uint8_t enable_connect_protocol; uint8_t h3_datagram; const nghttp3_vec *origin_list; uint64_t glitch_ratelim_burst; uint64_t glitch_ratelim_rate; nghttp3_qpack_indexing_strat qpack_indexing_strat; } nghttp3_settings; ``` -------------------------------- ### Define API Versioning Constants Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/README.md Use these macros to manage struct versioning for forward compatibility. ```c #define NGHTTP3_SETTINGS_V1 1 // Original #define NGHTTP3_SETTINGS_V2 2 // Added origin_list #define NGHTTP3_SETTINGS_V3 3 // Added glitch_ratelim_* #define NGHTTP3_SETTINGS_V4 4 // Added qpack_indexing_strat #define NGHTTP3_SETTINGS_VERSION NGHTTP3_SETTINGS_V4 ``` -------------------------------- ### Define nghttp3_info structure Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Holds library version information, retrieved via nghttp3_version(). ```c typedef struct nghttp3_info { int age; int version_num; const char *version_str; const char *proto_str; } nghttp3_info; ``` -------------------------------- ### Create a new QPACK encoder Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Allocates a new QPACK encoder instance with a specified maximum dynamic table capacity. ```c int nghttp3_qpack_encoder_new(nghttp3_qpack_encoder **pencoder, size_t hard_max_dtable_capacity, const nghttp3_mem *mem); ``` ```c nghttp3_qpack_encoder *encoder = NULL; int rv = nghttp3_qpack_encoder_new(&encoder, 4096, nghttp3_mem_default()); if (rv != 0) { // Handle error } // Use encoder... nghttp3_qpack_encoder_del(encoder); ``` -------------------------------- ### Configure WebSocket/TCP Tunneling Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Enable Extended CONNECT support and submit a CONNECT request for WebSocket tunneling. ```c nghttp3_settings settings = {0}; settings.enable_connect_protocol = 1; // Server-side: advertise support // Client sending CONNECT request nghttp3_nv headers[] = { {(uint8_t *)":method", (uint8_t *)"CONNECT", 7, 7, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":protocol", (uint8_t *)"websocket", 9, 9, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":authority", (uint8_t *)"example.com:443", 10, 15, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":path", (uint8_t *)"/", 5, 1, NGHTTP3_NV_FLAG_NONE}, }; int rv = nghttp3_conn_submit_request(conn, stream_id, headers, 4, NULL, NULL); ``` -------------------------------- ### Define nghttp3_begin_headers callback Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Invoked when an incoming HTTP header block begins. ```c typedef int (*nghttp3_begin_headers)(nghttp3_conn *conn, int64_t stream_id, void *conn_user_data, void *stream_user_data); ``` -------------------------------- ### Handle NGHTTP3_ERR_QPACK_HEADER_TOO_LARGE Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Check for header size violations and close the stream with the appropriate QUIC error code. ```c nghttp3_ssize rv = nghttp3_conn_read_stream2(conn, stream_id, buf, buflen); if (rv == NGHTTP3_ERR_QPACK_HEADER_TOO_LARGE) { fprintf(stderr, "Header too large\n"); nghttp3_conn_close_stream(conn, stream_id, NGHTTP3_H3_EXCESSIVE_LOAD); } ``` -------------------------------- ### Bind Control Stream Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Binds a local unidirectional QUIC stream for HTTP/3 control frames. Must be called exactly once per connection. ```c int nghttp3_conn_bind_control_stream(nghttp3_conn *conn, int64_t stream_id); ``` ```c // Assuming stream_id 2 is the local unidirectional control stream int rv = nghttp3_conn_bind_control_stream(conn, 2); if (rv != 0) { // Handle error } ``` -------------------------------- ### Set QPACK dynamic table indexing strategy Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Configures which headers are added to the dynamic table. Refer to types.md for valid indexing strategy values. ```c void nghttp3_qpack_encoder_set_indexing_strat( nghttp3_qpack_encoder *encoder, nghttp3_qpack_indexing_strat strat); ``` -------------------------------- ### nghttp3_qpack_decoder_new Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Initializes a new QPACK decoder instance with defined hard limits for dynamic table capacity and blocked streams. ```APIDOC ## nghttp3_qpack_decoder_new ### Description Creates a new QPACK decoder instance. The hard_max_dtable_capacity sets the absolute upper bound on dynamic table capacity, and max_blocked_streams limits the number of streams that can be blocked. ### Signature int nghttp3_qpack_decoder_new(nghttp3_qpack_decoder **decoder, size_t hard_max_dtable_capacity, size_t max_blocked_streams, const nghttp3_mem *mem); ### Parameters - **decoder** (nghttp3_qpack_decoder**) - Required - Pointer to the decoder instance to be initialized. - **hard_max_dtable_capacity** (size_t) - Required - Absolute upper bound on dynamic table capacity. - **max_blocked_streams** (size_t) - Required - Maximum number of streams that can be blocked. - **mem** (nghttp3_mem*) - Required - Memory allocator structure. ``` -------------------------------- ### Handle NGHTTP3_ERR_NOMEM Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Check for memory allocation failures when initializing library structures. ```c nghttp3_qpack_encoder *encoder = NULL; int rv = nghttp3_qpack_encoder_new(&encoder, 4096, mem); if (rv == NGHTTP3_ERR_NOMEM) { fprintf(stderr, "Out of memory\n"); exit(ENOMEM); } ``` -------------------------------- ### Bind QPACK streams in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Binds local unidirectional QUIC streams for QPACK header compression. Must be invoked before processing HTTP fields. ```c int nghttp3_conn_bind_qpack_streams(nghttp3_conn *conn, int64_t qpack_enc_stream_id, int64_t qpack_dec_stream_id); ``` ```c // Assuming streams 6 and 10 are local unidirectional QPACK streams int rv = nghttp3_conn_bind_qpack_streams(conn, 6, 10); if (rv != 0) { // Handle error } ``` -------------------------------- ### Create a new QPACK encoder with seed Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Allocates a new QPACK encoder using a seed for internal hash functions to mitigate collision attacks. ```c int nghttp3_qpack_encoder_new2(nghttp3_qpack_encoder **pencoder, size_t hard_max_dtable_capacity, uint64_t seed, const nghttp3_mem *mem); ``` ```c uint64_t seed = time(NULL) ^ (uint64_t)rand(); nghttp3_qpack_encoder *encoder = NULL; int rv = nghttp3_qpack_encoder_new2(&encoder, 4096, seed, nghttp3_mem_default()); ``` -------------------------------- ### nghttp3_qpack_stream_context_new Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Creates a new per-stream QPACK context required for decoding header blocks. ```APIDOC ## nghttp3_qpack_stream_context_new ### Description Creates a per-stream context for decoding multiple header blocks on the same stream. This is required for calling nghttp3_qpack_decoder_read_request(). ### Signature int nghttp3_qpack_stream_context_new(nghttp3_qpack_stream_context **psctx, int64_t stream_id, const nghttp3_mem *mem); ### Parameters - **psctx** (nghttp3_qpack_stream_context **) - Required - Pointer to store the created context. - **stream_id** (int64_t) - Required - The stream identifier. - **mem** (const nghttp3_mem *) - Required - The memory allocator to use. ### Returns - **int** - 0 on success, or NGHTTP3_ERR_NOMEM on failure. ``` -------------------------------- ### Implement C++ Linkage Wrapper Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/README.md Ensure C APIs are correctly exposed for C++ projects using extern "C". ```c #ifdef __cplusplus extern "C" { #endif // ... declarations ... #ifdef __cplusplus } #endif ``` -------------------------------- ### Submit and update stream priority Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Demonstrates submitting a request with default priority and subsequently updating it using nghttp3_conn_set_client_stream_priority. ```c // Create request with default priority nghttp3_conn_submit_request(conn, stream_id, headers, nheaders, NULL, NULL); // Later, adjust priority nghttp3_pri pri = { .urgency = 3, // Medium-low priority .incremental = 1 // Incremental scheduling }; int rv = nghttp3_conn_set_client_stream_priority(conn, stream_id, &pri); if (rv != 0) { // Handle error } ``` -------------------------------- ### Handle NGHTTP3_ERR_QPACK_DECOMPRESSION_FAILED in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Detects header decompression failures during request reading. ```c nghttp3_ssize rv = nghttp3_qpack_decoder_read_request(decoder, sctx, &nv, &flags, src, srclen); if (rv == NGHTTP3_ERR_QPACK_DECOMPRESSION_FAILED) { fprintf(stderr, "Cannot decompress header\n"); // Wait for encoder stream updates or close stream } ``` -------------------------------- ### Set C Standard Source: https://github.com/ngtcp2/nghttp3/blob/main/CMakeLists.txt Enforces C11 standard for the project. ```cmake set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) ``` -------------------------------- ### nghttp3_qpack_encoder_new2 Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Initializes a new QPACK encoder instance with a specified hard limit for the dynamic table capacity and a seed for internal hash functions. ```APIDOC ## nghttp3_qpack_encoder_new2 ### Description Creates a new QPACK encoder instance. The hard_max_dtable_capacity defines the absolute upper bound on dynamic table capacity, and the seed is used for internal hash functions. ### Signature int nghttp3_qpack_encoder_new2(nghttp3_qpack_encoder **encoder, size_t hard_max_dtable_capacity, uint64_t seed, const nghttp3_mem *mem); ### Parameters - **encoder** (nghttp3_qpack_encoder**) - Required - Pointer to the encoder instance to be initialized. - **hard_max_dtable_capacity** (size_t) - Required - Absolute upper bound on dynamic table capacity. - **seed** (uint64_t) - Required - Random seed for internal hash functions. - **mem** (nghttp3_mem*) - Required - Memory allocator structure. ``` -------------------------------- ### Enable HTTP/3 Datagrams Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Configure settings to enable unreliable datagram transmission. ```c nghttp3_settings settings = {0}; settings.h3_datagram = 1; // Enable datagram support // Library will send/receive SETTINGS_H3_DATAGRAM in SETTINGS frame ``` -------------------------------- ### nghttp3_qpack_encoder_set_indexing_strat Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Sets the dynamic table indexing strategy for the encoder. ```APIDOC ## nghttp3_qpack_encoder_set_indexing_strat ### Description Controls which headers are added to the dynamic table. ### Signature void nghttp3_qpack_encoder_set_indexing_strat(nghttp3_qpack_encoder *encoder, nghttp3_qpack_indexing_strat strat); ### Parameters - **encoder** (nghttp3_qpack_encoder *) - Encoder instance - **strat** (nghttp3_qpack_indexing_strat) - Indexing strategy ``` -------------------------------- ### Configure Debug Output Callback Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Sets a custom callback for formatted debug output. Only effective if the library is compiled with the DEBUGBUILD macro. ```c void nghttp3_set_debug_vprintf_callback( nghttp3_debug_vprintf_callback debug_vprintf_callback); ``` ```c typedef void (*nghttp3_debug_vprintf_callback)(const char *format, va_list args); ``` ```c #ifdef DEBUG void my_debug_output(const char *format, va_list args) { time_t now = time(NULL); struct tm *tm_info = localtime(&now); char time_buf[32]; strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", tm_info); fprintf(stderr, "[%s] nghttp3 debug: ", time_buf); vfprintf(stderr, format, args); fflush(stderr); } int main() { nghttp3_set_debug_vprintf_callback(my_debug_output); // ... rest of code ... } #endif ``` -------------------------------- ### Implement Basic Error Handling Pattern Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Standard pattern for processing return values from library functions, distinguishing between fatal, recoverable, and non-blocking errors. ```c int rv = nghttp3_conn_read_stream(conn, stream_id, buf, buflen); if (rv < 0) { // rv is negative error code if (rv < NGHTTP3_ERR_FATAL) { fprintf(stderr, "Fatal error: %s\n", nghttp3_strerror(rv)); uint64_t quic_error = nghttp3_err_infer_quic_app_error_code(rv); quic_conn_close(quic_conn, quic_error); break; } else if (rv == NGHTTP3_ERR_WOULDBLOCK) { // Retry later continue; } else { fprintf(stderr, "Error: %s\n", nghttp3_strerror(rv)); // Handle recoverable error } } else { // rv > 0 is success (bytes processed or similar) } ``` -------------------------------- ### nghttp3_version Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Retrieves library version information and protocol capabilities. ```APIDOC ## nghttp3_version ### Description Provides version information and protocol capabilities. Pass 0 to retrieve the current version information. ### Signature `const nghttp3_info *nghttp3_version(int least_version);` ### Parameters - **least_version** (int) - Required - Minimum required version (0 for current). ### Returns - **const nghttp3_info*** - Pointer to a static version structure. ``` -------------------------------- ### Configure Glitch Rate Limiter in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/configuration.md Adjusts token bucket parameters for glitch detection. Setting both values to 0 disables the rate limiter. ```c nghttp3_settings settings = {0}; // Conservative: 100 tokens, 50 per second // Tolerates ~2 seconds of moderate glitches settings.glitch_ratelim_burst = 100; settings.glitch_ratelim_rate = 50; // Aggressive: 1000 tokens, 500 per second // Tolerates ~2 seconds of heavy glitches settings.glitch_ratelim_burst = 1000; settings.glitch_ratelim_rate = 500; // Disabled settings.glitch_ratelim_burst = 0; settings.glitch_ratelim_rate = 0; ``` -------------------------------- ### Handle NGHTTP3_ERR_QPACK_DECODER_STREAM_ERROR in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Detects malformed updates within the decoder stream. ```c nghttp3_ssize rv = nghttp3_qpack_encoder_read_decoder(encoder, src, srclen); if (rv == NGHTTP3_ERR_QPACK_DECODER_STREAM_ERROR) { fprintf(stderr, "Decoder stream error\n"); nghttp3_conn_del(conn); } ``` -------------------------------- ### Retrieve library version with nghttp3_version Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/utilities.md Returns a pointer to a static structure containing version and protocol information. Pass 0 to retrieve the current library version. ```c const nghttp3_info *nghttp3_version(int least_version); ``` ```c const nghttp3_info *info = nghttp3_version(0); printf("nghttp3 version: %s\n", info->version_str); printf("Protocols: %s\n", info->proto_str); // Version checking if (info->version_num < 0x010d00) { fprintf(stderr, "Require nghttp3 >= 1.13.0\n"); exit(1); } ``` -------------------------------- ### nghttp3_qpack_encoder_new Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Allocates a new QPACK encoder with a specified maximum dynamic table capacity. ```APIDOC ## nghttp3_qpack_encoder_new ### Description Creates a new QPACK encoder instance. The dynamic table capacity starts at 0 and must be configured separately. ### Signature int nghttp3_qpack_encoder_new(nghttp3_qpack_encoder **pencoder, size_t hard_max_dtable_capacity, const nghttp3_mem *mem); ### Parameters - **pencoder** (nghttp3_qpack_encoder **) - Required - Pointer to store the allocated encoder. - **hard_max_dtable_capacity** (size_t) - Required - Upper bound of dynamic table size in bytes. - **mem** (const nghttp3_mem *) - Required - Memory allocator. ### Returns - **int** - 0 on success, or NGHTTP3_ERR_NOMEM on allocation failure. ``` -------------------------------- ### Submit graceful shutdown notice in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Initiates a graceful shutdown by sending a GOAWAY frame. The connection remains active for existing streams until drained. ```c int nghttp3_conn_submit_shutdown_notice(nghttp3_conn *conn); ``` ```c int rv = nghttp3_conn_submit_shutdown_notice(conn); if (rv != 0) { // Handle error } // Continue processing until drained ``` -------------------------------- ### Define nghttp3_mem Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Custom memory allocator interface structure. Use nghttp3_mem_default() to retrieve the default allocator. ```c typedef struct nghttp3_mem { void *user_data; nghttp3_malloc malloc; nghttp3_free free; nghttp3_calloc calloc; nghttp3_realloc realloc; } nghttp3_mem; ``` -------------------------------- ### nghttp3_qpack_decoder_get_icnt Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Retrieves the current insert count from the QPACK decoder. ```APIDOC ## nghttp3_qpack_decoder_get_icnt ### Description Returns the total insert count, which is used in acknowledgments sent on the decoder stream. ### Signature `uint64_t nghttp3_qpack_decoder_get_icnt(const nghttp3_qpack_decoder *decoder);` ### Parameters - **decoder** (const nghttp3_qpack_decoder *) - Required - Decoder instance ### Returns - **uint64_t** - Number of entries in the dynamic table. ``` -------------------------------- ### Read HTTP/3 stream data in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Processes incoming HTTP/3 frame data from a QUIC stream. May trigger callbacks and block if synchronization is required. ```c nghttp3_ssize nghttp3_conn_read_stream(nghttp3_conn *conn, int64_t stream_id, const uint8_t *src, size_t srclen); ``` ```c uint8_t buf[4096]; size_t nread = quic_recv(stream_id, buf, sizeof(buf)); nghttp3_ssize processed = nghttp3_conn_read_stream(conn, stream_id, buf, nread); if (processed < 0) { // Handle error } else if (processed < nread) { // Remaining data should be read again in next iteration } ``` -------------------------------- ### Submit HTTP/3 Trailers in C Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/core-api.md Defines the signature for submitting trailing headers after a request or response body. ```c int nghttp3_conn_submit_trailers(nghttp3_conn *conn, int64_t stream_id, const nghttp3_nv *nva, size_t nvlen); ``` -------------------------------- ### Handle NGHTTP3_ERR_WOULDBLOCK Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/errors.md Handle flow control or QPACK blocking scenarios during stream writes. ```c nghttp3_ssize written = nghttp3_conn_writev_stream(conn, stream_id, vec, &vcnt); if (written == NGHTTP3_ERR_WOULDBLOCK) { // Retry after processing decoder stream updates } ``` -------------------------------- ### Define nghttp3_recv_settings2 callback Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Invoked when a SETTINGS frame is received. This is preferred over the legacy nghttp3_recv_settings callback. ```c typedef int (*nghttp3_recv_settings2)(nghttp3_conn *conn, const nghttp3_proto_settings *settings, void *conn_user_data); ``` -------------------------------- ### Define nghttp3_pri structure Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/types.md Represents HTTP/3 stream priority settings. Urgency ranges from 0 to 7, where 0 is the highest priority. ```c typedef struct NGHTTP3_ALIGN(8) nghttp3_pri { uint32_t urgency; uint8_t incremental; } nghttp3_pri; ``` -------------------------------- ### Encode HTTP Headers with QPACK Source: https://github.com/ngtcp2/nghttp3/blob/main/_autodocs/qpack-api.md Encodes headers into three distinct buffers: prefix, compressed block, and encoder stream updates. All buffers must be managed by the caller and sent to the peer in the specified order. ```c int nghttp3_qpack_encoder_encode(nghttp3_qpack_encoder *encoder, nghttp3_buf *pbuf, nghttp3_buf *rbuf, nghttp3_buf *ebuf, int64_t stream_id, const nghttp3_nv *nva, size_t nvlen); ``` ```c nghttp3_buf pbuf, rbuf, ebuf; nghttp3_buf_init(&pbuf); nghttp3_buf_init(&rbuf); nghttp3_buf_init(&ebuf); nghttp3_nv headers[] = { {(uint8_t *)":method", (uint8_t *)"GET", 7, 3, NGHTTP3_NV_FLAG_NONE}, {(uint8_t *)":path", (uint8_t *)"/", 5, 1, NGHTTP3_NV_FLAG_NONE}, }; int rv = nghttp3_qpack_encoder_encode(encoder, &pbuf, &rbuf, &ebuf, stream_id, headers, sizeof(headers)/sizeof(headers[0])); if (rv != 0) { // Handle error } // Send pbuf.pos to pbuf.last, rbuf.pos to rbuf.last on stream // Send ebuf.pos to ebuf.last on encoder stream ```