Skip to content

Implement DTLSv1_get_timeout and DTLSv1_handle_timeout - #11974

Open
Frauschi wants to merge 1 commit into
wolfSSL:masterfrom
Frauschi:dtlsv1-timeout-apis
Open

Frauschi wants to merge 1 commit into
wolfSSL:masterfrom
Frauschi:dtlsv1-timeout-apis

Conversation

@Frauschi

@Frauschi Frauschi commented Nov 3, 2026

Copy link
Copy Markdown
Member

wolfSSL_DTLSv1_get_timeout always returned 0 with the full timeout and wolfSSL_DTLSv1_handle_timeout was a stub, so OpenSSL-style event loops never retransmitted a lost flight. This implements both on a per-object millisecond retransmission timer and a DTLS 1.3 ACK timer.

Changes

  • Track a retransmission timer, restarted on store, resend, backoff and reset, and a DTLS 1.3 ACK timer at a quarter of the timeout
  • get_timeout returns 1 with the time left while a timer runs, else 0, and no longer fills in dtls_timeout when none runs
  • handle_timeout returns 1 after acting on an expired timer, 0 when none expired, -1 on error
  • No retransmission timer while output is pending or the handshake is suspended on async crypto, non-blocking OCSP or a chain verify callback
  • Fix the DTLS 1.3 quick timeout retransmitting and doubling the timeout after a quarter wait
  • DTLS 1.3 sets SOCKET_ERROR_E at the maximum timeout, as DTLS 1.2 does
  • Lock the ACK timer state under WOLFSSL_RW_THREADED
  • Build TimeNowInMilliseconds for DTLS and merge its two tls13.c ladders into one in internal.c; whole-second clocks round elapsed time down
  • Fix the FreeRTOS millisecond clock wrapping after about 71 minutes at 1 kHz
  • DEOS clock reads through a const volatile pointer; Zephyr skips k_cpu_idle() on native_sim and native_posix
  • CMake exports HAVE_GETTIMEOFDAY to config.h

Testing

  • New test_wolfSSL_DTLSv1_timer suite for DTLS 1.2 and 1.3: expiry, backoff, max, reset, peer resend, blocked write, ACK timer, quick timeout, async suspend
  • Updated test_dtls_timeout and test_dtls_drop_client_ack

@Frauschi Frauschi self-assigned this Nov 3, 2026
Copilot AI balanced review requested due to automatic review settings November 3, 2026 18:26
@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

MemBrowse Memory Report · Explore what changed →

gcc-arm-cortex-m4-dtls13

  • FLASH: .text +320 B (+0.2%, 199,140 B / 1,048,576 B, total: 19% used)

zephyr-frdm_rw612

  • FLASH: datas +16 B, log_const_area -8 B, rodata +108 B, text +13,496 B (+4.8%, 296,076 B / 67,108,864 B, total: 0% used)
  • RAM: bss +49 B, datas +16 B (+0.1%, 58,423 B / 983,040 B, total: 6% used)

No memory changes detected for:


Catch memory regressions in CI with MemBrowse. Free for open source.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The retransmission timer is not restarted after blocked output flushes, risking premature retransmission or timeout failure, and the threaded session-ticket test omits scheduled ACK processing needed for its timer assertions.

2 open issues
What changed in this PR

Implements wolfSSL’s OpenSSL-compatible DTLS timeout APIs so event loops can schedule retransmissions and DTLS 1.3 acknowledgments.

Changes:

  • Adds per-connection retransmission and ACK timers with expiry handling, backoff, and reset logic.
  • Consolidates millisecond clocks and updates platform-specific timing behavior.
  • Adds DTLS timer tests covering expiry, blocked writes, ACKs, and suspended handshakes.
File Description
wolfssl/​internal.h Adds timer state and internal helper declarations.
tests/​api/​test_dtls.h Registers the new timer test suite.
tests/​api/​test_dtls.c Adds timer coverage and updates existing timeout tests.
src/​wolfio.c Uses shared timer-state detection for receive timeouts.
src/​tls13.c Removes clock implementations moved to internal.c.
src/​ssl_api_dtls.c Implements timeout queries and expired-timer handling.
src/​internal.c Adds timer helpers and consolidates platform clocks.
src/​dtls13.c Integrates retransmission and ACK timer management.
cmake/​config.in Exports HAVE_GETTIMEOFDAY to generated configuration.

Review effort: Balanced

Comment thread src/ssl_api_dtls.c Resolved
Comment thread tests/api/test_dtls.c Resolved
@Frauschi

Frauschi commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

@claude review

@Frauschi

Frauschi commented Nov 3, 2026

Copy link
Copy Markdown
Member Author

@wolfSSL-Fenrir-bot review balanced

@wolfSSL-Fenrir-bot wolfSSL-Fenrir-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fenrir Automated Review — PR #11974

Scan targets checked: wolfssl-src, wolfssl-bugs
Not reviewed (no scan target covers them): cmake/config.in, tests/api/test_dtls.h
Coverage: 6 of 7 in-scope changed file(s) opened by the reviewer; not opened: src/tls13.c

Fenrir result: Approved ✅

No new issues found in the changed files.

Advisory only — this automated result does not count as a GitHub approval.

Review tier: Balanced

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread src/internal.c Resolved
Comment thread src/ssl_api_dtls.c Resolved
@Frauschi
Frauschi force-pushed the dtlsv1-timeout-apis branch 2 times, most recently from 031caf4 to 0bace31 Compare November 5, 2026 08:19
@Frauschi Frauschi assigned wolfSSL-Bot and unassigned Frauschi Nov 5, 2026

@julek-wolfssl julek-wolfssl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the motivation behind this refactor? The two API functions could be implemented without making changes to the DTLS stack.

Comment thread src/wolfio.c
Comment on lines 739 to 740
/* Don't use ssl->options.handShakeDone since it is true even if
* we are in the process of renegotiation */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is now misplaced.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it back above the handShakeState check it describes.

Comment thread src/tls13.c
Comment on lines -2106 to -2712
#if defined(HAVE_SESSION_TICKET) || !defined(NO_PSK) || defined(WOLFSSL_DTLS13)
#ifdef WOLFSSL_32BIT_MILLI_TIME
#ifndef NO_ASN_TIME
#if defined(USER_TICKS)
#if 0
word32 TimeNowInMilliseconds(void)
{
/*
write your own clock tick function if don't want gettimeofday()
needs millisecond accuracy but doesn't have to correlated to EPOCH
*/
}
#endif

#elif defined(WOLFSSL_OPTEE)
word32 TimeNowInMilliseconds(void)
{
TEE_Time now;

/* Monotonic within the TA, and not the normal world's clock. */
TEE_GetSystemTime(&now);

return (word32)((now.seconds * 1000) + now.millis);
}

#elif defined(TIME_OVERRIDES)
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
word32 TimeNowInMilliseconds(void)
{
return (word32) wc_Time(0) * 1000;
}
#else
#ifndef HAVE_TIME_T_TYPE
typedef long time_t;
#endif
extern time_t XTIME(time_t * timer);

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32) XTIME(0) * 1000;
}
#endif

#elif defined(XTIME_MS)
word32 TimeNowInMilliseconds(void)
{
return (word32)XTIME_MS(0);
}

#elif defined(USE_WINDOWS_API)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
static int init = 0;
static LARGE_INTEGER freq;
LARGE_INTEGER count;

if (!init) {
QueryPerformanceFrequency(&freq);
init = 1;
}

QueryPerformanceCounter(&count);

return (word32)(count.QuadPart / (freq.QuadPart / 1000));
}

#elif defined(HAVE_RTP_SYS)
#include "rtptime.h"

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32)rtp_get_system_sec() * 1000;
}
#elif defined(WOLFSSL_DEOS)
word32 TimeNowInMilliseconds(void)
{
const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
word32 *systemTickPtr = systemTickPointer();

return (word32) (*systemTickPtr/systemTickTimeInHz) * 1000;
}
#elif defined(MICRIUM)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
OS_TICK ticks = 0;
OS_ERR err;

ticks = OSTimeGet(&err);

return (word32) (ticks / OSCfg_TickRate_Hz) * 1000;
}
#elif defined(MICROCHIP_TCPIP_V5)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32) (TickGet() / (TICKS_PER_SECOND / 1000));
}
#elif defined(MICROCHIP_TCPIP)
#if defined(MICROCHIP_MPLAB_HARMONY)
#include <system/tmr/sys_tmr.h>

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32)(SYS_TMR_TickCountGet() /
(SYS_TMR_TickCounterFrequencyGet() / 1000));
}
#else
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32)(SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000));
}

#endif

#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
TIME_STRUCT mqxTime;

_time_get_elapsed(&mqxTime);

return (word32) mqxTime.SECONDS * 1000;
}
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
#include "include/task.h"

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (unsigned int)(((float)xTaskGetTickCount()) /
(configTICK_RATE_HZ / 1000));
}
#elif defined(FREESCALE_KSDK_BM)
#include "lwip/sys.h" /* lwIP */

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return sys_now();
}

#elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)

word32 TimeNowInMilliseconds(void)
{
return (word32)osKernelGetTickCount();
}

#elif defined(WOLFSSL_TIRTOS)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32) Seconds_get() * 1000;
}
#elif defined(WOLFSSL_UTASKER)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
return (word32)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
}
#elif defined(WOLFSSL_LINUXKM)
word32 TimeNowInMilliseconds(void)
{
return (word32)wc_linuxkm_time_epoch_msecs();
}
#elif defined(WOLFSSL_QNX_CAAM)
word32 TimeNowInMilliseconds(void)
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
return (word32)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
}
#elif defined(FUSION_RTOS)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
struct timeval now;
if (FCL_GETTIMEOFDAY(&now, 0) < 0)
return 0;

/* Convert to milliseconds number. */
return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
}
#elif defined(WOLFSSL_ZEPHYR)
word32 TimeNowInMilliseconds(void)
{
int64_t t;
#if defined(CONFIG_ARCH_POSIX)
k_cpu_idle();
#endif
t = k_uptime_get(); /* returns current uptime in milliseconds */
return (word32)t;
}
#elif defined(FREERTOS)
word32 TimeNowInMilliseconds(void)
{
return (word32)((uint64_t)(xTaskGetTickCount() * 1000) /
configTICK_RATE_HZ);
}
#else
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
word32 TimeNowInMilliseconds(void)
{
struct timeval now;

if (gettimeofday(&now, 0) < 0)
return 0;

/* Convert to milliseconds number. */
return (word32)(now.tv_sec * 1000 + now.tv_usec / 1000);
}
#endif
#else
/* user must supply time in milliseconds function:
* word32 TimeNowInMilliseconds(void);
* The response is milliseconds elapsed
*/
#endif /* !NO_ASN_TIME */
#else
#ifndef NO_ASN_TIME
#if defined(USER_TICKS)
#if 0
sword64 TimeNowInMilliseconds(void)
{
/*
write your own clock tick function if don't want gettimeofday()
needs millisecond accuracy but doesn't have to correlated to EPOCH
*/
}
#endif

#elif defined(WOLFSSL_OPTEE)
sword64 TimeNowInMilliseconds(void)
{
TEE_Time now;

/* Monotonic within the TA, and not the normal world's clock. */
TEE_GetSystemTime(&now);

return ((sword64)now.seconds * 1000) + (sword64)now.millis;
}

#elif defined(TIME_OVERRIDES)
#if !defined(NO_ASN) && !defined(NO_ASN_TIME)
sword64 TimeNowInMilliseconds(void)
{
return (sword64) wc_Time(0) * 1000;
}
#else
#ifndef HAVE_TIME_T_TYPE
typedef long time_t;
#endif
extern time_t XTIME(time_t * timer);

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 32-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64) XTIME(0) * 1000;
}
#endif

#elif defined(XTIME_MS)
sword64 TimeNowInMilliseconds(void)
{
return (sword64)XTIME_MS(0);
}

#elif defined(USE_WINDOWS_API)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
static int init = 0;
static LARGE_INTEGER freq;
LARGE_INTEGER count;

if (!init) {
QueryPerformanceFrequency(&freq);
init = 1;
}

QueryPerformanceCounter(&count);

return (sword64)(count.QuadPart / (freq.QuadPart / 1000));
}

#elif defined(HAVE_RTP_SYS)
#include "rtptime.h"

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64)rtp_get_system_sec() * 1000;
}
#elif defined(WOLFSSL_DEOS)
sword64 TimeNowInMilliseconds(void)
{
const word32 systemTickTimeInHz = 1000000 / systemTickInMicroseconds();
word32 *systemTickPtr = systemTickPointer();

return (sword64) (*systemTickPtr/systemTickTimeInHz) * 1000;
}
#elif defined(MICRIUM)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
OS_TICK ticks = 0;
OS_ERR err;

ticks = OSTimeGet(&err);

return (sword64) (ticks / OSCfg_TickRate_Hz) * 1000;
}
#elif defined(MICROCHIP_TCPIP_V5)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64) (TickGet() / (TICKS_PER_SECOND / 1000));
}
#elif defined(MICROCHIP_TCPIP)
#if defined(MICROCHIP_MPLAB_HARMONY)
#include <system/tmr/sys_tmr.h>

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64)SYS_TMR_TickCountGet() /
(SYS_TMR_TickCounterFrequencyGet() / 1000);
}
#else
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64)SYS_TICK_Get() / (SYS_TICK_TicksPerSecondGet() / 1000);
}

#endif

#elif defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
TIME_STRUCT mqxTime;

_time_get_elapsed(&mqxTime);

return (sword64) mqxTime.SECONDS * 1000;
}
#elif defined(FREESCALE_FREE_RTOS) || defined(FREESCALE_KSDK_FREERTOS)
#include "include/task.h"

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64)xTaskGetTickCount() / (configTICK_RATE_HZ / 1000);
}
#elif defined(FREESCALE_KSDK_BM)
#include "lwip/sys.h" /* lwIP */

/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return sys_now();
}

#elif defined(WOLFSSL_CMSIS_RTOS) || defined(WOLFSSL_CMSIS_RTOSv2)

sword64 TimeNowInMilliseconds(void)
{
return (sword64)osKernelGetTickCount();
}

#elif defined(WOLFSSL_TIRTOS)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64) Seconds_get() * 1000;
}
#elif defined(WOLFSSL_UTASKER)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
return (sword64)(uTaskerSystemTick / (TICK_RESOLUTION / 1000));
}
#elif defined(WOLFSSL_LINUXKM)
sword64 TimeNowInMilliseconds(void)
{
s64 t;
#if LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)
struct timespec ts;
getnstimeofday(&ts);
t = ts.tv_sec * (s64)1000;
t += ts.tv_nsec / (s64)1000000;
#else
struct timespec64 ts;
#if LINUX_VERSION_CODE < KERNEL_VERSION(5, 0, 0)
ts = current_kernel_time64();
#else
ktime_get_coarse_real_ts64(&ts);
#endif
t = ts.tv_sec * 1000L;
t += ts.tv_nsec / 1000000L;
#endif
return (sword64)t;
}
#elif defined(WOLFSSL_QNX_CAAM)
sword64 TimeNowInMilliseconds(void)
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
return (sword64)(now.tv_sec * 1000 + now.tv_nsec / 1000000);
}
#elif defined(FUSION_RTOS)
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
struct timeval now;
if (FCL_GETTIMEOFDAY(&now, 0) < 0)
return 0;

/* Convert to milliseconds number. */
return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
}
#elif defined(WOLFSSL_ZEPHYR)
sword64 TimeNowInMilliseconds(void)
{
int64_t t;
#if defined(CONFIG_ARCH_POSIX)
k_cpu_idle();
#endif
t = k_uptime_get(); /* returns current uptime in milliseconds */
return (sword64)t;
}
#elif defined(FREERTOS)
sword64 TimeNowInMilliseconds(void)
{
return (sword64)((uint64_t)(xTaskGetTickCount() * 1000) /
configTICK_RATE_HZ);
}
#else
/* The time in milliseconds.
* Used for tickets to represent difference between when first seen and when
* sending.
*
* returns the time in milliseconds as a 64-bit value.
*/
sword64 TimeNowInMilliseconds(void)
{
struct timeval now;

if (gettimeofday(&now, 0) < 0)
return 0;

/* Convert to milliseconds number. */
return (sword64)now.tv_sec * 1000 + now.tv_usec / 1000;
}
#endif
#else
/* user must supply time in milliseconds function:
* sword64 TimeNowInMilliseconds(void);
* The response is milliseconds elapsed
*/
#endif /* !NO_ASN_TIME */
#endif /* WOLFSSL_32BIT_MILLI_TIME */
#endif /* HAVE_SESSION_TICKET || !NO_PSK || WOLFSSL_DTLS13 */

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was all this moved?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With --disable-tls13 the tls13.c ladder isn't compiled, but the DTLS 1.2 timers now need a millisecond clock too. It moved next to LowResTimer in internal.c so both share one copy instead of a second ladder.

Comment thread src/internal.c Outdated
Comment on lines +12017 to +12057
/* Get the DTLS timers that run.
*
* @param [in] ssl SSL/TLS object.
* @param [out] ackStart Start of the DTLS 1.3 ack timer. May be NULL.
* @return DTLS_TIMER_RTX and DTLS_TIMER_ACK bits, 0 when none runs.
* @return BAD_MUTEX_E when locking fails.
*/
int DtlsTimersRunning(WOLFSSL* ssl, word32* ackStart)
{
int running = 0;

(void)ackStart;

#ifdef WOLFSSL_DTLS13
if (IsAtLeastTLSv1_3(ssl->version)) {
if (ssl->dtls13Rtx.rtxRecords != NULL)
running |= DTLS_TIMER_RTX;
#ifdef WOLFSSL_RW_THREADED
if (wc_LockMutex(&ssl->dtls13Rtx.mutex) != 0)
return BAD_MUTEX_E;
#endif
if (ssl->dtls13FastTimeout && Dtls13AckSendable(ssl))
running |= DTLS_TIMER_ACK;
#ifndef NO_ASN_TIME
if (ackStart != NULL)
*ackStart = ssl->dtls_ack_timer_start;
#endif
#ifdef WOLFSSL_RW_THREADED
wc_UnLockMutex(&ssl->dtls13Rtx.mutex);
#endif
return running;
}
#endif /* WOLFSSL_DTLS13 */

if (ssl->options.handShakeState != HANDSHAKE_DONE &&
(ssl->dtls_tx_msg_list != NULL || ssl->dtls_tx_msg != NULL) &&
DtlsMsgPoolWaiting(ssl))
running |= DTLS_TIMER_RTX;

return running;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is the return being used for both status return and error information?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Split it: DtlsTimersRunning, and DtlsTimerLeft with the same pattern, now return 0 or BAD_MUTEX_E and report the timers through an out parameter.

Comment thread src/internal.c Outdated
Comment on lines +12824 to +12832
/* Return 1 when the DTLS timer clock counts whole seconds. */
int DtlsTimerLowRes(void)
{
#if defined(MS_TIME_LOW_RES) || defined(MS_TIME_FALLBACK)
return 1;
#else
return 0;
#endif
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This name implies it returns the same as LowResTimer.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed to DtlsTimerIsLowRes.

@Frauschi

Copy link
Copy Markdown
Member Author

To report the time left, the library has to know when the current flight went out, and master doesn't keep that. Its only timer state is dtls_start_timeout, which drives the non-blocking socket path in EmbedReceiveFrom in whole seconds. So the minimum is a timestamp set when a flight is stored or resent, plus a way to tell whether a timer runs at all. That check was inline in EmbedReceiveFrom, and DtlsTimersRunning() takes it over so both paths agree.

The rest came from edge cases the first version got wrong: the DTLS 1.3 ACK timer (a quarter of the timeout), no timer while our own write is blocked or the handshake is suspended on async crypto, and a DTLS 1.3 quick-timeout bug where Dtls13RtxTimeout cleared the flag before checking it, so the quarter-timeout ACK also retransmitted the flight and doubled the timeout. The clock ladder only moved so --disable-tls13 DTLS builds get a millisecond clock.

If it makes the review easier, I can split the quick-timeout fix and the ladder move into separate PRs and keep this one to the timer itself.

@julek-wolfssl julek-wolfssl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But why are the DTLS internals being changed? Is this fixing a bug report?

Also the quick timeout is not a "DTLS 1.3 ACK timer" so let's not call it that.

@Frauschi

Copy link
Copy Markdown
Member Author

No bug report; it came out of an OpenSSL-compat audit where handle_timeout was a stub, so event loops never retransmit. This is now one flight timestamp plus the two APIs, the quick-timeout fix moved to #12143, the "ack timer" is gone, and the other bugfixes will follow as separate PRs.

@Frauschi Frauschi removed their assignment Nov 16, 2026

@julek-wolfssl julek-wolfssl left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The stack changes are there to get the timing right, but the timer still doesn't measure what OpenSSL's does:

  • Every valid handshake message from the peer restarts it, so a partial peer flight pushes the deadline out (test_DTLSv1_timer_reset checks this). OpenSSL only starts its timer when it sends, and stops it once the peer's whole flight is in. With only the ServerHello arriving 400 ms after the ClientHello, OpenSSL's timer expires 1 s after the ClientHello and this PR's 1 s after the ServerHello.
  • In DTLS 1.3 the flight is dropped at the first message of the peer's next flight, so the timer stops there. OpenSSL 4.1 keeps it until the peer's whole flight is in or everything is ACKed.
  • A blocked flight keeps its queue-time start, so it can fire as soon as it's flushed.
  • On ports where TimeNowInMilliseconds() returns whole seconds (TIME_OVERRIDES, MICRIUM, WOLFSSL_DEOS, ...), it can fire up to a second early.

Since the timing is approximate either way, I'd rather not change the DTLS stack for it. The seven DtlsTimerStart() calls run on every DTLS connection, whether the app uses these APIs or not.

This can be done in ssl_api_dtls.c alone. Start the timer on the first get_timeout()/handle_timeout() call after a new flight. OpenSSL-style loops call DTLSv1_get_timeout() right after the call that sent the flight, so that's close enough.

  • Keep the existing checks in DtlsTimerLeft() to decide whether a flight waits. Clear the timer when none does.
  • Spot a new flight by saving ssl->keys.dtls_handshake_number when the timer starts. It changes for new handshake messages but not for retransmissions, in both 1.2 and 1.3.
  • Store the deadline when the timer starts, so resetting dtls_timeout on receive doesn't move it.
  • Restart the timer in handle_timeout() after wolfSSL_dtls_got_timeout() succeeds.
  • LowResTimer() is enough. Round up so it never fires early. It can be up to a second late.

That's two fields in struct WOLFSSL and no changes to internal.c or dtls13.c. It's coarser, and it starts on the first call after the flight rather than at the send. In return, receiving doesn't restart the timer, as in OpenSSL, and since no timer runs while output is pending, a blocked flight gets a fresh timer once it's flushed.

/* struct WOLFSSL, next to dtls_start_timeout */
    word32          dtls_timer_end;     /* LowResTimer() expiry, 0 when idle */
    word16          dtls_timer_seq;     /* tx handshake seq when started */

static void DtlsTimerRestart(WOLFSSL* ssl)
{
    ssl->dtls_timer_end = LowResTimer() + (word32)ssl->dtls_timeout + 1;
    ssl->dtls_timer_seq = ssl->keys.dtls_handshake_number;
}

static int DtlsTimerLeft(WOLFSSL* ssl, word32* left)
{
    word32 now;

    if (!DtlsFlightWaits(ssl)) {    /* the checks DtlsTimerLeft() has now */
        ssl->dtls_timer_end = 0;
        return 0;
    }
    if (ssl->dtls_timer_end == 0 ||
            ssl->dtls_timer_seq != ssl->keys.dtls_handshake_number)
        DtlsTimerRestart(ssl);
    now = LowResTimer();
    *left = (now < ssl->dtls_timer_end) ? ssl->dtls_timer_end - now : 0;
    return 1;
}

get_timeout() reports left in tv_sec. handle_timeout() stays as it is, plus DtlsTimerRestart(ssl) after a successful wolfSSL_dtls_got_timeout().

A quick prototype of this completes every lossy DTLS 1.2 and 1.3 handshake this PR completes, driven only by these two APIs.

wolfSSL_DTLSv1_get_timeout always returned 0 and reported the full
timeout instead of the time left, and wolfSSL_DTLSv1_handle_timeout was
a stub that did nothing. OpenSSL style event loops that wait for
get_timeout and then call handle_timeout never retransmitted a lost
flight.

The timer lives in the API layer and leaves the DTLS stack untouched. It
starts on the first get_timeout or handle_timeout call after a new
flight went out, which OpenSSL style loops make right after the call
that sent it. A new flight is spotted by
ssl->keys.dtls_handshake_number, which changes for every new handshake
message but not for retransmissions, in both DTLS 1.2 and 1.3. The timer
keeps its LowResTimer start and its length, the timeout plus one second
so the whole second clock never fires early; it can fire up to a second
late instead. The elapsed time is unsigned, as in EmbedReceiveFrom, so a
clock that steps back or a tick counter that wraps expires the timer at
once rather than stalling it. Since the length is fixed when the timer
starts, a peer message that resets the timeout does not move the expiry,
so part of the peer's flight arriving does not delay the retransmission,
as in OpenSSL. wolfSSL_clear stops the timer, since it restarts the
handshake message numbers.

get_timeout returns 1 with the seconds left while a flight waits for
the peer and 0 otherwise. A DTLS 1.2 flight waits while it is stored
and the handshake has not finished, a DTLS 1.3 flight while records are
kept for retransmission. No timer runs while the object's own output is
still pending or the handshake is suspended, so a blocked write or a
slow asynchronous signature cannot trigger a retransmission of a partly
sent flight, and a blocked flight gets a fresh timer once it is out. No
timer runs once a fatal alert closed the connection, the transport
reported a reset, or a close_notify was sent or received, so a pending
DTLS 1.3 KeyUpdate is not resent after it, or with a timeout of 0,
which means no timeout. Write duplicate objects run no timer, as the
DTLS 1.3 scheduled work API already leaves them out.

handle_timeout returns 0 when no timer runs or it has not expired yet.
Otherwise it calls wolfSSL_dtls_got_timeout, restarts the timer with
the backed off timeout and returns 1. When that fails, for example on
WANT_WRITE or once the timeout reached its maximum, it stops the timer
and returns -1, so a blocked retransmission gets a fresh timer once it
is out. For DTLS 1.3 it clears the quick timeout flag first, since the
full timeout expired, so the call retransmits instead of only sending
ACKs. Both return 0 when NO_ASN_TIME leaves no clock.

The DTLS 1.3 quick timeout is not reported by get_timeout, so with
these APIs the ACKs for a partly received flight go out with the next
full timeout.
@Frauschi
Frauschi force-pushed the dtlsv1-timeout-apis branch from c871332 to 23b9201 Compare November 20, 2026 15:16
@Frauschi

Copy link
Copy Markdown
Member Author

Reworked as you suggested: lazy start in ssl_api_dtls.c, new flight spotted via dtls_handshake_number, no internal.c or dtls13.c changes. One difference: it stores the start time and length, not the deadline, so a clock stepping back or a wrapping tick counter fires the timer instead of stalling it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants