add include <sys/socket.h>
[oweals/busybox.git] / libbb / parse_config.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * config file parser helper
4  *
5  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  * Also for use in uClibc (http://uclibc.org/) licensed under LGPLv2.1 or later.
9  */
10
11 /*
12 //usage:#define parse_trivial_usage
13 //usage:       "[-n MAXTOKENS] [-m MINTOKENS] [-d DELIMS] [-f FLAGS] FILE..."
14 //usage:#define parse_full_usage ""
15 */
16
17 #include "libbb.h"
18
19 #if defined ENABLE_PARSE && ENABLE_PARSE
20 int parse_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
21 int parse_main(int argc UNUSED_PARAM, char **argv)
22 {
23         const char *delims = "# \t";
24         unsigned flags = PARSE_NORMAL;
25         int mintokens = 0, ntokens = 128;
26
27         opt_complementary = "-1:n+:m+:f+";
28         getopt32(argv, "n:m:d:f:", &ntokens, &mintokens, &delims, &flags);
29         //argc -= optind;
30         argv += optind;
31         while (*argv) {
32                 parser_t *p = config_open(*argv);
33                 if (p) {
34                         int n;
35                         char **t = xmalloc(sizeof(char *) * ntokens);
36                         while ((n = config_read(p, t, ntokens, mintokens, delims, flags)) != 0) {
37                                 for (int i = 0; i < n; ++i)
38                                         printf("[%s]", t[i]);
39                                 puts("");
40                         }
41                         config_close(p);
42                 }
43                 argv++;
44         }
45         return EXIT_SUCCESS;
46 }
47 #endif
48
49 /*
50
51 Typical usage:
52
53 ----- CUT -----
54         char *t[3];  // tokens placeholder
55         parser_t *p = config_open(filename);
56         if (p) {
57                 // parse line-by-line
58                 while (config_read(p, t, 3, 0, delimiters, flags)) { // 1..3 tokens
59                         // use tokens
60                         bb_error_msg("TOKENS: [%s][%s][%s]", t[0], t[1], t[2]);
61                 }
62                 ...
63                 // free parser
64                 config_close(p);
65         }
66 ----- CUT -----
67
68 */
69
70 parser_t* FAST_FUNC config_open2(const char *filename, FILE* FAST_FUNC (*fopen_func)(const char *path))
71 {
72         FILE* fp;
73         parser_t *parser;
74
75         fp = fopen_func(filename);
76         if (!fp)
77                 return NULL;
78         parser = xzalloc(sizeof(*parser));
79         parser->fp = fp;
80         return parser;
81 }
82
83 parser_t* FAST_FUNC config_open(const char *filename)
84 {
85         return config_open2(filename, fopen_or_warn_stdin);
86 }
87
88 static void config_free_data(parser_t *parser)
89 {
90         free(parser->line);
91         parser->line = NULL;
92         if (PARSE_KEEP_COPY) { /* compile-time constant */
93                 free(parser->data);
94                 parser->data = NULL;
95         }
96 }
97
98 void FAST_FUNC config_close(parser_t *parser)
99 {
100         if (parser) {
101                 config_free_data(parser);
102                 fclose(parser->fp);
103                 free(parser);
104         }
105 }
106
107 /*
108 0. If parser is NULL return 0.
109 1. Read a line from config file. If nothing to read then return 0.
110    Handle continuation character. Advance lineno for each physical line.
111    Discard everything past comment character.
112 2. if PARSE_TRIM is set (default), remove leading and trailing delimiters.
113 3. If resulting line is empty goto 1.
114 4. Look for first delimiter. If !PARSE_COLLAPSE or !PARSE_TRIM is set then
115    remember the token as empty.
116 5. Else (default) if number of seen tokens is equal to max number of tokens
117    (token is the last one) and PARSE_GREEDY is set then the remainder
118    of the line is the last token.
119    Else (token is not last or PARSE_GREEDY is not set) just replace
120    first delimiter with '\0' thus delimiting the token.
121 6. Advance line pointer past the end of token. If number of seen tokens
122    is less than required number of tokens then goto 4.
123 7. Check the number of seen tokens is not less the min number of tokens.
124    Complain or die otherwise depending on PARSE_MIN_DIE.
125 8. Return the number of seen tokens.
126
127 mintokens > 0 make config_read() print error message if less than mintokens
128 (but more than 0) are found. Empty lines are always skipped (not warned about).
129 */
130 #undef config_read
131 int FAST_FUNC config_read(parser_t *parser, char **tokens, unsigned flags, const char *delims)
132 {
133         char *line;
134         int ntokens, mintokens;
135         int t, len;
136
137         ntokens = (uint8_t)flags;
138         mintokens = (uint8_t)(flags >> 8);
139
140         if (parser == NULL)
141                 return 0;
142
143 again:
144         memset(tokens, 0, sizeof(tokens[0]) * ntokens);
145         config_free_data(parser);
146
147         /* Read one line (handling continuations with backslash) */
148         line = bb_get_chunk_with_continuation(parser->fp, &len, &parser->lineno);
149         if (line == NULL)
150                 return 0;
151         parser->line = line;
152
153         /* Strip trailing line-feed if any */
154         if (len && line[len-1] == '\n')
155                 line[len-1] = '\0';
156
157         /* Skip token in the start of line? */
158         if (flags & PARSE_TRIM)
159                 line += strspn(line, delims + 1);
160
161         if (line[0] == '\0' || line[0] == delims[0])
162                 goto again;
163
164         if (flags & PARSE_KEEP_COPY)
165                 parser->data = xstrdup(line);
166
167         /* Tokenize the line */
168         t = 0;
169         do {
170                 /* Pin token */
171                 tokens[t] = line;
172
173                 /* Combine remaining arguments? */
174                 if ((t != (ntokens-1)) || !(flags & PARSE_GREEDY)) {
175                         /* Vanilla token, find next delimiter */
176                         line += strcspn(line, delims[0] ? delims : delims + 1);
177                 } else {
178                         /* Combining, find comment char if any */
179                         line = strchrnul(line, delims[0]);
180
181                         /* Trim any extra delimiters from the end */
182                         if (flags & PARSE_TRIM) {
183                                 while (strchr(delims + 1, line[-1]) != NULL)
184                                         line--;
185                         }
186                 }
187
188                 /* Token not terminated? */
189                 if (*line == delims[0])
190                         *line = '\0';
191                 else if (*line != '\0')
192                         *line++ = '\0';
193
194 #if 0 /* unused so far */
195                 if (flags & PARSE_ESCAPE) {
196                         strcpy_and_process_escape_sequences(tokens[t], tokens[t]);
197                 }
198 #endif
199                 /* Skip possible delimiters */
200                 if (flags & PARSE_COLLAPSE)
201                         line += strspn(line, delims + 1);
202
203                 t++;
204         } while (*line && *line != delims[0] && t < ntokens);
205
206         if (t < mintokens) {
207                 bb_error_msg("bad line %u: %d tokens found, %d needed",
208                                 parser->lineno, t, mintokens);
209                 if (flags & PARSE_MIN_DIE)
210                         xfunc_die();
211                 if (flags & PARSE_KEEP_COPY)
212                         free(parser->data);
213                 goto again;
214         }
215
216         return t;
217 }