a91be86d86fb73b45f3fe95309bfe82e70b51d2e
[tinc] / src / event.c
1 /*
2     event.c -- event queue
3     Copyright (C) 2002 Guus Sliepen <guus@sliepen.eu.org>,
4                   2002 Ivo Timmermans <ivo@o2w.nl>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: event.c,v 1.1.4.6 2002/09/09 22:32:30 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <xalloc.h>
27 #include <string.h>
28 #include <utils.h>
29 #include <avl_tree.h>
30 #include <time.h>
31
32 #include "event.h"
33
34 #include "system.h"
35
36 avl_tree_t *event_tree;
37 extern time_t now;
38
39 int id;
40
41 int event_compare(event_t *a, event_t *b)
42 {
43         if(a->time > b->time)
44                 return 1;
45
46         if(a->time < b->time)
47                 return -1;
48
49         return a->id - b->id;
50 }
51
52 void init_events(void)
53 {
54         cp();
55
56         event_tree = avl_alloc_tree((avl_compare_t) event_compare, NULL);
57 }
58
59 void exit_events(void)
60 {
61         cp();
62
63         avl_delete_tree(event_tree);
64 }
65
66 event_t *new_event(void)
67 {
68         cp();
69
70         return (event_t *) xmalloc_and_zero(sizeof(event_t));
71 }
72
73 void free_event(event_t *event)
74 {
75         cp();
76
77         free(event);
78 }
79
80 void event_add(event_t *event)
81 {
82         cp();
83
84         event->id = ++id;
85         avl_insert(event_tree, event);
86 }
87
88 void event_del(event_t *event)
89 {
90         cp();
91
92         avl_delete(event_tree, event);
93 }
94
95 event_t *get_expired_event(void)
96 {
97         event_t *event;
98
99         cp();
100
101         if(event_tree->head) {
102                 event = (event_t *) event_tree->head->data;
103
104                 if(event->time < now) {
105                         avl_delete(event_tree, event);
106                         return event;
107                 }
108         }
109
110         return NULL;
111 }