1 /**
2 * @file modules/uuid/uuid.c Generate and load UUID
3 *
4 * Copyright (C) 2010 Creytiv.com
5 */
6 #include <stdlib.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <re.h>
10 #include <baresip.h>
11
12
13 /**
14 * @defgroup uuid uuid
15 *
16 * UUID generator and loader
17 */
18
19
20 enum { UUID_LEN = 36 };
21
22
generate_random_uuid(FILE * f)23 static int generate_random_uuid(FILE *f)
24 {
25 if (re_fprintf(f, "%08x-%04x-%04x-%04x-%08x%04x",
26 rand_u32(), rand_u16(), rand_u16(), rand_u16(),
27 rand_u32(), rand_u16()) != UUID_LEN)
28 return ENOMEM;
29
30 return 0;
31 }
32
33
uuid_init(const char * file)34 static int uuid_init(const char *file)
35 {
36 FILE *f = NULL;
37 int err = 0;
38
39 f = fopen(file, "r");
40 if (f) {
41 err = 0;
42 goto out;
43 }
44
45 f = fopen(file, "w");
46 if (!f) {
47 err = errno;
48 warning("uuid: fopen() %s (%m)\n", file, err);
49 goto out;
50 }
51
52 err = generate_random_uuid(f);
53 if (err) {
54 warning("uuid: generate random UUID failed (%m)\n", err);
55 goto out;
56 }
57
58 info("uuid: generated new UUID in %s\n", file);
59
60 out:
61 if (f)
62 fclose(f);
63
64 return err;
65 }
66
67
uuid_load(const char * file,char * uuid,size_t sz)68 static int uuid_load(const char *file, char *uuid, size_t sz)
69 {
70 FILE *f = NULL;
71 int err = 0;
72
73 f = fopen(file, "r");
74 if (!f)
75 return errno;
76
77 if (!fgets(uuid, (int)sz, f))
78 err = errno;
79
80 (void)fclose(f);
81
82 debug("uuid: loaded UUID %s from file %s\n", uuid, file);
83
84 return err;
85 }
86
87
module_init(void)88 static int module_init(void)
89 {
90 struct config *cfg = conf_config();
91 char path[256];
92 int err = 0;
93
94 err = conf_path_get(path, sizeof(path));
95 if (err)
96 return err;
97
98 strncat(path, "/uuid", sizeof(path) - strlen(path) - 1);
99
100 err = uuid_init(path);
101 if (err)
102 return err;
103
104 err = uuid_load(path, cfg->sip.uuid, sizeof(cfg->sip.uuid));
105 if (err)
106 return err;
107
108 return 0;
109 }
110
111
112 EXPORT_SYM const struct mod_export DECL_EXPORTS(uuid) = {
113 "uuid",
114 NULL,
115 module_init,
116 NULL
117 };
118