summaryrefslogtreecommitdiff
path: root/modules/uuid/uuid.c
blob: ba1daa45297d3b0421bef91784073106430ed4a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/**
 * @file modules/uuid/uuid.c  Generate and load UUID
 *
 * Copyright (C) 2010 Creytiv.com
 */
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <re.h>
#include <baresip.h>


/**
 * @defgroup uuid uuid
 *
 * UUID generator and loader
 */


enum { UUID_LEN = 36 };


static int generate_random_uuid(FILE *f)
{
	if (re_fprintf(f, "%08x-%04x-%04x-%04x-%08x%04x",
		       rand_u32(), rand_u16(), rand_u16(), rand_u16(),
		       rand_u32(), rand_u16()) != UUID_LEN)
		return ENOMEM;

	return 0;
}


static int uuid_init(const char *file)
{
	FILE *f = NULL;
	int err = 0;

	f = fopen(file, "r");
	if (f) {
		err = 0;
		goto out;
	}

	f = fopen(file, "w");
	if (!f) {
		err = errno;
		warning("uuid: fopen() %s (%m)\n", file, err);
		goto out;
	}

	err = generate_random_uuid(f);
	if (err) {
		warning("uuid: generate random UUID failed (%m)\n", err);
		goto out;
	}

	info("uuid: generated new UUID in %s\n", file);

 out:
	if (f)
		fclose(f);

	return err;
}


static int uuid_load(const char *file, char *uuid, size_t sz)
{
	FILE *f = NULL;
	int err = 0;

	f = fopen(file, "r");
	if (!f)
		return errno;

	if (!fgets(uuid, (int)sz, f))
		err = errno;

	(void)fclose(f);

	debug("uuid: loaded UUID %s from file %s\n", uuid, file);

	return err;
}


static int module_init(void)
{
	struct config *cfg = conf_config();
	char path[256];
	int err = 0;

	err = conf_path_get(path, sizeof(path));
	if (err)
		return err;

	strncat(path, "/uuid", sizeof(path) - strlen(path) - 1);

	err = uuid_init(path);
	if (err)
		return err;

	err = uuid_load(path, cfg->sip.uuid, sizeof(cfg->sip.uuid));
	if (err)
		return err;

	return 0;
}


EXPORT_SYM const struct mod_export DECL_EXPORTS(uuid) = {
	"uuid",
	NULL,
	module_init,
	NULL
};