| 1 | /* |
| 2 | * mbedtls_threading.h - Win32 mutex callbacks for MBEDTLS_THREADING_ALT. |
| 3 | * |
| 4 | * On Windows, mbedtls is built with MBEDTLS_THREADING_C + MBEDTLS_THREADING_ALT |
| 5 | * (see thirdparty/mbedtls/include/mbedtls/mbedtls_config.h). The library then |
| 6 | * expects the embedder to supply the four mutex primitives via |
| 7 | * mbedtls_threading_set_alt(). These wrap a Win32 CRITICAL_SECTION; the matching |
| 8 | * mbedtls_threading_mutex_t type is defined in |
| 9 | * thirdparty/mbedtls/include/mbedtls/threading_alt.h. |
| 10 | * |
| 11 | * v_mbedtls_threading_setup() is called once from net.mbedtls' init() before any |
| 12 | * TLS use. On every other platform it is a no-op (pthread threading, or none). |
| 13 | */ |
| 14 | #ifndef V_MBEDTLS_THREADING_H |
| 15 | #define V_MBEDTLS_THREADING_H |
| 16 | |
| 17 | #if defined(_WIN32) && defined(MBEDTLS_THREADING_ALT) |
| 18 | |
| 19 | #include <windows.h> |
| 20 | #include <mbedtls/threading.h> |
| 21 | #include <mbedtls/error.h> |
| 22 | |
| 23 | static void v_mbedtls_mutex_init(mbedtls_threading_mutex_t *m) { |
| 24 | InitializeCriticalSection(&m->cs); |
| 25 | m->is_valid = 1; |
| 26 | } |
| 27 | |
| 28 | static void v_mbedtls_mutex_free(mbedtls_threading_mutex_t *m) { |
| 29 | if (m->is_valid) { |
| 30 | DeleteCriticalSection(&m->cs); |
| 31 | m->is_valid = 0; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | static int v_mbedtls_mutex_lock(mbedtls_threading_mutex_t *m) { |
| 36 | if (!m->is_valid) { |
| 37 | return MBEDTLS_ERR_THREADING_BAD_INPUT_DATA; |
| 38 | } |
| 39 | EnterCriticalSection(&m->cs); |
| 40 | return 0; |
| 41 | } |
| 42 | |
| 43 | static int v_mbedtls_mutex_unlock(mbedtls_threading_mutex_t *m) { |
| 44 | if (!m->is_valid) { |
| 45 | return MBEDTLS_ERR_THREADING_BAD_INPUT_DATA; |
| 46 | } |
| 47 | LeaveCriticalSection(&m->cs); |
| 48 | return 0; |
| 49 | } |
| 50 | |
| 51 | static void v_mbedtls_threading_setup(void) { |
| 52 | mbedtls_threading_set_alt(v_mbedtls_mutex_init, v_mbedtls_mutex_free, |
| 53 | v_mbedtls_mutex_lock, v_mbedtls_mutex_unlock); |
| 54 | } |
| 55 | |
| 56 | #else /* not (Windows + THREADING_ALT) */ |
| 57 | |
| 58 | static void v_mbedtls_threading_setup(void) { } |
| 59 | |
| 60 | #endif |
| 61 | |
| 62 | #endif /* V_MBEDTLS_THREADING_H */ |
| 63 | |