1 /* upsconf.c - code for handling ups.conf ini-style parsing
2
3 Copyright (C) 2001 Russell Kroll <rkroll@exploits.org>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19
20 #include <stdio.h>
21 #include <unistd.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 #include "upsconf.h"
26 #include "common.h"
27 #include "parseconf.h"
28
29 static char *ups_section;
30
31 /* handle arguments separated by parseconf */
conf_args(size_t numargs,char ** arg)32 static void conf_args(size_t numargs, char **arg)
33 {
34 if (numargs < 1)
35 return;
36
37 /* look for section headers - [upsname] */
38 if ((arg[0][0] == '[') && (arg[0][strlen(arg[0])-1] == ']')) {
39
40 free(ups_section);
41
42 arg[0][strlen(arg[0])-1] = '\0';
43 ups_section = xstrdup(&arg[0][1]);
44 return;
45 }
46
47 /* handle 'foo' (flag) */
48 if (numargs == 1) {
49 do_upsconf_args(ups_section, arg[0], NULL);
50 return;
51 }
52
53 if (numargs < 3)
54 return;
55
56 /* handle 'foo = bar', 'foo=bar', 'foo =bar' or 'foo= bar' forms */
57 if (!strncmp(arg[1], "=", 1)) {
58 do_upsconf_args(ups_section, arg[0], arg[2]);
59 return;
60 }
61 }
62
63 /* called for fatal errors in parseconf like malloc failures */
upsconf_err(const char * errmsg)64 static void upsconf_err(const char *errmsg)
65 {
66 upslogx(LOG_ERR, "Fatal error in parseconf(ups.conf): %s", errmsg);
67 }
68
69 /* open the ups.conf, parse it, and call back do_upsconf_args() */
read_upsconf(void)70 void read_upsconf(void)
71 {
72 char fn[SMALLBUF];
73 PCONF_CTX_t ctx;
74
75 ups_section = NULL;
76 snprintf(fn, sizeof(fn), "%s/ups.conf", confpath());
77
78 pconf_init(&ctx, upsconf_err);
79
80 if (!pconf_file_begin(&ctx, fn))
81 fatalx(EXIT_FAILURE, "Can't open %s: %s", fn, ctx.errmsg);
82
83 while (pconf_file_next(&ctx)) {
84 if (pconf_parse_error(&ctx)) {
85 upslogx(LOG_ERR, "Parse error: %s:%d: %s",
86 fn, ctx.linenum, ctx.errmsg);
87 continue;
88 }
89
90 conf_args(ctx.numargs, ctx.arglist);
91 }
92
93 pconf_finish(&ctx);
94
95 free(ups_section);
96 }
97