aboutsummaryrefslogtreecommitdiffstats
path: root/src/config.c
blob: 2165821cce1f44287fc8a8ceae728e05ccdca22c (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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
/**
 * @file  config.c
 * @brief Simple key=value configuration file parser implementation.
 */

#include "config.h"

#include <open62541/plugin/log_stdout.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Enough for typical config files; doubles on overflow. */
#define CONFIG_INITIAL_CAPACITY 16

/* Sufficient for file paths and URIs. */
#define CONFIG_LINE_MAX 1024

/* ========================================================================
 * Static Helpers
 * ======================================================================== */

/**
 * @brief Trims leading and trailing whitespace in place.
 *
 * Modifies the string by writing a NUL terminator after the last
 * non-whitespace character and returns a pointer past any leading
 * whitespace.
 */
static char *
trim (char *s)
{
  while (*s == ' ' || *s == '\t')
    s++;
  size_t len = strlen (s);
  while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t'))
    len--;
  s[len] = '\0';
  return s;
}

/**
 * @brief Appends a key-value pair to the config's dynamic array.
 *
 * Grows the array by doubling capacity when full.
 *
 * @return 0 on success, -1 on allocation failure.
 */
static int
configAppend (Config *cfg, const char *key, const char *value)
{
  if (cfg->count == cfg->capacity)
    {
      size_t newCap = cfg->capacity * 2;
      ConfigEntry *tmp = realloc (cfg->entries, newCap * sizeof (ConfigEntry));
      if (!tmp)
        {
          UA_LOG_ERROR (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                        "Config: out of memory");
          return -1;
        }
      cfg->entries = tmp;
      cfg->capacity = newCap;
    }

  cfg->entries[cfg->count].key = strdup (key);
  cfg->entries[cfg->count].value = strdup (value);
  if (!cfg->entries[cfg->count].key || !cfg->entries[cfg->count].value)
    {
      UA_LOG_ERROR (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                    "Config: out of memory");
      return -1;
    }
  cfg->count++;
  return 0;
}

/* ========================================================================
 * Public API
 * ======================================================================== */

int
configLoad (const char *path, Config *cfg)
{
  memset (cfg, 0, sizeof (Config));

  cfg->entries = malloc (CONFIG_INITIAL_CAPACITY * sizeof (ConfigEntry));
  if (!cfg->entries)
    {
      UA_LOG_ERROR (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                    "Config: out of memory");
      return -1;
    }
  cfg->capacity = CONFIG_INITIAL_CAPACITY;

  FILE *fp = fopen (path, "r");
  if (!fp)
    {
      UA_LOG_ERROR (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                    "Config: cannot open '%s'", path);
      free (cfg->entries);
      memset (cfg, 0, sizeof (Config));
      return -1;
    }

  char line[CONFIG_LINE_MAX];
  int lineNum = 0;

  while (fgets (line, sizeof (line), fp))
    {
      lineNum++;

      /* Strip trailing newline / carriage return. */
      size_t len = strlen (line);
      while (len > 0 && (line[len - 1] == '\n' || line[len - 1] == '\r'))
        line[--len] = '\0';

      /* Skip blank lines and comments. */
      char *trimmed = trim (line);
      if (*trimmed == '\0' || *trimmed == '#')
        continue;

      /* Find the '=' separator. */
      char *eq = strchr (trimmed, '=');
      if (!eq)
        {
          UA_LOG_ERROR (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                        "Config: syntax error at %s:%d "
                        "(missing '=')",
                        path, lineNum);
          fclose (fp);
          configFree (cfg);
          return -1;
        }

      *eq = '\0';
      char *key = trim (trimmed);
      char *value = trim (eq + 1);

      if (*key == '\0')
        {
          UA_LOG_ERROR (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                        "Config: empty key at %s:%d", path, lineNum);
          fclose (fp);
          configFree (cfg);
          return -1;
        }

      if (configAppend (cfg, key, value) != 0)
        {
          fclose (fp);
          configFree (cfg);
          return -1;
        }
    }

  fclose (fp);
  return 0;
}

const char *
configGet (const Config *cfg, const char *key)
{
  for (size_t i = 0; i < cfg->count; i++)
    {
      if (strcmp (cfg->entries[i].key, key) == 0)
        return cfg->entries[i].value;
    }
  return NULL;
}

const char *
configRequire (const Config *cfg, const char *key, const char *program)
{
  const char *val = configGet (cfg, key);
  if (!val)
    UA_LOG_FATAL (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                  "%s: missing required config key '%s'", program, key);
  return val;
}

int
configRequireInt (const Config *cfg, const char *key, const char *program)
{
  const char *val = configRequire (cfg, key, program);
  if (!val)
    return -1;

  char *endptr;
  long num = strtol (val, &endptr, 10);
  if (*endptr != '\0')
    {
      UA_LOG_FATAL (UA_Log_Stdout, UA_LOGCATEGORY_USERLAND,
                    "%s: config key '%s' is not a valid integer: '%s'",
                    program, key, val);
      return -1;
    }
  return (int)num;
}

void
configFree (Config *cfg)
{
  for (size_t i = 0; i < cfg->count; i++)
    {
      free (cfg->entries[i].key);
      free (cfg->entries[i].value);
    }
  free (cfg->entries);
  memset (cfg, 0, sizeof (Config));
}