fix event handler list initialization
[project/ubus.git] / ubusd_id.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5
6 #include "ubusmsg.h"
7 #include "ubusd_id.h"
8
9 static int random_fd = -1;
10
11 static int ubus_cmp_id(const void *k1, const void *k2, void *ptr)
12 {
13         const uint32_t *id1 = k1, *id2 = k2;
14
15         if (*id1 < *id2)
16                 return -1;
17         else
18                 return *id1 > *id2;
19 }
20
21 static int ubus_cmp_str(const void *k1, const void *k2, void *ptr)
22 {
23         return strcmp(k1, k2);
24 }
25
26 void ubus_init_string_tree(struct avl_tree *tree, bool dup)
27 {
28         avl_init(tree, ubus_cmp_str, dup, NULL);
29 }
30
31 void ubus_init_id_tree(struct avl_tree *tree)
32 {
33         if (random_fd < 0) {
34                 random_fd = open("/dev/urandom", O_RDONLY);
35                 if (random_fd < 0) {
36                         perror("open");
37                         exit(1);
38                 }
39         }
40
41         avl_init(tree, ubus_cmp_id, false, NULL);
42 }
43
44 bool ubus_alloc_id(struct avl_tree *tree, struct ubus_id *id, uint32_t val)
45 {
46         id->avl.key = &id->id;
47         if (val) {
48                 id->id = val;
49                 return avl_insert(tree, &id->avl) == 0;
50         }
51
52         do {
53                 if (read(random_fd, &id->id, sizeof(id->id)) != sizeof(id->id))
54                         return false;
55
56                 if (id->id < UBUS_SYSTEM_OBJECT_MAX)
57                         continue;
58         } while (avl_insert(tree, &id->avl) != 0);
59
60         return true;
61 }
62