-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.c
83 lines (73 loc) · 2.86 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
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
#include "config.h"
static struct config cfg = {
.cbfs_host = "localhost:8484",
.cbfs_username = NULL,
.cbfs_password = NULL,
.couchbase_host = "localhost:8091",
.couchbase_username = "cbfs",
.couchbase_password = NULL,
.couchbase_bucket = "cbfs"
};
static char *get_string(cJSON *obj) {
if (strlen(obj->valuestring) > 0) {
return strdup(obj->valuestring);
}
return NULL;
}
struct config *get_configuration(void) {
struct stat st;
if (stat("config.json", &st) == 0) {
char *buffer = malloc(st.st_size + 1);
buffer[st.st_size] = '\0';
FILE *fp = fopen("config.json", "rb");
fread(buffer, 1, st.st_size, fp);
fclose(fp);
memset(&cfg, 0, sizeof(cfg));
cJSON *doc = cJSON_Parse(buffer);
if (doc == NULL) {
fprintf(stderr, "Failed to parse configuration file\n");
exit(EXIT_FAILURE);
}
cJSON *fields = doc->child;
while (fields != NULL) {
if (strcmp(fields->string, "cbfs_host") == 0) {
cfg.cbfs_host = get_string(fields);
} else if (strcmp(fields->string, "cbfs_username") == 0) {
cfg.cbfs_username = get_string(fields);
} else if (strcmp(fields->string, "cbfs_password") == 0) {
cfg.cbfs_password = get_string(fields);
} else if (strcmp(fields->string, "couchbase_host") == 0) {
cfg.couchbase_host = get_string(fields);
} else if (strcmp(fields->string, "couchbase_username") == 0) {
cfg.couchbase_username = get_string(fields);
} else if (strcmp(fields->string, "couchbase_password") == 0) {
cfg.couchbase_password = get_string(fields);
} else if (strcmp(fields->string, "couchbase_bucket") == 0) {
cfg.couchbase_bucket = get_string(fields);
} else {
fprintf(stderr, "Unknown field: %s\n", fields->string);
}
fields = fields->next;
}
cJSON_Delete(doc);
free(buffer);
}
fprintf(stdout, "mount_cbfs using the following configuration:\n{\n");
fprintf(stdout, " \"cbfs_host\" : \"%s\"\n", cfg.cbfs_host);
fprintf(stdout, " \"cbfs_username\" : \"%s\"\n", cfg.cbfs_username);
fprintf(stdout, " \"cbfs_password\" : \"%s\"\n", cfg.cbfs_password);
fprintf(stdout, " \"couchbase_host\" : \"%s\"\n", cfg.couchbase_host);
fprintf(stdout, " \"couchbase_username\" : \"%s\"\n",
cfg.couchbase_username);
fprintf(stdout, " \"couchbase_password\" : \"%s\"\n",
cfg.couchbase_password);
fprintf(stdout, " \"couchbase_bucket\" : \"%s\"\n",
cfg.couchbase_bucket);
fprintf(stdout, "}\n");
return &cfg;
}