|
| 1 | +#include <time.h> |
| 2 | +#include <stdint.h> |
| 3 | +#include <sys/time.h> |
| 4 | + |
| 5 | +typedef struct { |
| 6 | + struct timespec end_time; |
| 7 | + int int_ms; |
| 8 | + int fin_ms; |
| 9 | + int active; |
| 10 | +} timing_delay_context; |
| 11 | + |
| 12 | +void |
| 13 | +mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms) |
| 14 | +{ |
| 15 | + timing_delay_context *ctx = (timing_delay_context *)data; |
| 16 | + |
| 17 | + ctx->int_ms = (int)int_ms; |
| 18 | + ctx->fin_ms = (int)fin_ms; |
| 19 | + ctx->active = 1; |
| 20 | + |
| 21 | + if (fin_ms == 0) { |
| 22 | + // Cancel |
| 23 | + ctx->active = 0; |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + // current time + fin_ms = end_time |
| 28 | + struct timespec now; |
| 29 | + clock_gettime(CLOCK_MONOTONIC, &now); |
| 30 | + ctx->end_time.tv_sec = now.tv_sec + fin_ms / 1000; |
| 31 | + ctx->end_time.tv_nsec = now.tv_nsec + (fin_ms % 1000) * 1000000; |
| 32 | + if (ctx->end_time.tv_nsec >= 1000000000) { |
| 33 | + ctx->end_time.tv_sec += 1; |
| 34 | + ctx->end_time.tv_nsec -= 1000000000; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +int |
| 39 | +mbedtls_timing_get_delay(void *data) |
| 40 | +{ |
| 41 | + timing_delay_context *ctx = (timing_delay_context *)data; |
| 42 | + |
| 43 | + if (ctx->fin_ms == 0 || !ctx->active) return -1; |
| 44 | + |
| 45 | + struct timespec now; |
| 46 | + clock_gettime(CLOCK_MONOTONIC, &now); |
| 47 | + |
| 48 | + int64_t elapsed_ms = (ctx->end_time.tv_sec - now.tv_sec) * 1000 + |
| 49 | + (ctx->end_time.tv_nsec - now.tv_nsec) / 1000000; |
| 50 | + |
| 51 | + if (elapsed_ms <= -ctx->fin_ms) { |
| 52 | + return 2; // Final delay has passed |
| 53 | + } else if (elapsed_ms <= -ctx->int_ms) { |
| 54 | + return 1; // Intermediate delay has passed |
| 55 | + } else { |
| 56 | + return 0; // Still active, but no delay |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +// Stub |
| 61 | +unsigned long |
| 62 | +mbedtls_timing_hardclock(void) |
| 63 | +{ |
| 64 | + static unsigned long counter = 0; |
| 65 | + return ++counter; |
| 66 | +} |
| 67 | + |
0 commit comments