1 /*
2  *  OpenVPN -- An application to securely tunnel IP networks
3  *             over a single TCP/UDP port, with support for SSL/TLS-based
4  *             session authentication and key exchange,
5  *             packet encryption, packet authentication, and
6  *             packet compression.
7  *
8  *  Copyright (C) 2002-2022 OpenVPN Inc <sales@openvpn.net>
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2
12  *  as published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License along
20  *  with this program; if not, write to the Free Software Foundation, Inc.,
21  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23 
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #elif defined(_MSC_VER)
27 #include "config-msvc.h"
28 #endif
29 
30 #include "syshead.h"
31 
32 #include "interval.h"
33 
34 #include "memdbg.h"
35 
36 void
interval_init(struct interval * top,int horizon,int refresh)37 interval_init(struct interval *top, int horizon, int refresh)
38 {
39     CLEAR(*top);
40     top->refresh = refresh;
41     top->horizon = horizon;
42 }
43 
44 bool
event_timeout_trigger(struct event_timeout * et,struct timeval * tv,const int et_const_retry)45 event_timeout_trigger(struct event_timeout *et,
46                       struct timeval *tv,
47                       const int et_const_retry)
48 {
49     bool ret = false;
50     const time_t local_now = now;
51 
52     if (et->defined)
53     {
54         time_t wakeup = et->last - local_now + et->n;
55         if (wakeup <= 0)
56         {
57 #if INTERVAL_DEBUG
58             dmsg(D_INTERVAL, "EVENT event_timeout_trigger (%d) etcr=%d", et->n,
59                  et_const_retry);
60 #endif
61             if (et_const_retry < 0)
62             {
63                 et->last = local_now;
64                 wakeup = et->n;
65                 ret = true;
66             }
67             else
68             {
69                 wakeup = et_const_retry;
70             }
71         }
72 
73         if (tv && wakeup < tv->tv_sec)
74         {
75 #if INTERVAL_DEBUG
76             dmsg(D_INTERVAL, "EVENT event_timeout_wakeup (%d/%d) etcr=%d",
77                  (int) wakeup, et->n, et_const_retry);
78 #endif
79             tv->tv_sec = wakeup;
80             tv->tv_usec = 0;
81         }
82     }
83     return ret;
84 }
85