From 46ccc2efe905c0ebd7c26641c5af3cf461d98d51 Mon Sep 17 00:00:00 2001 From: "Roger A. Light" Date: Fri, 3 Apr 2015 07:48:55 +0100 Subject: [PATCH] [463479] Make _mosquitto_mid_generate() thread safe. Thanks to bdwalker. Bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=463479 --- ChangeLog.txt | 1 + lib/mosquitto.c | 2 ++ lib/mosquitto_internal.h | 1 + lib/util_mosq.c | 13 ++++++++++++- 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/ChangeLog.txt b/ChangeLog.txt index d0e10f61..bb67dd21 100644 --- a/ChangeLog.txt +++ b/ChangeLog.txt @@ -17,6 +17,7 @@ Client library: - Fix crash on multiple calls to mosquitto_lib_init/mosquitto_lib_cleanup. Closes #462780. - Allow longer paths on Windows. Closes #462781. +- Make _mosquitto_mid_generate() thread safe. Closes #463479. 1.4 - 20150218 diff --git a/lib/mosquitto.c b/lib/mosquitto.c index cc438c82..bd9dbd30 100644 --- a/lib/mosquitto.c +++ b/lib/mosquitto.c @@ -211,6 +211,7 @@ int mosquitto_reinitialise(struct mosquitto *mosq, const char *id, bool clean_se pthread_mutex_init(&mosq->msgtime_mutex, NULL); pthread_mutex_init(&mosq->in_message_mutex, NULL); pthread_mutex_init(&mosq->out_message_mutex, NULL); + pthread_mutex_init(&mosq->mid_mutex, NULL); mosq->thread_id = pthread_self(); #endif @@ -293,6 +294,7 @@ void _mosquitto_destroy(struct mosquitto *mosq) pthread_mutex_destroy(&mosq->msgtime_mutex); pthread_mutex_destroy(&mosq->in_message_mutex); pthread_mutex_destroy(&mosq->out_message_mutex); + pthread_mutex_destroy(&mosq->mid_mutex); } #endif if(mosq->sock != INVALID_SOCKET){ diff --git a/lib/mosquitto_internal.h b/lib/mosquitto_internal.h index 6e148cde..4c341163 100644 --- a/lib/mosquitto_internal.h +++ b/lib/mosquitto_internal.h @@ -187,6 +187,7 @@ struct mosquitto { pthread_mutex_t state_mutex; pthread_mutex_t in_message_mutex; pthread_mutex_t out_message_mutex; + pthread_mutex_t mid_mutex; pthread_t thread_id; #endif bool clean_session; diff --git a/lib/util_mosq.c b/lib/util_mosq.c index 2909a219..273a040a 100644 --- a/lib/util_mosq.c +++ b/lib/util_mosq.c @@ -147,12 +147,23 @@ void _mosquitto_check_keepalive(struct mosquitto *mosq) uint16_t _mosquitto_mid_generate(struct mosquitto *mosq) { + /* FIXME - this would be better with atomic increment, but this is safer + * for now for a bug fix release. + * + * If this is changed to use atomic increment, callers of this function + * will have to be aware that they may receive a 0 result, which may not be + * used as a mid. + */ + uint16_t mid; assert(mosq); + pthread_mutex_lock(&mosq->mid_mutex); mosq->last_mid++; if(mosq->last_mid == 0) mosq->last_mid++; + mid = mosq->last_mid; + pthread_mutex_unlock(&mosq->mid_mutex); - return mosq->last_mid; + return mid; } /* Check that a topic used for publishing is valid.