blob: 002857d0803ecc04508f20fe74204e86a831b7a8 [file] [log] [blame]
Neels Hofmeyrab7dc402019-11-20 03:35:37 +01001/* Copyright 2019 by sysmocom s.f.m.c. GmbH <info@sysmocom.de>
2 *
3 * All Rights Reserved
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20#include <osmocom/core/timer.h>
21#include <osmocom/hlr/timestamp.h>
22
23/* Central implementation to set a timestamp to the current time, in case we want to modify this in the future. */
24void timestamp_update(timestamp_t *timestamp)
25{
26 struct timeval tv;
27 time_t raw;
28 struct tm utc;
29 /* The simpler way would be just time(&raw), but by using osmo_gettimeofday() we can also use
30 * osmo_gettimeofday_override for unit tests independent from real time. */
31 osmo_gettimeofday(&tv, NULL);
32 raw = tv.tv_sec;
33 gmtime_r(&raw, &utc);
34 *timestamp = mktime(&utc);
35}
36
37/* Calculate seconds since a given timestamp was taken. Return true for a valid age returned in age_p, return false if
38 * the timestamp is either in the future or the age surpasses uint32_t range. When false is returned, *age_p is set to
39 * UINT32_MAX. */
40bool timestamp_age(const timestamp_t *timestamp, uint32_t *age_p)
41{
42 int64_t age64;
43 timestamp_t now;
44 timestamp_update(&now);
45 age64 = (int64_t)now - (int64_t)(*timestamp);
46 if (age64 < 0 || age64 > UINT32_MAX) {
47 *age_p = UINT32_MAX;
48 return false;
49 }
50 *age_p = (uint32_t)age64;
51 return true;
52}
53