1
0
mirror of https://github.com/eclipse/mosquitto.git synced 2025-05-08 08:40:13 +08:00

fix CLOCK_BOOTTIME use on kernels not having it

When the libc headers used to build mosquitto define CLOCK_BOOTTIME but
the kernel where mosquitto runs does not implement CLOCK_BOOTTIME, all
timestamps are wrong (uninitialized data), because there is no check for
the success of the clock_gettime() calls.

This adds probing for the availability of CLOCK_BOOTTIME from
mosquitto_lib_init(), falling back to CLOCK_MONOTONIC, and then modifies
mosquitto_time() to use the selected clock. Probing at init time avoids
having to do two clock_gettime() calls for every timestamp if
CLOCK_BOOTTIME is not available.

It also fixes a similar problem in mosquitto_lib_init().

Signed-off-by: Diego Santa Cruz <diego.santacruz@spinetix.com>
This commit is contained in:
Diego Santa Cruz 2024-07-31 12:27:13 +00:00 committed by Roger Light
parent a87b5ff6d8
commit 688fa86de4
3 changed files with 30 additions and 9 deletions

View File

@ -38,6 +38,7 @@ Contributors:
#include "mqtt_protocol.h"
#include "net_mosq.h"
#include "packet_mosq.h"
#include "time_mosq.h"
#include "will_mosq.h"
static unsigned int init_refcount = 0;
@ -57,15 +58,15 @@ int mosquitto_lib_init(void)
int rc;
if (init_refcount == 0) {
mosquitto_time_init();
#ifdef WIN32
srand((unsigned int)GetTickCount64());
#elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK)
struct timespec tp;
#ifdef CLOCK_BOOTTIME
clock_gettime(CLOCK_BOOTTIME, &tp);
#else
clock_gettime(CLOCK_MONOTONIC, &tp);
if (clock_gettime(CLOCK_BOOTTIME, &tp) != 0)
#endif
clock_gettime(CLOCK_MONOTONIC, &tp);
srand((unsigned int)tp.tv_nsec);
#elif defined(__APPLE__)
uint64_t ticks;

View File

@ -36,6 +36,27 @@ Contributors:
#include "mosquitto.h"
#include "time_mosq.h"
#if _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK)
static clockid_t time_clock;
#endif
void mosquitto_time_init(void)
{
#if _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK)
struct timespec tp;
#ifdef CLOCK_BOOTTIME
if (clock_gettime(CLOCK_BOOTTIME, &tp) == 0) {
time_clock = CLOCK_BOOTTIME;
} else {
time_clock = CLOCK_MONOTONIC;
}
#else
time_clock = CLOCK_MONOTONIC;
#endif
#endif
}
time_t mosquitto_time(void)
{
#ifdef WIN32
@ -43,12 +64,10 @@ time_t mosquitto_time(void)
#elif _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK)
struct timespec tp;
#ifdef CLOCK_BOOTTIME
clock_gettime(CLOCK_BOOTTIME, &tp);
#else
clock_gettime(CLOCK_MONOTONIC, &tp);
#endif
return tp.tv_sec;
if (clock_gettime(time_clock, &tp) == 0)
return tp.tv_sec;
return (time_t) -1;
#elif defined(__APPLE__)
static mach_timebase_info_data_t tb;
uint64_t ticks;

View File

@ -19,6 +19,7 @@ Contributors:
#ifndef TIME_MOSQ_H
#define TIME_MOSQ_H
void mosquitto_time_init(void);
time_t mosquitto_time(void);
#endif