-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathconfig.c
99 lines (77 loc) · 1.99 KB
/
config.c
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
#include "config.h"
#include "rcon.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <glib.h>
#define CONFIG_KEY_HOSTNAME "hostname"
/* It could be either a port number or a service from /etc/services.
* But it is more intuitive if it is called "port"
*/
#define CONFIG_KEY_SERVICE "port"
#define CONFIG_KEY_PASSWORD "password"
#define CONFIG_KEY_MINECRAFT "minecraft"
static GKeyFile *config = NULL;
int config_load(char const *filename)
{
GError *error = NULL;
config_free();
config = g_key_file_new();
if (config == NULL) {
return -1;
}
if (!g_key_file_load_from_file(config, filename, G_KEY_FILE_NONE, &error)) {
fprintf(stderr, "Failed to load configuration file: %s: %s\n",
filename, error->message
);
g_clear_error(&error);
config_free();
return -2;
}
return 0;
}
void config_free(void)
{
if (config) {
g_key_file_free(config);
config = NULL;
}
}
int config_host_data(char const *name, char **hostname,
char **service, char **passwd,
bool *minecraft)
{
gchar *h = NULL, *s = NULL, *p = NULL;
gboolean mc = FALSE;
return_if_true(config == NULL, -1);
if (!g_key_file_has_group(config, name)) {
return -2;
}
h = g_key_file_get_string(config, name, CONFIG_KEY_HOSTNAME, NULL);
if (h == NULL) {
return -3;
}
s = g_key_file_get_string(config, name, CONFIG_KEY_SERVICE, NULL);
if (s == NULL) {
g_free(h);
return -3;
}
p = g_key_file_get_string(config, name, CONFIG_KEY_PASSWORD, NULL);
mc = g_key_file_get_boolean(config, name, CONFIG_KEY_MINECRAFT, NULL);
if (hostname) {
*hostname = strdup(h);
}
if (service) {
*service = strdup(s);
}
if (passwd && p) {
*passwd = strdup(p);
}
if (minecraft) {
*minecraft = mc;
}
g_free(h);
g_free(s);
g_free(p);
return 0;
}