| 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 | #ifndef WIN32_LEAN_AND_MEAN |
| 20 | #define WIN32_LEAN_AND_MEAN |
| 21 | #endif |
| 22 | #include <windows.h> |
| 23 | #include <mbedtls/threading.h> |
| 24 | #include <mbedtls/error.h> |
| 25 | |
| 26 | static void v_mbedtls_mutex_init(mbedtls_threading_mutex_t *m) { |
| 27 | InitializeCriticalSection(&m->cs); |
| 28 | m->is_valid = 1; |
| 29 | } |
| 30 | |
| 31 | static void v_mbedtls_mutex_free(mbedtls_threading_mutex_t *m) { |
| 32 | if (m->is_valid) { |
| 33 | DeleteCriticalSection(&m->cs); |
| 34 | m->is_valid = 0; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | static int v_mbedtls_mutex_lock(mbedtls_threading_mutex_t *m) { |
| 39 | if (!m->is_valid) { |
| 40 | return MBEDTLS_ERR_THREADING_BAD_INPUT_DATA; |
| 41 | } |
| 42 | EnterCriticalSection(&m->cs); |
| 43 | return 0; |
| 44 | } |
| 45 | |
| 46 | static int v_mbedtls_mutex_unlock(mbedtls_threading_mutex_t *m) { |
| 47 | if (!m->is_valid) { |
| 48 | return MBEDTLS_ERR_THREADING_BAD_INPUT_DATA; |
| 49 | } |
| 50 | LeaveCriticalSection(&m->cs); |
| 51 | return 0; |
| 52 | } |
| 53 | |
| 54 | static void v_mbedtls_threading_setup(void) { |
| 55 | mbedtls_threading_set_alt(v_mbedtls_mutex_init, v_mbedtls_mutex_free, |
| 56 | v_mbedtls_mutex_lock, v_mbedtls_mutex_unlock); |
| 57 | } |
| 58 | |
| 59 | #else /* not (Windows + THREADING_ALT) */ |
| 60 | |
| 61 | static void v_mbedtls_threading_setup(void) { } |
| 62 | |
| 63 | #endif |
| 64 | |
| 65 | #endif /* V_MBEDTLS_THREADING_H */ |
| 66 | |