xref: /openbsd-src/usr.sbin/smtpd/expand.c (revision 5054e3e78af0749a9bb00ba9a024b3ee2d90290f)
1 /*	$OpenBSD: expand.c,v 1.3 2009/11/09 23:49:34 gilles Exp $	*/
2 
3 /*
4  * Copyright (c) 2009 Gilles Chehade <gilles@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/queue.h>
21 #include <sys/tree.h>
22 #include <sys/param.h>
23 #include <sys/socket.h>
24 
25 #include <ctype.h>
26 #include <errno.h>
27 #include <event.h>
28 #include <fcntl.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <util.h>
33 
34 #include "smtpd.h"
35 
36 struct expand_node *
37 expandtree_lookup(struct expandtree *expandtree, struct expand_node *node)
38 {
39 	struct expand_node key;
40 
41 	key = *node;
42 	return RB_FIND(expandtree, expandtree, &key);
43 }
44 
45 void
46 expandtree_increment_node(struct expandtree *expandtree, struct expand_node *node)
47 {
48 	struct expand_node *p;
49 
50 	p = expandtree_lookup(expandtree, node);
51 	if (p == NULL) {
52 		p = calloc(1, sizeof(struct expand_node));
53 		if (p == NULL)
54 			fatal("calloc");
55 		*p = *node;
56 		if (RB_INSERT(expandtree, expandtree, p))
57 			fatalx("expandtree_increment_node: node already exists");
58 	}
59 	p->refcnt++;
60 }
61 
62 void
63 expandtree_decrement_node(struct expandtree *expandtree, struct expand_node *node)
64 {
65 	struct expand_node *p;
66 
67 	p = expandtree_lookup(expandtree, node);
68 	if (p == NULL)
69 		fatalx("expandtree_decrement_node: node doesn't exist.");
70 
71 	p->refcnt--;
72 }
73 
74 void
75 expandtree_remove_node(struct expandtree *expandtree, struct expand_node *node)
76 {
77 	struct expand_node *p;
78 
79 	p = expandtree_lookup(expandtree, node);
80 	if (p == NULL)
81 		fatalx("expandtree_remove: node doesn't exist.");
82 
83 	RB_REMOVE(expandtree, expandtree, p);
84 }
85 
86 int
87 expand_cmp(struct expand_node *e1, struct expand_node *e2)
88 {
89 	if (e1->type < e2->type)
90 		return -1;
91 
92 	if (e1->type > e2->type)
93 		return 1;
94 
95 	return memcmp(&e1->u, &e2->u, sizeof(e1->u));
96 }
97 
98 RB_GENERATE(expandtree, expand_node, entry, expand_cmp);
99